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.codehaus.enunciate.modules.xfire.EnunciatedJAXWSOperationBinding.java

/**
 * Loads the set of input properties for the specified operation.
 *
 * @param op The operation.//from w  ww  .  ja  v a2 s.  co  m
 * @return The input properties, or null if none were found.
 */
protected OperationBeanInfo getRequestInfo(OperationInfo op) throws XFireFault {
    Method method = op.getMethod();
    Class ei = method.getDeclaringClass();
    Package pckg = ei.getPackage();
    SOAPBinding.ParameterStyle paramStyle = SOAPBinding.ParameterStyle.WRAPPED;
    if (method.isAnnotationPresent(SOAPBinding.class)) {
        SOAPBinding annotation = method.getAnnotation(SOAPBinding.class);
        paramStyle = annotation.parameterStyle();
    } else if (ei.isAnnotationPresent(SOAPBinding.class)) {
        SOAPBinding annotation = ((SOAPBinding) ei.getAnnotation(SOAPBinding.class));
        paramStyle = annotation.parameterStyle();
    }

    boolean schemaValidate = method.isAnnotationPresent(SchemaValidate.class)
            || ei.isAnnotationPresent(SchemaValidate.class) || pckg.isAnnotationPresent(SchemaValidate.class);

    if (paramStyle == SOAPBinding.ParameterStyle.BARE) {
        //return a bare operation info.
        //it's not necessarily the first parameter type! there could be a header or OUT parameter...
        int paramIndex;
        WebParam annotation = null;
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        if (parameterAnnotations.length == 0) {
            throw new IllegalStateException("A BARE web service must have input parameters.");
        }

        PARAM_ANNOTATIONS: for (paramIndex = 0; paramIndex < parameterAnnotations.length; paramIndex++) {
            Annotation[] annotations = parameterAnnotations[paramIndex];
            for (Annotation candidate : annotations) {
                if (candidate instanceof WebParam && !((WebParam) candidate).header()) {
                    WebParam.Mode mode = ((WebParam) candidate).mode();
                    switch (mode) {
                    case OUT:
                    case INOUT:
                        annotation = (WebParam) candidate;
                        break PARAM_ANNOTATIONS;
                    }
                }
            }
        }

        if (annotation == null) {
            paramIndex = 0;
        }

        return new OperationBeanInfo(method.getParameterTypes()[paramIndex], null, op.getInputMessage(),
                schemaValidate);
    } else {
        String requestWrapperClassName;
        RequestWrapper requestWrapperInfo = method.getAnnotation(RequestWrapper.class);
        if ((requestWrapperInfo != null) && (requestWrapperInfo.className() != null)
                && (requestWrapperInfo.className().length() > 0)) {
            requestWrapperClassName = requestWrapperInfo.className();
        } else {
            StringBuilder builder = new StringBuilder(pckg == null ? "" : pckg.getName());
            if (builder.length() > 0) {
                builder.append(".");
            }

            builder.append("jaxws.");

            String methodName = method.getName();
            builder.append(capitalize(methodName));
            requestWrapperClassName = builder.toString();
        }

        Class wrapperClass;
        try {
            wrapperClass = ClassLoaderUtils.loadClass(requestWrapperClassName, getClass());
        } catch (ClassNotFoundException e) {
            LOG.error("Unabled to find request wrapper class " + requestWrapperClassName + "... Operation "
                    + op.getQName() + " will not be able to recieve...");
            return null;
        }

        return new OperationBeanInfo(wrapperClass, loadOrderedProperties(wrapperClass), op.getInputMessage(),
                schemaValidate);
    }

}

From source file:com.blackbear.flatworm.config.impl.DefaultAnnotationConfigurationReaderImpl.java

/**
 * Load the configuration for the specified Classes, but keep track of what is being requested for retry to avoid an infinite loop.
 *
 * @param lastRetryList The last set of classes that were marked for retry.
 * @param classes       The classes to process.
 * @return This is a convenience method to make it easy to assign the {@link FileFormat} constructed to the invoker of the {@code
 * loadConfiguration} call.//from w w  w.  j  av a  2 s .com
 * @throws FlatwormConfigurationException should any issues arise while parsing the annotated configuration.
 */
protected FileFormat loadConfiguration(List<Class<?>> lastRetryList, Collection<Class<?>> classes)
        throws FlatwormConfigurationException {
    List<Class<?>> classesToReprocess = new ArrayList<>();
    FlatwormConfigurationException lastException = null;

    for (Class<?> clazz : classes) {
        try {
            RecordBO recordBO = null;

            // Record Annotations.
            if (clazz.isAnnotationPresent(Record.class)) {
                recordBO = loadRecord(clazz.getAnnotation(Record.class));
                recordCache.put(clazz.getName(), recordBO);
                fileFormat.addRecord(recordBO);
            } else if (clazz.isAnnotationPresent(RecordLink.class)) {
                // See if we have loaded the RecordBO yet - if not, we'll need to try again later.
                Class<?> recordClass = loadRecordLinkClass(clazz.getAnnotation(RecordLink.class));
                if (recordCache.containsKey(recordClass.getName())) {
                    recordBO = recordCache.get(recordClass.getName());
                } else {
                    classesToReprocess.add(clazz);
                }
            }

            // We must always have a reference to the record - if we don't have it then we'll need to
            // reprocess the item later.
            if (recordBO != null) {
                // See what field-level annotations might exist.
                processFieldAnnotations(recordBO, clazz);
            }
        } catch (FlatwormConfigurationException e) {
            classesToReprocess.add(clazz);
            lastException = e;
        }
    }

    // See if we need to reprocess or kick-out.
    if (!classesToReprocess.isEmpty()) {
        if (isValidRetryList(lastRetryList, classesToReprocess)) {
            fileFormat = loadConfiguration(classesToReprocess, classesToReprocess);
        } else {
            String errMessage = "Unable to complete loading configuration as the following classes "
                    + "provided are not resolvable for a number of reasons. Ensure that all Records and RecordLinks are properly"
                    + " defined. All classes involved must either have a Record annotation or a RecordLink annotation."
                    + String.format("%n") + classesToReprocess.toString();
            if (lastException != null) {
                throw new FlatwormConfigurationException(errMessage, lastException);
            } else {
                throw new FlatwormConfigurationException(errMessage);
            }
        }
    }

    return fileFormat;
}

From source file:org.evosuite.setup.TestClusterGenerator.java

public static boolean canUse(Class<?> c) {
    //if (Throwable.class.isAssignableFrom(c))
    //   return false;
    if (Modifier.isPrivate(c.getModifiers()))
        return false;

    if (!Properties.USE_DEPRECATED && c.isAnnotationPresent(Deprecated.class)) {
        logger.debug("Skipping deprecated class {}", c.getName());
        return false;
    }//from w ww  .  j  a  v a 2 s  . c  o  m

    if (c.isAnonymousClass()) {
        return false;
    }

    if (ANONYMOUS_MATCHER1.matcher(c.getName()).matches()) {
        logger.debug("{} looks like an anonymous class, ignoring it", c);
        return false;
    }

    if (ANONYMOUS_MATCHER2.matcher(c.getName()).matches()) {
        logger.debug("{} looks like an anonymous class, ignoring it", c);
        return false;
    }

    if (c.getName().startsWith("junit"))
        return false;

    if (isEvoSuiteClass(c) && !MockList.isAMockClass(c.getCanonicalName())) {
        return false;
    }

    if (c.getEnclosingClass() != null) {
        if (!canUse(c.getEnclosingClass()))
            return false;
    }

    if (c.getDeclaringClass() != null) {
        if (!canUse(c.getDeclaringClass()))
            return false;
    }

    // If the SUT is not in the default package, then
    // we cannot import classes that are in the default
    // package
    if (!c.isArray() && !c.isPrimitive() && !Properties.CLASS_PREFIX.isEmpty() && !c.getName().contains(".")) {
        return false;
    }

    if (Modifier.isPublic(c.getModifiers())) {
        return true;
    }

    // If default access rights, then check if this class is in the same package as the target class
    if (!Modifier.isPrivate(c.getModifiers())) {
        //              && !Modifier.isProtected(c.getModifiers())) {
        String packageName = ClassUtils.getPackageName(c);
        if (packageName.equals(Properties.CLASS_PREFIX)) {
            return true;
        }
    }

    logger.debug("Not public");
    return false;
}

From source file:net.udidb.engine.ops.impls.help.HelpMessageProvider.java

@Inject
public HelpMessageProvider(@Named("OP_PACKAGES") String[] opPackages) {

    Set<URL> packages = new HashSet<>();
    for (String opPackage : opPackages) {
        packages.addAll(ClasspathHelper.forPackage(opPackage));
    }/*from ww w  . j  av  a2s.  c o m*/
    Reflections reflections = new Reflections(packages, new SubTypesScanner());
    for (Class<? extends Operation> opClass : reflections.getSubTypesOf(Operation.class)) {
        if (Modifier.isAbstract(opClass.getModifiers()))
            continue;

        HelpMessage[] helpMessages = opClass.getAnnotationsByType(HelpMessage.class);
        DisplayName displayName = opClass.getAnnotation(DisplayName.class);

        if (helpMessages.length == 0 || displayName == null) {
            throw new RuntimeException(opClass.getSimpleName() + " is an invalid Operation");
        }

        String name = displayName.value();

        HelpMessageDescriptor descriptor = new HelpMessageDescriptor();

        descriptor.global = opClass.isAnnotationPresent(GlobalOperation.class);
        descriptor.shortMessage = selectMessage(helpMessages);
        descriptor.longMessage = createLongMessage(name, descriptor.shortMessage, opClass);

        helpMessageDescriptors.put(name, descriptor);
    }
}

From source file:org.firebrandocm.dao.ClassMetadata.java

/**
 * Private Helper. Scans for named query annotations an initializes the named queries associated with this persistence factory
 *
 * @param target the target class//from ww w .  j  av a2s . c o  m
 */
private void initializeNamedQueries(Class<T> target) {
    List<NamedQuery> queries = new ArrayList<NamedQuery>();
    if (target.isAnnotationPresent(NamedQueries.class)) {
        NamedQuery[] value = target.getAnnotation(NamedQueries.class).value();
        for (int i = 0, valueLength = value.length; i < valueLength; i++) {
            NamedQuery namedQuery = value[i];
            queries.add(namedQuery);
        }
    }
    if (target.isAnnotationPresent(NamedQuery.class)) {
        queries.add(target.getAnnotation(NamedQuery.class));
    }
    for (NamedQuery query : queries) {
        if (namedQueries.containsKey(query.name())) {
            throw new IllegalStateException(String.format("Duplicated named query name: %s", query.name()));
        }
        namedQueries.put(query.name(), query.query());
    }
}

From source file:org.firebrandocm.dao.ClassMeta.java

/**
     * Private Helper. Scans for named query annotations an initializes the named queries associated with this persistence factory
     */*from w  ww.  ja v  a 2 s  . com*/
     * @param target the target class
     */
    private void initializeNamedQueries(Class<T> target) {
        List<NamedQuery> queries = new ArrayList<NamedQuery>();
        if (target.isAnnotationPresent(NamedQueries.class)) {
            NamedQuery[] value = target.getAnnotation(NamedQueries.class).value();
            for (int i = 0, valueLength = value.length; i < valueLength; i++) {
                NamedQuery namedQuery = value[i];
                queries.add(namedQuery);
            }
        }
        if (target.isAnnotationPresent(NamedQuery.class)) {
            queries.add(target.getAnnotation(NamedQuery.class));
        }
        for (NamedQuery query : queries) {
            if (namedQueries.containsKey(query.name())) {
                throw new IllegalStateException(String.format("Duplicated named query name: %s", query.name()));
            }
            namedQueries.put(query.name(), query.query());
        }
    }

From source file:com.blackbear.flatworm.config.impl.DefaultAnnotationConfigurationReaderImpl.java

/**
 * Load the {@link SegmentElement} metadata and associated {@link RecordElement} data (and so on) for the given {@code Field} within the
 * given {@code clazz}. Due to the tree-like structure of {@link SegmentElementBO} instances, this could result in several recursive
 * calls as the bean tree is traversed. This will add the {@link SegmentElementBO} instance to the {@link LineBO} referenced within the
 * {@link SegmentElement} annotation.//w  w w  . j  a v  a 2s  .  c  om
 *
 * @param clazz The class instance that owns the {@code field}.
 * @param field The {@code field} that has the {@link SegmentElement} annotation.
 * @return a constructed {@link SegmentElementBO} instance from the data found within the {@link SegmentElement} annotation.
 * @throws FlatwormConfigurationException should the annotated metadata prove invalid.
 */
public SegmentElementBO loadSegment(Class<?> clazz, Field field) throws FlatwormConfigurationException {
    SegmentElementBO segmentElementBO = new SegmentElementBO();
    SegmentElement annotatedElement = field.getAnnotation(SegmentElement.class);

    LineBO line = lineCache.get(annotatedElement.lineIndex());
    LineElementCollection elementCollection = lineElementDeque.isEmpty() ? line : lineElementDeque.getLast();
    elementCollection.addLineElement(segmentElementBO);

    Class<?> fieldType = Util.getActualFieldType(field);

    // Need to see if this is a collection or a single attributes.
    if (fieldType != null) {
        if (fieldType.isAnnotationPresent(RecordLink.class) || fieldType.isAnnotationPresent(Record.class)) {
            lineElementDeque.add(segmentElementBO);
            FieldIdentityImpl fieldIdentity = loadFieldIdentity(annotatedElement.fieldIdentity());
            segmentElementBO.setOrder(annotatedElement.order());
            segmentElementBO.setFieldIdentity(fieldIdentity);

            CardinalityBO cardinality;
            if (Collection.class.isAssignableFrom(field.getType()) || field.getType().isArray()) {
                segmentElementBO.setCardinality(loadCardinality(annotatedElement.cardinality()));

            } else {
                // This is a singular instance.
                cardinality = new CardinalityBO();
                cardinality.setMinCount(Integer.MIN_VALUE);
                cardinality.setMaxCount(Integer.MAX_VALUE);
                cardinality.setCardinalityMode(CardinalityMode.SINGLE);
            }

            cardinality = segmentElementBO.getCardinality();
            cardinality.setParentBeanRef(clazz.getName());
            cardinality.setPropertyName(field.getName());
            cardinality.setBeanRef(fieldType.getName());

            loadConfiguration(fieldType);
            lineElementDeque.removeLast();
        } else {
            throw new FlatwormConfigurationException(String.format(
                    "Class %s has a %s defined with type %s, which must have a %s or %s annotation.",
                    clazz.getName(), SegmentElement.class.getName(), fieldType.getName(),
                    RecordLink.class.getName(), Record.class.getName()));
        }
    }

    return segmentElementBO;
}

From source file:org.nuxeo.functionaltests.AbstractTest.java

/**
 * Fills an instantiated page/form/widget attributes
 *
 * @since 5.7/*www .  j  a  v a  2  s  .co  m*/
 */
public static <T> T fillElement(Class<T> pageClassToProxy, T page) {
    PageFactory.initElements(new VariableElementLocatorFactory(driver, AJAX_TIMEOUT_SECONDS), page);
    // check all required WebElements on the page and wait for their
    // loading
    final List<String> fieldNames = new ArrayList<>();
    final List<WrapsElement> elements = new ArrayList<>();
    for (Field field : pageClassToProxy.getDeclaredFields()) {
        if (field.getAnnotation(Required.class) != null) {
            try {
                field.setAccessible(true);
                fieldNames.add(field.getName());
                elements.add((WrapsElement) field.get(page));
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }

    Wait<T> wait = new FluentWait<>(page).withTimeout(LOAD_TIMEOUT_SECONDS, TimeUnit.SECONDS)
            .pollingEvery(POLLING_FREQUENCY_MILLISECONDS, TimeUnit.MILLISECONDS);
    try {
        return wait.until(aPage -> {
            String notLoaded = anyElementNotLoaded(elements, fieldNames);
            if (notLoaded == null) {
                // check if there are Jquery ajax requests to complete
                if (pageClassToProxy.isAnnotationPresent(WaitForJQueryAjaxOnLoading.class)) {
                    new AjaxRequestManager(driver).waitForJQueryRequests();
                }

                return aPage;
            } else {
                return null;
            }
        });
    } catch (TimeoutException e) {
        throw new TimeoutException("not loaded: " + anyElementNotLoaded(elements, fieldNames), e);
    }
}

From source file:org.artifactory.spring.ArtifactoryApplicationContext.java

private void orderReloadableBeans(Set<Class<? extends ReloadableBean>> beansLeftToInit,
        Class<? extends ReloadableBean> beanClass) {
    if (!beansLeftToInit.contains(beanClass)) {
        // Already done
        return;/*from  w  w w. ja  v a2 s .  co  m*/
    }
    ReloadableBean initializingBean = beanForType(beanClass);
    Class<?> targetClass = AopUtils.getTargetClass(initializingBean);
    Reloadable annotation;
    if (targetClass.isAnnotationPresent(Reloadable.class)) {
        annotation = targetClass.getAnnotation(Reloadable.class);
    } else {
        throw new IllegalStateException(
                "Bean " + targetClass.getName() + " requires the @Reloadable annotation to be present.");
    }
    Class<? extends ReloadableBean>[] dependsUpon = annotation.initAfter();
    for (Class<? extends ReloadableBean> doBefore : dependsUpon) {
        //Sanity check that prerequisite bean was registered
        if (!toInitialize.contains(doBefore)) {
            throw new IllegalStateException("Bean '" + beanClass.getName() + "' requires bean '"
                    + doBefore.getName() + "' to be initialized, but no such bean is registered for init.");
        }
        if (!doBefore.isInterface()) {
            throw new IllegalStateException("Cannot order bean with implementation class.\n"
                    + " Please provide an interface extending " + ReloadableBean.class.getName());
        }
        orderReloadableBeans(beansLeftToInit, doBefore);
    }
    // Avoid double init
    if (beansLeftToInit.remove(beanClass)) {
        reloadableBeans.add(initializingBean);
    }
}

From source file:com.opensymphony.xwork2.util.finder.ClassFinder.java

public List<Class> findAnnotatedClasses(Class<? extends Annotation> annotation) {
    classesNotLoaded.clear();// w  w w . java  2  s.c om
    List<Class> classes = new ArrayList<Class>();
    List<Info> infos = getAnnotationInfos(annotation.getName());
    for (Info info : infos) {
        if (info instanceof ClassInfo) {
            ClassInfo classInfo = (ClassInfo) info;
            try {
                Class clazz = classInfo.get();
                // double check via proper reflection
                if (clazz.isAnnotationPresent(annotation)) {
                    classes.add(clazz);
                }
            } catch (Throwable e) {
                if (LOG.isErrorEnabled())
                    LOG.error("Error loading class [#0]", e, classInfo.getName());
                classesNotLoaded.add(classInfo.getName());
            }
        }
    }
    return classes;
}