Example usage for java.lang Class isAnnotationPresent

List of usage examples for java.lang Class isAnnotationPresent

Introduction

In this page you can find the example usage for java.lang Class isAnnotationPresent.

Prototype

@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 

Source Link

Usage

From source file:net.redwarp.library.database.TableInfo.java

@SuppressWarnings("unchecked")
private TableInfo(Class<T> c) {
    mClass = c;/*from   w w  w . j a va 2s.  c  o m*/

    if (c.isAnnotationPresent(Version.class)) {
        final Version version = c.getAnnotation(Version.class);
        mVersion = version.value();
    } else {
        mVersion = 1;
    }

    Field[] fields = mClass.getDeclaredFields();
    //        mFieldMap = new HashMap<>(fields.length);
    mColumns = new HashMap<>(fields.length);
    mObjectFields = new ArrayList<>();

    List<String> columnNames = new ArrayList<>(fields.length);
    List<Field> finalFields = new ArrayList<>(fields.length);
    List<Field> chainDeleteFields = new ArrayList<>(fields.length);

    for (Field field : fields) {
        if (!Modifier.isStatic(field.getModifiers())) {
            SQLiteUtils.SQLiteType type = SQLiteUtils.getSqlLiteTypeForField(field);
            if (type != null) {
                field.setAccessible(true);
                if (field.isAnnotationPresent(PrimaryKey.class)) {
                    if (primaryKey != null) {
                        throw new RuntimeException("There can be only one primary key");
                    }
                    final PrimaryKey primaryKeyAnnotation = field.getAnnotation(PrimaryKey.class);
                    String name = primaryKeyAnnotation.name();
                    if ("".equals(name)) {
                        name = getColumnName(field);
                    }
                    columnNames.add(name);
                    primaryKey = new Column(name, field, SQLiteUtils.SQLiteType.INTEGER);
                } else {
                    final String name = getColumnName(field);
                    columnNames.add(name);
                    mColumns.put(field, new Column(name, field, type));
                }

                finalFields.add(field);
            } else {
                // Not a basic field;
                if (field.isAnnotationPresent(Chain.class)) {
                    // We must serialize/unserialize this as well
                    final Chain chainAnnotation = field.getAnnotation(Chain.class);
                    if (chainAnnotation.delete()) {
                        chainDeleteFields.add(field);
                    }
                    final String name = getColumnName(field);
                    columnNames.add(name);
                    Column column = new Column(name, field, SQLiteUtils.SQLiteType.INTEGER);
                    mColumns.put(field, column);
                    mObjectFields.add(field);
                    finalFields.add(field);
                }
            }
        }
    }
    mColumnNames = columnNames.toArray(new String[columnNames.size()]);
    mFields = finalFields.toArray(new Field[finalFields.size()]);
    mChainDeleteFields = chainDeleteFields.toArray(new Field[chainDeleteFields.size()]);
}

From source file:com.impetus.kundera.metadata.ValidatorImpl.java

/**
 * Checks the validity of a class for Cassandra entity.
 * //w w w . jav a 2  s .com
 * @param clazz
 *            validates this class
 * 
 * @return returns 'true' if valid
 */
@Override
// TODO: reduce Cyclomatic complexity
public final void validate(final Class<?> clazz) {

    if (classes.contains(clazz)) {
        return;
    }

    LOG.debug("Validating " + clazz.getName());

    // Is Entity?
    if (!clazz.isAnnotationPresent(Entity.class)) {
        throw new PersistenceException(clazz.getName() + " is not annotated with @Entity");
    }

    // must have a default no-argument constructor
    try {
        clazz.getConstructor();
    } catch (NoSuchMethodException nsme) {
        throw new PersistenceException(clazz.getName() + " must have a default no-argument constructor.");
    }

    // what type is it? ColumnFamily or SuperColumnFamily, Document or simply relational entity?
    if (clazz.isAnnotationPresent(SuperColumnFamily.class) || clazz.isAnnotationPresent(ColumnFamily.class)) {
        LOG.debug("Entity is for NoSQL database: " + clazz.getName());
    } else if (!clazz.isAnnotationPresent(Document.class)) {
        LOG.debug("Entity is for document based database: " + clazz.getName());
    } else {
        LOG.debug("Entity is for relational database table: " + clazz.getName());
    }

    // check for @Key and ensure that there is just 1 @Key field of String
    // type.
    List<Field> keys = new ArrayList<Field>();
    for (Field field : clazz.getDeclaredFields()) {
        if (field.isAnnotationPresent(Id.class)) {
            keys.add(field);
        }
    }

    if (keys.size() == 0) {
        throw new PersistenceException(clazz.getName() + " must have an @Id field.");
    } else if (keys.size() > 1) {
        throw new PersistenceException(clazz.getName() + " can only have 1 @Id field.");
    }

    if (!keys.get(0).getType().equals(String.class)) {
        throw new PersistenceException(clazz.getName() + " @Id must be of String type.");
    }

    // save in cache
    classes.add(clazz);
}

From source file:org.jfunktor.core.meta.api.MetaScanner.java

private void scanAndRegister(Class interfaceType) {
    for (Class impl : JMattrServiceLoader.load(interfaceType)) {
        impl.getProtectionDomain().getCodeSource().getLocation();
        if (impl.isAnnotationPresent(Provider.class)) {
            //Provider annotation = (Provider) impl.getAnnotation(Provider.class);

            try {
                validateType(interfaceType, impl);

                //do the required binding here
                proc.process(impl, registry);

                if (log.isTraceEnabled()) {
                    log.trace(String.format("Registered Provider %s", impl.getName()));
                }/*from   ww w.  ja  v  a2  s  .co  m*/
            } catch (NotAProviderException e) {
                log.error(String.format("Invalid Provider Definition ", impl.getName()), e);
            }
        } else {
            if (log.isInfoEnabled()) {
                log.info(String.format(
                        "Class %s does not seem to be annotated with Provider annotations. Pls check the implementation!",
                        impl));
            }
        }

    }

}

From source file:com.geodevv.testing.irmina.IrminaContextLoader.java

/**
 * Determine if the supplied {@link Class} meets the criteria for being
 * considered a <em>default configuration class</em> candidate.
 * <p>Specifically, such candidates:
 * <ul>/*w  w w. ja v a 2 s .  c  o  m*/
 * <li>must not be <code>null</code></li>
 * <li>must not be <code>private</code></li>
 * <li>must not be <code>final</code></li>
 * <li>must be <code>static</code></li>
 * <li>must be annotated with {@code @Configuration}</li>
 * </ul>
 *
 * @param clazz the class to check
 * @return <code>true</code> if the supplied class meets the candidate criteria
 */
private boolean isDefaultConfigurationClassCandidate(Class<?> clazz) {
    return clazz != null && isStaticNonPrivateAndNonFinal(clazz)
            && clazz.isAnnotationPresent(Configuration.class);
}

From source file:com.google.code.rees.scope.spring.SpringConversationArbitrator.java

@Override
protected String[] getConversationsWithInheritance(Class<?> clazz, String actionSuffix) {
    List<String> conversations = new ArrayList<String>();
    for (Class<?> conversationControllerClass : getConversationControllers(clazz)) {
        if (clazz.isAnnotationPresent(ConversationController.class)) {
            ConversationController controller = conversationControllerClass
                    .getAnnotation(ConversationController.class);
            String[] newConversations = controller.conversations();
            if (controller.value().equals(ConversationController.DEFAULT_VALUE)) {
                if (newConversations.length == 0) {
                    newConversations = new String[] {
                            NamingUtil.getConventionName(conversationControllerClass, actionSuffix) };
                }/*from   www  .  ja  v a 2  s  .  co  m*/
            } else {
                conversations.add(controller.value());
            }
            conversations.addAll(Arrays.asList(newConversations));
        } else {
            com.google.code.rees.scope.spring.ConversationController controller = conversationControllerClass
                    .getAnnotation(com.google.code.rees.scope.spring.ConversationController.class);
            String[] newConversations = controller.conversations();
            if (controller.value()
                    .equals(com.google.code.rees.scope.spring.ConversationController.DEFAULT_VALUE)) {
                if (newConversations.length == 0) {
                    newConversations = new String[] {
                            NamingUtil.getConventionName(conversationControllerClass, actionSuffix) };
                }
            } else {
                conversations.add(controller.value());
            }
            conversations.addAll(Arrays.asList(newConversations));
        }
    }
    return conversations.toArray(new String[] {});
}

From source file:org.fornax.cartridges.sculptor.framework.test.AbstractDbUnitAnnotationAwareTransactionalTests.java

/**
 * Get the table name from a domainobject class
 *
 * @param domainObjectClass/*from   w  ww .  j  a va2 s .co m*/
 * @return the table name
 *
 */
protected String getTableName(Class<?> domainObjectClass) {
    String table = null;
    if (domainObjectClass.isAnnotationPresent(Table.class)) {
        table = domainObjectClass.getAnnotation(Table.class).name();
    } else {
        table = domainObjectClass.getSimpleName();
    }
    return table;
}

From source file:info.dolezel.fatrat.plugins.helpers.JarClassLoader.java

private Set<Class> findClasses(File directory, String packageName, Class annotation)
        throws ClassNotFoundException, IOException {
    Set<Class> classes = new HashSet<Class>();
    if (!directory.exists()) {

        String fullPath = directory.toString();
        String jarPath = fullPath.replaceFirst("[.]jar[!].*", ".jar").replaceFirst("file:", "");
        JarFile jarFile = new JarFile(jarPath);
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String entryName = entry.getName();
            if (entryName.endsWith(".class") && !entryName.contains("$")) {
                String className = entryName.replace('/', '.').replace('\\', '.').replace(".class", "");
                Class cls = this.loadClass(className);

                if (annotation == null || cls.isAnnotationPresent(annotation))
                    classes.add(cls);// ww  w.  j  av  a 2s .  c o m
            }
        }
    } else {
        File[] files = directory.listFiles();
        for (File file : files) {
            if (file.isDirectory()) {
                assert !file.getName().contains(".");
                classes.addAll(findClasses(file, packageName + "." + file.getName(), annotation));
            } else if (file.getName().endsWith(".class")) {
                Class cls = this.loadClass(
                        packageName + '.' + file.getName().substring(0, file.getName().length() - 6));

                if (annotation == null || cls.isAnnotationPresent(annotation))
                    classes.add(cls);
            }
        }
    }
    return classes;
}

From source file:net.famzangl.minecraft.minebot.ai.command.CommandRegistry.java

private void checkCommandClass(Class<?> commandClass) {
    if (!commandClass.isAnnotationPresent(AICommand.class)) {
        throw new IllegalArgumentException(
                "AICommand is not set for the class " + commandClass.getName() + ".");
    }/*from   www  .ja v  a  2s  . c o m*/
}

From source file:com.nortal.jroad.mapping.XTeeEndpointMapping.java

/**
 * Attempts to get the full XRoad method name for the given {@link AbstractXTeeBaseEndpoint}, by processing the
 * {@link XRoadService} annotation -- if this is not present the method name will be a concatenation of X-Tee database
 * name, unqualified class name of given {@link AbstractXTeeBaseEndpoint} (as service name) and "v1" (as version
 * number).//  ww  w  .j  a  v a2  s  . c  o  m
 * 
 * @param clazz XRoad service endpoint implementation class
 * @param databaseName name of the XRoad database
 * @return the XRoadService method name that was constructed according to aforementioned rules
 */
private String getXRoadMethodName(Class<? extends AbstractXTeeBaseEndpoint> clazz, String databaseName) {
    String version = "v1";
    String serviceName = null;
    if (clazz.isAnnotationPresent(XTeeService.class)) {
        XTeeService serviceAnnotation = clazz.getAnnotation(XTeeService.class);
        version = serviceAnnotation.version();
        if (!serviceAnnotation.name().equals("") || !serviceAnnotation.value().equals("")) {
            serviceName = serviceAnnotation.name().equals("") ? serviceAnnotation.value()
                    : serviceAnnotation.name();
        }

    }
    if (serviceName == null) {
        serviceName = getServiceName(clazz.getSimpleName());
    }

    StringBuilder sb = new StringBuilder(databaseName).append(".").append(serviceName).append(".")
            .append(version);
    return sb.toString();
}

From source file:de.matzefratze123.heavyspleef.core.FlagManager.java

public void addFlag(AbstractFlag<?> flag) {
    Class<?> clazz = flag.getClass();

    Validate.isTrue(clazz.isAnnotationPresent(Flag.class),
            "Flag class " + clazz.getCanonicalName() + " must annotate " + Flag.class.getCanonicalName());
    Flag flagAnnotation = clazz.getAnnotation(Flag.class);

    //Generate the full path
    StringBuilder pathBuilder = new StringBuilder();

    Flag lastParentFlagData = flagAnnotation;
    while (lastParentFlagData != null) {
        pathBuilder.insert(0, lastParentFlagData.name());

        Class<? extends AbstractFlag<?>> parentClass = lastParentFlagData.parent();
        lastParentFlagData = parentClass.getAnnotation(Flag.class);

        if (lastParentFlagData != null) {
            pathBuilder.insert(0, ":");
        }//from ww w .  j a  v a2  s  . c om
    }

    String path = pathBuilder.toString();

    if (flags.containsKey(path)) {
        return;
    }

    flags.put(path, flag);

    if (clazz.isAnnotationPresent(BukkitListener.class)) {
        Bukkit.getPluginManager().registerEvents(flag, plugin);
    }

    if (flagAnnotation.hasGameProperties()) {
        Map<GameProperty, Object> flagGamePropertiesMap = new EnumMap<GameProperty, Object>(GameProperty.class);
        flag.defineGameProperties(flagGamePropertiesMap);

        if (!flagGamePropertiesMap.isEmpty()) {
            GamePropertyBundle properties = new GamePropertyBundle(flag, flagGamePropertiesMap);
            propertyBundles.add(properties);
        }
    }
}