@Override @SuppressWarnings("unchecked") public ResourceReferenceFactory<Object> registerEjbInjectionPoint( final InjectionPoint injectionPoint ) { if (injectionPoint.getAnnotated().getAnnotation(EJB.class) == null) { throw new IllegalStateException("Unhandled injection point: " + injectionPoint); } final Type type = injectionPoint.getType(); final ResourceReferenceFactory<Object> alternative = alternatives.alternativeFor(type); if (alternative != null) { return alternative; } final EjbDescriptor<Object> descriptor = (EjbDescriptor<Object>) lookup.lookup(type); if (descriptor == null) { throw new IllegalStateException("No EJB descriptor found for EJB injection point: " + injectionPoint); } return factory.createInstance(descriptor); }
private <T> ProducerFactory<T> factory(final Object mock) { return new ProducerFactory<T>() { @Override public <T1> Producer<T1> createProducer(final Bean<T1> bean) { return new Producer<T1>() { @Override public T1 produce(final CreationalContext<T1> ctx) { return (T1) mock; } @Override public void dispose(final T1 instance) { } @Override public Set<InjectionPoint> getInjectionPoints() { return Collections.emptySet(); } }; } }; }
@Override public Object resolveResource(InjectionPoint injectionPoint) { Resource resource = getResourceAnnotation(injectionPoint); if (resource == null) { throw new IllegalArgumentException("No @Resource annotation found on " + injectionPoint); } if (injectionPoint.getMember() instanceof Method && ((Method) injectionPoint.getMember()).getParameterTypes().length != 1) { throw new IllegalArgumentException( "Injection point represents a method which doesn't follow JavaBean conventions (must have exactly one parameter) " + injectionPoint); } String name; if (!resource.lookup().equals("")) { name = resource.lookup(); } else { name = getResourceName(injectionPoint); } return resources.get(name); }
private String getResourceName(InjectionPoint injectionPoint) { Resource resource = getResourceAnnotation(injectionPoint); String mappedName = resource.mappedName(); if (!mappedName.equals("")) { return mappedName; } String name = resource.name(); if (!name.equals("")) { return RESOURCE_LOOKUP_PREFIX + "/" + name; } String propertyName; if (injectionPoint.getMember() instanceof Field) { propertyName = injectionPoint.getMember().getName(); } else if (injectionPoint.getMember() instanceof Method) { propertyName = getPropertyName((Method) injectionPoint.getMember()); if (propertyName == null) { throw new IllegalArgumentException("Injection point represents a method which doesn't follow " + "JavaBean conventions (unable to determine property name) " + injectionPoint); } } else { throw new AssertionError("Unable to inject into " + injectionPoint); } String className = injectionPoint.getMember().getDeclaringClass().getName(); return RESOURCE_LOOKUP_PREFIX + "/" + className + "/" + propertyName; }
@Inject protected void CrudService(InjectionPoint ip) { if (ip != null && ip.getType() != null && ip.getMember() != null) { try { //Used for generic service injection, e.g: @Inject @Service CrudService<Entity,Key> resolveEntity(ip); } catch (Exception e) { LOG.warning(String.format("Could not resolve entity type and entity key via injection point [%s]. Now trying to resolve via generic superclass of [%s].", ip.getMember().getName(), getClass().getName())); } } if (entityClass == null) { //Used on service inheritance, e.g: MyService extends CrudService<Entity, Key> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; entityKey = (Class<PK>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[1]; } }
@Produces @AppData("PRODUCER") public String getAppDataValueAsString(InjectionPoint injectionPoint) { Annotated annotated = injectionPoint.getAnnotated(); String key = null; String value = null; if (annotated.isAnnotationPresent(AppData.class)) { AppData annotation = annotated.getAnnotation(AppData.class); key = annotation.value(); value = properties.getProperty(key); } if (value == null) { throw new IllegalArgumentException("No AppData value found for key " + key); } return value; }
@Produces @CoreSetting("PRODUCER") public String getUserSetting(InjectionPoint injectionPoint) { Annotated annotated = injectionPoint.getAnnotated(); if (annotated.isAnnotationPresent(CoreSetting.class)) { String settingPath = annotated.getAnnotation(CoreSetting.class).value(); Object object = yamlCoreSettings; String[] split = settingPath.split("\\."); int c = 0; while (c < split.length) { try { object = PropertyUtils.getProperty(object, split[c]); c++; } catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { LogManager.getLogger(getClass()).error("Failed retrieving setting " + settingPath, e); return null; } } return String.valueOf(object); } return null; }
@Produces public I18nMap createL10nMap(InjectionPoint injectionPoint) { Annotated annotated = injectionPoint.getAnnotated(); String baseName; if (annotated.isAnnotationPresent(I18nData.class)) { baseName = annotated.getAnnotation(I18nData.class).value().getSimpleName(); } else { baseName = injectionPoint.getBean().getBeanClass().getSimpleName(); } File langFile = new File(langBase, baseName + ".properties"); I18NMapImpl l10NMap = new I18NMapImpl(commonLang); try (InputStream stream = new FileInputStream(langFile)) { l10NMap.load(stream); } catch (IOException e) { // I18n data will be injected in all components, // but a component is not required to have a language definition // This implementation will return an empty I18nMap containing only able to supply common strings } return l10NMap; }
@SuppressWarnings("unchecked") @Dependent @Produces @ConfigProperty <T> Optional<T> produceOptionalConfigValue(InjectionPoint injectionPoint) { Type type = injectionPoint.getAnnotated().getBaseType(); final Class<T> valueType; if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; Type[] typeArguments = parameterizedType.getActualTypeArguments(); valueType = unwrapType(typeArguments[0]); } else { valueType = (Class<T>) String.class; } return Optional.ofNullable(getValue(injectionPoint, valueType)); }
private <T> T getValue (InjectionPoint injectionPoint, Class<T> target) { Config config = getConfig(injectionPoint); String name = getName(injectionPoint); try { if (name == null) { return null; } Optional<T> optionalValue = config.getOptionalValue(name, target); if (optionalValue.isPresent()) { return optionalValue.get(); } else { String defaultValue = getDefaultValue(injectionPoint); if (defaultValue != null) { return ((WildFlyConfig)config).convert(defaultValue, target); } else { return null; } } } catch (RuntimeException e) { return null; } }
public void validate(@Observes AfterDeploymentValidation add, BeanManager bm) { List<String> deploymentProblems = new ArrayList<>(); Config config = ConfigProvider.getConfig(); for (InjectionPoint injectionPoint : injectionPoints) { Type type = injectionPoint.getType(); ConfigProperty configProperty = injectionPoint.getAnnotated().getAnnotation(ConfigProperty.class); if (type instanceof Class) { String key = getConfigKey(injectionPoint, configProperty); if (!config.getOptionalValue(key, (Class)type).isPresent()) { String defaultValue = configProperty.defaultValue(); if (defaultValue == null || defaultValue.equals(ConfigProperty.UNCONFIGURED_VALUE)) { deploymentProblems.add("No Config Value exists for " + key); } } } } if (!deploymentProblems.isEmpty()) { add.addDeploymentProblem(new DeploymentException("Error while validating Configuration\n" + String.join("\n", deploymentProblems))); } }
static String getConfigKey(InjectionPoint ip, ConfigProperty configProperty) { String key = configProperty.name(); if (!key.trim().isEmpty()) { return key; } if (ip.getAnnotated() instanceof AnnotatedMember) { AnnotatedMember member = (AnnotatedMember) ip.getAnnotated(); AnnotatedType declaringType = member.getDeclaringType(); if (declaringType != null) { String[] parts = declaringType.getJavaClass().getCanonicalName().split("\\."); StringBuilder sb = new StringBuilder(parts[0]); for (int i = 1; i < parts.length; i++) { sb.append(".").append(parts[i]); } sb.append(".").append(member.getJavaMember().getName()); return sb.toString(); } } throw new IllegalStateException("Could not find default name for @ConfigProperty InjectionPoint " + ip); }
@Produces @Crypto public PasswordEncoder passwordEncoder(InjectionPoint ip) { Crypto crypto = ip.getAnnotated().getAnnotation(Crypto.class); Crypto.Type type = crypto.value(); PasswordEncoder encoder; switch (type) { case PLAIN: encoder = new PlainPasswordEncoder(); break; case BCRYPT: encoder = new BCryptPasswordEncoder(); break; default: encoder = new PlainPasswordEncoder(); break; } return encoder; }
/** * * @param ip * @param beanManager * @return */ private <T> Bean<T> createBeanAdapter(InjectionPoint ip, BeanManager beanManager) { final Type type = ip.getType(); final Class<T> rawType = ReflectionUtils.getRawType(type); final ContextualLifecycle<T> lifecycleAdapter = new BodyLifecycle<T>(ip, beanManager); final BeanBuilder<T> beanBuilder = new BeanBuilder<T>(beanManager) .readFromType(new AnnotatedTypeBuilder<T>().readFromType(rawType).create()) .beanClass(Body.class) // see https://issues.jboss.org/browse/WELD-2165 .name(ip.getMember().getName()) .qualifiers(ip.getQualifiers()) .beanLifecycle(lifecycleAdapter) .scope(Dependent.class) .passivationCapable(false) .alternative(false) .nullable(true) .id("BodyBean#" + type.toString()) .addType(type); //java.lang.Object needs to be present (as type) in any case return beanBuilder.create(); }
@Test @SuppressWarnings({ "rawtypes", "unchecked" }) public void logger_injectionPoint_noBean() { final InjectionPoint ip = mock(InjectionPoint.class); final Member member = mock(Member.class); when(ip.getMember()).thenReturn(member); when(member.getDeclaringClass()).thenReturn((Class) LogProducerTest.class); final Logger log = LogProducer.logger(ip); assertEquals("NOP", log.getName()); verify(ip).getBean(); verify(ip).getMember(); verify(member).getDeclaringClass(); verifyNoMoreInteractions(ip, member); }
@Test public void pathParam_destination() { final InjectionPoint ip = mock(InjectionPoint.class); final PathParser parser = new PathParser("/{there}"); final DestinationChanged dc = mock(DestinationChanged.class); when(dc.getDestination()).thenReturn("/here"); final Annotated annotated = mock(Annotated.class); when(ip.getAnnotated()).thenReturn(annotated); when(annotated.getAnnotation(PathParam.class)).thenReturn(createPathParam("there")); final String param = PathParamProducer.pathParam(ip, parser, null, dc); assertEquals("here", param); verify(dc).getDestination(); verify(ip).getAnnotated(); verify(annotated).getAnnotation(PathParam.class); verifyNoMoreInteractions(ip, dc, annotated); }
@Produces @ConfigProperty public Object resolveAndConvert(final InjectionPoint injectionPoint) { LOGGER.finest( () -> "Inject: " + injectionPoint); final ConfigProperty annotation = injectionPoint.getAnnotated().getAnnotation(ConfigProperty.class); String key = annotation.name(); if(key.isEmpty()){ key = getDefaultKey(injectionPoint); } // unless the extension is not installed, this should never happen because the extension // enforces the resolvability of the config String defaultTextValue = annotation.defaultValue().equals(ConfigProperty.UNCONFIGURED_VALUE) ? null : annotation.defaultValue(); ConversionContext conversionContext = createConversionContext(key, injectionPoint); Object value = resolveValue(defaultTextValue, conversionContext, injectionPoint); if (value == null) { throw new ConfigException(String.format( "Can't resolve any of the possible config keys: %s to the required target type: %s, supported formats: %s", key, conversionContext.getTargetType(), conversionContext.getSupportedFormats().toString())); } LOGGER.finest(String.format("Injecting %s for key %s in class %s", key, value.toString(), injectionPoint.toString())); return value; }
/** * Creates a SnoopEEServiceClient for the named service. * * @param ip The injection point * @return a configured SnoopEE service client */ @SnoopEE @Produces @Dependent public SnoopEEServiceClient lookup(InjectionPoint ip) { final String applicationName = ip.getAnnotated().getAnnotation(SnoopEE.class).serviceName(); LOGGER.config(() -> "producing " + applicationName); String serviceUrl = "http://" + readProperty("snoopeeService", snoopeeConfig); LOGGER.config(() -> "Service URL: " + serviceUrl); return new SnoopEEServiceClient.Builder(applicationName) .serviceUrl(serviceUrl) .build(); }
@Inject public AsyncReferenceImpl(InjectionPoint injectionPoint, Vertx vertx, BeanManager beanManager, @Any WeldInstance<Object> instance) { this.isDone = new AtomicBoolean(false); this.future = new VertxCompletableFuture<>(vertx); this.instance = instance; ParameterizedType parameterizedType = (ParameterizedType) injectionPoint.getType(); Type requiredType = parameterizedType.getActualTypeArguments()[0]; Annotation[] qualifiers = injectionPoint.getQualifiers().toArray(new Annotation[] {}); // First check if there is a relevant async producer method available WeldInstance<Object> completionStage = instance.select(new ParameterizedTypeImpl(CompletionStage.class, requiredType), qualifiers); if (completionStage.isAmbiguous()) { failure(new AmbiguousResolutionException( "Ambiguous async producer methods for type " + requiredType + " with qualifiers " + injectionPoint.getQualifiers())); } else if (!completionStage.isUnsatisfied()) { // Use the produced CompletionStage initWithCompletionStage(completionStage.getHandler()); } else { // Use Vertx worker thread initWithWorker(requiredType, qualifiers, vertx, beanManager); } }
/** * Get the property key to use. * In case the {@link ConfigProperty#name()} is empty we will try to determine the key name from the InjectionPoint. */ public static String getConfigKey(InjectionPoint ip, ConfigProperty configProperty) { String key = configProperty.name(); if (key.length() > 0) { return key; } if (ip.getAnnotated() instanceof AnnotatedMember) { AnnotatedMember member = (AnnotatedMember) ip.getAnnotated(); AnnotatedType declaringType = member.getDeclaringType(); if (declaringType != null) { String[] parts = declaringType.getJavaClass().getName().split("."); String cn = parts[parts.length-1]; parts[parts.length-1] = Character.toLowerCase(cn.charAt(0)) + (cn.length() > 1 ? cn.substring(1) : ""); StringBuilder sb = new StringBuilder(parts[0]); for (int i = 1; i < parts.length; i++) { sb.append(".").append(parts[i]); } // now add the field name sb.append(".").append(member.getJavaMember().getName()); return sb.toString(); } } throw new IllegalStateException("Could not find default name for @ConfigProperty InjectionPoint " + ip); }
@Produces @Link public String expose(InjectionPoint ip) { Annotated field = ip.getAnnotated(); Link link = field.getAnnotation(Link.class); String linkName = link.name(); if (linkName.isEmpty()) { linkName = ip.getMember().getName().toUpperCase(); } int portNumber = link.portNumber(); String resource = link.path(); if (resource.isEmpty()) { return URIProvider.computeUri(linkName, portNumber); } else { return URIProvider.computeUri(linkName, portNumber, resource); } }
@Produces @Dependent @Property public Integer produceIntegerProperty(InjectionPoint injectionPoint) { try { final String value = getProperty(injectionPoint); if (value != null) { return Integer.valueOf(value); } final Type type = injectionPoint.getType(); return type.equals(int.class) ? Integer.valueOf(0) : null; } catch (Exception e) { throw new InjectionException(e); } }
@Produces @Dependent @Property public Long produceLongProperty(InjectionPoint injectionPoint) { try { final String value = getProperty(injectionPoint); if (value != null) { return Long.valueOf(value); } final Type type = injectionPoint.getType(); return type.equals(long.class) ? Long.valueOf(0L) : null; } catch (Exception e) { throw new InjectionException(e); } }
@Produces @Dependent @Property public Float produceFloatProperty(InjectionPoint injectionPoint) { try { final String value = getProperty(injectionPoint); if (value != null) { return Float.valueOf(value); } final Type type = injectionPoint.getType(); return type.equals(float.class) ? Float.valueOf(0f) : null; } catch (Exception e) { throw new InjectionException(e); } }
@Produces @Dependent @Property public Double produceDoubleProperty(InjectionPoint injectionPoint) { try { final String value = getProperty(injectionPoint); if (value != null) { return Double.valueOf(value); } final Type type = injectionPoint.getType(); return type.equals(double.class) ? Double.valueOf(0d) : null; } catch (Exception e) { throw new InjectionException(e); } }
@Produces @Dependent @Property public BigInteger produceBigIntegerProperty(InjectionPoint injectionPoint) { try { final BigDecimal value = produceBigDecimalProperty(injectionPoint); if (value != null) { return value.toBigInteger(); } } catch (Exception e) { throw new InjectionException(e); } return null; }
@Produces @Dependent @Property public Date produceDateProperty(InjectionPoint injectionPoint) { try { final String value = getProperty(injectionPoint); final Date date; if (value != null) { final Property annotation = injectionPoint.getAnnotated().getAnnotation(Property.class); final String pattern = annotation.pattern(); DateFormat format = new SimpleDateFormat(pattern.isEmpty() ? "yyyy-MM-dd'T'HH:mm:ss.SSSZ" : pattern); date = format.parse(value); } else { date = null; } return date; } catch (Exception e) { throw new InjectionException(e); } }
public void validate(@Observes AfterDeploymentValidation add) { List<String> deploymentProblems = new ArrayList<>(); config = ConfigProvider.getConfig(); for (InjectionPoint injectionPoint : injectionPoints) { Type type = injectionPoint.getType(); ConfigProperty configProperty = injectionPoint.getAnnotated().getAnnotation(ConfigProperty.class); if (type instanceof Class) { // a direct injection of a ConfigProperty // that means a Converter must exist. String key = ConfigInjectionBean.getConfigKey(injectionPoint, configProperty); if (!config.getOptionalValue(key, (Class) type).isPresent()) { deploymentProblems.add("No Config Value exists for " + key); } } } if (!deploymentProblems.isEmpty()) { add.addDeploymentProblem(new DeploymentException("Error while validating Configuration\n" + String.join("\n", deploymentProblems))); } }
@Override public Object resolve(final InjectionPoint injectionPoint) { if (RestServer.class != injectionPoint.getType()) { return null; } final RestServerImpl server = new RestServerImpl( annotationScanner, dependencyInjection, dependencyInjection.getInstancesOf(StaticResourceResolver.class, releaser) ); servers.add(server); return server; }
@Override public Object resolve(final InjectionPoint injectionPoint) { if (null == injectionPoint.getAnnotated().getAnnotation(Resource.class)) { return null; } if (ConnectionFactory.class != injectionPoint.getType()) { return null; } return new TestEEfiConnectionFactory(testQueue::addMessage); }
@Override public Object resolve(final InjectionPoint injectionPoint) { final Resource annotation = injectionPoint.getAnnotated().getAnnotation(Resource.class); if (null == annotation) { return null; } if (Queue.class != injectionPoint.getType()) { return null; } return new TestEEfiQueue(annotation.mappedName()); }
@Override public Object resolve(final InjectionPoint injectionPoint) { if (null == injectionPoint.getAnnotated().getAnnotation(Resource.class)) { return null; } if (TestQueue.class != injectionPoint.getType()) { return null; } return testQueue; }
@Override public Object resolve(final InjectionPoint injectionPoint) { final Resource annotation = injectionPoint.getAnnotated().getAnnotation(Resource.class); if (null == annotation) { return null; } if (Topic.class != injectionPoint.getType()) { return null; } return new TestEEfiTopic(annotation.mappedName()); }
@Override public Object resolve(final InjectionPoint injectionPoint) { if (injectionPoint.getType() != DataSource.class) { return null; } final Resource annotation = injectionPoint.getAnnotated().getAnnotation(Resource.class); if (annotation == null) { return null; } return resolve(null, annotation.mappedName()); }
@Override public ResourceReferenceFactory<EntityManager> registerPersistenceContextInjectionPoint( final InjectionPoint injectionPoint ) { final PersistenceContext persistenceContext = injectionPoint .getAnnotated() .getAnnotation(PersistenceContext.class); final String unitName = persistenceContext.unitName(); return registerPersistenceContextInjectionPoint(unitName); }
@Override public Object resolve(final InjectionPoint injectionPoint) { if (injectionPoint.getAnnotated().getAnnotation(Resource.class) == null) { return null; } return resources.get(injectionPoint.getAnnotated().getAnnotation(Resource.class).mappedName()); }
public <T, X> void injectionPoints( final @Observes ProcessInjectionPoint<T, X> processInjectionPoint ) { final Type type = processInjectionPoint.getInjectionPoint().getType(); final Object mock = mockStore.findFor(type); if (mock == null) { return; } LOG.debug("Mocking injection point: {}", processInjectionPoint.getInjectionPoint()); final InjectionPoint original = processInjectionPoint.getInjectionPoint(); processInjectionPoint.setInjectionPoint(new ForwardingInjectionPoint() { @Override public Set<Annotation> getQualifiers() { final Set<Annotation> ret = new HashSet<>(super.getQualifiers()).stream() .filter(it -> !(it instanceof Default)) .collect(toSet()); ret.add(MOCKED); return ret; } @Override protected InjectionPoint delegate() { return original; } }); mockedInjectionPoints.add(original); }
@Produces @BankProducer public Bank createBank(@Any Instance<Bank> instance, InjectionPoint injectionPoint) { Annotated annotated = injectionPoint.getAnnotated(); BankType bankTypeAnnotation = annotated.getAnnotation(BankType.class); Class<? extends Bank> bankType = bankTypeAnnotation.value().getBankType(); return instance.select(bankType).get(); }
@Produces public Span produceSpan(InjectionPoint ip) { Scope scope = tracer.scopeManager().active(); if (null == scope) { String spanName = ip.getMember().getName(); return tracer.buildSpan(spanName).startActive().span(); } return scope.span(); }
@Produces public Scope produceScope(InjectionPoint ip) { Scope scope = tracer.scopeManager().active(); if (null == scope) { String spanName = ip.getMember().getName(); return tracer.buildSpan(spanName).startActive(); } return scope; }