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:de.hackerspacebremen.format.JSONFormatter.java

@Override
public T reformat(final String object, final Class<T> entityClass) throws FormatException {
    T result = null;/*from w ww  . java 2 s  . c o m*/
    final Map<String, Field> fieldMap = new HashMap<String, Field>();
    if (entityClass.isAnnotationPresent(Entity.class)) {
        final Field[] fields = entityClass.getDeclaredFields();
        for (final Field field : fields) {
            if (field.isAnnotationPresent(FormatPart.class)) {
                fieldMap.put(field.getAnnotation(FormatPart.class).key(), field);
            }
        }
        try {
            final JSONObject json = new JSONObject(object);
            result = entityClass.newInstance();
            for (final String key : fieldMap.keySet()) {
                if (json.has(key)) {
                    final Field field = fieldMap.get(key);
                    final Method method = entityClass.getMethod(this.getSetter(field.getName()),
                            new Class<?>[] { field.getType() });

                    final String type = field.getType().toString();
                    if (type.equals("class com.google.appengine.api.datastore.Key")) {
                        method.invoke(result, KeyFactory.stringToKey(json.getString(key)));
                    } else if (type.equals("class com.google.appengine.api.datastore.Text")) {
                        method.invoke(result, new Text(json.getString(key)));
                    } else if (type.equals("boolean")) {
                        method.invoke(result, json.getBoolean(key));
                    } else if (type.equals("long")) {
                        method.invoke(result, json.getLong(key));
                    } else if (type.equals("int")) {
                        method.invoke(result, json.getInt(key));
                    } else {
                        method.invoke(result, json.get(key));
                    }
                }
            }
        } catch (JSONException e) {
            logger.warning("JSONException occured: " + e.getMessage());
            throw new FormatException();
        } catch (NoSuchMethodException e) {
            logger.warning("NoSuchMethodException occured: " + e.getMessage());
            throw new FormatException();
        } catch (SecurityException e) {
            logger.warning("SecurityException occured: " + e.getMessage());
            throw new FormatException();
        } catch (IllegalAccessException e) {
            logger.warning("IllegalAccessException occured: " + e.getMessage());
            throw new FormatException();
        } catch (IllegalArgumentException e) {
            logger.warning("IllegalArgumentException occured: " + e.getMessage());
            throw new FormatException();
        } catch (InvocationTargetException e) {
            logger.warning("InvocationTargetException occured: " + e.getMessage());
            throw new FormatException();
        } catch (InstantiationException e) {
            logger.warning("InstantiationException occured: " + e.getMessage());
            throw new FormatException();
        }
    }
    return result;
}

From source file:test.automation.execution.TestExecutor.java

private Set<Class> getTestableClasses() throws ClassNotFoundException {
    final Set<File> files = getFiles(new ClassFilter(), getTestClassPath());
    LOGGER.trace("testable classes:" + files);
    final Set<Class> testableClasses = new HashSet<Class>();

    for (final File file : files) {
        final String className = getClassName(file);
        LOGGER.trace("className:" + className);
        if (className.startsWith("${REMOVED}")) {
            final Class testClass = Class.forName(className);
            if (testClass.isAnnotationPresent(TestURL.class)) {
                testableClasses.add(testClass);
            }//w  ww  .ja  v a 2s  .  co  m
        }
    }

    LOGGER.trace("testable classes:" + testableClasses);
    return (testableClasses);
}

From source file:org.seedstack.io.internal.IOPlugin.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override//from www . j av  a2 s .c  o m
public InitState init(InitContext initContext) {
    if (round.isFirst()) {
        Map<Specification, Collection<Class<?>>> scannedClassesByAnnotationClass = initContext
                .scannedTypesBySpecification();

        // Gets all implementation of TemplateLoader
        Collection<Class<?>> templateLoaderClasses = scannedClassesByAnnotationClass.get(templateLoaderSpec);

        if (templateLoaderClasses != null) {
            for (Class<?> templateLoaderClass : templateLoaderClasses) {
                if (TemplateLoader.class.isAssignableFrom(templateLoaderClass)) {

                    if (StaticTemplateLoader.class.isAssignableFrom(templateLoaderClass)) {
                        Class<StaticTemplateLoader<?>> staticTemplateLoaderClass = (Class<StaticTemplateLoader<?>>) templateLoaderClass;
                        StaticTemplateLoader<?> staticTemplateLoader;
                        try {
                            staticTemplateLoader = staticTemplateLoaderClass.newInstance();
                        } catch (Exception e) {
                            throw new RuntimeException("Unable to instantiate StaticTemplateLoader "
                                    + staticTemplateLoaderClass.getCanonicalName(), e);
                        }
                        templateLoaderRegexs.add(staticTemplateLoader);

                    } else {
                        Class<TemplateLoader<?>> dynamicTemplateLoaderClass = (Class<TemplateLoader<?>>) templateLoaderClass;
                        TemplateLoader<?> dynamicTemplateLoader;
                        try {
                            dynamicTemplateLoader = dynamicTemplateLoaderClass.newInstance();
                        } catch (Exception e) {
                            throw new RuntimeException("Unable to instantiate TemplateLoader "
                                    + dynamicTemplateLoaderClass.getCanonicalName(), e);
                        }
                        templateLoaders.add(dynamicTemplateLoader);
                    }
                }
            }
        }

        // Gets all implementation of Renderer
        Collection<Class<?>> rendererClasses = scannedClassesByAnnotationClass.get(rendererSpec);
        if (rendererClasses != null) {
            for (Class<?> rendererClass : rendererClasses) {
                if (Renderer.class.isAssignableFrom(rendererClass)
                        && rendererClass.isAnnotationPresent(Named.class)) {
                    renderers.put(rendererClass.getAnnotation(Named.class).value(),
                            (Class<Renderer>) rendererClass);
                }
            }
        }

        // Gets all implementation of Parser
        Collection<Class<?>> parserClasses = scannedClassesByAnnotationClass.get(parserSpec);
        if (parserClasses != null) {
            for (Class<?> parserClass : parserClasses) {
                if (Parser.class.isAssignableFrom(parserClass)
                        && parserClass.isAnnotationPresent(Named.class)) {
                    parsers.put(parserClass.getAnnotation(Named.class).value(), (Class<Parser>) parserClass);
                }
            }
        }

        return InitState.NON_INITIALIZED;
    } else {
        Map<String, Collection<String>> mapResourcesByRegex = initContext.mapResourcesByRegex();

        for (StaticTemplateLoader<?> staticTemplateLoader : templateLoaderRegexs) {
            Map<String, URL> templateURLs = new HashMap<String, URL>();

            Collection<String> templateUrls = mapResourcesByRegex.get(staticTemplateLoader.templatePathRegex());
            for (String templateUrl : templateUrls) {
                if (templateUrl.startsWith(META_INF_TEMPLATES)) {
                    String templateName = StringUtils.substringAfter(templateUrl, META_INF_TEMPLATES);
                    Matcher matcher = Pattern.compile(staticTemplateLoader.templatePathRegex())
                            .matcher(templateName);
                    if (matcher.matches()) {
                        URL url = IOPlugin.class.getResource("/" + templateUrl);
                        if (url != null) {
                            templateURLs.put(matcher.group(1), url);
                        }
                    }
                }
            }
            staticTemplateLoader.setTemplateURLs(templateURLs);
            this.templateLoaders.add(staticTemplateLoader);

        }
    }
    return InitState.INITIALIZED;
}

From source file:org.brushingbits.jnap.struts2.config.RestControllerConfigBuilder.java

@Override
protected String determineActionName(Class<?> actionClass) {
    String actionName = StringUtils.EMPTY;
    if (actionClass.isAnnotationPresent(Path.class)) {
        actionName = actionClass.getAnnotation(Path.class).value().trim();
        // clean surrounding slashes
        actionName = actionName.replaceAll("^\\/|\\/$", StringUtils.EMPTY);
    } else {//from   w  w  w .j  a  va2s  . c om
        actionName = super.determineActionName(actionClass);
    }
    return actionName;
}

From source file:com.aceevo.ursus.core.UrsusJerseyApplication.java

private void configureTyrus(T configuration, NetworkListener listener) {

    Set<Class<?>> classes = getClasses();

    Set<Class<?>> tyrusEndpoints = new HashSet<>();
    for (Class<?> clazz : classes) {
        if (clazz.isAnnotationPresent(ServerEndpoint.class)) {
            tyrusEndpoints.add(clazz);//from  ww w.  ja v  a2s  .c  o m
        }
    }

    UrsusTyrusServerContainer ursusTyrusServerContainer;
    try {
        ursusTyrusServerContainer = new UrsusTyrusServerContainer(tyrusEndpoints, serverEndpointConfigs,
                configuration.getHttpServer().getRootContext(),
                configuration.getTyrus().getIncomingBufferSize());
        GrizzlyServerFilter grizzlyServerFilter = new GrizzlyServerFilter(ursusTyrusServerContainer);
        listener.registerAddOn(new TyrusAddOn(grizzlyServerFilter));
    } catch (DeploymentException e) {
        throw new RuntimeException("Unable to deploy WebSocket endpoints", e);
    }
}

From source file:org.sprintapi.hyperdata.gson.HyperDataAdapterFactory.java

@SuppressWarnings("unchecked")
@Override//from  w w  w. j a v a  2  s.c  o m
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {

    Class<? super T> raw = type.getRawType();

    if (!Object.class.isAssignableFrom(raw) || HyperMap.class.isAssignableFrom(raw)) {
        return null; // it's a primitive or HyperMap
    }

    if (!raw.isAnnotationPresent(HyperdataContainer.class)) {
        return null; // it's not hyperdata
    }

    MetadataAccess metadataAccess = new MetadataAccess();

    Set<String> profiles = new LinkedHashSet<String>();

    Class<?> c = raw;
    while (c != null) {
        if (c.getClass().equals(Object.class)) {
            break;
        }

        HyperdataContainer hdc = c.getAnnotation(HyperdataContainer.class);
        if ((hdc != null) && (hdc.profile().length > 0)) {
            profiles.addAll(Arrays.asList(hdc.profile()));
        }
        Class<?>[] interfaces = c.getInterfaces();
        if (interfaces != null) {
            for (Class<?> i : interfaces) {
                hdc = i.getAnnotation(HyperdataContainer.class);
                if ((hdc != null) && (hdc.profile().length > 0)) {
                    profiles.addAll(Arrays.asList(hdc.profile()));
                }
            }
        }

        c = c.getSuperclass();
    }

    metadataAccess.profile = profiles.toArray(new String[0]);

    for (Method method : raw.getMethods()) {
        if (method.isAnnotationPresent(MetadataContainer.class)) {
            if (method.getName().startsWith("get")) {
                metadataAccess.getter = method;
                metadataAccess.fieldName = method.getName().substring(3);

            } else if (method.getName().startsWith("set")) {
                metadataAccess.setter = method;
                metadataAccess.fieldName = method.getName().substring(3);
            }
        }
    }

    if (metadataAccess.fieldName != null) {
        if (metadataAccess.getter == null) {
            for (Method method : raw.getMethods()) {
                if (method.getName().equals("get" + metadataAccess.fieldName)) {
                    metadataAccess.getter = method;
                    break;
                }
            }
        } else if (metadataAccess.setter == null) {
            for (Method method : raw.getMethods()) {
                if (method.getName().equals("set" + metadataAccess.fieldName)) {
                    metadataAccess.setter = method;
                    break;
                }
            }
        }
        metadataAccess.fieldName = WordUtils.uncapitalize(metadataAccess.fieldName);
    }

    ObjectConstructor<T> constructor = constructorConstructor.get(type);
    return (TypeAdapter<T>) new HyperDataTypeAdapter(metadataAccess, constructorConstructor,
            (ObjectConstructor<Object>) constructor, getBoundFields(gson, type, raw), gson, this);
}

From source file:com.evolveum.midpoint.repo.sql.query2.definition.ClassDefinitionParser.java

private void addVirtualDefinitionsForClass(Class jpaClass, JpaEntityDefinition entityDef) {
    if (!jpaClass.isAnnotationPresent(QueryEntity.class)) {
        return;//from   w  w  w . j av  a 2 s . co  m
    }

    QueryEntity qEntity = (QueryEntity) jpaClass.getAnnotation(QueryEntity.class);

    for (VirtualAny any : qEntity.anyElements()) {
        QName jaxbName = new QName(any.jaxbNameNamespace(), any.jaxbNameLocalPart());
        VirtualAnyContainerDefinition def = new VirtualAnyContainerDefinition(any.ownerType());
        JpaLinkDefinition linkDefinition = new JpaLinkDefinition(jaxbName, null, null, false, def);
        entityDef.addDefinition(linkDefinition);
    }

    for (VirtualCollection collection : qEntity.collections()) {
        // only collections of entities expected at this moment
        VirtualCollectionSpecification colSpec = new VirtualCollectionSpecification(
                collection.additionalParams());
        QName jaxbName = createQName(collection.jaxbName());
        String jpaName = collection.jpaName();
        JpaEntityDefinition content = parseClass(collection.collectionType());
        JpaLinkDefinition linkDefinition = new JpaLinkDefinition(jaxbName, jpaName, colSpec, false, content);
        entityDef.addDefinition(linkDefinition);
    }

    for (VirtualEntity entity : qEntity.entities()) {
        QName jaxbName = createQName(entity.jaxbName());
        String jpaName = normalizeJpaName(entity.jpaName());
        if (jpaName != null) {
            throw new IllegalStateException(
                    "Only self-pointing virtual entities are supported for now; this one is not: " + jaxbName
                            + " in " + entityDef);
        }
        JpaDataNodeDefinition target = new JpaEntityPointerDefinition(entityDef); // pointer to avoid loops
        JpaLinkDefinition linkDefinition = new JpaLinkDefinition(jaxbName, jpaName, null, false, target);
        entityDef.addDefinition(linkDefinition);
    }
}

From source file:io.twipple.springframework.data.clusterpoint.convert.support.CustomConversions.java

/**
 * Registers a conversion for the given converter. Inspects either generics or the convertible pairs returned
 * by a {@link GenericConverter}./*from   w  w  w .j a  v a  2s  .  com*/
 *
 * @param converter the converter to register.
 */
private void registerConversion(@NotNull Object converter) {

    Assert.notNull(converter);

    Class<?> type = converter.getClass();
    boolean isWriting = type.isAnnotationPresent(WritingConverter.class);
    boolean isReading = type.isAnnotationPresent(ReadingConverter.class);

    if (converter instanceof GenericConverter) {
        GenericConverter genericConverter = (GenericConverter) converter;
        for (GenericConverter.ConvertiblePair pair : genericConverter.getConvertibleTypes()) {
            register(new ConverterRegistration(pair, isReading, isWriting));
        }
    } else if (converter instanceof Converter) {
        Class<?>[] arguments = GenericTypeResolver.resolveTypeArguments(converter.getClass(), Converter.class);
        register(new ConverterRegistration(arguments[0], arguments[1], isReading, isWriting));
    } else {
        throw new IllegalArgumentException("Unsupported Converter type!");
    }
}

From source file:com.impetus.kundera.metadata.processor.TableProcessor.java

@Override
public void process(Class<?> clazz, EntityMetadata metadata) {
    if (!clazz.isAnnotationPresent(Table.class)) {
        // FIXME: why return? why not throw run time exception?
        return;//from w w  w.  ja  v a2 s .c o m
    }

    LOG.debug("Processing @Entity(" + clazz.getName() + ") for Persistence Object.");

    populateMetadata(metadata, clazz);

}