org.junit.runners.Suite#java.lang.annotation.Annotation源码实例Demo

下面列出了org.junit.runners.Suite#java.lang.annotation.Annotation 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: jadira   文件: BasicBinder.java
private <S, T> Converter<S, T> determineConverter(Class<S> candidateClass, Class<T> output, Class<? extends Annotation> qualifier) {
	
	if (!candidateClass.equals(Object.class)) {
		Converter<S, T> match = findConverter(candidateClass, output, qualifier);
		if (match != null) {
			return match;
		}

		@SuppressWarnings("unchecked")	
		Class<S>[] interfaces = (Class<S>[])candidateClass.getInterfaces();
		for (Class<S> candidateInterface : interfaces) {
			match = determineConverter(candidateInterface, output, qualifier);
			if (match != null) {
				return match;
			}	
		}
		
		Class<? super S> superClass = (Class<? super S>)candidateClass.getSuperclass();
		
		@SuppressWarnings("unchecked")
		Converter<S,T> superMatch = (Converter<S, T>) determineConverter(superClass, output, qualifier);
		return superMatch;
	} else {
		return null;
	}
}
 
/**
 * Build an adapted {@link AnnotatedElement} for the given annotations,
 * typically for use with other methods on {@link AnnotatedElementUtils}.
 * @param annotations the annotations to expose through the {@code AnnotatedElement}
 * @since 4.3
 */
public static AnnotatedElement forAnnotations(final Annotation... annotations) {
	return new AnnotatedElement() {
		@Override
		@SuppressWarnings("unchecked")
		@Nullable
		public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
			for (Annotation ann : annotations) {
				if (ann.annotationType() == annotationClass) {
					return (T) ann;
				}
			}
			return null;
		}
		@Override
		public Annotation[] getAnnotations() {
			return annotations;
		}
		@Override
		public Annotation[] getDeclaredAnnotations() {
			return annotations;
		}
	};
}
 
源代码3 项目: mango   文件: DefaultParameterContextTest.java
@Test
public void testTryExpandBindingParameter() throws Exception {
  List<Annotation> empty = Collections.emptyList();
  ParameterDescriptor p0 = ParameterDescriptor.create(0, String.class, empty, "1");
  ParameterDescriptor p1 = ParameterDescriptor.create(1, User.class, empty, "2");
  List<ParameterDescriptor> pds = Arrays.asList(p0, p1);

  ParameterContext ctx = DefaultParameterContext.create(pds);

  BindingParameter bp = BindingParameter.create("userBag", "item.itemId", null);
  BindingParameter nbp = ctx.tryExpandBindingParameter(bp);

  bp = BindingParameter.create("userId", "", null);
  nbp = ctx.tryExpandBindingParameter(bp);
  assertThat(nbp, equalTo(BindingParameter.create("2", "userId", null)));

  bp = BindingParameter.create("userIds", "", null);
  nbp = ctx.tryExpandBindingParameter(bp);
  assertThat(nbp, nullValue());
}
 
@SuppressWarnings({"unchecked", "PMD.AvoidInstantiatingObjectsInLoops"})
private static MatchedMethod analyzeMethod(final Method method, final List<Class<?>> params,
                                           final GenericsContext targetGenerics) {
    final List<ParamInfo> ordinalParamsInfo = Lists.newArrayList();
    final List<Class<?>> types = targetGenerics.method(method).resolveParameters();
    final Annotation[][] annotations = method.getParameterAnnotations();
    boolean extended = false;
    for (int i = 0; i < types.size(); i++) {
        // ignore extensions (they always add value)
        try {
            if (ExtUtils.findParameterExtension(annotations[i]) == null) {
                ordinalParamsInfo.add(new ParamInfo(i, types.get(i)));
            } else {
                extended = true;
            }
        } catch (Exception ex) {
            throw new IllegalStateException(String.format("Error analysing method %s parameter %s",
                    RepositoryUtils.methodToString(method), i), ex);
        }
    }
    MatchedMethod res = null;
    if (isParametersCompatible(params, ordinalParamsInfo)) {
        res = new MatchedMethod(method, ordinalParamsInfo, extended);
    }
    return res;
}
 
private Integer getIndexOfAnnotatedParam(final Method method, final Class<? extends Annotation> annotationClass) {
    final Annotation[][] paramAnnotationArrays = method.getParameterAnnotations();
    Integer foundIndex = null;

    if (paramAnnotationArrays != null && paramAnnotationArrays.length > 0) {
        for (int ix = 0; ix < paramAnnotationArrays.length; ix++) {
            if (getAnnotation(annotationClass, paramAnnotationArrays[ix]) != null) {
                if (foundIndex != null) {
                    throwException("Multiple annotations of type [%s] found on method [%s]", annotationClass, method);
                }
                foundIndex = ix;
            }
        }
    }

    return foundIndex;
}
 
源代码6 项目: openjdk-8   文件: ExternalMetadataReader.java
public Annotation[][] getParameterAnnotations(final Method m) {
    Merger<Annotation[][]> merger = new Merger<Annotation[][]>(reader(m.getDeclaringClass())) {
        Annotation[][] reflection() {
            return ExternalMetadataReader.super.getParameterAnnotations(m);
        }

        Annotation[][] external() {
            JavaMethod jm = getJavaMethod(m, reader);
            Annotation[][] a = m.getParameterAnnotations();
            for (int i = 0; i < m.getParameterTypes().length; i++) {
                if (jm == null) continue;
                JavaParam jp = jm.getJavaParams().getJavaParam().get(i);
                a[i] = getAnnotations(jp.getParamAnnotation());
            }
            return a;
        }
    };
    return merger.merge();
}
 
源代码7 项目: restcommander   文件: FileBinder.java
@SuppressWarnings("unchecked")
public File bind(String name, Annotation[] annotations, String value, Class actualClass, Type genericType) {
    if (value == null || value.trim().length() == 0) {
        return null;
    }
    List<Upload> uploads = (List<Upload>) Request.current().args.get("__UPLOADS");
    for (Upload upload : uploads) {
        if (upload.getFieldName().equals(value)) {
            File file = upload.asFile();
            if (file.length() > 0) {
                return file;
            }
            return null;
        }
    }
    return null;
}
 
源代码8 项目: cxf   文件: MultipartProvider.java
private <T> Object fromAttachment(Attachment multipart, Class<T> c, Type t, Annotation[] anns)
    throws IOException {
    if (DataHandler.class.isAssignableFrom(c)) {
        return multipart.getDataHandler();
    } else if (DataSource.class.isAssignableFrom(c)) {
        return multipart.getDataHandler().getDataSource();
    } else if (Attachment.class.isAssignableFrom(c)) {
        return multipart;
    } else {
        if (mediaTypeSupported(multipart.getContentType())) {
            mc.put("org.apache.cxf.multipart.embedded", true);
            mc.put("org.apache.cxf.multipart.embedded.ctype", multipart.getContentType());
            mc.put("org.apache.cxf.multipart.embedded.input",
                   multipart.getDataHandler().getInputStream());
            anns = new Annotation[]{};
        }
        MessageBodyReader<T> r =
            mc.getProviders().getMessageBodyReader(c, t, anns, multipart.getContentType());
        if (r != null) {
            InputStream is = multipart.getDataHandler().getInputStream();
            return r.readFrom(c, t, anns, multipart.getContentType(), multipart.getHeaders(),
                              is);
        }
    }
    return null;
}
 
源代码9 项目: grpc-java-contrib   文件: GrpcServerHost.java
private Collection<BindableService> getServicesFromApplicationContext() {
    Map<String, Object> possibleServices = new HashMap<>();

    for (Class<? extends Annotation> annotation : serverFactory.forAnnotations()) {
        possibleServices.putAll(applicationContext.getBeansWithAnnotation(annotation));
    }

    Collection<String> invalidServiceNames = possibleServices.entrySet().stream()
            .filter(e -> !(e.getValue() instanceof BindableService))
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());

    if (!invalidServiceNames.isEmpty()) {
        throw new IllegalStateException((format(
                "The following beans are annotated with @GrpcService, but are not BindableServices: %s",
                String.join(", ", invalidServiceNames))));
    }

    return possibleServices.values().stream().map(s -> (BindableService) s).collect(Collectors.toList());
}
 
源代码10 项目: servicetalk   文件: RouteExecutionStrategyUtils.java
/**
 * Returns {@link ExecutionStrategy} for the specified {@link Method} and validates that configuration of
 * {@link RouteExecutionStrategy} annotation is correct if present.
 *
 * @param method {@link Method} to validate
 * @param clazz {@link Class} to validate
 * @param strategyFactory a {@link RouteExecutionStrategyFactory} that creates a specific{@link ExecutionStrategy}
 * @param errors collection to track all errors related to misconfiguration
 * @param noOffloadsExecutionStrategy an {@link ExecutionStrategy} for {@link NoOffloadsRouteExecutionStrategy}
 * @param <T> specific implementation type of {@link ExecutionStrategy}
 * @return a defined {@link ExecutionStrategy} or {@code null} if not defined
 */
@Nullable
public static <T extends ExecutionStrategy> T getAndValidateRouteExecutionStrategyAnnotationIfPresent(
        final Method method,
        final Class<?> clazz,
        final RouteExecutionStrategyFactory<T> strategyFactory,
        final Set<String> errors,
        final T noOffloadsExecutionStrategy) {

    final Annotation annotation = validateAnnotation(method, clazz, errors);
    if (annotation == null) {
        return null;
    }

    if (annotation instanceof NoOffloadsRouteExecutionStrategy) {
        return noOffloadsExecutionStrategy;
    }

    return validateId(annotation, method, strategyFactory, errors);
}
 
源代码11 项目: servicetalk   文件: RouteExecutionStrategyUtils.java
/**
 * Returns {@link RouteExecutionStrategy} annotation if exists on {@link Method} or {@link Class}.
 *
 * @param method an endpoint method
 * @param clazz an endpoint class
 * @return {@link RouteExecutionStrategy} annotation if exists on {@link Method} or {@link Class}
 */
@Nullable
public static Annotation getRouteExecutionStrategyAnnotation(final Method method, final Class<?> clazz) {
    Annotation annotation = method.getAnnotation(NoOffloadsRouteExecutionStrategy.class);
    if (annotation != null) {
        return annotation;
    }
    annotation = method.getAnnotation(RouteExecutionStrategy.class);
    if (annotation != null) {
        return annotation;
    }
    annotation = clazz.getAnnotation(NoOffloadsRouteExecutionStrategy.class);
    if (annotation != null) {
        return annotation;
    }
    return clazz.getAnnotation(RouteExecutionStrategy.class);
}
 
源代码12 项目: jdk8u60   文件: NativeHeaderTest.java
/** Combo test to run all test cases in all modes. */
void run() throws Exception {
    javac = JavacTool.create();
    fm = javac.getStandardFileManager(null, null, null);

    for (RunKind rk: RunKind.values()) {
        for (GenKind gk: GenKind.values()) {
            for (Method m: getClass().getDeclaredMethods()) {
                Annotation a = m.getAnnotation(Test.class);
                if (a != null) {
                    init(rk, gk, m.getName());
                    try {
                        m.invoke(this, new Object[] { rk, gk });
                    } catch (InvocationTargetException e) {
                        Throwable cause = e.getCause();
                        throw (cause instanceof Exception) ? ((Exception) cause) : e;
                    }
                    System.err.println();
                }
            }
        }
    }
    System.err.println(testCount + " tests" + ((errorCount == 0) ? "" : ", " + errorCount + " errors"));
    if (errorCount > 0)
        throw new Exception(errorCount + " errors found");
}
 
源代码13 项目: boost   文件: PropertiesReader.java
@Override
public Properties readFrom(Class<Properties> type, Type genericType, Annotation[] annotations, MediaType mediaType,
        MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
        throws IOException, WebApplicationException {

    JsonReader jr = Json.createReader(entityStream);
    JsonObject json = jr.readObject();
    Properties retVal = new Properties();

    json.keySet().forEach(key -> {
        JsonValue value = json.get(key);
        if (!JsonValue.NULL.equals(value)) {
            if (value.getValueType() != JsonValue.ValueType.STRING) {
                throw new IllegalArgumentException(
                        "Non-String JSON prop value found in payload.  Sample data is more than this sample can deal with.  It's not intended to handle any payload.");
            }
            JsonString jstr = (JsonString) value;

            retVal.setProperty(key, jstr.getString());
        }
    });
    return retVal;
}
 
源代码14 项目: es   文件: PageableMethodArgumentResolver.java
/**
 * Asserts that every {@link Pageable} parameter of the given parameters carries an {@link org.springframework.beans.factory.annotation.Qualifier} annotation to
 * distinguish them from each other.
 *
 * @param parameterTypes
 * @param annotations
 */
private void assertQualifiersFor(Class<?>[] parameterTypes, Annotation[][] annotations) {

    Set<String> values = new HashSet<String>();

    for (int i = 0; i < annotations.length; i++) {

        if (Pageable.class.equals(parameterTypes[i])) {

            Qualifier qualifier = findAnnotation(annotations[i]);

            if (null == qualifier) {
                throw new IllegalStateException(
                        "Ambiguous Pageable arguments in handler method. If you use multiple parameters of type Pageable you need to qualify them with @Qualifier");
            }

            if (values.contains(qualifier.value())) {
                throw new IllegalStateException("Values of the user Qualifiers must be unique!");
            }

            values.add(qualifier.value());
        }
    }
}
 
源代码15 项目: openjdk-jdk8u-backup   文件: NativeHeaderTest.java
/** Combo test to run all test cases in all modes. */
void run() throws Exception {
    javac = JavacTool.create();
    fm = javac.getStandardFileManager(null, null, null);

    for (RunKind rk: RunKind.values()) {
        for (GenKind gk: GenKind.values()) {
            for (Method m: getClass().getDeclaredMethods()) {
                Annotation a = m.getAnnotation(Test.class);
                if (a != null) {
                    init(rk, gk, m.getName());
                    try {
                        m.invoke(this, new Object[] { rk, gk });
                    } catch (InvocationTargetException e) {
                        Throwable cause = e.getCause();
                        throw (cause instanceof Exception) ? ((Exception) cause) : e;
                    }
                    System.err.println();
                }
            }
        }
    }
    System.err.println(testCount + " tests" + ((errorCount == 0) ? "" : ", " + errorCount + " errors"));
    if (errorCount > 0)
        throw new Exception(errorCount + " errors found");
}
 
源代码16 项目: TarsJava   文件: TarsInvokeContext.java
@SuppressWarnings("unchecked")
public TarsInvokeContext(Method method, Object[] arguments, Map<String, String> attachments) {
    super(method, arguments, attachments);

    Annotation[][] as = method.getParameterAnnotations();
    for (int i = 0, length = as.length; i < length; i++) {
        if (TarsHelper.isContext(as[i])) {
            getAttachments().putAll((Map<String, String>) arguments[i]);
        }
    }
}
 
源代码17 项目: javageci   文件: GeciAnnotationTools.java
private static String geParam(Annotation annotation, Method method) {
    try {
        method.setAccessible(true);
        return (String) method.invoke(annotation);
    } catch (IllegalAccessException | InvocationTargetException e) {
        return "";
    }
}
 
源代码18 项目: kripton   文件: KriptonProcessor.java
protected Set<Class<? extends Annotation>> getSupportedAnnotationClasses() {
	Set<Class<? extends Annotation>> annotations = new LinkedHashSet<Class<? extends Annotation>>();

	annotations.addAll(typeProcessor.getSupportedAnnotationClasses());
	annotations.addAll(sharedPreferencesProcessor.getSupportedAnnotationClasses());
	annotations.addAll(dataSourceProcessor.getSupportedAnnotationClasses());
	annotations.addAll(many2ManyProcessor.getSupportedAnnotationClasses());

	return annotations;
}
 
源代码19 项目: tomee   文件: Observers.java
private boolean isObserver(final Method method) {
    for (final Annotation[] annotations : method.getParameterAnnotations()) {
        for (final Annotation annotation : annotations) {
            if (annotation.annotationType().equals(Observes.class)) {
                return true;
            }
        }
    }
    return false;
}
 
源代码20 项目: typescript-generator   文件: ModelParser.java
protected boolean isAnnotatedPropertyIncluded(Function<Class<? extends Annotation>, Annotation> getAnnotationFunction, String propertyDescription) {
    boolean isIncluded = settings.includePropertyAnnotations.isEmpty()
            || Utils.hasAnyAnnotation(getAnnotationFunction, settings.includePropertyAnnotations);
    if (!isIncluded) {
        TypeScriptGenerator.getLogger().verbose("Skipping '" + propertyDescription + "' because it doesn't have any annotation from 'includePropertyAnnotations'");
        return false;
    }
    boolean isExcluded = Utils.hasAnyAnnotation(getAnnotationFunction, settings.excludePropertyAnnotations);
    if (isExcluded) {
        TypeScriptGenerator.getLogger().verbose("Skipping '" + propertyDescription + "' because it has some annotation from 'excludePropertyAnnotations'");
        return false;
    }
    return true;
}
 
源代码21 项目: Aria   文件: ParamObtainUtil.java
/**
 * 判断是否是任务失败的回调注解
 *
 * @return {@code true}是任务失败的回调注解
 */
private boolean isFailAnnotation(Class<? extends Annotation> annotationClazz) {
  return annotationClazz == Download.onTaskFail.class
      || annotationClazz == DownloadGroup.onTaskFail.class
      || annotationClazz == DownloadGroup.onSubTaskFail.class
      || annotationClazz == Upload.onTaskFail.class;
}
 
private static String toSimpleString(Annotation ann) {
    Class<? extends Annotation> annotationType = ann.annotationType();
    Object value;
    try {
        value = annotationType.getDeclaredMethod("value").invoke(ann);
    } catch (IllegalAccessException | InvocationTargetException
        | NoSuchMethodException e) {
        throw new RuntimeException(e);
    }
    return "@" + annotationType.getSimpleName() + "(" + value + ")";
}
 
源代码23 项目: blog_demos   文件: CustomAutowireConfigurer.java
@Override
@SuppressWarnings("unchecked")
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
	if (this.customQualifierTypes != null) {
		if (!(beanFactory instanceof DefaultListableBeanFactory)) {
			throw new IllegalStateException(
					"CustomAutowireConfigurer needs to operate on a DefaultListableBeanFactory");
		}
		DefaultListableBeanFactory dlbf = (DefaultListableBeanFactory) beanFactory;
		if (!(dlbf.getAutowireCandidateResolver() instanceof QualifierAnnotationAutowireCandidateResolver)) {
			dlbf.setAutowireCandidateResolver(new QualifierAnnotationAutowireCandidateResolver());
		}
		QualifierAnnotationAutowireCandidateResolver resolver =
				(QualifierAnnotationAutowireCandidateResolver) dlbf.getAutowireCandidateResolver();
		for (Object value : this.customQualifierTypes) {
			Class<? extends Annotation> customType = null;
			if (value instanceof Class) {
				customType = (Class<? extends Annotation>) value;
			}
			else if (value instanceof String) {
				String className = (String) value;
				customType = (Class<? extends Annotation>) ClassUtils.resolveClassName(className, this.beanClassLoader);
			}
			else {
				throw new IllegalArgumentException(
						"Invalid value [" + value + "] for custom qualifier type: needs to be Class or String.");
			}
			if (!Annotation.class.isAssignableFrom(customType)) {
				throw new IllegalArgumentException(
						"Qualifier type [" + customType.getName() + "] needs to be annotation type");
			}
			resolver.addQualifierType(customType);
		}
	}
}
 
源代码24 项目: ymate-platform-v2   文件: DefaultBeanFactory.java
@Override
public void registerHandler(Class<? extends Annotation> annoClass, IBeanHandler handler) {
    if (!__beanHandlerMap.containsKey(annoClass)) {
        __beanHandlerMap.put(annoClass, handler);
        //
        if (__owner.getConfig().isDevelopMode() && _LOG.isInfoEnabled()) {
            _LOG.info("Handler class [" + annoClass.getSimpleName() + ":" + handler.getClass().getName() + "] registered.");
        }
    } else if (__owner.getConfig().isDevelopMode() && _LOG.isWarnEnabled()) {
        _LOG.warn("Handler class [" + annoClass.getSimpleName() + ":" + handler.getClass().getName() + "] duplicate registration is not allowed");
    }
}
 
源代码25 项目: jblink   文件: DefaultObsRegistry.java
public void addObserver (Object obs, Class<? extends Annotation> annot)
   throws BlinkException
{
   if (om != null)
   {
      for (Method m : obs.getClass ().getMethods ())
         if (m.isAnnotationPresent (annot))
            pendObservers.add (new PendObs (m, obs));
   }
   else
      throw new RuntimeException ("DefaultObsRegistry: Cannot add " +
                                  "dynamic observer if no data model is " +
                                  "specified: " + obs.getClass ());
}
 
源代码26 项目: flow   文件: AbstractRouteRegistryInitializer.java
private void validateRouteAnnotation(Class<?> route,
        Class<? extends Annotation> annotation) {
    Route routeAnnotation = route.getAnnotation(Route.class);
    if (routeAnnotation != null
            && !UI.class.equals(routeAnnotation.layout())) {
        if (route.isAnnotationPresent(annotation)) {
            throw new InvalidRouteLayoutConfigurationException(String
                    .format("%s annotation needs to be on the top parent layout '%s' not on '%s'",
                            annotation.getSimpleName(),
                            RouteUtil
                                    .getTopParentLayout(route,
                                            RouteUtil.resolve(route,
                                                    routeAnnotation))
                                    .getName(),
                            route.getName()));
        }

        List<Class<? extends RouterLayout>> parentLayouts = RouteUtil
                .getParentLayouts(route,
                        RouteUtil.resolve(route, routeAnnotation));
        Class<? extends RouterLayout> topParentLayout = RouteUtil
                .getTopParentLayout(route,
                        RouteUtil.resolve(route, routeAnnotation));

        validateParentAnnotation(parentLayouts, topParentLayout,
                annotation);
    }
}
 
源代码27 项目: jqm   文件: HttpCacheImpl.java
@Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException
{
    for (Annotation a : responseContext.getEntityAnnotations())
    {
        if (a.annotationType() == HttpCache.class)
        {
            String value = ((HttpCache) a).value();
            responseContext.getHeaders().putSingle(HttpHeaders.CACHE_CONTROL, value);
            break;
        }
    }
}
 
源代码28 项目: mycore   文件: MCRContentAbstractWriter.java
private static Optional<String> getTransformerId(Annotation[] annotations, String format, String detail) {
    return Stream.of(annotations)
        .filter(a -> MCRParams.class.isAssignableFrom(a.annotationType()))
        .map(MCRParams.class::cast)
        .flatMap(p -> Stream.of(p.values()))
        .filter(p -> p.name().equals(PARAM_OBJECTTYPE))
        .findAny()
        .map(MCRParam::value)
        .map(objectType -> objectType + "-" + format + "-" + detail);
}
 
源代码29 项目: cxf   文件: AegisElementProviderTest.java
@Test
public void testWriteTo() throws Exception {
    MessageBodyWriter<Object> p = new AegisElementProvider<>();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    AegisTestBean bean = new AegisTestBean();
    bean.setBoolValue(Boolean.TRUE);
    bean.setStrValue("hovercraft");
    p.writeTo(bean, null, null, new Annotation[]{},
              MediaType.APPLICATION_OCTET_STREAM_TYPE,
              new MetadataMap<String, Object>(), os);
    byte[] bytes = os.toByteArray();
    String xml = new String(bytes, "utf-8");
    assertEquals(simpleBeanXml, xml);
}
 
源代码30 项目: cxf   文件: JAXBElementProviderTest.java
@Test
public void testWriteWithCustomPrefixes() throws Exception {
    JAXBElementProvider<TagVO2> provider = new JAXBElementProvider<>();
    provider.setNamespacePrefixes(
        Collections.singletonMap("http://tags", "prefix"));
    TagVO2 tag = new TagVO2("a", "b");

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    provider.writeTo(tag, TagVO2.class, TagVO2.class,
                   new Annotation[0], MediaType.TEXT_XML_TYPE, new MetadataMap<String, Object>(), bos);
    assertTrue(bos.toString().contains("prefix:thetag"));
}