Example usage for java.lang.reflect Method getDeclaredAnnotation

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

Introduction

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

Prototype

@Override
public <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) 

Source Link

Usage

From source file:alfio.datamapper.QueryType.java

private static JdbcAction actionFromContext(Method method, String template) {
    if (method.getDeclaredAnnotation(AutoGeneratedKey.class) == null) {
        return actionFromTemplate(template);
    }/*  w  ww.ja v  a 2  s  . c  om*/
    return JdbcAction.INSERT_W_AUTO_GENERATED_KEY;
}

From source file:com.blurengine.blur.framework.ticking.TickMethodsCache.java

/**
 * Loads and caches a {@link Class}//from   w  w  w.  j a  va2s  .  c o m
 *
 * @param clazz class to load and cache for future usage
 *
 * @return list of {@link TickMethod} represented the cached methods
 *
 * @throws IllegalArgumentException thrown if {@code clazz} is {@code Tickable.class}
 */
public static Collection<TickMethod> loadClass(@Nonnull Class<?> clazz) throws IllegalArgumentException {
    Preconditions.checkNotNull(clazz, "clazz cannot be null.");
    if (!LOADED_CLASSES.contains(clazz)) {

        Collection<TickMethod> tickMethods = CLASS_TICK_METHODS.get(clazz); // empty cache list, automatically updates

        { // Load superclasses first
            Class<?> superclass = clazz.getSuperclass();
            // No need for while loop as loadClass will end up reaching here if necessary.
            if (!superclass.equals(Object.class)) {
                tickMethods.addAll(loadClass(superclass));
            }
        }

        for (Method method : clazz.getDeclaredMethods()) {
            TickMethod tickMethod = getTickMethod(clazz, method);
            if (tickMethod != null) {
                tickMethods.add(tickMethod);
            } else {
                Tick tick = method.getDeclaredAnnotation(Tick.class);
                if (tick != null) {
                    try {
                        Preconditions.checkArgument(method.getParameterCount() <= 1,
                                "too many parameters in tick method " + method.getName() + ".");
                        if (method.getParameterCount() > 0) {
                            Preconditions.checkArgument(
                                    method.getParameterTypes()[0].isAssignableFrom(TickerTask.class),
                                    "Invalid parameter in tick method " + method.getName() + ".");
                        }
                        boolean passParams = method.getParameterCount() > 0;
                        // Tickables may be marked private for organisation.
                        method.setAccessible(true);

                        tickMethods.add(new TickMethod(method, passParams, tick));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        LOADED_CLASSES.add(clazz);
    }
    return Collections.unmodifiableCollection(CLASS_TICK_METHODS.get(clazz));
}

From source file:ch.digitalfondue.npjt.QueryType.java

@SuppressWarnings("unchecked")
private static <T> AffectedRowCountAndKey<T> executeUpdateAndKeepKeys(String template, Method method,
        NamedParameterJdbcTemplate jdbc, SqlParameterSource parameters) {

    Class<T> keyClass = (Class<T>) ((ParameterizedType) method.getGenericReturnType())
            .getActualTypeArguments()[0];

    KeyHolder keyHolder = new GeneratedKeyHolder();

    int result = jdbc.update(template, parameters, keyHolder);
    Map<String, Object> keys = keyHolder.getKeys();
    Object key;//  w  w w.  j  a  v  a 2  s  .  co  m
    if (keys.size() > 1) {
        AutoGeneratedKey spec = Objects.requireNonNull(method.getDeclaredAnnotation(AutoGeneratedKey.class),
                "more than one key for query " + template + ": annotation @AutoGeneratedKey required");
        key = Objects.requireNonNull(keys.get(spec.value()), "the key with name " + spec.value()
                + " has returned null for query " + template + ": required a non null key");
    } else if (Number.class.isAssignableFrom(keyClass)) {
        Class<? extends Number> c = (Class<? extends Number>) keyClass;
        return new AffectedRowCountAndKey<>(result,
                (T) NumberUtils.convertNumberToTargetClass(keyHolder.getKey(), c));
    } else {
        key = keys.values().iterator().next();
    }
    return new AffectedRowCountAndKey<>(result, keyClass.cast(key));
}

From source file:io.stallion.reflection.PropertyUtils.java

public static <T extends Annotation> T getAnnotationForProperty(Class cls, String name, Class<T> anno) {
    String postFix = name.toUpperCase();
    if (name.length() > 1) {
        postFix = name.substring(0, 1).toUpperCase() + name.substring(1);
    }/* w  w w. j  av a 2  s .  c  o m*/
    Method method = null;
    try {
        method = cls.getMethod("get" + postFix);
    } catch (NoSuchMethodException e) {

    }
    if (method == null) {
        try {
            method = cls.getMethod("is" + postFix);
        } catch (NoSuchMethodException e) {

        }
    }
    if (method == null) {
        return null;
    }
    if (method.getModifiers() != Modifier.PUBLIC) {
        return null;
    }
    if (method.isAnnotationPresent(anno)) {
        return method.getDeclaredAnnotation(anno);
    }
    return null;
}

From source file:com.mastercard.test.spring.security.SpringSecurityJUnit4ClassRunnerTests.java

@Test
public void describeChildCreatesDescriptionForWithTestUserTest() throws Exception {
    SpringSecurityJUnit4ClassRunner runner = new SpringSecurityJUnit4ClassRunner(MockWithMockUserTest.class);

    Method method2Test = MockWithMockUserTest.class.getMethod("testWithWithMockUser");
    FrameworkMethod method = new AnnotationFrameworkMethod(new FrameworkMethod(method2Test),
            method2Test.getDeclaredAnnotation(WithMockUser.class));
    Description actualDescription = runner.describeChild(method);

    BlockJUnit4ClassRunner expectedRunner = new BlockJUnit4ClassRunner(MockWithMockUserTest.class);
    Method method1 = BlockJUnit4ClassRunner.class.getDeclaredMethod("describeChild", FrameworkMethod.class);
    method1.setAccessible(true);/*from   www  .  ja  v a2s .  c om*/
    Description expectedDescription = (Description) method1.invoke(expectedRunner, method);

    assertDescriptionDetailsEqual(expectedDescription, actualDescription);
    assertEquals(expectedDescription.getChildren().size(), actualDescription.getChildren().size());
}

From source file:com.hablutzel.cmdline.CommandLineApplication.java

/**
 * This method scans the subclass for annotations
 * that denote the command line options and arguments,
 * and configures the systems so that the members that
 * have been annotated in that way are set up for calling
 * at command line processing time//from   w w w  .j  a v  a2 s .  c  om
 *
 */
private final void configure() throws CommandLineException {

    // Find all the fields in our subclass
    for (Method method : this.getClass().getDeclaredMethods()) {

        // If this method is marked with a  command line option, then configure
        // a corresponding commons-cli command line option here
        if (method.isAnnotationPresent(CommandLineOption.class)) {
            CommandLineOption commandLineOption = method.getDeclaredAnnotation(CommandLineOption.class);
            if (commandLineOption != null) {

                // Get the basic information about the option - the name and description
                String shortName = commandLineOption.shortForm().equals("") ? null
                        : commandLineOption.shortForm();
                String longName = commandLineOption.longForm().equals("") ? null : commandLineOption.longForm();
                String description = commandLineOption.usage();

                // If both the short and long name are null, then use the field name as the long name
                if (shortName == null && longName == null) {
                    longName = method.getName();
                }

                // The signature of the method determines what kind of command line
                // option is allowed. Basically, if the method does not take an argument,
                // then the option does not take arguments either. In this case, the
                // method is just called when the option is present.
                //
                // If the method does take argument, there are restrictions on the arguments
                // that are allowed. If there is a single argument, then the method will be
                // called for each argument supplied to the option. Generally in this case you
                // want the maximum number of option arguments to be 1, and you are just getting
                // the value of the argument. On the other hand, if the single argument is either
                // and array or a List<>, then the arguments will be passed in as an argument
                // or list respectively.
                //
                // Methods with more than 1 argument are not allowed. Methods with return types
                // other than boolean are not allowed. Methods that throw an exception other than
                // org.apache.commons.cli.CommandLineException are not allowed,
                //
                // If the method returns a boolean, and calling that method returns FALSE, then the
                // command line main function will not be called.
                //
                // The class of the argument has to be convertable using common-beanutils
                // conversion facilities
                CommandLineMethodHelper helper = getHelperForCommandOption(method, commandLineOption);

                // Now create and configure an option based on what the method is capable of handling
                // and the command line option parameters
                boolean allowsArguments = helper.methodType != MethodType.Boolean;
                Option option = new Option(shortName, longName, allowsArguments, description);

                // Configure it
                option.setRequired(commandLineOption.required());
                if (option.hasArg()) {
                    option.setType(helper.elementType);
                    option.setArgs(commandLineOption.maximumArgumentCount());
                    option.setValueSeparator(commandLineOption.argumentSeparator());
                    option.setOptionalArg(commandLineOption.optionalArgument());
                }

                // Remember it, both in the commons-cli options set and
                // in our list of elements for later post-processing
                options.addOption(option);
                optionHelperMap.put(option, helper);
            }

            // This was not a command line option method - is it the main command line method?
        } else if (method.isAnnotationPresent(CommandLineMain.class)) {

            // Make sure we only have one
            if (mainHelper != null) {
                throw new CommandLineException("Cannot have two main methods specified");
            } else {
                mainHelper = getHelperForCommandLineMain(method);
            }
        }
    }
}

From source file:io.stallion.dataAccess.db.DB.java

private Schema annotatedModelToSchema(Class cls) {
    Table table = (Table) cls.getDeclaredAnnotation(Table.class);
    if (table == null) {
        throw new UsageException("Trying to register model with database, but it has no @Table annotation: "
                + cls.getCanonicalName());
    }/*from ww w  . j  a  v  a2s .  c  om*/
    if (empty(table.name())) {
        throw new UsageException(
                "Trying to register model with database, but it has no name for the @Table annotation: "
                        + cls.getCanonicalName());
    }
    Schema schema = new Schema(table.name(), cls);
    Object inst = null;
    try {
        inst = cls.newInstance();
    } catch (InstantiationException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
    ExtraKeyDefinitions keyDefinitions = (ExtraKeyDefinitions) cls
            .getDeclaredAnnotation(ExtraKeyDefinitions.class);
    if (keyDefinitions != null) {
        for (String def : keyDefinitions.value()) {
            schema.getExtraKeyDefinitions().add(def);
        }
    }

    for (Method method : cls.getMethods()) {
        if (!method.getName().startsWith("get") && !method.getName().startsWith("is")) {
            continue;
        }
        // If a property starts with "is", the type must be boolean, or else we continue;
        if (method.getName().startsWith("is") && (!method.getReturnType().isAssignableFrom(boolean.class))
                && !method.getReturnType().isAssignableFrom(Boolean.class)) {
            continue;
        }

        String propertyName = "";
        if (method.getName().startsWith("is")) {
            propertyName = method.getName().substring(2);
        } else {
            propertyName = method.getName().substring(3);
        }
        if (empty(propertyName)) {
            continue;
        }
        propertyName = propertyName.substring(0, 1).toLowerCase() + propertyName.substring(1);
        Column columnAnno = method.getAnnotation(Column.class);
        if (columnAnno == null) {
            continue;
        }

        String columnName = propertyName.toLowerCase();
        if (!StringUtils.isBlank(columnAnno.name())) {
            columnName = columnAnno.name();
        }
        Col col = new Col();
        col.setPropertyName(propertyName);
        col.setName(columnName);
        col.setUpdateable(columnAnno.updatable());
        col.setjType(method.getReturnType());
        col.setInsertable(columnAnno.insertable());

        col.setDbType(columnAnno.columnDefinition());
        col.setNullable(columnAnno.nullable());
        col.setLength(columnAnno.length());
        // If the column cannot be null, we need a default value
        if (!columnAnno.nullable()) {
            col.setDefaultValue(PropertyUtils.getProperty(inst, propertyName));
        }
        VirtualColumn virtualAnno = method.getAnnotation(VirtualColumn.class);
        if (virtualAnno != null) {
            col.setVirtual(true);
            col.setInsertable(false);
            col.setUpdateable(false);
        }

        Converter converterAnno = method.getDeclaredAnnotation(Converter.class);
        Log.finest("Adding schema Column {0}", columnName);
        if (converterAnno != null) {
            Log.finest("ConverterAnno {0} {1} {2} ", columnName, converterAnno, converterAnno.name());
            if (empty(converterAnno.name())) {
                try {
                    AttributeConverter converter = (AttributeConverter) converterAnno.cls().newInstance();
                    if (converter instanceof TypedCollectionAttributeConverter) {
                        if (converterAnno.elementClass() == null
                                || converterAnno.elementClass().equals(Object.class)) {
                            throw new UsageException(
                                    "You used a TypedCollectionAttributeConverter but did not set the value for elementClass which controls the type of object that you want to convert to. ");
                        }
                        ((TypedCollectionAttributeConverter) converter)
                                .setElementClass(converterAnno.elementClass());
                    }
                    col.setAttributeConverter(converter);
                    //col.setConverterClassName(converterAnno.cls().getCanonicalName());
                } catch (InstantiationException e) {
                    throw new RuntimeException(e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                }

            } else {
                col.setConverterClassName(converterAnno.name());
            }
        }
        if (method.getAnnotation(AlternativeKey.class) != null) {
            col.setAlternativeKey(true);
            schema.getKeyNames().add(col.getName());
        }
        if (method.getAnnotation(UniqueKey.class) != null) {
            col.setUniqueKey(true);
            UniqueKey uk = (UniqueKey) method.getAnnotation(UniqueKey.class);
            col.setCaseInsensitive(uk.caseInsensitive());
            schema.getKeyNames().add(col.getName());
        }
        if (columnAnno.unique()) {
            col.setUniqueKey(true);
            schema.getKeyNames().add(col.getName());
        }

        schema.getColumns().add(col);

    }
    return schema;
}

From source file:org.apache.geode.management.internal.cli.help.Helper.java

public void addCommand(CliCommand command, Method commandMethod) {
    // put all the command synonyms in the command map
    Arrays.stream(command.value()).forEach(cmd -> {
        commands.put(cmd, commandMethod);
    });//from  w  w  w  .j  a v  a  2s.  co  m

    // resolve the hint message for each method
    CliMetaData cliMetaData = commandMethod.getDeclaredAnnotation(CliMetaData.class);
    if (cliMetaData == null)
        return;
    String[] related = cliMetaData.relatedTopic();

    // for hint message, we only need to show the first synonym
    String commandString = command.value()[0];
    if (related == null) {
        return;
    }
    Arrays.stream(related).forEach(topic -> {
        Topic foundTopic = topics.get(topic);
        if (foundTopic == null) {
            throw new IllegalArgumentException("No such topic found in the initial map: " + topic);
        }
        foundTopic.addRelatedCommand(commandString, command.help());
    });
}

From source file:org.apache.geode.management.internal.cli.help.Helper.java

/**
 * get help string for a specific command, or a brief description of all the commands if buffer is
 * null or empty//from ww w . ja  v  a  2 s  .  c  o m
 */
public String getHelp(String buffer, int terminalWidth) {
    if (StringUtils.isBlank(buffer)) {
        return getHelp().toString(terminalWidth);
    }

    Method method = commands.get(buffer);
    if (method == null) {
        return "no help exists for this command.";
    }

    HelpBlock helpBlock = getHelp(method.getDeclaredAnnotation(CliCommand.class),
            method.getParameterAnnotations(), method.getParameterTypes());
    return helpBlock.toString(terminalWidth);
}