Example usage for java.lang.reflect Method getAnnotation

List of usage examples for java.lang.reflect Method getAnnotation

Introduction

In this page you can find the example usage for java.lang.reflect Method getAnnotation.

Prototype

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

Source Link

Usage

From source file:Main.java

/**
 * Converts a given object to a form encoded map
 * @param objName Name of the object/*from   www  . j  av  a 2s  . c o m*/
 * @param obj The object to convert into a map
 * @param objectMap The object map to populate
 * @param processed List of objects hashCodes that are already parsed
 * @throws InvalidObjectException
 */
private static void objectToMap(String objName, Object obj, Map<String, Object> objectMap,
        HashSet<Integer> processed) throws InvalidObjectException {
    //null values need not to be processed
    if (obj == null)
        return;

    //wrapper types are autoboxed, so reference checking is not needed
    if (!isWrapperType(obj.getClass())) {
        //avoid infinite recursion
        if (processed.contains(obj.hashCode()))
            return;
        processed.add(obj.hashCode());
    }

    //process arrays
    if (obj instanceof Collection<?>) {
        //process array
        if ((objName == null) || (objName.isEmpty()))
            throw new InvalidObjectException("Object name cannot be empty");

        Collection<?> array = (Collection<?>) obj;
        //append all elements in the array into a string
        int index = 0;
        for (Object element : array) {
            //load key value pair
            String key = String.format("%s[%d]", objName, index++);
            loadKeyValuePairForEncoding(key, element, objectMap, processed);
        }
    } else if (obj instanceof Map) {
        //process map
        Map<?, ?> map = (Map<?, ?>) obj;
        //append all elements in the array into a string            
        for (Map.Entry<?, ?> pair : map.entrySet()) {
            String attribName = pair.getKey().toString();
            String key = attribName;
            if ((objName != null) && (!objName.isEmpty())) {
                key = String.format("%s[%s]", objName, attribName);
            }
            loadKeyValuePairForEncoding(key, pair.getValue(), objectMap, processed);
        }
    } else {
        //process objects
        // invoke getter methods
        Method[] methods = obj.getClass().getMethods();
        for (Method method : methods) {
            //is a getter?
            if ((method.getParameterTypes().length != 0) || (!method.getName().startsWith("get")))
                continue;

            //get json attribute name
            Annotation getterAnnotation = method.getAnnotation(JsonGetter.class);
            if (getterAnnotation == null)
                continue;

            //load key name
            String attribName = ((JsonGetter) getterAnnotation).value();
            String key = attribName;
            if ((objName != null) && (!objName.isEmpty())) {
                key = String.format("%s[%s]", objName, attribName);
            }

            try {
                //load key value pair
                Object value = method.invoke(obj);
                loadKeyValuePairForEncoding(key, value, objectMap, processed);
            } catch (Exception ex) {
            }
        }
        // load fields
        Field[] fields = obj.getClass().getFields();
        for (Field field : fields) {
            //load key name
            String attribName = field.getName();
            String key = attribName;
            if ((objName != null) && (!objName.isEmpty())) {
                key = String.format("%s[%s]", objName, attribName);
            }

            try {
                //load key value pair
                Object value = field.get(obj);
                loadKeyValuePairForEncoding(key, value, objectMap, processed);
            } catch (Exception ex) {
            }
        }
    }
}

From source file:com.gargoylesoftware.htmlunit.source.JQueryExtractor.java

/**
 * Generates the java code of the test cases.
 * @param testClass the class containing the tests
 * @param dir the directory which holds the expectations
 * @throws Exception if an error occurs.
 *///from   w w  w .ja v a2  s .  c o  m
public static void generateTestCases(final Class<? extends WebDriverTestCase> testClass, final File dir)
        throws Exception {
    final Browser[] browsers = Browser.values();
    // main browsers regardless of version e.g. "FF"
    final List<String> mainNames = new ArrayList<>();
    for (final Browser b : browsers) {
        final String name = b.name();
        if (!"NONE".equals(name) && Character.isLetter(name.charAt(name.length() - 1))) {
            mainNames.add(name);
        }
    }

    final Map<String, List<String>> browserVersions = new HashMap<>();
    for (final Browser b : browsers) {
        final String name = b.name();
        for (final String mainName : mainNames) {
            if (!name.equals(mainName) && name.startsWith(mainName)) {
                List<String> list = browserVersions.get(mainName);
                if (list == null) {
                    list = new ArrayList<>();
                    browserVersions.put(mainName, list);
                }
                list.add(name);
            }
        }
    }
    final Map<String, Expectations> browserExpectations = new HashMap<>();
    for (final File file : dir.listFiles()) {
        if (file.isFile() && file.getName().endsWith(".txt")) {
            for (final Browser b : browsers) {
                final String browserName = b.name();
                if (file.getName().equalsIgnoreCase("results." + browserName.replace('_', '.') + ".txt")) {
                    browserExpectations.put(browserName, Expectations.readExpectations(file));
                }
            }
        }
    }

    // gather all the tests (some tests don't get executed for all browsers)
    final List<Test> allTests = computeTestsList(browserExpectations);

    final Collection<String> availableBrowserNames = new TreeSet<>(browserExpectations.keySet());
    for (final Test test : allTests) {
        final Map<String, String> testExpectation = new TreeMap<>();
        final Map<Integer, List<String>> lineToBrowser = new TreeMap<>();
        for (final String browserName : availableBrowserNames) {
            final Expectation expectation = browserExpectations.get(browserName).getExpectation(test);
            if (expectation != null) {
                List<String> browsersForLine = lineToBrowser.get(expectation.getLine());
                if (browsersForLine == null) {
                    browsersForLine = new ArrayList<>();
                    lineToBrowser.put(expectation.getLine(), browsersForLine);
                }
                browsersForLine.add(browserName);
                final String str = expectation.getTestResult();
                testExpectation.put(browserName,
                        str.replaceAll("\\\\", "\\\\\\\\").replaceAll("\\\"", "\\\\\""));
            }
        }
        System.out.println("    /**");
        System.out.println("     * Test " + lineToBrowser + ".");
        System.out.println("     * @throws Exception if an error occurs");
        System.out.println("     */");
        System.out.println("    @Test");
        System.out.print("    @Alerts(");

        final boolean allSame = testExpectation.size() == availableBrowserNames.size()
                && new HashSet<>(testExpectation.values()).size() == 1;
        if (allSame) {
            final String first = testExpectation.keySet().iterator().next();
            String expectation = testExpectation.get(first);
            if (expectation.length() > 100) {
                expectation = expectation.substring(0, 50) + "\"\n            + \"" + expectation.substring(50);
            }
            System.out.print("\"" + expectation + '"');
        } else {
            boolean first = true;
            for (final String browserName : availableBrowserNames) {
                final String expectation = testExpectation.get(browserName);
                if (expectation == null) {
                    continue; // test didn't run for this browser
                }
                if (!first) {
                    System.out.println(",");
                    System.out.print("        ");
                }
                System.out.print(browserName + " = \"" + expectation + '"');
                first = false;
            }
        }
        System.out.println(")");

        final String methodName = test.getName().replaceAll("\\W", "_");
        try {
            final Method method = testClass.getMethod(methodName);
            final NotYetImplemented notYetImplemented = method.getAnnotation(NotYetImplemented.class);
            if (null != notYetImplemented) {
                final Browser[] notYetImplementedBrowsers = notYetImplemented.value();
                if (notYetImplementedBrowsers.length > 0) {
                    final List<String> browserNames = new ArrayList<>(notYetImplementedBrowsers.length);
                    for (Browser browser : notYetImplementedBrowsers) {
                        browserNames.add(browser.name());
                    }
                    Collections.sort(browserNames);

                    // TODO dirty hack
                    if (browserNames.size() == 3 && browserNames.contains("CHROME")
                            && browserNames.contains("FF") && browserNames.contains("IE")) {
                        System.out.println("    @NotYetImplemented");
                    } else {
                        System.out.print("    @NotYetImplemented(");
                        if (browserNames.size() > 1) {
                            System.out.print("{ ");
                        }
                        System.out.print(StringUtils.join(browserNames, ", "));
                        if (browserNames.size() > 1) {
                            System.out.print(" }");
                        }
                        System.out.println(")");
                    }
                }
            }
        } catch (final NoSuchMethodException e) {
            // ignore
        }

        System.out
                .println("    public void " + test.getName().replaceAll("\\W", "_") + "() throws Exception {");
        System.out.println("        runTest(\"" + test.getName().replace("\"", "\\\"") + "\");");
        System.out.println("    }");
        System.out.println();
    }
}

From source file:cn.teamlab.wg.framework.struts2.breadcrumb.BreadCrumbInterceptor.java

@SuppressWarnings("unchecked")
protected static BreadCrumb findAnnotation(Class aclass, Method method) {
    BreadCrumb crumb = null;// w w w  . j  a  v a2  s .c  o m

    /*
     * Check if it is an annotated method
     */
    if (method != null) {
        crumb = method.getAnnotation(BreadCrumb.class);
    }

    /*
     * Check if we have an annotated class
     */
    if (crumb == null) {
        crumb = (BreadCrumb) aclass.getAnnotation(BreadCrumb.class);
    }

    return crumb;
}

From source file:com.heliosphere.athena.base.resource.bundle.ResourceBundleManager.java

/**
 * Returns the resource bundle string of a given enumerated value for the given enumeration class. This
 * method is generally used by enumeration classes using the {@code BundleEnum} annotation.
 * <hr>/*from   w ww .  j  a  va2s .  co  m*/
 * @param eClass Class of the enumeration.
 * @param e Enumerated value.
 * @param locale {@link Locale} to use for resource string retrieval.
 * @return Resource bundle string.
 */
@SuppressWarnings("nls")
public static final String getResourceForMethodName(@NonNull final Class<? extends Enum<?>> eClass,
        final Enum<?> e, final Locale locale) {
    String key = null;
    ResourceBundle bundle;
    String methodName = null;
    String className;

    int index = 1;
    boolean found = false;
    while (!found) {
        className = Thread.currentThread().getStackTrace()[index].getClassName();
        if (className.equals(eClass.getName())) {
            methodName = Thread.currentThread().getStackTrace()[index].getMethodName();
            found = true;
        } else {
            index++;
        }
    }

    if (found) {
        for (Method method : eClass.getMethods()) {
            BundleEnum annotation = method.getAnnotation(BundleEnum.class);
            if (annotation != null && method.getName().equals(methodName)) {
                bundle = ResourceBundle.getBundle(annotation.file(), locale);
                key = annotation.path() + "." + e.name();
                return bundle.getString(key);
            }
        }
    }

    throw new ResourceBundleException(BundleAthenaBase.ResourceBundleInvalidKey, null, key, null, locale, e);
}

From source file:com.heliosphere.demeter.base.resource.bundle.ResourceBundleManager.java

/**
 * Returns the resource bundle string of a given enumerated value for the given enumeration class. This
 * method is generally used by enumeration classes using the {@code BundleEnum} annotation.
 * <hr>//w  w w .  ja  v a  2s  . c  o m
 * @param eClass Class of the enumeration.
 * @param e Enumerated value.
 * @param locale {@link Locale} to use for resource string retrieval.
 * @return Resource bundle string.
 */
@SuppressWarnings("nls")
public static final String getResourceForMethodName(@NonNull final Class<? extends Enum<?>> eClass,
        final Enum<?> e, final Locale locale) {
    String key = null;
    ResourceBundle bundle;
    String methodName = null;
    String className;

    int index = 1;
    boolean found = false;
    while (!found) {
        className = Thread.currentThread().getStackTrace()[index].getClassName();
        if (className.equals(eClass.getName())) {
            methodName = Thread.currentThread().getStackTrace()[index].getMethodName();
            found = true;
        } else {
            index++;
        }
    }

    if (found) {
        for (Method method : eClass.getMethods()) {
            BundleEnum annotation = method.getAnnotation(BundleEnum.class);
            if (annotation != null && method.getName().equals(methodName)) {
                bundle = ResourceBundle.getBundle(annotation.file(), locale);
                key = annotation.path() + "." + e.name();
                return bundle.getString(key);
            }
        }
    }

    throw new ResourceBundleException(BundleDemeterBase.ResourceBundleInvalidKey, null, key, null, locale, e);
}

From source file:com.wxxr.nirvana.json.JSONUtil.java

/**
 * List visible methods carrying the/*from   w w  w .ja  v a2s  .  c  om*/
 *
 * @SMDMethod annotation
 *
 * @param ignoreInterfaces
 *            if true, only the methods of the class are examined. If false,
 *            annotations on every interfaces' methods are examined.
 */
@SuppressWarnings("unchecked")
public static Method[] listSMDMethods(Class clazz, boolean ignoreInterfaces) {
    final List<Method> methods = new LinkedList<Method>();
    if (ignoreInterfaces) {
        for (Method method : clazz.getMethods()) {
            SMDMethod smdMethodAnnotation = method.getAnnotation(SMDMethod.class);
            if (smdMethodAnnotation != null) {
                methods.add(method);
            }
        }
    } else {
        // recurse the entire superclass/interface hierarchy and add in
        // order encountered
        JSONUtil.visitInterfaces(clazz, new JSONUtil.ClassVisitor() {
            public boolean visit(Class aClass) {
                for (Method method : aClass.getMethods()) {
                    SMDMethod smdMethodAnnotation = method.getAnnotation(SMDMethod.class);
                    if ((smdMethodAnnotation != null) && !methods.contains(method)) {
                        methods.add(method);
                    }
                }
                return true;
            }
        });
    }

    Method[] methodResult = new Method[methods.size()];
    return methods.toArray(methodResult);
}

From source file:ei.ne.ke.cassandra.cql3.EntitySpecificationUtils.java

/**
 * Constructs a map of {@link String}S representing column names to {@link
 * Field}S./*from   w ww.  j a va 2s  . co  m*/
 *
 * @param entityClazz
 * @return
 */
public static <T> Map<String, AttributeAccessor> createAccessors(Class<T> entityClazz) {
    Preconditions.checkNotNull(entityClazz);
    Map<String, AttributeAccessor> map = Maps.newLinkedHashMap();
    for (Field f : entityClazz.getDeclaredFields()) {
        javax.persistence.Column c = f.getAnnotation(javax.persistence.Column.class);
        if (c == null) {
            continue;
        }
        String normalizedName = normalizeCqlElementName(c.name());
        if (map.containsKey(normalizedName)) {
            throw new IllegalStateException(String.format("Duplicate column name '%s'", normalizedName));
        }
        AttributeAccessor accessor = new AttributeAccessorFieldIntrospection(f);
        map.put(normalizedName, accessor);
    }
    for (Method firstMethod : entityClazz.getDeclaredMethods()) {
        javax.persistence.Column c = firstMethod.getAnnotation(javax.persistence.Column.class);
        if (c == null) {
            continue;
        }
        String normalizedName = normalizeCqlElementName(c.name());
        /*
         * For bean getters and setters, we allow to annotate either the
         * getter or the setter and will find the corresponding counterpart.
         * If the column name is already mapped, then there's either a
         * @Column-annotated field, or the previous reversed pair of getters
         * and setters was found. Either way, ignore this annotated method.
         */
        if (map.containsKey(normalizedName)) {
            continue;
        }
        String firstMethodName = firstMethod.getName();
        AttributeAccessor accessor = null;

        if (firstMethodName.startsWith("set")) {
            String attributeName = firstMethodName.substring(NON_BOOLEAN_BEAN_PROPERTY_ACCESSOR_PREFIX_LENGTH);
            Method secondMethod = findGetterMethod(entityClazz, attributeName);
            if (secondMethod == null) {
                throw new IllegalArgumentException(String.format("No counterpart to %s", firstMethodName));
            }
            accessor = new AttributeAccessorBeanMethods(secondMethod, firstMethod);
        } else if (firstMethodName.startsWith("is")) {
            String attributeName = firstMethodName.substring(BOOLEAN_BEAN_PROPERTY_ACCESSOR_PREFIX_LENGTH);
            Method secondMethod = findSetterMethod(entityClazz, attributeName);
            if (secondMethod == null) {
                throw new IllegalArgumentException(String.format("No counterpart to %s", firstMethodName));
            }
            accessor = new AttributeAccessorBeanMethods(firstMethod, secondMethod);
        } else if (firstMethodName.startsWith("get")) {
            String attributeName = firstMethodName.substring(NON_BOOLEAN_BEAN_PROPERTY_ACCESSOR_PREFIX_LENGTH);
            /*
             * Find the corresponding setter.
             */
            Method secondMethod = findSetterMethod(entityClazz, attributeName);
            if (secondMethod == null) {
                throw new IllegalArgumentException(String.format("No counterpart to %s", firstMethodName));
            }
            accessor = new AttributeAccessorBeanMethods(firstMethod, secondMethod);
        }
        map.put(normalizedName, accessor);
    }

    return map;
}

From source file:com.inspiresoftware.lib.dto.geda.interceptor.impl.TransferableUtils.java

private static Map<Occurrence, AdviceConfig> resolveConfiguration(final Method method,
        final Class<?> targetClass, final boolean trySpecific) {

    Method specificMethod = method;
    Transferable annotation = specificMethod.getAnnotation(Transferable.class);

    if (annotation == null && trySpecific) {

        specificMethod = AopUtils.getMostSpecificMethod(method, targetClass);
        annotation = specificMethod.getAnnotation(Transferable.class);

    }/*  w  w w  .  j ava 2  s  .  c o m*/

    if (annotation == null) {
        return Collections.emptyMap();
    }

    final Map<Occurrence, AdviceConfig> cfg = new HashMap<Occurrence, AdviceConfig>();
    resolveConfiguration(cfg, specificMethod.getName(), specificMethod.getParameterTypes(),
            specificMethod.getReturnType(), annotation);
    return cfg;

}

From source file:com.struts2ext.json.JSONUtil.java

/**
 * List visible methods carrying the//from www. ja va 2 s . c o m
 * 
 * @SMDMethod annotation
 * @param ignoreInterfaces
 *            if true, only the methods of the class are examined. If false,
 *            annotations on every interfaces' methods are examined.
 */
public static Method[] listSMDMethods(Class<?> clazz, boolean ignoreInterfaces) {
    final List<Method> methods = new LinkedList<Method>();
    if (ignoreInterfaces) {
        for (Method method : clazz.getMethods()) {
            SMDMethod smdMethodAnnotation = method.getAnnotation(SMDMethod.class);
            if (smdMethodAnnotation != null) {
                methods.add(method);
            }
        }
    } else {
        // recurse the entire superclass/interface hierarchy and add in
        // order encountered
        JSONUtil.visitInterfaces(clazz, new JSONUtil.ClassVisitor() {
            public boolean visit(Class<?> aClass) {
                for (Method method : aClass.getMethods()) {
                    SMDMethod smdMethodAnnotation = method.getAnnotation(SMDMethod.class);
                    if ((smdMethodAnnotation != null) && !methods.contains(method)) {
                        methods.add(method);
                    }
                }
                return true;
            }
        });
    }

    Method[] methodResult = new Method[methods.size()];
    return methods.toArray(methodResult);
}

From source file:com.diversityarrays.kdxplore.stats.StatsUtil.java

static public void initCheck() {
    if (checkDone) {
        return;/*from   w w w  . j  a va 2s. c om*/
    }
    Set<String> okIfExhibitMissing = new HashSet<>();
    Collections.addAll(okIfExhibitMissing, "getFormat", "getValueClass", "getStatsName", "getLowOutliers",
            "getHighOutliers");
    List<String> errors = new ArrayList<String>();

    Set<String> unMatchedStatNameValues = new HashSet<String>();
    for (SimpleStatistics.StatName sname : StatName.values()) {
        unMatchedStatNameValues.add(sname.displayName);
    }

    for (Method m : SimpleStatistics.class.getDeclaredMethods()) {

        if (!Modifier.isPublic(m.getModifiers())) {
            continue; // shouldn't happen!
        }

        ExhibitColumn ec = m.getAnnotation(ExhibitColumn.class);

        if (ec == null) {
            if (okIfExhibitMissing.contains(m.getName())) {
                //               if ("getQuartiles".equals(m.getName())) {
                //                  System.err.println("%TODO: @ExhibitColumn for 'SimpleStatistics.getQuartiles()'");
                //               }
            } else {
                errors.add("Missing @ExhibitColumn: " + m.getName());
            }
        } else {
            String ecValue = ec.value();
            boolean found = false;
            for (SimpleStatistics.StatName sname : StatName.values()) {
                if (sname.displayName.equals(ecValue)) {
                    unMatchedStatNameValues.remove(sname.displayName);
                    METHOD_BY_STATNAME.put(sname, m);
                    found = true;
                    break;
                }
            }
            if (!found) {
                errors.add("Doesn't match any StatName: '" + ecValue + "', method=" + m.getName());
            }
        }
    }

    if (!unMatchedStatNameValues.isEmpty()) {
        errors.add(StringUtil.join("Unmatched StatName values: ", " ", unMatchedStatNameValues));
    }

    if (!errors.isEmpty()) {
        throw new RuntimeException(StringUtil.join("Problems in SimpleStatistics config: ", "\n", errors));
    }

    checkDone = true;
}