Java Code Examples for javax.ws.rs.ext.Provider

The following examples show how to use javax.ws.rs.ext.Provider. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
/**
 * Initialize Mojarra.
 * 
 * @param classes the classes.
 * @param servletContext the Servlet context.
 * @throws ServletException when a Servlet error occurs.
 */
@Override
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
    
    DefaultWebApplication context = (DefaultWebApplication) servletContext;
    
    Set<Class<?>> jerseyClasses = new HashSet<>();
    
    context.getAnnotationManager()
           .getAnnotations(Path.class, Provider.class, ApplicationPath.class)
           .stream()
           .map(e -> e.getTarget())
           .forEach(e -> addClass(e, jerseyClasses));
    
    
    jerseyClasses.addAll(context.getAnnotationManager().getInstances(Application.class));
    
    JerseyServletContainerInitializer containerInitializer = new JerseyServletContainerInitializer();
    containerInitializer.onStartup(jerseyClasses, servletContext);
}
 
Example 2
Source Project: redpipe   Source File: FCSPlugin.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Completable deployToResteasy(VertxResteasyDeployment deployment) {
	return Completable.defer(() -> {
		JsonArray packages = AppGlobals.get().getConfig().getJsonArray("scan");
		if(packages == null) {
			System.err.println("Not scanning any packages, please specify the 'scan' array of packages in configuration");
		}else {
			String[] packagesToScan = (String[]) packages.getList().toArray(new String[packages.size()]);
			new FastClasspathScanner(packagesToScan)
			.matchClassesWithAnnotation(Path.class, klass -> {
				if(!Modifier.isAbstract(klass.getModifiers()))
					deployment.getActualResourceClasses().add(klass);
			})
			.matchClassesWithAnnotation(Provider.class, klass -> {
				if(!Modifier.isAbstract(klass.getModifiers()))
					deployment.getActualProviderClasses().add(klass);
			})
			.scan();
		}
		return super.deployToResteasy(deployment);
	});
}
 
Example 3
Source Project: redpipe   Source File: Server.java    License: Apache License 2.0 6 votes vote down vote up
protected Single<VertxResteasyDeployment> setupResteasy(Class<?>... resourceOrProviderClasses) {
	return Single.defer(() -> {
		// Build the Jax-RS hello world deployment
		VertxResteasyDeployment deployment = new VertxResteasyDeployment();
		deployment.getDefaultContextObjects().put(Vertx.class, AppGlobals.get().getVertx());
		deployment.getDefaultContextObjects().put(AppGlobals.class, AppGlobals.get());

		return doOnPlugins(plugin -> plugin.deployToResteasy(deployment)).toSingle(() -> {
			for(Class<?> klass : resourceOrProviderClasses) {
				if(klass.isAnnotationPresent(Path.class))
					deployment.getActualResourceClasses().add(klass);
				if(klass.isAnnotationPresent(Provider.class))
					deployment.getActualProviderClasses().add(klass);
			}
			try {
				deployment.start();
			}catch(ExceptionInInitializerError err) {
				// rxjava behaves badly on LinkageError
				RedpipeUtil.rethrow(err.getCause());
			}
			return deployment;
		}).doOnError(t -> t.printStackTrace());
	});
}
 
Example 4
Source Project: Cheddar   Source File: RestResourceConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Autowired
public RestResourceConfig(final ApplicationContext applicationContext) {
    property("contextConfig", applicationContext);
    scanner = new ClassPathScanningCandidateComponentProvider(true);
    scanner.resetFilters(false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(Path.class));
    scanner.addIncludeFilter(new AnnotationTypeFilter(Provider.class));
    register(RequestContextFilter.class);
    register(MultiPartFeature.class);
    register(ObjectMapperProvider.class);
    register(JacksonFeature.class);
    registerResources("com.clicktravel.cheddar.rest.exception.mapper", "com.clicktravel.cheddar.server.http.filter",
            "com.clicktravel.cheddar.server.rest.resource.status", "com.clicktravel.services",
            "com.clicktravel.cheddar.rest.body.writer");
    property(ServerProperties.LOCATION_HEADER_RELATIVE_URI_RESOLUTION_DISABLED, true);
    property(ServerProperties.WADL_FEATURE_DISABLE, true);
}
 
Example 5
Source Project: oryx   Source File: OryxApplication.java    License: Apache License 2.0 6 votes vote down vote up
private Set<Class<?>> doGetClasses() {
  String packages =
      servletContext.getInitParameter(OryxApplication.class.getName() + ".packages");
  log.info("Creating JAX-RS from endpoints in package(s) {}", packages);
  Objects.requireNonNull(packages);
  Set<Class<?>> classes = new HashSet<>();
  for (String thePackage : packages.split(",")) {
    Reflections reflections = new Reflections(thePackage);
    classes.addAll(getClassesInPackageAnnotatedBy(thePackage, reflections, Path.class));
    classes.addAll(getClassesInPackageAnnotatedBy(thePackage, reflections, Produces.class));
    classes.addAll(getClassesInPackageAnnotatedBy(thePackage, reflections, Provider.class));
  }
  // Want to configure these globally, but not depend on Jersey, even though it's
  // what will be used in practice by the provided apps.
  for (String optionalJerseyClass : new String[] {
        "org.glassfish.jersey.message.DeflateEncoder",
        "org.glassfish.jersey.message.GZipEncoder",
        "org.glassfish.jersey.server.filter.EncodingFilter"}) {
    if (ClassUtils.classExists(optionalJerseyClass)) {
      classes.add(ClassUtils.loadClass(optionalJerseyClass));
    }
  }
  log.debug("Found JAX-RS resources: {}", classes);
  return classes;
}
 
Example 6
Source Project: cxf   Source File: JAXRSCdiResourceExtension.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public <T> void collect(@Observes final ProcessBean< T > event) {
    if (event.getAnnotated().isAnnotationPresent(ApplicationPath.class)) {
        applicationBeans.add(event.getBean());
    } else if (event.getAnnotated().isAnnotationPresent(Path.class)) {
        serviceBeans.add(event.getBean());
    } else if (event.getAnnotated().isAnnotationPresent(Provider.class)) {
        providerBeans.add(event.getBean());
    } else if (event.getBean().getTypes().contains(javax.ws.rs.core.Feature.class)) {
        providerBeans.add(event.getBean());
    } else if (event.getBean().getTypes().contains(Feature.class)) {
        featureBeans.add((Bean< ? extends Feature >)event.getBean());
    } else if (CdiBusBean.CXF.equals(event.getBean().getName())
            && Bus.class.isAssignableFrom(event.getBean().getBeanClass())) {
        hasBus = true;
    } else if (event.getBean().getQualifiers().contains(DEFAULT)) {
        event.getBean().getTypes().stream()
            .filter(e -> Object.class != e && InjectionUtils.STANDARD_CONTEXT_CLASSES.contains(e.getTypeName()))
            .findFirst()
            .ifPresent(type -> existingStandardClasses.add(type.getTypeName()));
    }
}
 
Example 7
Source Project: cxf   Source File: AbstractSpringComponentScanServer.java    License: Apache License 2.0 6 votes vote down vote up
protected void addCxfProvider(Object bean) {
    org.apache.cxf.annotations.Provider ann =
        bean.getClass().getAnnotation(org.apache.cxf.annotations.Provider.class);
    if (ann.scope() == Scope.Client) {
        return;
    }
    if (ann.value() == org.apache.cxf.annotations.Provider.Type.Feature) {
        cxfFeatures.add((Feature)bean);
    } else if (ann.value() == org.apache.cxf.annotations.Provider.Type.InInterceptor) {
        super.getInInterceptors().add((Interceptor<?>)bean);
    } else if (ann.value() == org.apache.cxf.annotations.Provider.Type.OutInterceptor) {
        super.getOutInterceptors().add((Interceptor<?>)bean);
    } else if (ann.value() == org.apache.cxf.annotations.Provider.Type.OutFaultInterceptor) {
        super.getOutFaultInterceptors().add((Interceptor<?>)bean);
    }
}
 
Example 8
Source Project: cxf   Source File: AbstractJaxrsClassesScanServer.java    License: Apache License 2.0 6 votes vote down vote up
protected void setJaxrsResources(JAXRSServerFactoryBean factory) {
    try {
        final Map< Class< ? extends Annotation >, Collection< Class< ? > > > classes =
            ClasspathScanner.findClasses(basePackages, Provider.class, Path.class);

        List<Object> jaxrsServices = JAXRSServerFactoryBeanDefinitionParser
            .createBeansFromDiscoveredClasses(super.applicationContext, classes.get(Path.class), null);
        List<Object> jaxrsProviders = JAXRSServerFactoryBeanDefinitionParser
            .createBeansFromDiscoveredClasses(super.applicationContext, classes.get(Provider.class), null);

        factory.setServiceBeans(jaxrsServices);
        factory.setProviders(jaxrsProviders);
    } catch (Exception ex) {
        throw new ServiceConstructionException(ex);
    }

}
 
Example 9
Source Project: cxf   Source File: JaxrsServletContainerInitializer.java    License: Apache License 2.0 6 votes vote down vote up
private Map< Class< ? extends Annotation >, Collection< Class< ? > > > groupByAnnotations(
    final Set< Class< ? > > classes) {

    final Map< Class< ? extends Annotation >, Collection< Class< ? > > > grouped =
        new HashMap<>();

    grouped.put(Provider.class, new ArrayList< Class< ? > >());
    grouped.put(Path.class, new ArrayList< Class< ? > >());

    if (classes != null) {
        for (final Class< ? > clazz: classes) {
            if (!classShouldBeIgnored(clazz)) {
                for (final Entry<Class<? extends Annotation>, Collection<Class<?>>> entry : grouped.entrySet()) {
                    if (clazz.isAnnotationPresent(entry.getKey())) {
                        entry.getValue().add(clazz);
                    }
                }
            }
        }
    }

    return grouped;
}
 
Example 10
Source Project: cxf   Source File: JaxRsWebClientConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void setJaxrsResources(JAXRSClientFactoryBean factory) {
    factory.setServiceClass(WebClient.class);

    if (!StringUtils.isEmpty(scanPackages)) {
        try {
            final Map< Class< ? extends Annotation >, Collection< Class< ? > > > classes =
                ClasspathScanner.findClasses(scanPackages, Provider.class);

            factory.setProviders(
                JAXRSClientFactoryBeanDefinitionParser.getProviders(context, classes.get(Provider.class)));
        } catch (Exception ex) {
            throw new ServiceConstructionException(ex);
        }
    }
}
 
Example 11
Source Project: cxf   Source File: JaxRsProxyClientConfiguration.java    License: Apache License 2.0 6 votes vote down vote up
protected void setJaxrsResources(JAXRSClientFactoryBean factory) {
    Class<?> serviceClass = getServiceClass();
    if (serviceClass != null) {
        factory.setServiceClass(serviceClass);
    } else if (!StringUtils.isEmpty(scanPackages)) {
        try {
            final Map< Class< ? extends Annotation >, Collection< Class< ? > > > classes =
                ClasspathScanner.findClasses(scanPackages, Path.class, Provider.class);
            factory.setServiceClass(
                JAXRSClientFactoryBeanDefinitionParser.getServiceClass(classes.get(Path.class)));
            factory.setProviders(
                JAXRSClientFactoryBeanDefinitionParser.getProviders(context, classes.get(Provider.class)));
        } catch (Exception ex) {
            throw new ServiceConstructionException(ex);
        }
    }
}
 
Example 12
@SuppressWarnings({"unchecked"})
protected void processBindings(Injector injector, EverrestApplication everrest) {
    for (Binding<?> binding : injector.getBindings().values()) {
        Key<?> bindingKey = binding.getKey();
        Type type = bindingKey.getTypeLiteral().getType();
        if (type instanceof Class) {
            Class clazz = (Class)type;
            if (clazz.getAnnotation(Provider.class) != null) {
                ProviderDescriptor providerDescriptor = new ProviderDescriptorImpl(clazz);
                everrest.addFactory(new GuiceObjectFactory<>(providerDescriptor, binding.getProvider()));
            } else if (clazz.getAnnotation(Filter.class) != null) {
                FilterDescriptor filterDescriptor = new FilterDescriptorImpl(clazz);
                everrest.addFactory(new GuiceObjectFactory<>(filterDescriptor, binding.getProvider()));
            } else if (clazz.getAnnotation(Path.class) != null) {
                ResourceDescriptor resourceDescriptor;
                if (bindingKey.getAnnotation() != null && bindingKey.getAnnotationType().isAssignableFrom(BindingPath.class)) {
                    String path = ((BindingPath)bindingKey.getAnnotation()).value();
                    resourceDescriptor = new AbstractResourceDescriptor(path, clazz);
                } else {
                    resourceDescriptor = new AbstractResourceDescriptor(clazz);
                }
                everrest.addFactory(new GuiceObjectFactory<>(resourceDescriptor, binding.getProvider()));
            }
        }
    }
}
 
Example 13
Source Project: camunda-bpm-platform   Source File: CXFServerBootstrap.java    License: Apache License 2.0 6 votes vote down vote up
private void separateProvidersAndResources(Application application, List<Class<?>> resourceClasses, List<Object> providerInstances) {
  Set<Class<?>> classes = application.getClasses();

  for (Class<?> clazz : classes) {
    Annotation[] annotations = clazz.getAnnotations();
    for (Annotation annotation : annotations) {
      if (annotation.annotationType().equals(Provider.class)) {
        // for providers we have to create an instance
        try {
          providerInstances.add(clazz.newInstance());
          break;
        } catch (Exception e) {
          throw new RuntimeException(e);
        }
      } else if (annotation.annotationType().equals(Path.class)) {
        resourceClasses.add(clazz);
        break;
      }
    }
  }
}
 
Example 14
Source Project: act-platform   Source File: EndpointsModule.java    License: ISC License 5 votes vote down vote up
@Override
protected void configure() {
  // Instruct RESTEasy to use a customized ObjectMapper (required to correctly serialize ResultStash).
  bind(ObjectMapperResolver.class);

  // Bind classes composing the REST API (endpoints and exception mappings).
  bindAnnotatedClasses(API_PACKAGE, Path.class);
  bindAnnotatedClasses(MAPPINGS_PACKAGE, Provider.class);
}
 
Example 15
Source Project: didi-eureka-server   Source File: EurekaServerAutoConfiguration.java    License: MIT License 5 votes vote down vote up
/**
 * Construct a Jersey {@link javax.ws.rs.core.Application} with all the resources
 * required by the Eureka server.
 */
@Bean
public javax.ws.rs.core.Application jerseyApplication(Environment environment,
		ResourceLoader resourceLoader) {

	ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
			false, environment);

	// Filter to include only classes that have a particular annotation.
	//
	provider.addIncludeFilter(new AnnotationTypeFilter(Path.class));
	provider.addIncludeFilter(new AnnotationTypeFilter(Provider.class));

	// Find classes in Eureka packages (or subpackages)
	//
	Set<Class<?>> classes = new HashSet<Class<?>>();
	for (String basePackage : EUREKA_PACKAGES) {
		Set<BeanDefinition> beans = provider.findCandidateComponents(basePackage);
		for (BeanDefinition bd : beans) {
			Class<?> cls = ClassUtils.resolveClassName(bd.getBeanClassName(),
					resourceLoader.getClassLoader());
			classes.add(cls);
		}
	}

	// Construct the Jersey ResourceConfig
	//
	Map<String, Object> propsAndFeatures = new HashMap<String, Object>();
	propsAndFeatures.put(
			// Skip static content used by the webapp
			ServletContainer.PROPERTY_WEB_PAGE_CONTENT_REGEX,
			EurekaConstants.DEFAULT_PREFIX + "/(fonts|images|css|js)/.*");

	DefaultResourceConfig rc = new DefaultResourceConfig(classes);
	rc.setPropertiesAndFeatures(propsAndFeatures);

	return rc;
}
 
Example 16
Source Project: robe   Source File: ProviderScanner.java    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void scanAndAdd(Environment environment, Injector injector, Reflections reflections) {
    Set<Class<?>> providerClasses = reflections.getTypesAnnotatedWith(Provider.class);
    for (Class<?> provider : providerClasses) {
        environment.jersey().register(provider);
        LOGGER.info("Added provider class: " + provider);
    }
}
 
Example 17
/**
 * Construct a Jersey {@link javax.ws.rs.core.Application} with all the resources
 * required by the Eureka server.
 * @param environment an {@link Environment} instance to retrieve classpath resources
 * @param resourceLoader a {@link ResourceLoader} instance to get classloader from
 * @return created {@link Application} object
 */
@Bean
public javax.ws.rs.core.Application jerseyApplication(Environment environment,
		ResourceLoader resourceLoader) {

	ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(
			false, environment);

	// Filter to include only classes that have a particular annotation.
	//
	provider.addIncludeFilter(new AnnotationTypeFilter(Path.class));
	provider.addIncludeFilter(new AnnotationTypeFilter(Provider.class));

	// Find classes in Eureka packages (or subpackages)
	//
	Set<Class<?>> classes = new HashSet<>();
	for (String basePackage : EUREKA_PACKAGES) {
		Set<BeanDefinition> beans = provider.findCandidateComponents(basePackage);
		for (BeanDefinition bd : beans) {
			Class<?> cls = ClassUtils.resolveClassName(bd.getBeanClassName(),
					resourceLoader.getClassLoader());
			classes.add(cls);
		}
	}

	// Construct the Jersey ResourceConfig
	Map<String, Object> propsAndFeatures = new HashMap<>();
	propsAndFeatures.put(
			// Skip static content used by the webapp
			ServletContainer.PROPERTY_WEB_PAGE_CONTENT_REGEX,
			EurekaConstants.DEFAULT_PREFIX + "/(fonts|images|css|js)/.*");

	DefaultResourceConfig rc = new DefaultResourceConfig(classes);
	rc.setPropertiesAndFeatures(propsAndFeatures);

	return rc;
}
 
Example 18
Source Project: cxf   Source File: JAXRSCdiResourceExtension.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Extracts relevant beans from producers.
 * @param event process bean event
 * @param baseType base type of the producer
 */
private <T> void processProducer(final ProcessBean<T> event, final Type baseType) {
    if (baseType instanceof Class<?>) {
        final Class<?> clazz = (Class<?>)baseType;
        if (clazz.isAnnotationPresent(Path.class)) {
            serviceBeans.add(event.getBean());
        } else if (clazz.isAnnotationPresent(Provider.class)) {
            providerBeans.add(event.getBean());
        } else if (clazz.isAnnotationPresent(ApplicationPath.class)) {
            applicationBeans.add(event.getBean());
        } 
    }
}
 
Example 19
Source Project: cxf   Source File: AbstractSpringComponentScanServer.java    License: Apache License 2.0 5 votes vote down vote up
protected void setJaxrsResources(JAXRSServerFactoryBean factory) {
    Set<String> componentScanPackagesSet = parseSetProperty(componentScanPackages);
    Set<String> componentScanBeansSet = parseSetProperty(componentScanBeans);
        
    for (String beanName : applicationContext.getBeanDefinitionNames()) {
        if (isValidComponent(beanName, Path.class, componentScanPackagesSet, componentScanBeansSet)) {
            SpringResourceFactory resourceFactory = new SpringResourceFactory(beanName);
            resourceFactory.setApplicationContext(applicationContext);
            resourceProviders.add(resourceFactory);
        } else if (isValidComponent(beanName, Provider.class, componentScanPackagesSet, componentScanBeansSet)) {
            jaxrsProviders.add(getProviderBean(beanName));
        } else if (isValidComponent(beanName, org.apache.cxf.annotations.Provider.class, 
                                componentScanPackagesSet, componentScanBeansSet)) {
            addCxfProvider(getProviderBean(beanName));
        }
    }

    if (!StringUtils.isEmpty(classesScanPackages)) {
        try {
            final Map< Class< ? extends Annotation >, Collection< Class< ? > > > classes =
                ClasspathScanner.findClasses(classesScanPackages, Provider.class,
                                             org.apache.cxf.annotations.Provider.class);

            jaxrsProviders.addAll(JAXRSServerFactoryBeanDefinitionParser
                .createBeansFromDiscoveredClasses(applicationContext, classes.get(Provider.class), null));
            warnIfDuplicatesAvailable(jaxrsProviders);
            addCxfProvidersFromClasses(classes.get(org.apache.cxf.annotations.Provider.class));
        } catch (Exception ex) {
            throw new ServiceConstructionException(ex);
        }
    }

    factory.setResourceProviders(getResourceProviders());
    factory.setProviders(getJaxrsProviders());
    setFactoryCxfProviders(factory);

}
 
Example 20
Source Project: cxf   Source File: ResourceUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean isValidProvider(Class<?> c) {
    if (c == null || c == Object.class) {
        return false;
    }
    if (c.getAnnotation(Provider.class) != null) {
        return true;
    }
    for (Class<?> itf : c.getInterfaces()) {
        if (SERVER_PROVIDER_CLASS_NAMES.contains(itf.getName())) {
            return true;
        }
    }
    return isValidProvider(c.getSuperclass());
}
 
Example 21
Source Project: cxf   Source File: AbstractJaxRsClientConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
protected Client createClient() {
    JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
    bean.setBus(bus);
    bean.setAddress(address);
    bean.setThreadSafe(threadSafe);
    setJaxrsResources(bean);

    for (String beanName : context.getBeanDefinitionNames()) {
        if (context.findAnnotationOnBean(beanName, Provider.class) != null) {
            bean.setProvider(context.getBean(beanName));
        } else if (context.findAnnotationOnBean(beanName, org.apache.cxf.annotations.Provider.class) != null) {
            addCxfProvider(bean, context.getBean(beanName));
        }
    }

    Map<String, String> extraHeaders = new HashMap<>();
    if (!StringUtils.isEmpty(accept)) {
        extraHeaders.put("Accept", accept);
    }
    if (!StringUtils.isEmpty(contentType)) {
        extraHeaders.put("Content-Type", contentType);
    }
    if (!extraHeaders.isEmpty()) {
        bean.setHeaders(extraHeaders);
    }
    return bean.create();
}
 
Example 22
Source Project: cxf   Source File: AbstractJaxRsClientConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
protected void addCxfProvider(JAXRSClientFactoryBean factory, Object provider) {
    org.apache.cxf.annotations.Provider ann =
        provider.getClass().getAnnotation(org.apache.cxf.annotations.Provider.class);
    if (ann.scope() == Scope.Server) {
        return;
    }
    if (ann.value() == org.apache.cxf.annotations.Provider.Type.Feature) {
        factory.getFeatures().add((Feature)provider);
    } else if (ann.value() == org.apache.cxf.annotations.Provider.Type.InInterceptor) {
        factory.getInInterceptors().add((Interceptor<?>)provider);
    } else if (ann.value() == org.apache.cxf.annotations.Provider.Type.OutInterceptor) {
        factory.getOutInterceptors().add((Interceptor<?>)provider);
    }

}
 
Example 23
Source Project: hammock   Source File: JerseyCdiExtension.java    License: Apache License 2.0 5 votes vote down vote up
public <T> void observeProviders(@WithAnnotations({ Provider.class }) @Observes ProcessAnnotatedType<T> event) {
    AnnotatedType<T> annotatedType = event.getAnnotatedType();

    if (!annotatedType.getJavaClass().isInterface()) {
        this.providers.add(annotatedType.getJavaClass());
    }
}
 
Example 24
Source Project: everrest   Source File: FieldInjectorImpl.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * @param field
 *         java.lang.reflect.Field
 */
public FieldInjectorImpl(Field field, ParameterResolverFactory parameterResolverFactory) {
    this.field = field;
    this.parameterResolverFactory = parameterResolverFactory;
    this.annotations = field.getDeclaredAnnotations();

    final Class<?> declaringClass = field.getDeclaringClass();

    this.setter = getSetter(declaringClass, field);

    Annotation annotation = null;
    String defaultValue = null;
    boolean encoded = false;

    final boolean isProvider = declaringClass.getAnnotation(Provider.class) != null;
    final List<String> allowedAnnotation = isProvider ? PROVIDER_FIELDS_ANNOTATIONS : RESOURCE_FIELDS_ANNOTATIONS;

    for (int i = 0, length = annotations.length; i < length; i++) {
        Class<?> annotationType = annotations[i].annotationType();
        if (allowedAnnotation.contains(annotationType.getName())) {
            if (annotation != null) {
                throw new RuntimeException(
                        String.format("JAX-RS annotations on one of fields %s are equivocality. Annotations: %s and %s can't be applied to one field. ",
                                      field, annotation, annotations[i]));
            }
            annotation = annotations[i];
        } else if (annotationType == Encoded.class && !isProvider) {
            encoded = true;
        } else if (annotationType == DefaultValue.class && !isProvider) {
            defaultValue = ((DefaultValue)annotations[i]).value();
        }
    }
    this.defaultValue = defaultValue;
    this.annotation = annotation;
    this.encoded = encoded || declaringClass.getAnnotation(Encoded.class) != null;
}
 
Example 25
Source Project: everrest   Source File: RestComponentResolver.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
public void addSingleton(Object instance) {
    Class clazz = instance.getClass();
    if (clazz.getAnnotation(Provider.class) != null) {
        if (instance instanceof ContextResolver) {
            providers.addContextResolver((ContextResolver)instance);
        }
        if (instance instanceof ExceptionMapper) {
            providers.addExceptionMapper((ExceptionMapper)instance);
        }
        if (instance instanceof MessageBodyReader) {
            providers.addMessageBodyReader((MessageBodyReader)instance);
        }
        if (instance instanceof MessageBodyWriter) {
            providers.addMessageBodyWriter((MessageBodyWriter)instance);
        }
    } else if (clazz.getAnnotation(Filter.class) != null) {
        if (instance instanceof MethodInvokerFilter) {
            providers.addMethodInvokerFilter((MethodInvokerFilter)instance);
        }
        if (instance instanceof RequestFilter) {
            providers.addRequestFilter((RequestFilter)instance);
        }
        if (instance instanceof ResponseFilter) {
            providers.addResponseFilter((ResponseFilter)instance);
        }
    } else if (clazz.getAnnotation(Path.class) != null) {
        resources.addResource(instance, null);
    }
}
 
Example 26
Source Project: everrest   Source File: RestComponentResolver.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
public void addPerRequest(Class clazz) {
    if (clazz.getAnnotation(Provider.class) != null) {
        if (ContextResolver.class.isAssignableFrom(clazz)) {
            providers.addContextResolver(clazz);
        }
        if (ExceptionMapper.class.isAssignableFrom(clazz)) {
            providers.addExceptionMapper(clazz);
        }
        if (MessageBodyReader.class.isAssignableFrom(clazz)) {
            providers.addMessageBodyReader(clazz);
        }
        if (MessageBodyWriter.class.isAssignableFrom(clazz)) {
            providers.addMessageBodyWriter(clazz);
        }
    } else if (clazz.getAnnotation(Filter.class) != null) {
        if (MethodInvokerFilter.class.isAssignableFrom(clazz)) {
            providers.addMethodInvokerFilter(clazz);
        }
        if (RequestFilter.class.isAssignableFrom(clazz)) {
            providers.addRequestFilter(clazz);
        }
        if (ResponseFilter.class.isAssignableFrom(clazz)) {
            providers.addResponseFilter(clazz);
        }
    } else if (clazz.getAnnotation(Path.class) != null) {
        resources.addResource(clazz, null);
    }
}
 
Example 27
Source Project: everrest   Source File: RestComponentResolver.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings({"unchecked"})
public void addFactory(ObjectFactory factory) {
    Class clazz = factory.getObjectModel().getObjectClass();
    if (clazz.getAnnotation(Provider.class) != null) {
        if (ContextResolver.class.isAssignableFrom(clazz)) {
            providers.addContextResolver(factory);
        }
        if (ExceptionMapper.class.isAssignableFrom(clazz)) {
            providers.addExceptionMapper(factory);
        }
        if (MessageBodyReader.class.isAssignableFrom(clazz)) {
            providers.addMessageBodyReader(factory);
        }
        if (MessageBodyWriter.class.isAssignableFrom(clazz)) {
            providers.addMessageBodyWriter(factory);
        }
    } else if (clazz.getAnnotation(Filter.class) != null) {
        if (MethodInvokerFilter.class.isAssignableFrom(clazz)) {
            providers.addMethodInvokerFilter(factory);
        }
        if (RequestFilter.class.isAssignableFrom(clazz)) {
            providers.addRequestFilter(factory);
        }
        if (ResponseFilter.class.isAssignableFrom(clazz)) {
            providers.addResponseFilter(factory);
        }
    } else if (clazz.getAnnotation(Path.class) != null) {
        resources.addResource(factory);
    }
}
 
Example 28
Source Project: everrest   Source File: EverrestJetty.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private boolean isRestResource(Class<?> resourceClass) {
    return resourceClass.isAnnotationPresent(Path.class) ||
           resourceClass.isAnnotationPresent(Provider.class) ||
           resourceClass.isAnnotationPresent(Filter.class) ||
           resourceClass.isAssignableFrom(ExceptionMapper.class) ||
           resourceClass.isAssignableFrom(ContextResolver.class) ||
           resourceClass.isAssignableFrom(MessageBodyReader.class) ||
           resourceClass.isAssignableFrom(MessageBodyWriter.class) ||
           resourceClass.isAssignableFrom(MethodInvokerFilter.class) ||
           resourceClass.isAssignableFrom(RequestFilter.class) ||
           resourceClass.isAssignableFrom(ResponseFilter.class);
}
 
Example 29
Source Project: everrest   Source File: EverrestJetty.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public ObjectFactory<? extends ObjectModel> createFactory(Object testObject, Field field) {
    Class clazz = (Class)field.getType();
    if (clazz.getAnnotation(Provider.class) != null) {
        ProviderDescriptor providerDescriptor = new ProviderDescriptorImpl(clazz);
        return new TestResourceFactory<>(providerDescriptor, testObject, field);
    } else if (clazz.getAnnotation(Filter.class) != null) {
        FilterDescriptor filterDescriptor = new FilterDescriptorImpl(clazz);
        return new TestResourceFactory<>(filterDescriptor, testObject, field);
    } else if (clazz.getAnnotation(Path.class) != null) {
        AbstractResourceDescriptor resourceDescriptor = new AbstractResourceDescriptor(clazz);
        return new TestResourceFactory<>(resourceDescriptor, testObject, field);
    }
    return null;
}
 
Example 30
Source Project: tomee   Source File: RESTService.java    License: Apache License 2.0 5 votes vote down vote up
private static <T> boolean isProvider(final Class<T> clazz) {
    return MessageBodyReader.class.isAssignableFrom(clazz) ||
            MessageBodyWriter.class.isAssignableFrom(clazz) ||
            ParamConverter.class.isAssignableFrom(clazz) ||
            ContainerRequestFilter.class.isAssignableFrom(clazz) ||
            ContainerResponseFilter.class.isAssignableFrom(clazz) ||
            ReaderInterceptor.class.isAssignableFrom(clazz) ||
            WriterInterceptor.class.isAssignableFrom(clazz) ||
            ParamConverterProvider.class.isAssignableFrom(clazz) ||
            ContextResolver.class.isAssignableFrom(clazz) ||
            Feature.class.isAssignableFrom(clazz) ||
            new MetaAnnotatedClass<>(clazz).isAnnotationPresent(Provider.class);
}