下面列出了org.junit.runners.Suite#java.lang.annotation.Annotation 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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;
}
};
}
@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;
}
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();
}
@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;
}
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;
}
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());
}
/**
* 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);
}
/**
* 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);
}
/** 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");
}
@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;
}
/**
* 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());
}
}
}
/** 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");
}
@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]);
}
}
}
private static String geParam(Annotation annotation, Method method) {
try {
method.setAccessible(true);
return (String) method.invoke(annotation);
} catch (IllegalAccessException | InvocationTargetException e) {
return "";
}
}
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;
}
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;
}
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;
}
/**
* 判断是否是任务失败的回调注解
*
* @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 + ")";
}
@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);
}
}
}
@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");
}
}
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 ());
}
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);
}
}
@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;
}
}
}
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);
}
@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);
}
@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"));
}