Example usage for java.lang Class getAnnotation

List of usage examples for java.lang Class getAnnotation

Introduction

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

Prototype

@SuppressWarnings("unchecked")
public <A extends Annotation> A getAnnotation(Class<A> annotationClass) 

Source Link

Usage

From source file:com.github.gekoh.yagen.util.MappingUtils.java

public static String getJpaEntityName(Class entityClass) {
    Entity entity = (Entity) entityClass.getAnnotation(Entity.class);
    if (entity == null) {
        return null;
    }//  w  w w  . j a v  a2s.com
    return StringUtils.isNotEmpty(entity.name()) ? entity.name() : entityClass.getSimpleName();
}

From source file:com.predic8.membrane.annot.bean.MCUtil.java

private static void addXML(Object object, String id, XMLStreamWriter xew, SerializationContext sc)
        throws XMLStreamException {
    if (object == null)
        throw new InvalidParameterException("'object' must not be null.");

    Class<? extends Object> clazz = object.getClass();

    MCElement e = clazz.getAnnotation(MCElement.class);
    if (e == null)
        throw new IllegalArgumentException("'object' must be @MCElement-annotated.");

    BeanWrapperImpl src = new BeanWrapperImpl(object);

    xew.writeStartElement(e.name());//from  w  w w  .j a v a  2  s.co  m

    if (id != null)
        xew.writeAttribute("id", id);

    HashSet<String> attributes = new HashSet<String>();
    for (Method m : clazz.getMethods()) {
        if (!m.getName().startsWith("set"))
            continue;
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));
        MCAttribute a = m.getAnnotation(MCAttribute.class);
        if (a != null) {
            Object value = src.getPropertyValue(propertyName);
            String str;
            if (value == null)
                continue;
            else if (value instanceof String)
                str = (String) value;
            else if (value instanceof Boolean)
                str = ((Boolean) value).toString();
            else if (value instanceof Integer)
                str = ((Integer) value).toString();
            else if (value instanceof Long)
                str = ((Long) value).toString();
            else if (value instanceof Enum<?>)
                str = value.toString();
            else {
                MCElement el = value.getClass().getAnnotation(MCElement.class);
                if (el != null) {
                    str = defineBean(sc, value, null, true);
                } else {
                    str = "?";
                    sc.incomplete = true;
                }
            }

            if (a.attributeName().length() > 0)
                propertyName = a.attributeName();

            attributes.add(propertyName);
            xew.writeAttribute(propertyName, str);
        }
    }
    for (Method m : clazz.getMethods()) {
        if (!m.getName().startsWith("set"))
            continue;
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));
        MCOtherAttributes o = m.getAnnotation(MCOtherAttributes.class);
        if (o != null) {
            Object value = src.getPropertyValue(propertyName);
            if (value instanceof Map<?, ?>) {
                Map<?, ?> map = (Map<?, ?>) value;
                for (Map.Entry<?, ?> entry : map.entrySet()) {
                    Object key = entry.getKey();
                    Object val = entry.getValue();
                    if (!(key instanceof String) || !(val instanceof String)) {
                        sc.incomplete = true;
                        key = "incompleteAttributes";
                        val = "?";
                    }
                    if (attributes.contains(key))
                        continue;
                    attributes.add((String) key);
                    xew.writeAttribute((String) key, (String) val);
                }
            } else {
                xew.writeAttribute("incompleteAttributes", "?");
                sc.incomplete = true;
            }
        }
    }

    List<Method> childElements = new ArrayList<Method>();
    for (Method m : clazz.getMethods()) {
        if (!m.getName().startsWith("set"))
            continue;
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));

        MCChildElement c = m.getAnnotation(MCChildElement.class);
        if (c != null) {
            childElements.add(m);
        }
        MCTextContent t = m.getAnnotation(MCTextContent.class);
        if (t != null) {
            Object value = src.getPropertyValue(propertyName);
            if (value == null) {
                continue;
            } else if (value instanceof String) {
                xew.writeCharacters((String) value);
            } else {
                xew.writeCharacters("?");
                sc.incomplete = true;
            }
        }
    }

    Collections.sort(childElements, new Comparator<Method>() {

        @Override
        public int compare(Method o1, Method o2) {
            MCChildElement c1 = o1.getAnnotation(MCChildElement.class);
            MCChildElement c2 = o2.getAnnotation(MCChildElement.class);
            return c1.order() - c2.order();
        }
    });

    for (Method m : childElements) {
        String propertyName = AnnotUtils.dejavaify(m.getName().substring(3));

        Object value = src.getPropertyValue(propertyName);
        if (value != null) {
            if (value instanceof Collection<?>) {
                for (Object item : (Collection<?>) value)
                    addXML(item, null, xew, sc);
            } else {
                addXML(value, null, xew, sc);
            }
        }
    }

    xew.writeEndElement();
}

From source file:com.serli.chell.framework.form.FormStructure.java

private static synchronized FormFieldConfiguration getFieldConfiguration(Annotation annotation) {
    Class<? extends Annotation> annotationType = annotation.annotationType();
    FormFieldConfiguration ffc = FORM_FIELD_CONFIGURATION.get(annotationType);
    if (ffc == null) {
        FormFieldMetadata fieldMetadata = annotationType.getAnnotation(FormFieldMetadata.class);
        if (fieldMetadata != null) {
            Class<? extends FormFieldConfiguration> ffcClass = fieldMetadata.configuration();
            if (!NoConfiguration.class.equals(ffcClass)) {
                ffc = SingletonFactory.get(ffcClass);
            } else {
                Class<? extends FieldConverter> converterClass = fieldMetadata.converter();
                Class<? extends Constraint> constraintClass = fieldMetadata.constraint();
                if (IdentityFieldConverter.class.equals(converterClass)) {
                    converterClass = null;
                }/*from   www  . j a v a 2 s .c  o m*/
                if (NoConstraint.class.equals(constraintClass)) {
                    constraintClass = null;
                }
                ffc = new ValidationConfiguration(converterClass, constraintClass);
            }
        } else {
            FormInputMetadata inputMetaData = annotationType.getAnnotation(FormInputMetadata.class);
            if (inputMetaData != null) {
                Class<? extends InputConfiguration> configurationClass = inputMetaData.configuration();
                InputConfiguration ic = ClassUtils.newInstance(configurationClass);
                ffc = ic.initialize(inputMetaData, annotationType);
            } else {
                ffc = NoConfiguration.INSTANCE;
            }
        }
        FORM_FIELD_CONFIGURATION.put(annotationType, ffc);
    }
    return ffc;
}

From source file:org.vaadin.addons.springsecurityviewprovider.SpringSecurityViewProvider.java

@SuppressWarnings("unchecked")
public final static ViewProvider createViewProvider(final Authentication authentication,
        Boolean enableCaching) {/*w w w .j  a v  a 2 s  . c om*/
    final SpringSecurityViewProvider springViewProvider = new SpringSecurityViewProvider();
    springViewProvider.enableCaching = enableCaching;

    try {
        final ApplicationContext applicationContext = springViewProvider.applicationContext;

        // Retrieve the default SecurityExpressionHandler 
        final MethodSecurityExpressionHandler securityExpressionHandler = applicationContext
                .getBean(DefaultMethodSecurityExpressionHandler.class);
        // The method that is protected in the end
        final Method getViewMethod = SpringSecurityViewProvider.class.getMethod("getView", String.class);
        // A parser to evaluate parse the permissions.
        final SpelExpressionParser parser = new SpelExpressionParser();

        // Although beans can be retrieved by annotation they must be retrieved by name
        // to avoid instanciating them
        for (String beanName : applicationContext.getBeanDefinitionNames()) {
            final Class<?> beanClass = applicationContext.getType(beanName);
            // only work with Views that are described by our specialed Description
            if (beanClass.isAnnotationPresent(ViewDescription.class)
                    && View.class.isAssignableFrom(beanClass)) {
                final ViewDescription viewDescription = beanClass.getAnnotation(ViewDescription.class);
                // requires no special permissions and can be immediatly added
                if (StringUtils.isBlank(viewDescription.requiredPermissions())) {
                    springViewProvider.views.put(viewDescription.name(), (Class<? extends View>) beanClass);
                }
                // requires permissions
                else {
                    // this is actually borrowed from the code in org.springframework.security.access.prepost.PreAuthorize
                    final EvaluationContext evaluationContext = securityExpressionHandler
                            .createEvaluationContext(authentication, new SimpleMethodInvocation(
                                    springViewProvider, getViewMethod, viewDescription.name()));
                    // only add the view to my provider if the permissions evaluate to true                  
                    if (ExpressionUtils.evaluateAsBoolean(
                            parser.parseExpression(viewDescription.requiredPermissions()), evaluationContext))
                        springViewProvider.views.put(viewDescription.name(), (Class<? extends View>) beanClass);
                }
            }
        }
    } catch (NoSuchMethodException | SecurityException e) {
        // Won't happen
    }

    return springViewProvider;
}

From source file:azkaban.common.utils.Utils.java

/**
 * Get an annotation from the class//from   w w  w . j  a  v  a  2  s . com
 * 
 * @param <T> The Annotation type
 * @param theClass The class to read the annotation from
 * @param annotation The annotation to read
 * @return The annotation if it is there
 * @throws IllegalArgumentException if the Annotation is not present
 */
public static <T extends Annotation> T getRequiredAnnotation(Class<?> theClass, Class<T> annotation) {
    T t = theClass.getAnnotation(annotation);
    if (t == null)
        throw new IllegalArgumentException("The expected annotation '" + annotation.getName()
                + "' was not found on class '" + theClass.getName() + "'.");
    return t;
}

From source file:com.cuubez.visualizer.resource.ResourceMetaDataScanner.java

public static boolean isResource(Class<?> clazz) {

    if (Modifier.isInterface(clazz.getModifiers()) || Modifier.isAbstract(clazz.getModifiers())) {
        return false;
    }//from  w  w w. j  a  va  2  s .c  o m

    if (clazz.getAnnotation(Path.class) != null && clazz.getAnnotation(Group.class) != null) {
        return true;
    }

    Class<?> declaringClass = clazz;

    while (!declaringClass.equals(Object.class)) {
        // try a superclass
        Class<?> superclass = declaringClass.getSuperclass();
        if (superclass.getAnnotation(Path.class) != null && clazz.getAnnotation(Group.class) != null) {
            return true;
        }

        // try interfaces
        Class<?>[] interfaces = declaringClass.getInterfaces();
        for (Class<?> interfaceClass : interfaces) {
            if (interfaceClass.getAnnotation(Path.class) != null && clazz.getAnnotation(Group.class) != null) {
                return true;
            }
        }
        declaringClass = declaringClass.getSuperclass();
    }
    return false;
}

From source file:com.eviware.x.form.support.ADialogBuilder.java

/**
 * Allow to use custom Ok, Cancel buttons...
 * <p/>//from  w w  w  .j  a va2 s . c  om
 * This means user have to add control for closing dialog.
 *
 * @param formClass
 * @param actions
 * @param useDefaultOkCancel
 * @return
 */
public static XFormDialog buildDialog(Class<? extends Object> formClass, ActionList actions,
        boolean useDefaultOkCancel) {

    if (useDefaultOkCancel) {
        return buildDialog(formClass, actions);
    }
    AForm formAnnotation = formClass.getAnnotation(AForm.class);
    if (formAnnotation == null) {
        throw new RuntimeException("formClass is not annotated correctly..");
    }

    MessageSupport messages = MessageSupport.getMessages(formClass);

    XFormDialogBuilder builder = XFormFactory.createDialogBuilder(messages.get(formAnnotation.name()));
    XForm form = createForm(builder, null);

    for (Field field : formClass.getFields()) {
        AField fieldAnnotation = field.getAnnotation(AField.class);
        if (fieldAnnotation != null) {
            try {
                addFormField(form, field, fieldAnnotation, messages);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    ActionList defaultActions = StringUtils.isBlank(formAnnotation.helpUrl()) ? null
            : builder.buildHelpActions(formAnnotation.helpUrl());

    if (actions == null) {
        actions = defaultActions;
    } else {
        // since there is only one action do it like this
        actions.insertAction(defaultActions.getActionAt(0), 0);
    }
    XFormDialog dialog = builder.buildDialog(actions, messages.get(formAnnotation.description()),
            UISupport.createImageIcon(formAnnotation.icon()));

    return dialog;
}

From source file:gov.nih.nci.firebird.data.CredentialTest.java

private static String getDiscriminator(Class<? extends AbstractCredential<?>> clazz) {
    DiscriminatorValue a = clazz.getAnnotation(DiscriminatorValue.class);
    return a.value();
}

From source file:com.reactivetechnologies.platform.rest.WebbitRestServerBean.java

/**
 * /*from   w w  w .j  a va  2 s .  c om*/
 * @param restletClass
 * @return
 * @throws InstantiationException
 * @throws IllegalAccessException
 */
static JAXRSInstanceMetadata scanJaxRsClass(Class<?> restletClass)
        throws InstantiationException, IllegalAccessException {
    final JAXRSInstanceMetadata proxy = new JAXRSInstanceMetadata(restletClass.newInstance());
    if (restletClass.isAnnotationPresent(Path.class)) {
        String rootUri = restletClass.getAnnotation(Path.class).value();
        if (rootUri == null)
            rootUri = "";
        proxy.setRootUri(rootUri);
    }
    ReflectionUtils.doWithMethods(restletClass, new MethodCallback() {

        @Override
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            String subUri = "";
            if (method.isAnnotationPresent(Path.class)) {
                subUri = method.getAnnotation(Path.class).value();
            }
            if (method.isAnnotationPresent(GET.class)) {
                MethodDetail m = createMethodDetail(method);
                proxy.addGetMethod(proxy.getRootUri() + subUri, m);
            }
            if (method.isAnnotationPresent(POST.class)) {
                MethodDetail m = createMethodDetail(method);
                proxy.addPostMethod(proxy.getRootUri() + subUri, m);
            }
            if (method.isAnnotationPresent(DELETE.class)) {
                MethodDetail m = createMethodDetail(method);
                proxy.addDelMethod(proxy.getRootUri() + subUri, m);
            }

        }
    }, new MethodFilter() {

        @Override
        public boolean matches(Method method) {
            return (method.isAnnotationPresent(GET.class) || method.isAnnotationPresent(POST.class)
                    || method.isAnnotationPresent(DELETE.class));
        }
    });

    return proxy;
}

From source file:org.agiso.core.i18n.util.I18nUtils.java

public static String getCode(Class<?> c) {
    if (c.isAnnotationPresent(I18n.class)) {
        if (c.getAnnotation(I18n.class).value().length() > 0) {
            return c.getAnnotation(I18n.class).value();
        } else {// w w w .ja v  a 2  s  . c  o  m
            return c.getName();
        }
    }
    // else if(c.isAnnotationPresent(I18nRef.class)) {
    //    Object ref = c.getAnnotation(I18nRef.class).value();
    //    if(((Class<?>)ref).isEnum()) {
    //       return getCode((Enum<?>)ref);
    //    } else {
    //       return getCode((Class<?>)ref);
    //    }
    // }
    return c.getName();
}