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.openmrs.module.tribe.TribeActivator.java

private void extractTribeColumn() {
    // check whether tribe module is installed in an old OpenMRS
    // throw exception if it is
    boolean isOldOpenMRS = true;
    try {//from  w  w  w  . jav a 2 s .c o  m
        Class cls = OpenmrsClassLoader.getInstance().loadClass("org.openmrs.Tribe");
        if (cls.isAnnotationPresent(Deprecated.class))
            isOldOpenMRS = false;
    } catch (ClassNotFoundException e) {
        // OpenMRS version ok
        isOldOpenMRS = false;
    }
    if (isOldOpenMRS) {
        throw new ModuleException(
                "Tribe module cannot be used with this OpenMRS version. Please upgrade OpenMRS.");
    }

    // now convert patient tribes to tribe attributes
    AdministrationService as = Context.getAdministrationService();

    // check whether patient table has tribe column
    log.info("Ignore the error message if occurs: "
            + "Error while running sql: SELECT distinct tribe from patient where 1 = 0");
    log.info("The above message indicates that you are running a new implementation "
            + "which does not have a tribe column in the patient table.");
    boolean isTribeColumnExists = true;

    DataSource ds = new SingleConnectionDataSource(Context.getRuntimeProperties().getProperty("connection.url"),
            Context.getRuntimeProperties().getProperty("connection.username"),
            Context.getRuntimeProperties().getProperty("connection.password"), true);
    JdbcTemplate jdbc = new JdbcTemplate(ds);

    jdbc.setMaxRows(1);
    try {

        jdbc.queryForList("SELECT distinct tribe from patient where 1 = 0");

    } catch (Exception e) {
        isTribeColumnExists = false;

    }

    // now convert patient tribes to tribe attributes

    if (isTribeColumnExists) {
        // create tribe attributes
        try {
            log.info("Transforming tribe details");
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_SQL_LEVEL_ACCESS);
            as.executeSQL(
                    "INSERT INTO person_attribute (person_id, value, person_attribute_type_id, creator, date_created, uuid)"
                            + " SELECT patient_id, tribe,"
                            + " (SELECT person_attribute_type_id FROM person_attribute_type WHERE name = 'Tribe')"
                            + " , 1, now(), UUID() FROM patient WHERE tribe IS NOT NULL;",
                    false);
        } finally {
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_SQL_LEVEL_ACCESS);
        }

        // drop tribe column in patient, this will make these scripts not run again
        log.info("Dropping old tribe column");
        try {
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_SQL_LEVEL_ACCESS);
            as.executeSQL("ALTER TABLE patient DROP FOREIGN KEY belongs_to_tribe;", false);
        } catch (Exception e) {
            log.warn("Unable to drop foreign key patient.belongs_to_tribe", e);
        } finally {
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_SQL_LEVEL_ACCESS);
        }

        try {
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_SQL_LEVEL_ACCESS);
            as.executeSQL("ALTER TABLE patient DROP COLUMN tribe;", false);
        } catch (Exception e) {
            log.warn("Unable to drop column patient.tribe", e);
        } finally {
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_SQL_LEVEL_ACCESS);
        }

        log.info("Tribe data conversion complete");
    }

    // add View Tribes privilege to Authenticated role if not exists
    try {
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_SQL_LEVEL_ACCESS);
        UserService us = Context.getUserService();
        Role authenticatedRole = us.getRole(OpenmrsConstants.AUTHENTICATED_ROLE);
        if (!authenticatedRole.hasPrivilege(TribeConstants.PRIV_VIEW_TRIBES)) {
            as.executeSQL("INSERT INTO role_privilege (role, privilege) VALUES ('"
                    + OpenmrsConstants.AUTHENTICATED_ROLE + "', '" + TribeConstants.PRIV_VIEW_TRIBES + "')",
                    false);
        }
    } finally {
        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_SQL_LEVEL_ACCESS);
    }
}

From source file:com.googlecode.jsonrpc4j.spring.AutoJsonRpcServiceExporter.java

/**
 * Registers the new beans with the bean factory.
 *//*from  ww  w . jav  a2  s.c  o m*/
private void registerServiceProxy(DefaultListableBeanFactory dlbf, String servicePath, String serviceBeanName) {
    BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(JsonServiceExporter.class)
            .addPropertyReference("service", serviceBeanName);
    BeanDefinition serviceBeanDefinition = findBeanDefintion(dlbf, serviceBeanName);
    for (Class<?> iface : getBeanInterfaces(serviceBeanDefinition, dlbf.getBeanClassLoader())) {
        if (iface.isAnnotationPresent(JsonRpcService.class)) {
            String serviceInterface = iface.getName();
            LOG.fine(format("Registering interface '%s' for JSON-RPC bean [%s].", serviceInterface,
                    serviceBeanName));
            builder.addPropertyValue("serviceInterface", serviceInterface);
            break;
        }
    }
    if (objectMapper != null) {
        builder.addPropertyValue("objectMapper", objectMapper);
    }

    if (errorResolver != null) {
        builder.addPropertyValue("errorResolver", errorResolver);
    }

    if (invocationListener != null) {
        builder.addPropertyValue("invocationListener", invocationListener);
    }

    if (registerTraceInterceptor != null) {
        builder.addPropertyValue("registerTraceInterceptor", registerTraceInterceptor);
    }

    builder.addPropertyValue("backwardsComaptible", Boolean.valueOf(backwardsComaptible));
    builder.addPropertyValue("rethrowExceptions", Boolean.valueOf(rethrowExceptions));
    builder.addPropertyValue("allowExtraParams", Boolean.valueOf(allowExtraParams));
    builder.addPropertyValue("allowLessParams", Boolean.valueOf(allowLessParams));
    builder.addPropertyValue("exceptionLogLevel", exceptionLogLevel);
    dlbf.registerBeanDefinition(servicePath, builder.getBeanDefinition());
}

From source file:code.elix_x.excore.utils.nbt.mbt.encoders.NBTClassEncoder.java

@Override
public NBTTagCompound toNBT(MBT mbt, Object t) {
    NBTTagCompound nbt = new NBTTagCompound();
    Class clazz = t.getClass();
    if (encodeClass)
        nbt.setString(CLASS, clazz.getName());
    while (clazz != null && clazz != Object.class) {
        if (!clazz.isAnnotationPresent(MBTIgnore.class)) {
            for (Field field : clazz.getDeclaredFields()) {
                if (!field.isAnnotationPresent(MBTIgnore.class)) {
                    field.setAccessible(true);
                    if ((encodeFinal || !Modifier.isFinal(field.getModifiers()))
                            && (encodeStatic || !Modifier.isStatic(field.getModifiers()))) {
                        try {
                            nbt.setTag(field.getName(), mbt.toNBT(field.get(t)));
                        } catch (IllegalArgumentException e) {
                            Throwables.propagate(e);
                        } catch (IllegalAccessException e) {
                            Throwables.propagate(e);
                        }/*from w  w  w .  ja  v  a  2 s.  c o  m*/
                    }
                }
            }
        }
        clazz = encodeSuper ? clazz.getSuperclass() : Object.class;
    }
    return nbt;
}

From source file:org.pantsbuild.tools.junit.impl.ConsoleRunnerImpl.java

private static boolean isTest(final Class<?> clazz) {
    // Must be a public concrete class to be a runnable junit Test.
    if (clazz.isInterface() || Modifier.isAbstract(clazz.getModifiers())
            || !Modifier.isPublic(clazz.getModifiers())) {
        return false;
    }//  w  w w.ja  va  2  s.c o m

    // The class must have some public constructor to be instantiated by the runner being used
    if (!Iterables.any(Arrays.asList(clazz.getConstructors()), IS_PUBLIC_CONSTRUCTOR)) {
        return false;
    }

    // Support junit 3.x Test hierarchy.
    if (junit.framework.Test.class.isAssignableFrom(clazz)) {
        return true;
    }

    // Support classes using junit 4.x custom runners.
    if (clazz.isAnnotationPresent(RunWith.class)) {
        return true;
    }

    // Support junit 4.x @Test annotated methods.
    return Iterables.any(Arrays.asList(clazz.getMethods()), IS_ANNOTATED_TEST_METHOD);
}

From source file:org.alfresco.repo.publishing.JaxbHttpMessageConverter.java

@Override
protected Object readFromSource(Class<?> clazz, HttpHeaders headers, Source source) throws IOException {
    try {//from   w w w. j  ava  2  s.com
        Unmarshaller unmarshaller = createUnmarshaller(clazz);
        if (clazz.isAnnotationPresent(XmlRootElement.class)) {
            return unmarshaller.unmarshal(source);
        } else {
            JAXBElement<?> jaxbElement = unmarshaller.unmarshal(source, clazz);
            return jaxbElement.getValue();
        }
    } catch (UnmarshalException ex) {
        throw new HttpMessageNotReadableException("Could not unmarshal to [" + clazz + "]: " + ex.getMessage(),
                ex);

    } catch (JAXBException ex) {
        throw new HttpMessageConversionException("Could not instantiate JAXBContext: " + ex.getMessage(), ex);
    }
}

From source file:org.springframework.yarn.config.annotation.SpringYarnAnnotationPostProcessor.java

/**
 * Checks if class is a stereotype meaning if there is
 * a Component annotation present./* w ww  .ja  v  a  2  s.  c om*/
 *
 * @param beanClass the bean class
 * @return true, if is stereotype
 */
private boolean isStereotype(Class<?> beanClass) {
    List<Annotation> annotations = new ArrayList<Annotation>(Arrays.asList(beanClass.getAnnotations()));
    Class<?>[] interfaces = beanClass.getInterfaces();
    for (Class<?> iface : interfaces) {
        annotations.addAll(Arrays.asList(iface.getAnnotations()));
    }
    for (Annotation annotation : annotations) {
        Class<? extends Annotation> annotationType = annotation.annotationType();
        if (annotationType.equals(Component.class) || annotationType.isAnnotationPresent(Component.class)) {
            return true;
        }
    }
    return false;
}

From source file:org.springframework.data.mongodb.core.convert.CustomConversions.java

/**
 * Registers a conversion for the given converter. Inspects either generics or the {@link ConvertiblePair}s returned
 * by a {@link GenericConverter}.//from w  w w  . j av  a  2 s  .c o m
 * 
 * @param converter
 */
private void registerConversion(Object 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 (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.nick.scalpel.Scalpel.java

private void wireClz(Object o) {
    Class clz = o.getClass();
    for (ClassWirer clzWirer : mClassWirers) {
        if (clz.isAnnotationPresent(clzWirer.annotationClass())) {
            clzWirer.wire(o);/* w ww. j av  a  2  s. co m*/
        }
    }
}

From source file:org.jasig.portlet.courses.dao.xml.Jaxb2CourseSummaryHttpMessageConverter.java

@Override
protected Object readFromSource(Class<? extends Object> clazz, HttpHeaders headers, Source source)
        throws IOException {
    try {//from w  ww  .  j  a v a2s .c om
        Unmarshaller unmarshaller = createWrapperUnmarshaller(clazz);
        if (clazz.isAnnotationPresent(XmlRootElement.class)) {
            return unmarshaller.unmarshal(source);
        } else {
            JAXBElement<? extends Object> jaxbElement = unmarshaller.unmarshal(source, clazz);
            return jaxbElement.getValue();
        }
    } catch (UnmarshalException ex) {
        throw new HttpMessageNotReadableException("Could not unmarshal to [" + clazz + "]: " + ex.getMessage(),
                ex);

    } catch (JAXBException ex) {
        throw new HttpMessageConversionException("Could not instantiate JAXBContext: " + ex.getMessage(), ex);
    }
}

From source file:org.castor.cpa.jpa.info.JPACallbackHandler.java

/**
 * Walks callbacks hierarchy accordingly.
 * //from  ww w.ja  v a  2 s .c o m
 * @param annotationClass
 *            the annotation to look for
 * @param object
 *            the object to walk hierarchy for
 * @param <A>
 *            helper annotation generics
 * @throws InvocationTargetException
 *             on callback invocation error
 * @throws IllegalAccessException
 *             on illegal method access error
 * @throws InstantiationException
 *             on instantiation error
 */
private <A extends Annotation> void walkCallbacksHierarchyFor(final Class<A> annotationClass,
        final Object object) throws InvocationTargetException, IllegalAccessException, InstantiationException {
    final Class<?> klass = object.getClass();
    if (klass.isAnnotationPresent(Entity.class)) {
        final Class<?> superclass = klass.getSuperclass();
        if (superclass != Object.class) {
            walkCallbacksHierarchyFor(annotationClass, superclass.newInstance());
        }
        if (!_excludeSuperclassListeners) {
            invokeListenerCallbacksFor(annotationClass, klass);
        }
        if (klass.isAnnotationPresent(ExcludeSuperclassListeners.class)) {
            _excludeSuperclassListeners = true;
        }
        _objectsToInvokeCallbacksOn.add(object);
    }
}