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:org.red5.io.amf.Output.java

/** {@inheritDoc} */
public void writeObject(Object object, Serializer serializer) {
    if (checkWriteReference(object))
        return;//w ww .j  ava 2s  .c  o  m

    storeReference(object);
    // Create new map out of bean properties
    BeanMap beanMap = new BeanMap(object);
    // Set of bean attributes
    Set<BeanMap.Entry<?, ?>> set = beanMap.entrySet();
    if ((set.size() == 0) || (set.size() == 1 && beanMap.containsKey("class"))) {
        // BeanMap is empty or can only access "class" attribute, skip it
        writeArbitraryObject(object, serializer);
        return;
    }

    // Write out either start of object marker for class name or "empty" start of object marker
    Class<?> objectClass = object.getClass();
    if (!objectClass.isAnnotationPresent(Anonymous.class)) {
        buf.put(AMF.TYPE_CLASS_OBJECT);
        putString(buf, objectClass.getName());
    } else {
        buf.put(AMF.TYPE_OBJECT);
    }

    if (object instanceof ICustomSerializable) {
        ((ICustomSerializable) object).serialize(this, serializer);
        buf.put((byte) 0x00);
        buf.put((byte) 0x00);
        buf.put(AMF.TYPE_END_OF_OBJECT);
        return;
    }

    // Iterate thru entries and write out property names with separators
    for (BeanMap.Entry<?, ?> entry : set) {
        if (entry.getKey().toString().equals("class")) {
            continue;
        }

        String keyName = entry.getKey().toString();
        // Check if the Field corresponding to the getter/setter pair is transient
        if (dontSerializeField(objectClass, keyName))
            continue;

        putString(buf, keyName);
        serializer.serialize(this, entry.getValue());
    }
    // Write out end of object mark
    buf.put((byte) 0x00);
    buf.put((byte) 0x00);
    buf.put(AMF.TYPE_END_OF_OBJECT);
}

From source file:com.fitbur.testify.di.spring.SpringServiceLocator.java

@Override
public <T> T getService(Type type, Set<? extends Annotation> annotations) {
    TypeToken<?> token = TypeToken.of(type);

    Object instance;//w w w.  jav  a 2  s .  co m
    Optional<Class<? extends Annotation>> beanAnnotation = empty();
    Class rawType = token.getRawType();

    Optional<String> beanName = annotations.parallelStream()
            .filter(p -> p.annotationType().equals(Qualifier.class)).map(Qualifier.class::cast)
            .map(Qualifier::value).findFirst();

    if (!beanName.isPresent()) {
        beanName = annotations.parallelStream().filter(p -> p.annotationType().equals(Named.class))
                .map(Named.class::cast).map(Named::value).findFirst();
    }

    if (!beanName.isPresent()) {
        Set<Class<? extends Annotation>> customQualfiers = serviceAnnotations.getCustomQualifiers();

        for (Annotation annotation : annotations) {
            Class<? extends Annotation> annotationType = annotation.annotationType();

            for (Class<? extends Annotation> customQualfier : customQualfiers) {
                if (annotationType.isAnnotationPresent(customQualfier)
                        || annotationType.equals(Qualifier.class)) {
                    beanAnnotation = of(annotationType);
                    break;
                }
            }

            if (beanAnnotation.isPresent()) {
                break;
            }
        }
    }

    if (beanName.isPresent()) {
        String name = beanName.get();
        if (token.isSubtypeOf(Provider.class)) {
            TypeVariable<Class<Provider>> paramType = Provider.class.getTypeParameters()[0];
            rawType = token.resolveType(paramType).getRawType();
            instance = new ServiceProvider(this, name, rawType);
        } else if (token.isSubtypeOf(Optional.class)) {
            TypeVariable<Class<Optional>> paramType = Optional.class.getTypeParameters()[0];
            rawType = token.resolveType(paramType).getRawType();
            instance = Optional.ofNullable(context.getBean(name, rawType));
        } else {
            instance = context.getBean(name, rawType);
        }
    } else if (beanAnnotation.isPresent()) {
        Map<String, Object> beans = context.getBeansWithAnnotation(beanAnnotation.get());
        instance = beans.entrySet().parallelStream().map(p -> {
            Object value;
            if (token.isSubtypeOf(Provider.class)) {
                value = new ServiceProvider(this, p.getKey(), p.getValue().getClass());
            } else if (token.isSubtypeOf(Optional.class)) {
                value = of(p.getValue());
            } else {
                value = p.getValue();
            }

            return value;
        }).findFirst().get();
    } else {
        instance = getService(type);
    }

    return (T) instance;
}

From source file:org.red5.io.amf.Output.java

/**
 * Writes an arbitrary object to the output.
 *
 * @param serializer    Output writer//from ww  w  . ja v  a 2  s  .c  om
 * @param object        Object to write
 */
protected void writeArbitraryObject(Object object, Serializer serializer) {
    if (log.isDebugEnabled()) {
        log.debug("writeObject");
    }
    // If we need to serialize class information...
    Class<?> objectClass = object.getClass();
    if (!objectClass.isAnnotationPresent(Anonymous.class)) {
        // Write out start object marker for class name
        buf.put(AMF.TYPE_CLASS_OBJECT);
        putString(buf, objectClass.getName());
    } else {
        // Write out start object marker without class name
        buf.put(AMF.TYPE_OBJECT);
    }

    // Get public field values
    Map<String, Object> values = new HashMap<String, Object>();
    // Iterate thru fields of an object to build "name-value" map from it
    for (Field field : objectClass.getFields()) {
        if (field.isAnnotationPresent(DontSerialize.class)) {
            if (log.isDebugEnabled()) {
                log.debug("Skipping " + field.getName() + " because its marked with @DontSerialize");
            }
            continue;
        } else {
            int modifiers = field.getModifiers();
            if (Modifier.isTransient(modifiers)) {
                log.warn("Using \"transient\" to declare fields not to be serialized is "
                        + "deprecated and will be removed in Red5 0.8, use \"@DontSerialize\" instead.");
                continue;
            }
        }

        Object value;
        try {
            // Get field value
            value = field.get(object);
        } catch (IllegalAccessException err) {
            // Swallow on private and protected properties access exception
            continue;
        }
        // Put field to the map of "name-value" pairs
        values.put(field.getName(), value);
    }

    // Output public values
    Iterator<Map.Entry<String, Object>> it = values.entrySet().iterator();
    // Iterate thru map and write out properties with separators
    while (it.hasNext()) {
        Map.Entry<String, Object> entry = it.next();
        // Write out prop name
        putString(buf, entry.getKey());
        // Write out
        serializer.serialize(this, entry.getValue());
    }
    // Write out end of object marker
    buf.put((byte) 0x00);
    buf.put((byte) 0x00);
    buf.put(AMF.TYPE_END_OF_OBJECT);
}

From source file:therian.operator.copy.PropertyCopier.java

private PropertyCopier(Mapping mapping, Matching matching) {
    try {// ww w  .  ja v  a 2 s  .c  o m
        @SuppressWarnings("rawtypes")
        final Class<? extends PropertyCopier> c = getClass();
        this.matching = matching;

        if (mapping == null) {
            Validate.validState(c.isAnnotationPresent(Matching.class),
                    "%s specifies neither @Mapping nor @Matching", c);
            mappings = Collections.emptyList();
        } else {
            mappings = parse(mapping);
        }
    } catch (Exception e) {
        throw new OperatorDefinitionException(this, e);
    }
}

From source file:com.laxser.blitz.web.impl.module.ModulesBuilderImpl.java

private boolean isCandidate(Class<?> clazz) {
    if (clazz.isAnnotationPresent(Ignored.class)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Ignores bean definition because it's present by @Ignored : " + clazz.getName());
        }//from  ww w  .  j av  a2s .c o  m
        return false;
    }
    if (!Modifier.isPublic(clazz.getModifiers())) {
        if (logger.isDebugEnabled()) {
            logger.debug("Ignores bean definition because it's not a public class: " + clazz.getName());
        }
        return false;
    }
    if (Modifier.isAbstract(clazz.getModifiers())) {
        if (logger.isDebugEnabled()) {
            logger.debug("Ignores bean definition because it's a abstract class: " + clazz.getName());
        }
        return false;
    }
    if (clazz.getDeclaringClass() != null) {
        if (logger.isDebugEnabled()) {
            logger.debug("Ignores bean definition because it's a inner class: " + clazz.getName());
        }
        return false;
    }
    return true;
}

From source file:thewebsemantic.Bean2RDF.java

/**
 * Adds class axioms determined by present annotations.
 * //from www .  ja  v a  2 s  .c o m
 * @param cls - Java class (which contains annotations)
 * @param owlClass - OWL class in which the Java class is mapped
 * @return OWL class
 */
private Resource applyAnnotations(Class<?> cls, OntClass owlClass) {

    // Version info
    if (cls.isAnnotationPresent(VersionInfo.class)) {
        owlClass.setVersionInfo(cls.getAnnotation(VersionInfo.class).value());
    }

    // Comment
    if (cls.isAnnotationPresent(Comment.class)) {
        String language = cls.getAnnotation(Comment.class).lang();
        owlClass.setComment(cls.getAnnotation(Comment.class).value(), language.equals("") ? null : language);
    }

    // SeeAlso
    if (cls.isAnnotationPresent(SeeAlso.class)) {
        String seeAlso = cls.getAnnotation(SeeAlso.class).value();
        Resource res = ResourceFactory.createResource(seeAlso);
        owlClass.setSeeAlso(res);
    }

    // Label
    if (cls.isAnnotationPresent(Label.class)) {
        String language = cls.getAnnotation(Label.class).lang();
        owlClass.setLabel(cls.getAnnotation(Label.class).value(), language.equals("") ? null : language);
    }

    // IsDefinedBy
    if (cls.isAnnotationPresent(IsDefinedBy.class)) {
        String value = cls.getAnnotation(IsDefinedBy.class).value();
        Resource res = ResourceFactory.createResource(value);
        owlClass.setIsDefinedBy(res);
    }

    // EquivalentClass
    if (cls.isAnnotationPresent(EquivalentClass.class)) {
        OntClass eqClass = om.createClass(cls.getAnnotation(EquivalentClass.class).value());
        owlClass.setEquivalentClass(eqClass);
    }

    // DisjointWith
    if (cls.isAnnotationPresent(DisjointWith.class)) {
        OntClass disClass = om.createClass(cls.getAnnotation(DisjointWith.class).value());
        owlClass.setDisjointWith(disClass);
    }

    // ComplementOf
    if (cls.isAnnotationPresent(ComplementOf.class)) {
        OntClass comClass = om.createClass(cls.getAnnotation(ComplementOf.class).value());
        owlClass.convertToComplementClass(comClass);
    }

    // Deprecated
    if (cls.isAnnotationPresent(Deprecated.class)) {
        owlClass.addProperty(RDF.type, OWL.DeprecatedClass);
    }

    // SameAs
    if (cls.isAnnotationPresent(SameAs.class)) {
        String same = cls.getAnnotation(SameAs.class).value();
        Resource res = ResourceFactory.createResource(same);
        owlClass.setSameAs(res);
    }

    // DifferentFrom
    if (cls.isAnnotationPresent(DifferentFrom.class)) {
        String different = cls.getAnnotation(DifferentFrom.class).value();
        Resource res = ResourceFactory.createResource(different);
        owlClass.setDifferentFrom(res);
    }

    // AllDifferent
    if (cls.isAnnotationPresent(AllDifferent.class)) {
        com.hp.hpl.jena.ontology.AllDifferent allDif = om.createAllDifferent();
        allDif.addDistinctMember(owlClass); // add annotated class
        String[] values = cls.getAnnotation(AllDifferent.class).value();
        Resource res;
        for (String value : values) {
            res = ResourceFactory.createResource(value);
            allDif.addDistinctMember(res);
        }
    }

    return owlClass;
}

From source file:com.reactivetechnologies.platform.datagrid.core.HazelcastInstanceProxy.java

void addMapConfig(Class<?> c) {
    if (!c.isAnnotationPresent(HzMapConfig.class))
        throw new IllegalArgumentException(c + " not annotated with @" + HzMapConfig.class.getSimpleName());

    HzMapConfig hc = c.getAnnotation(HzMapConfig.class);
    MapConfig mapC = new MapConfig(hc.name());
    if (hzConfig.getMapConfigs().containsKey(hc.name())) {
        mapC = hzConfig.getMapConfig(hc.name());
    }//w ww .jav  a  2  s  . co m

    mapC.setAsyncBackupCount(hc.asyncBackupCount());
    mapC.setBackupCount(hc.backupCount());
    mapC.setEvictionPercentage(hc.evictPercentage());
    mapC.setEvictionPolicy(EvictionPolicy.valueOf(hc.evictPolicy()));
    mapC.setInMemoryFormat(InMemoryFormat.valueOf(hc.inMemoryFormat()));
    mapC.setMaxIdleSeconds(hc.idleSeconds());
    mapC.setMergePolicy(hc.evictPolicy());
    mapC.setMinEvictionCheckMillis(hc.evictCheckMillis());
    mapC.setTimeToLiveSeconds(hc.ttlSeconds());
    mapC.setMaxSizeConfig(new MaxSizeConfig(hc.maxSize(), MaxSizePolicy.valueOf(hc.maxSizePolicy())));
    mapC.setStatisticsEnabled(hc.statisticsOn());

    hzConfig.getMapConfigs().put(mapC.getName(), mapC);
}

From source file:org.thiesen.helenaorm.HelenaColumnDAO.java

public HelenaColumnDAO(final Class<T> clz, final String hostname, final int port,
        final SerializeUnknownClasses serializationPolicy,
        final ImmutableMap<Class<?>, TypeMapping<?>> typeMappings) {

    if (!clz.isAnnotationPresent(HelenaColumnBean.class)) {
        throw new IllegalArgumentException(
                "Trying to get a HelenaColumnDAO for a class that is not mapped with @HelenaColumnBean");
    }/*from   w  ww . j  av a2  s  .  co  m*/

    final HelenaColumnBean annotation = clz.getAnnotation(HelenaColumnBean.class);
    this.typeConverter = new TypeConverter(typeMappings, serializationPolicy);
    //      this.clz = clz;

    this.keyspace = annotation.keyspace();
    this.columnFamily = annotation.columnFamily();
    this.secondaryColumnFamily = annotation.secondaryColumnFamily();

    this.hostname = hostname;
    this.port = port;

    if (annotation.consistency() != null) {
        this.setConsistencyLevel(annotation.consistency());
    }

    this.fields = new HashMap<String, Field>();
    for (Field field : clz.getDeclaredFields()) {
        this.fields.put(field.getName(), field);
    }

    this.propertyDescriptors = PropertyUtils.getPropertyDescriptors(clz);
    for (final PropertyDescriptor descriptor : propertyDescriptors) {
        if (isKeyProperty(descriptor)) {
            this.keyPropertyDescriptor = descriptor;
        } else if (isColumnProperty(descriptor)) {
            this.columnPropertyDescriptor = descriptor;
        } else if (isValueProperty(descriptor)) {
            this.valuePropertyDescriptor = descriptor;
        }
    }

    if (keyPropertyDescriptor == null) {
        throw new HelenaRuntimeException(
                "Could not find key of class " + clz.getName() + ", did you annotate with @KeyProperty");
    }

    if (columnPropertyDescriptor == null) {
        throw new HelenaRuntimeException(
                "Could not find column of class " + clz.getName() + ", did you annotate with @ColumnProperty");
    }
}

From source file:org.broadinstitute.gatk.tools.walkers.help.WalkerDocumentationHandler.java

/**
 * Utility function that determines the default downsampling settings for an instance of class c.
 *
 * @param myClass the class to query for the settings
 * @param dsSettings an empty HashMap in which to collect the info
 * @return a hash set of the downsampling settings, otherwise an empty set
 *//*w  w w  . j a  v a2  s. c o m*/
private HashMap<String, Object> getDownSamplingSettings(Class myClass, HashMap<String, Object> dsSettings) {
    //
    // Check for RODWalker first
    if (!checkForRODWalker(myClass).equals("yes")) {
        //
        // Retrieve annotation
        if (myClass.isAnnotationPresent(Downsample.class)) {
            final Annotation thisAnnotation = myClass.getAnnotation(Downsample.class);
            if (thisAnnotation instanceof Downsample) {
                final Downsample dsAnnotation = (Downsample) thisAnnotation;
                dsSettings.put("by", dsAnnotation.by().toString());
                dsSettings.put("to_cov", dsAnnotation.toCoverage());
            }
        }
    }
    return dsSettings;
}

From source file:org.optaplanner.core.impl.domain.solution.cloner.FieldAccessingSolutionCloner.java

protected boolean isClassDeepCloned(Class<?> type) {
    return solutionDescriptor.hasEntityDescriptor(type)
            || solutionDescriptor.getSolutionClass().isAssignableFrom(type)
            || type.isAnnotationPresent(DeepPlanningClone.class);
}