/** * Constructor that creates a new class injector for the given class. * * @param bean information about the injected class. * @param resolvers all resolvers which are registered in the application. */ JerseyInstanceInjector(Bean<T> bean, Collection<InjectionResolver> resolvers) { this.bean = bean; this.cachedFields = analyzeFields(bean.getBeanClass(), resolvers); }
private static boolean fullSignatureChanged(Bean<?> bean, Map<String, String> oldFullSignatures) { try { String newSignature = ClassSignatureComparerHelper.getJavaClassSignature(bean.getBeanClass(), ClassSignatureElement.values()); String oldSignature = oldFullSignatures.get(bean.getBeanClass().getName()); return oldSignature != null && newSignature != null && !oldSignature.equals(newSignature); } catch (Exception e) { LOGGER.error("Full signature evaluation failed beanClass='{}'", e, bean.getBeanClass().getName()); } return true; }
private static boolean fullSignatureChanged(Bean<?> bean, Map<String, String> oldFullSignatures) { try { String newSignature = ClassSignatureComparerHelper.getJavaClassSignature(bean.getBeanClass(), ClassSignatureElement.values()); String oldSignature = oldFullSignatures.get(bean.getBeanClass().getName()); return oldSignature != null && newSignature != null && !oldSignature.equals(newSignature); } catch (Exception e) { LOGGER.error("Full signature evaluation failed beanClass='{}'", e, bean.getBeanClass().getName()); } return true; }
private void register(AfterBeanDiscovery afterBeanDiscovery, Set<Annotation> qualifiers, Bean<?> bean) { LOGGER.info(String.format("Registering bean '%s' with qualifiers %s.", bean.getBeanClass().getName(), qualifiers)); afterBeanDiscovery.addBean(bean); } }
@Override @SuppressWarnings("unchecked") public <T> List<ServiceHolder<T>> getAllServiceHolders(Class<T> contractOrImpl, Annotation... qualifiers) { List<ServiceHolder<T>> result = new ArrayList<>(); for (Bean<?> bean : beanManager.getBeans(contractOrImpl, qualifiers)) { CreationalContext<?> ctx = beanManager.createCreationalContext(bean); T reference = (T) beanManager.getReference(bean, contractOrImpl, ctx); int rank = 1; if (bean instanceof JerseyBean) { rank = ((JerseyBean) bean).getRank(); } result.add(new ServiceHolderImpl<>(reference, (Class<T>) bean.getBeanClass(), bean.getTypes(), rank)); } return result; }
@Override public Object create(final String ref, Class<?> cls, final ClassLoader classLoader) throws Exception { final BeanManager beanManager = getBeanManager(); final Bean<?> bean = getBean(ref, beanManager); if (bean == null) { return null; } final CreationalContext<?> context = beanManager.createCreationalContext(bean); final Object result = beanManager.getReference(bean, bean.getBeanClass(), context); contexts.put(result, new Holder(bean, context)); return result; }
@Override public Class<?> getArtifactClass(final String ref, final ClassLoader classLoader) { final Bean<?> bean = getBean(ref, getBeanManager()); return bean == null ? null : bean.getBeanClass(); }
private InjectionTarget getInjectionTarget(Class<?> clazz) { InjectionTarget<?> target = injectionTargets.get(clazz); if (target != null) { return target; } final BeanManagerImpl beanManager = BeanManagerProxy.unwrap(beanManagerSupplier.get()); Bean<?> bean = null; Set<Bean<?>> beans = new HashSet<>(beanManager.getBeans(clazz, Any.Literal.INSTANCE)); Iterator<Bean<?>> it = beans.iterator(); //we may have resolved some sub-classes //go through and remove them from the bean set while (it.hasNext()) { Bean<?> b = it.next(); if(b.getBeanClass() != clazz) { it.remove(); } } if(beans.size() == 1) { bean = beans.iterator().next(); } InjectionTarget<?> newTarget = InjectionTargets.createInjectionTarget(clazz, bean, beanManager, true); target = injectionTargets.putIfAbsent(clazz, newTarget); if (target == null) { return newTarget; } else { return target; } }
/** * Return all bean instances. * * @param bean the bean * @return the bean instances */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static List<Object> getBeanInstances(Bean<?> bean) { List<Object> result = new ArrayList<>(); Class<? extends Context> contextClass = getContextClass(bean.getScope()); Map beanRegistry = (Map) getBeanRegistry(contextClass); if (beanRegistry != null) { Map m = (Map) beanRegistry.get(bean.getBeanClass().getName()); if (m != null) { result.addAll(m.keySet()); } else { LOGGER.debug("BeanRegistry is empty for bean class '{}'", bean.getBeanClass().getName()); } } else { LOGGER.error("BeanRegistry field not found in context class '{}'", contextClass.getName()); } return result; }
private DelegatingGauge<?> buildDelegatingGauge(String gaugeName, AnnotatedMethodConfigurator<?> site, BeanManager bm) { Bean<?> bean = bm.getBeans(site.getAnnotated().getJavaMember().getDeclaringClass()) .stream() .findFirst() .orElseThrow(() -> new IllegalArgumentException("Cannot find bean for annotated gauge " + gaugeName)); return DelegatingGauge.newInstance( site.getAnnotated().getJavaMember(), getReference(bm, bean.getBeanClass(), bean), site.getAnnotated().getJavaMember().getReturnType()); }
private void doRecreateProxy(ClassLoader classLoader, Map<Object, Object> registeredBeans, Class<?> proxyClass) { ClassLoader oldContextClassLoader = Thread.currentThread().getContextClassLoader(); try { ProxyClassLoadingDelegate.beginProxyRegeneration(); Class<?> proxyFactoryClass = null; for (Entry<Object, Object> entry : registeredBeans.entrySet()) { Bean<?> bean = (Bean<?>) entry.getKey(); if (bean != null) { Set<Type> types = bean.getTypes(); if (types.contains(proxyClass)) { Thread.currentThread().setContextClassLoader(bean.getBeanClass().getClassLoader()); if (proxyFactoryClass == null) { proxyFactoryClass = classLoader.loadClass("org.jboss.weld.bean.proxy.ProxyFactory"); } Object proxyFactory = entry.getValue(); LOGGER.info("Recreate proxyClass '{}' for bean class '{}'.", proxyClass.getName(), bean.getClass()); ReflectionHelper.invoke(proxyFactory, proxyFactoryClass, "getProxyClass", new Class[] {}); } } } } catch (Exception e) { LOGGER.error("recreateProxyFactory() exception {}.", e, e.getMessage()); } finally { Thread.currentThread().setContextClassLoader(oldContextClassLoader); ProxyClassLoadingDelegate.endProxyRegeneration(); } }
/** * Records metric producer fields defined by the application. Ignores producers * with non-default qualifiers and library producers. * * @param ppf Producer field. */ private void recordProducerFields(@Observes ProcessProducerField<? extends org.eclipse.microprofile.metrics.Metric, ?> ppf) { LOGGER.log(Level.FINE, () -> "### recordProducerFields " + ppf.getBean().getBeanClass()); if (!MetricProducer.class.equals(ppf.getBean().getBeanClass())) { Metric metric = ppf.getAnnotatedProducerField().getAnnotation(Metric.class); if (metric != null) { Optional<? extends Annotation> hasQualifier = ppf.getAnnotatedProducerField() .getAnnotations() .stream() .filter(annotation -> annotation.annotationType().isAnnotationPresent(Qualifier.class)) .findFirst(); // Ignore producers with non-default qualifiers if (!hasQualifier.isPresent() || hasQualifier.get() instanceof Default) { producers.put(ppf.getBean(), ppf.getAnnotatedProducerField()); } } } }
/** * Records metric producer methods defined by the application. Ignores producers * with non-default qualifiers and library producers. * * @param ppm Producer method. */ private void recordProducerMethods(@Observes ProcessProducerMethod<? extends org.eclipse.microprofile.metrics.Metric, ?> ppm) { LOGGER.log(Level.FINE, () -> "### recordProducerMethods " + ppm.getBean().getBeanClass()); if (!MetricProducer.class.equals(ppm.getBean().getBeanClass())) { Metric metric = ppm.getAnnotatedProducerMethod().getAnnotation(Metric.class); if (metric != null) { Optional<? extends Annotation> hasQualifier = ppm.getAnnotatedProducerMethod() .getAnnotations() .stream() .filter(annotation -> annotation.annotationType().isAnnotationPresent(Qualifier.class)) .findFirst(); // Ignore producers with non-default qualifiers if (!hasQualifier.isPresent() || hasQualifier.get() instanceof Default) { producers.put(ppm.getBean(), ppm.getAnnotatedProducerMethod()); } } } }
private static EnhancedAnnotatedType<?> createAnnotatedTypeForExistingBeanClass(String bdaId, Bean<?> bean) { ClassTransformer classTransformer = getClassTransformer(); SlimAnnotatedType<?> annotatedType = classTransformer.getBackedAnnotatedType(bean.getBeanClass(), bdaId); return EnhancedAnnotatedTypeImpl.of(annotatedType, classTransformer); }
if (bean.getBeanClass().isInterface()) { continue; LOGGER.debug("Skipping bean redefinition. Bean '{}' signature was not changed.", bean.getBeanClass().getName()); continue; if (isReinjectingContext(bean)) { doReloadInjectionTargetBean(beanManager, (InjectionTargetBean) bean, oldSignatures, reloadStrategy); LOGGER.debug("Bean reloaded '{}'.", bean.getBeanClass().getName()); } else { LOGGER.info("Bean '{}' redefined.", bean.getBeanClass().getName()); LOGGER.warning("Class '{}' reloading not supported.", bean.getBeanClass().getName());
@Override public void inject(T instance, CreationalContext<T> ctx) { /* * If an instance contains any fields which be injected by Jersey then Jersey attempts to inject them using annotations * retrieves from registered InjectionResolvers. */ try { injector.get().inject(instance); } catch (Throwable cause) { throw new InjectionException( "Exception occurred during Jersey/JAX-RS annotations processing in the class: " + bean.getBeanClass(), cause); } /* * The rest of the fields (annotated by @Inject) are injected using CDI. */ super.inject(instance, ctx); }
if (bean.getBeanClass().isInterface()) { continue; LOGGER.debug("Skipping bean redefinition. Bean '{}' signature was not changed.", bean.getBeanClass().getName()); continue; if (isReinjectingContext(bean)) { doReloadAbstractClassBean(beanManager, (AbstractClassBean) bean, oldSignatures, reloadStrategy); LOGGER.debug("Bean reloaded '{}'", bean.getBeanClass().getName()); continue; LOGGER.info("Bean '{}' redefined", bean.getBeanClass().getName()); } else { LOGGER.warning("Bean '{}' reloading not supported.", bean.getBeanClass().getName());
/** * Returns the injectee for a field. * * @param bean bean in which the field is placed. * @param field the field to analyze. * @return the list (in order) of parameters to the constructor. */ private static Injectee getFieldInjectee(Bean<?> bean, Field field) { Set<Annotation> annotations = Arrays.stream(field.getAnnotations()) .collect(ImmutableCollectors.toImmutableSet()); Type adjustedType = ReflectionUtils.resolveField(bean.getBeanClass(), field); InjecteeImpl injectee = new InjecteeImpl(); injectee.setParentClassScope(bean.getScope()); if (isProvider(adjustedType)) { ParameterizedType paramType = (ParameterizedType) adjustedType; injectee.setRequiredType(paramType.getActualTypeArguments()[0]); injectee.setProvider(true); } else { injectee.setRequiredType(adjustedType); } injectee.setParent(field); injectee.setRequiredQualifiers(getFieldAdjustedQualifierAnnotations(field, annotations)); return injectee; }
private void addSessionBeanInterface(Bean<?> bean) { for (Type type : bean.getTypes()) { if ((type instanceof Class<?>) && ((Class<?>) type).isInterface()) { Class<?> clazz = (Class<?>) type; if (Utils.isJaxrsAnnotatedClass(clazz)) { sessionBeanInterface.put(bean.getBeanClass(), type); LogMessages.LOGGER.debug(Messages.MESSAGES.typeWillBeUsedForLookup(type, bean.getBeanClass())); return; } } } LogMessages.LOGGER.debug(Messages.MESSAGES.noLookupInterface(bean.getBeanClass())); }
/** * Observes ProcessSessionBean events and creates a (Bean class {@literal ->} Local * interface) map for Session beans with local interfaces. This map is * necessary since RESTEasy identifies a bean class as JAX-RS components * while CDI requires a local interface to be used for lookup. * * @param <T> type * @param event event * */ public <T> void observeSessionBeans(@Observes ProcessSessionBean<T> event) { Bean<Object> sessionBean = event.getBean(); if (Utils.isJaxrsComponent(sessionBean.getBeanClass())) { addSessionBeanInterface(sessionBean); } }