Example usage for java.lang.reflect Method isAnnotationPresent

List of usage examples for java.lang.reflect Method isAnnotationPresent

Introduction

In this page you can find the example usage for java.lang.reflect Method isAnnotationPresent.

Prototype

@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 

Source Link

Usage

From source file:cn.wanghaomiao.seimi.core.SeimiProcessor.java

@Override
public void run() {
    while (true) {
        Request request = null;/*  w w  w  .j a v  a  2s .co  m*/
        try {
            request = queue.bPop(crawlerModel.getCrawlerName());
            if (request == null) {
                continue;
            }
            if (crawlerModel == null) {
                logger.error("No such crawler name:'{}'", request.getCrawlerName());
                continue;
            }
            if (request.isStop()) {
                logger.info("SeimiProcessor[{}] will stop!", Thread.currentThread().getName());
                break;
            }
            //
            if (!StructValidator.validateAnno(request)) {
                logger.warn("Request={} is illegal", JSON.toJSONString(request));
                continue;
            }
            if (!StructValidator.validateAllowRules(crawler.allowRules(), request.getUrl())) {
                logger.warn("Request={} will be dropped by allowRules=[{}]", JSON.toJSONString(request),
                        StringUtils.join(crawler.allowRules(), ","));
                continue;
            }
            if (StructValidator.validateDenyRules(crawler.denyRules(), request.getUrl())) {
                logger.warn("Request={} will be dropped by denyRules=[{}]", JSON.toJSONString(request),
                        StringUtils.join(crawler.denyRules(), ","));
                continue;
            }
            //???Request???
            if (request.getCurrentReqCount() >= request.getMaxReqCount()) {
                continue;
            }
            if (!request.isSkipDuplicateFilter() && crawlerModel.isUseUnrepeated() && queue.isProcessed(request)
                    && request.getCurrentReqCount() == 0) {
                logger.info("This request has bean processed,so current request={} will be dropped!",
                        JSON.toJSONString(request));
                continue;
            }
            queue.addProcessed(request);
            HttpClient hc;
            if (crawlerModel.isUseCookie()) {
                hc = HttpClientFactory.getHttpClient(10000, crawler.getCookieStore());
            } else {
                hc = HttpClientFactory.getHttpClient();
            }
            RequestBuilder requestBuilder = RequestGenerator.getHttpRequestBuilder(request, crawlerModel);

            HttpContext httpContext = new BasicHttpContext();
            HttpResponse httpResponse = hc.execute(requestBuilder.build(), httpContext);
            Response seimiResponse = renderResponse(httpResponse, request, httpContext);
            Matcher mm = metaRefresh.matcher(seimiResponse.getContent());
            int refreshCount = 0;
            while (!request.isUseSeimiAgent() && mm.find() && refreshCount < 3) {
                String nextUrl = mm.group(1).replaceAll("'", "");
                if (!nextUrl.startsWith("http")) {
                    String prefix = getRealUrl(httpContext);
                    nextUrl = prefix + nextUrl;
                }
                logger.info("Seimi refresh url to={} from={}", nextUrl, requestBuilder.getUri());
                requestBuilder.setUri(nextUrl);
                httpResponse = hc.execute(requestBuilder.build(), httpContext);
                seimiResponse = renderResponse(httpResponse, request, httpContext);
                mm = metaRefresh.matcher(seimiResponse.getContent());
                refreshCount += 1;
            }

            Method requestCallback = crawlerModel.getMemberMethods().get(request.getCallBack());
            if (requestCallback == null) {
                continue;
            }
            for (SeimiInterceptor interceptor : interceptors) {
                Interceptor interAnno = interceptor.getClass().getAnnotation(Interceptor.class);
                if (interAnno.everyMethod()
                        || requestCallback.isAnnotationPresent(interceptor.getTargetAnnotationClass())
                        || crawlerModel.getClazz()
                                .isAnnotationPresent(interceptor.getTargetAnnotationClass())) {
                    interceptor.before(requestCallback, seimiResponse);
                }
            }
            if (crawlerModel.getDelay() > 0) {
                TimeUnit.SECONDS.sleep(crawlerModel.getDelay());
            }
            requestCallback.invoke(crawlerModel.getInstance(), seimiResponse);
            for (SeimiInterceptor interceptor : interceptors) {
                Interceptor interAnno = interceptor.getClass().getAnnotation(Interceptor.class);
                if (interAnno.everyMethod()
                        || requestCallback.isAnnotationPresent(interceptor.getTargetAnnotationClass())
                        || crawlerModel.getClazz()
                                .isAnnotationPresent(interceptor.getTargetAnnotationClass())) {
                    interceptor.after(requestCallback, seimiResponse);
                }
            }
            logger.debug("Crawler[{}] ,url={} ,responseStatus={}", crawlerModel.getCrawlerName(),
                    request.getUrl(), httpResponse.getStatusLine().getStatusCode());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            if (request == null) {
                continue;
            }
            if (request.getCurrentReqCount() < request.getMaxReqCount()) {
                request.incrReqCount();
                queue.push(request);
                logger.info(
                        "Request process error,req will go into queue again,url={},maxReqCount={},currentReqCount={}",
                        request.getUrl(), request.getMaxReqCount(), request.getCurrentReqCount());
            } else if (request.getCurrentReqCount() >= request.getMaxReqCount()
                    && request.getMaxReqCount() > 0) {
                crawler.handleErrorRequest(request);
            }

        }
    }
}

From source file:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java

private ValueGenerationType determineValueGenerationType(Method method) {
    if (method.isAnnotationPresent(GeneratedValue.class)) {
        final GeneratedValue generatedValue = method.getAnnotation(GeneratedValue.class);
        return generatedValue.strategy().equals(GenerationType.AUTO) ? dialect.getDefaultGenerationType()
                : (generatedValue.strategy().equals(GenerationType.IDENTITY) ? ValueGenerationType.IDENTITY
                        : (generatedValue.strategy().equals(GenerationType.SEQUENCE)
                                ? ValueGenerationType.SEQUENCE
                                : (generatedValue.strategy().equals(GenerationType.TABLE)
                                        ? ValueGenerationType.TABLE
                                        : null)));
    } else {//from w  w w  .  j a  va  2 s.  c  o  m
        return null;
    }
}

From source file:nz.co.senanque.vaadinsupport.MaduraPropertyWrapper.java

public MaduraPropertyWrapper(String name, ValidationObject owner, Method setter, Method getter, Hints hints,
        MessageSource messageSource) {//from   w  ww .j  a v a  2s  .  c om
    m_name = name;
    m_label = name;
    m_writePermission = null;
    m_description = null;
    m_hints = hints;
    m_setter = setter;
    m_getter = getter;
    m_owner = owner;
    m_dataType = setter.getParameterTypes()[0];
    m_fieldMetadata = null;
    figureFormattedProperty();
    m_messageSource = messageSource;
    m_email = getter.isAnnotationPresent(Email.class);
}

From source file:org.springmodules.xt.model.generator.factory.FactoryGeneratorInterceptor.java

private Object putConstructorArg(final Object[] args, final Method method) {
    if (args.length != 1) {
        throw new IllegalStateException(
                "The setter method " + method.getName() + " must have only one argument!");
    } else {/*from w  w w.  j  a v  a2 s .c o  m*/
        String name = StringUtils.uncapitalize(method.getName().substring(3));
        ConstructorArg annotation = method.getAnnotation(ConstructorArg.class);
        int position = annotation.position();
        Class type = null;
        if (method.isAnnotationPresent(ConstructorArgType.class)) {
            type = method.getAnnotation(ConstructorArgType.class).type();
        } else {
            type = args[0].getClass();
        }
        ConstructorArgPair pair = new ConstructorArgPair();
        pair.setValue(args[0]);
        pair.setType(type);
        this.constructorArgs.put(position, pair);
        this.values.put(name, args[0]);
        logger.debug(new StringBuilder("Put constructor arg with position and value: ").append(position)
                .append(",").append(args[0]));
        return null;
    }
}

From source file:uk.ac.imperial.presage2.core.simulator.RunnableSimulation.java

private void findScheduleFunctions(Object o, Set<Pair<Method, Object>> initialisors,
        Set<Pair<Method, Object>> presteppers, Set<Pair<Method, Object>> steppers,
        Set<Pair<Method, Object>> finalisors, Set<Pair<Method, Object>> finishConditions) {
    boolean foundFunction = false;
    for (Method m : o.getClass().getMethods()) {
        if (m.isAnnotationPresent(Initialisor.class)) {
            if (m.getParameterTypes().length != 0) {
                throw new RuntimeException(
                        "Initialisor function cannot take arguments. @Initialisor annotated function "
                                + m.getName() + " takes " + m.getParameterTypes().length);
            }/*from ww w . java  2 s  . c om*/
            initialisors.add(Pair.of(m, o));
            foundFunction = true;
        } else if (m.isAnnotationPresent(PreStep.class)) {
            Class<?>[] paramTypes = m.getParameterTypes();
            boolean valid = paramTypes.length == 0;
            valid |= (paramTypes.length == 1 && paramTypes[0] == Integer.TYPE);
            if (!valid) {
                throw new RuntimeException(
                        "Step function may only take one integer arugment. @PreStep annotated function "
                                + m.getName() + " takes " + m.getParameterTypes().length + " of types: "
                                + Arrays.toString(paramTypes));
            }
            presteppers.add(Pair.of(m, o));
            foundFunction = true;
        } else if (m.isAnnotationPresent(Step.class)) {
            Class<?>[] paramTypes = m.getParameterTypes();
            boolean valid = paramTypes.length == 0;
            valid |= (paramTypes.length == 1 && paramTypes[0] == Integer.TYPE);
            if (!valid) {
                throw new RuntimeException(
                        "Step function may only take one integer arugment. @Step annotated function "
                                + m.getName() + " takes " + m.getParameterTypes().length + " of types: "
                                + Arrays.toString(paramTypes));
            }
            steppers.add(Pair.of(m, o));
            foundFunction = true;
        } else if (m.isAnnotationPresent(Finalisor.class)) {
            if (m.getParameterTypes().length != 0) {
                throw new RuntimeException(
                        "Finalisor function cannot take arguments. @Finalisor annotated function " + m.getName()
                                + " takes " + m.getParameterTypes().length);
            }
            finalisors.add(Pair.of(m, o));
            foundFunction = true;
        } else if (m.isAnnotationPresent(FinishCondition.class)) {
            Class<?>[] paramTypes = m.getParameterTypes();
            boolean valid = paramTypes.length == 0;
            valid |= (paramTypes.length == 1 && paramTypes[0] == Integer.TYPE);
            valid &= m.getReturnType() == Boolean.TYPE;
            if (!valid) {
                throw new RuntimeException(
                        "FinishCondition function may only take one integer argument and must return a boolean. "
                                + "@Step annotated function " + m.getName() + " takes "
                                + m.getParameterTypes().length + " of types: " + Arrays.toString(paramTypes)
                                + " and returns " + m.getReturnType());
            }
            finishConditions.add(Pair.of(m, o));
            foundFunction = true;
        }
    }
    // legacy support for TimeDriven
    if (o instanceof TimeDriven) {
        try {
            steppers.add(Pair.of(TimeDriven.class.getMethod("incrementTime"), o));
            foundFunction = true;
        } catch (NoSuchMethodException e) {
            throw new RuntimeException("Couldn't find incrementTime in TimeDriven!?", e);
        }
    }

    if (!foundFunction) {
        logger.warn("No candidate function found in object " + o);
    } else {
        newObjects = true;
    }
}

From source file:com.googlecode.jdbcproc.daofactory.impl.block.service.ParametersSetterBlockServiceImpl.java

private boolean isMetaLoginInfoPresented(Method aMethod) {
    return aMethod.isAnnotationPresent(AMetaLoginInfo.class);
}

From source file:com.googlecode.jdbcproc.daofactory.impl.block.service.ParametersSetterBlockServiceImpl.java

private boolean isConsumerKeyPresented(Method aMethod) {
    return aMethod.isAnnotationPresent(AConsumerKey.class);
}

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

/**
 * Private Helper./*from  w  w w  .ja  va 2  s . co m*/
 * Processes a method scanning for persistence annotations
 *
 * @param method the method
 */
private void processMethod(Method method) {
    if (method.isAnnotationPresent(OnEvent.class)) {
        OnEvent onEvent = method.getAnnotation(OnEvent.class);
        Set<Method> methods = entityEventListenersMap.get(onEvent.value());
        if (methods == null) {
            methods = new LinkedHashSet<Method>();
            entityEventListenersMap.put(onEvent.value(), methods);
        }
        methods.add(method);
    }
}

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

/**
     * Private Helper./*from   w  w  w  . j a  v  a  2 s  .c  om*/
     * Processes a method scanning for persistence annotations
     *
     * @param method the method
     */
    private void processMethod(Method method) {
        if (method.isAnnotationPresent(OnEvent.class)) {
            OnEvent onEvent = method.getAnnotation(OnEvent.class);
            Set<Method> methods = entityEventListenersMap.get(onEvent.value());
            if (methods == null) {
                methods = new LinkedHashSet<Method>();
                entityEventListenersMap.put(onEvent.value(), methods);
            }
            methods.add(method);
        }
    }

From source file:com.evolveum.midpoint.prism.marshaller.PrismBeanInspector.java

private boolean isAttributeUncached(Field field, Method getter) {
    if (field == null && getter == null) {
        return false;
    } else {/*from ww  w . j a va2 s . co  m*/
        return field != null && field.isAnnotationPresent(XmlAttribute.class)
                || getter != null && getter.isAnnotationPresent(XmlAttribute.class);
    }
}