Java Code Examples for java.lang.annotation.Annotation

The following examples show how to use java.lang.annotation.Annotation. These examples are extracted from open source projects.
Example 1
Project: jadira   File: BasicBinder.java    License: Apache License 2.0 6 votes vote down vote up
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;
	}
}
 
Example 2
Project: java-technology-stack   File: AnnotatedElementUtils.java    License: MIT License 6 votes vote down vote up
/**
 * 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;
		}
	};
}
 
Example 3
Project: mango   File: DefaultParameterContextTest.java    License: Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 4
Project: guice-persist-orient   File: TargetMethodAnalyzer.java    License: MIT License 6 votes vote down vote up
@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;
}
 
Example 5
Project: simple-spring-memcached   File: DataIndexBuilder.java    License: MIT License 6 votes vote down vote up
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;
}
 
Example 6
Project: openjdk-8   File: ExternalMetadataReader.java    License: GNU General Public License v2.0 6 votes vote down vote up
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();
}
 
Example 7
Project: restcommander   File: FileBinder.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 8
Project: cxf   File: MultipartProvider.java    License: Apache License 2.0 6 votes vote down vote up
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;
}
 
Example 9
Project: grpc-java-contrib   File: GrpcServerHost.java    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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());
}
 
Example 10
Project: servicetalk   File: RouteExecutionStrategyUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 11
Project: servicetalk   File: RouteExecutionStrategyUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 12
Project: jdk8u60   File: NativeHeaderTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** 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");
}
 
Example 13
Project: boost   File: PropertiesReader.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@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;
}
 
Example 14
Project: es   File: PageableMethodArgumentResolver.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 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());
        }
    }
}
 
Example 15
Project: openjdk-jdk8u-backup   File: NativeHeaderTest.java    License: GNU General Public License v2.0 6 votes vote down vote up
/** 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");
}
 
Example 16
Project: TarsJava   File: TarsInvokeContext.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@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]);
        }
    }
}
 
Example 17
Project: javageci   File: GeciAnnotationTools.java    License: Apache License 2.0 5 votes vote down vote up
private static String geParam(Annotation annotation, Method method) {
    try {
        method.setAccessible(true);
        return (String) method.invoke(annotation);
    } catch (IllegalAccessException | InvocationTargetException e) {
        return "";
    }
}
 
Example 18
Project: kripton   File: KriptonProcessor.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 19
Project: tomee   File: Observers.java    License: Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 20
Project: typescript-generator   File: ModelParser.java    License: MIT License 5 votes vote down vote up
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;
}
 
Example 21
Project: Aria   File: ParamObtainUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 判断是否是任务失败的回调注解
 *
 * @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;
}
 
Example 22
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 + ")";
}
 
Example 23
Project: blog_demos   File: CustomAutowireConfigurer.java    License: Apache License 2.0 5 votes vote down vote up
@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);
		}
	}
}
 
Example 24
Project: ymate-platform-v2   File: DefaultBeanFactory.java    License: Apache License 2.0 5 votes vote down vote up
@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");
    }
}
 
Example 25
Project: jblink   File: DefaultObsRegistry.java    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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 ());
}
 
Example 26
Project: flow   File: AbstractRouteRegistryInitializer.java    License: Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 27
Project: jqm   File: HttpCacheImpl.java    License: Apache License 2.0 5 votes vote down vote up
@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;
        }
    }
}
 
Example 28
Project: mycore   File: MCRContentAbstractWriter.java    License: GNU General Public License v3.0 5 votes vote down vote up
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);
}
 
Example 29
Project: cxf   File: AegisElementProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 30
Project: cxf   File: JAXBElementProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
@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"));
}
 
Example 31
Project: deltaspike   File: SecurityUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static Annotation resolveSecurityBindingType(Annotation annotation)
{
    List<Annotation> result = getAllAnnotations(annotation.annotationType().getAnnotations(),
        new HashSet<Integer>());

    for (Annotation foundAnnotation : result)
    {
        if (foundAnnotation.annotationType().isAnnotationPresent(SecurityBindingType.class))
        {
            return foundAnnotation;
        }
    }
    throw new IllegalStateException(annotation.annotationType().getName() + " is a " + Stereotype.class.getName() +
            " but it isn't annotated with " + SecurityBindingType.class.getName());
}
 
Example 32
Project: Ferma   File: InVertexMethodHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <E> DynamicType.Builder<E> processMethod(final DynamicType.Builder<E> builder, final Method method, final Annotation annotation) {
    final java.lang.reflect.Parameter[] arguments = method.getParameters();

    if (ReflectionUtility.isGetMethod(method))
        if (arguments == null || arguments.length == 0)
            return this.getNode(builder, method, annotation);
        else
            throw new IllegalStateException(method.getName() + " was annotated with @InVertex but had arguments.");
    else
        throw new IllegalStateException(method.getName() + " was annotated with @InVertex but did not begin with: get");
}
 
Example 33
Project: cxf   File: FormEncodingProviderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testReadFrom() throws Exception {
    @SuppressWarnings("rawtypes")
    FormEncodingProvider<MultivaluedMap> ferp
        = new FormEncodingProvider<>();
    InputStream is = getClass().getResourceAsStream("singleValPostBody.txt");
    @SuppressWarnings("unchecked")
    MultivaluedMap<String, String> mvMap =
        ferp.readFrom(MultivaluedMap.class, null,
        new Annotation[]{}, MediaType.APPLICATION_FORM_URLENCODED_TYPE, null, is);
    assertEquals("Wrong entry for foo", "bar", mvMap.getFirst("foo"));
    assertEquals("Wrong entry for boo", "far", mvMap.getFirst("boo"));

}
 
Example 34
Project: weex   File: ObjectMapper.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
private static Method getJsonValueMethodImpl(Class<?> clazz) {
  Method[] methods = clazz.getMethods();
  for(int i = 0; i < methods.length; ++i) {
    Annotation jsonValue = methods[i].getAnnotation(JsonValue.class);
    if (jsonValue != null) {
      return methods[i];
    }
  }
  return null;
}
 
Example 35
Project: mycore   File: MCRWrappedXMLWriter.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
    if (Stream.of(annotations).noneMatch(a -> XmlElementWrapper.class.isAssignableFrom(a.annotationType()))) {
        return false;
    }
    if (Collection.class.isAssignableFrom(type)) {
        return verifyGenericType(genericType) && Stream.of(MediaType.APPLICATION_XML_TYPE, MediaType.TEXT_XML_TYPE)
            .anyMatch(t -> t.isCompatible(mediaType));
    } else {
        return type.isArray() && verifyArrayType(type)
            && Stream.of(MediaType.APPLICATION_XML_TYPE, MediaType.TEXT_XML_TYPE)
                .anyMatch(t -> t.isCompatible(mediaType));
    }
}
 
Example 36
Project: openjdk-jdk8u   File: ElementRepAnnoTester.java    License: GNU General Public License v2.0 5 votes vote down vote up
private boolean compareArrVals(Annotation[] actualAnnos, String[] expectedAnnos) {
    // Look if test case was run.
    if (actualAnnos == specialAnnoArray) {
        return false; // no testcase matches
    }
    if (actualAnnos.length != expectedAnnos.length) {
        System.out.println("Length not same. "
                + " actualAnnos length = " + actualAnnos.length
                + " expectedAnnos length = " + expectedAnnos.length);
        printArrContents(actualAnnos);
        printArrContents(expectedAnnos);
        return false;
    } else {
        int i = 0;
        String[] actualArr = new String[actualAnnos.length];
        for (Annotation a : actualAnnos) {
            actualArr[i++] = a.toString();
        }
        List<String> actualList = Arrays.asList(actualArr);
        List<String> expectedList = Arrays.asList(expectedAnnos);

        if (!actualList.containsAll(expectedList)) {
            System.out.println("Array values are not same");
            printArrContents(actualAnnos);
            printArrContents(expectedAnnos);
            return false;
        }
    }
    return true;
}
 
Example 37
Project: ranger   File: KMSJSONReader.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object readFrom(Class<Object> type, Type genericType,
    Annotation[] annotations, MediaType mediaType,
    MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
    throws IOException, WebApplicationException {
  return JsonUtilsV2.getMapper().readValue(entityStream, type);
}
 
Example 38
Project: openjdk-8   File: Class.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * @throws NullPointerException {@inheritDoc}
 * @since 1.8
 */
@Override
@SuppressWarnings("unchecked")
public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass) {
    Objects.requireNonNull(annotationClass);

    return (A) annotationData().declaredAnnotations.get(annotationClass);
}
 
Example 39
Project: spring-openapi   File: OpenApiTransformer.java    License: MIT License 5 votes vote down vote up
protected void applyArrayAnnotationDetails(ArrayProperty schema, Annotation annotation) {
	if (annotation instanceof Size) {
		schema.setMinItems(((Size) annotation).min());
		schema.setMaxItems(((Size) annotation).max());
	} else if (annotation instanceof Deprecated) {
		schema.setVendorExtension("x-deprecated", true);
	}
}
 
Example 40
Project: nexus-public   File: ManagedObjectRegistrar.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Construct mbean for given {@link BeanEntry} discovering its attributes and operations.
 */
private MBean mbean(final ManagedObject descriptor, final BeanEntry<Annotation, Object> entry) throws Exception {
  Class<?> type = entry.getImplementationClass();

  ReflectionMBeanBuilder builder = new ReflectionMBeanBuilder(type);

  // attach manged target
  builder.target(new Supplier<Object>()
  {
    @Override
    public Object get() {
      return entry.getProvider().get();
    }
  });

  // allow custom description, or expose what sisu tells us
  String description = Strings.emptyToNull(descriptor.description());
  if (description == null) {
    description = entry.getDescription();
  }
  builder.description(description);

  // discover managed members
  builder.discover();

  return builder.build();
}