@Uri("") @Produces @Typed(MockEndpoint.class) // Qualifiers are dynamically added in CdiCamelExtension private static MockEndpoint mockEndpointFromUri(InjectionPoint ip, @Any Instance<CamelContext> instance, CdiCamelExtension extension) { Uri uri = getQualifierByType(ip, Uri.class).get(); try { CamelContext context = uri.context().isEmpty() ? selectContext(ip, instance, extension) : selectContext(uri.context(), instance); return context.getEndpoint(uri.value(), MockEndpoint.class); } catch (Exception cause) { throw new InjectionException("Error injecting mock endpoint annotated with " + uri + " into " + ip, cause); } }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { Instance<Object> instance = CDI.current(); User user = instance.select(User.class).get(); List<AccountRole> roles = user.getAccountRoles(); if (Arrays.stream(permissions.roles()).anyMatch(roles::contains)) { return; } Permission permission = instance.select(permissions.value()).get(); if (permission.test(requestContext)) { return; } throw new ForbiddenException(); }
@Before public void prepare() { ZonedDateTimeAdapter adapter = new ZonedDateTimeAdapter(); Instance<BoundStatement> getByIdStatement = mock(Instance.class); when(getByIdStatement.get()) .thenReturn(new BoundStatement(session.prepare(BoundStatements.GET_BY_ID.getValue()))); Instance<BoundStatement> createStatement = mock(Instance.class); when(createStatement.get()) .thenReturn(new BoundStatement(session.prepare(BoundStatements.CREATE.getValue()))); tokenService = new TokenService(); tokenService.session = session; tokenService.zonedDateTimeAdapter = adapter; tokenService.stmtGetById = getByIdStatement; tokenService.stmtCreate = createStatement; }
@Inject public PreferenceStoreImpl(final PreferenceStorage storage, final PreferenceScopeFactory scopeFactory, @Customizable final PreferenceScopeResolutionStrategy defaultScopeResolutionStrategy, final Instance<PreferenceScopeResolutionStrategy> preferenceScopeResolutionStrategy, final InjectionPoint ip) { this.storage = storage; this.scopeFactory = scopeFactory; if (preferenceScopeResolutionStrategy.isUnsatisfied()) { if (ip != null) { String componentKey = null; Annotation annotation = ip.getAnnotated().getAnnotation(ComponentKey.class); if (annotation != null) { componentKey = ((ComponentKey) annotation).value(); } this.defaultScopeResolutionStrategy = new DefaultPreferenceScopeResolutionStrategy(scopeFactory, componentKey); } else { this.defaultScopeResolutionStrategy = defaultScopeResolutionStrategy; } } else { this.defaultScopeResolutionStrategy = preferenceScopeResolutionStrategy.get(); } }
@Inject public Row(View view, Instance<ComponentColumn> columnInstance, Instance<ColumnWithComponents> columnWithComponentsInstance, DnDManager dndManager, LayoutDragComponentHelper layoutDragComponentHelper, Event<ComponentDropEvent> componentDropEvent, Event<ComponentRemovedEvent> componentRemovedEvent, Event<RowResizeEvent> rowResizeEvent) { this.view = view; this.columnInstance = columnInstance; this.columnWithComponentsInstance = columnWithComponentsInstance; this.dndManager = dndManager; this.layoutDragComponentHelper = layoutDragComponentHelper; this.componentDropEvent = componentDropEvent; this.componentRemovedEvent = componentRemovedEvent; this.rowResizeEvent = rowResizeEvent; }
@Inject public CopyServiceImpl(@Named("ioStrategy") IOService ioService, User identity, SessionInfo sessionInfo, Instance<CopyHelper> helpers, Event<ResourceCopiedEvent> resourceCopiedEvent, Instance<CopyRestrictor> copyRestrictorBeans, PathNamingService pathNamingService) { this.ioService = ioService; this.identity = identity; this.sessionInfo = sessionInfo; this.helpers = helpers; this.resourceCopiedEvent = resourceCopiedEvent; this.copyRestrictorBeans = copyRestrictorBeans; this.pathNamingService = pathNamingService; }
@Before public void setup() { securityConstraints = mock(Instance.class); event1 = generateEvent(new SocialUser("admin")); event2 = generateEvent(new SocialUser("dora")); events = new ArrayList<>(); events.add(event1); events.add(event2); constraint1 = mock(SocialSecurityConstraint.class); constraint2 = mock(SocialSecurityConstraint.class); when(securityConstraints.iterator()).thenReturn(createSecurityConstraintsIterator()); socialSecurityConstraintsManager = new SocialSecurityConstraintsManager() { @Override Instance<SocialSecurityConstraint> getSocialSecurityConstraints() { Instance<SocialSecurityConstraint> mock = mock(Instance.class); when(mock.iterator()).thenReturn(createSecurityConstraintsIterator()); return mock; } }; }
@Inject public PanelManagerImpl( Event<PlaceGainFocusEvent> placeGainFocusEvent, Event<PlaceLostFocusEvent> placeLostFocusEvent, Event<PanelFocusEvent> panelFocusEvent, Event<SelectPlaceEvent> selectPlaceEvent, Event<PlaceMaximizedEvent> placeMaximizedEvent, Event<PlaceMinimizedEvent> placeMinimizedEventEvent, Event<PlaceHiddenEvent> placeHiddenEvent, SyncBeanManager iocManager, Instance<PlaceManager> placeManager, LayoutSelection layoutSelection, BeanFactory beanFactory) { this.placeGainFocusEvent = placeGainFocusEvent; this.placeLostFocusEvent = placeLostFocusEvent; this.panelFocusEvent = panelFocusEvent; this.selectPlaceEvent = selectPlaceEvent; this.placeMaximizedEvent = placeMaximizedEvent; this.placeMinimizedEvent = placeMinimizedEventEvent; this.placeHiddenEvent = placeHiddenEvent; this.iocManager = iocManager; this.placeManager = placeManager; this.layoutSelection = layoutSelection; this.beanFactory = beanFactory; }
@Before public void setupGuvnorM2Repository() { ArtifactRepositoryPreference pref = mock(ArtifactRepositoryPreference.class); when(pref.getGlobalM2RepoDir()).thenReturn("repositories/kie"); when(pref.isGlobalM2RepoDirEnabled()).thenReturn(true); when(pref.isDistributionManagementM2RepoDirEnabled()).thenReturn(true); when(pref.isWorkspaceM2RepoDirEnabled()).thenReturn(false); WorkspaceNameResolver resolver = mock(WorkspaceNameResolver.class); when(resolver.getWorkspaceName()).thenReturn("global"); ArtifactRepositoryProducer producer = new ArtifactRepositoryProducer(pref, resolver); producer.initialize(); Instance<ArtifactRepository> repositories = new MockInstanceImpl<>(producer.produceLocalRepository(), producer.produceGlobalRepository(), producer.produceDistributionManagementRepository()); ArtifactRepositoryService factory = new ArtifactRepositoryService(repositories); repository = new GuvnorM2Repository(factory); repository.init(); }
/** * Test of getJsTopicMessageControllerFromJsTopicControls method, of class. */ @Test public void getJsTopicMessageControllerFromJsTopicControlsTest() { System.out.println("getJsTopicMessageControllerFromJsTopicControls"); JsTopicMessageController jtmc = mock(JsTopicMessageController.class); Instance select = mock(Instance.class); when(topicMessageController.select(any(JsTopicCtrlsAnnotationLiteral.class))).thenReturn(select); when(select.isUnsatisfied()).thenReturn(Boolean.TRUE).thenReturn(Boolean.FALSE); doReturn(jtmc).when(instance).getJsTopicMessageControllerFromIterable(eq(TOPIC), any(Instance.class)); JsTopicMessageController result = instance.getJsTopicMessageControllerFromJsTopicControls(TOPIC); assertThat(result).isNull(); result = instance.getJsTopicMessageControllerFromJsTopicControls(TOPIC); assertThat(result).isEqualTo(jtmc); }
/** * Test of checkAccessTopicFromJsTopicAccessControllers method, of class. * @throws java.lang.IllegalAccessException */ @Test(expected = IllegalAccessException.class) public void checkAccessTopicFromJsTopicControlsTest() throws IllegalAccessException { System.out.println("checkAccessTopicFromJsTopicControls"); UserContext userContext = mock(UserContext.class); Instance instances = mock(Instance.class); when(topicAccessController.select(eq(new JsTopicCtrlsAnnotationLiteral()))).thenReturn(instances); when(instances.isUnsatisfied()).thenReturn(Boolean.TRUE).thenReturn(Boolean.FALSE); doReturn(Boolean.TRUE).doReturn(Boolean.FALSE).doThrow(IllegalAccessException.class).when(instance).checkAccessTopicFromJsTopicAccessControllers(eq(userContext), eq(TOPIC1), eq(instances)); boolean result = instance.checkAccessTopicFromJsTopicControls(userContext, TOPIC1); assertThat(result).isFalse(); result = instance.checkAccessTopicFromJsTopicControls(userContext, TOPIC1); assertThat(result).isTrue(); result = instance.checkAccessTopicFromJsTopicControls(userContext, TOPIC1); assertThat(result).isFalse(); instance.checkAccessTopicFromJsTopicControls(userContext, TOPIC1); }
protected AbstractLightblueProxyServlet getTestServlet(CloseableHttpClient httpClient, LightblueClientConfiguration clientConfig, final String serviceUri, ServletConfig servletConfig) throws ServletException { Instance<LightblueClientConfiguration> instance = new StubInstance<>(clientConfig); AbstractLightblueProxyServlet servlet; servlet = new AbstractLightblueProxyServlet(httpClient, instance) { @Override protected String serviceUriForRequest(HttpServletRequest request) throws ServletException { return serviceUri + servicePathForRequest(request); } ; }; if (servletConfig == null) { servlet.init(); } else { servlet.init(servletConfig); } return servlet; }
public AuthorizationCodeGrant asCodeGrant(Instance<AbstractAuthorizationGrant> grantInstance) { AuthorizationCodeGrant grant = grantInstance.select(AuthorizationCodeGrant.class).get(); grant.init(user, client, authenticationTime); grant.setAuthorizationCode(new AuthorizationCode(authorizationCodeString, authorizationCodeCreationDate, authorizationCodeExpirationDate)); grant.setScopes(scopes); grant.setGrantId(grantId); grant.setSessionDn(sessionDn); grant.setCodeChallenge(codeChallenge); grant.setCodeChallengeMethod(codeChallengeMethod); grant.setAcrValues(acrValues); grant.setNonce(nonce); grant.setClaims(claims); return grant; }
@SuppressWarnings({ "unchecked" }) @Test public void testByDir() throws TemplateProcessorException { Instance<ProxiedParam<String>> templateDirectory = Mockito.mock(Instance.class); ProxiedParam<String> pp = new ProxiedParam<>(); pp.setParam(Paths.get("src/test/resources/templates/").toAbsolutePath().toString()); Mockito.when(templateDirectory.isUnsatisfied()).thenReturn(Boolean.FALSE); Mockito.when(templateDirectory.get()).thenReturn(pp); TemplateConfigProducer producer = new TemplateConfigProducer(templateDirectory); TemplateProcessor p = new TemplateProcessor(producer.produceConfiguration()); Assert.assertEquals("template val.", p.processTemplate("test2.ftl", null)); }
/** * Initialise all statistics modules that are found in the system * @param modules */ @Inject protected void initModules(@Any Instance<StatisticsModule> modules) { log.info("Apache Marmotta StatisticsService starting up ..."); this.modules = new LinkedHashMap<String,StatisticsModule>(); for(StatisticsModule module : modules) { registerModule(module.getName(),module); } if(configurationService.getBooleanConfiguration("statistics.enabled",false)) { enableAll(); } else { disableAll(); } }
@PostConstruct protected void initialize() { log.debug("initializing AuthenticationService"); final String prov = configurationService.getStringConfiguration("user.auth.provider", DEFAULT_AUTH_PROVIDER_NAMED); Instance<AuthenticationProvider> selected = CDIUtils.selectNamed(providers, prov); if (selected.isAmbiguous()) { authenticationProvider = selected.iterator().next(); log.error("multiple candidates for AuthenticationProvider '{}' found. Chose randomly!", prov); } else if (selected.isUnsatisfied()) { log.error("no candidate for AuthenticationProvider '{}' found, falling back to default", prov); authenticationProvider = CDIUtils.selectNamed(providers, DEFAULT_AUTH_PROVIDER_NAMED).iterator().next(); } else { authenticationProvider = selected.get(); } }
public HealthCheckModel performHealthChecks() { Instance<HealthCheck> healthChecks = this.healthChecks; if (requireAnnotation) { healthChecks = this.healthChecks.select(HealthLiteral.INSTANCE); } List<HealthCheck> healthCheckBeans = healthChecks.stream() .collect(toList()); List<HealthResultModel> results = healthCheckBeans.stream() .map(HealthCheck::call) .map(r -> new HealthResultModel(r.getName(), r.getState().name(), r.getData().orElse(emptyMap()))) .collect(toList()); boolean anyDown = results.stream().anyMatch(r -> r.getState().equalsIgnoreCase(HealthCheckResponse.State.DOWN.name())); try { if (anyDown) { return toModel(HealthCheckResponse.State.DOWN, results); } else { return toModel(HealthCheckResponse.State.UP, results); } } finally { healthCheckBeans.forEach(healthChecks::destroy); } }
@Inject public GuidedRuleEditorCopyHelper(final @Named("ioStrategy") IOService ioService, final GuidedRuleDRLResourceTypeDefinition drlResourceType, final GuidedRuleDSLRResourceTypeDefinition dslrResourceType, final GuidedRuleEditorServiceUtilities utilities, final CommentedOptionFactory commentedOptionFactory, final DataModelService dataModelService, final Instance<RuleModelIActionPersistenceExtension> persistenceExtensionInstance) { this.ioService = ioService; this.drlResourceType = drlResourceType; this.dslrResourceType = dslrResourceType; this.utilities = utilities; this.commentedOptionFactory = commentedOptionFactory; this.dataModelService = dataModelService; persistenceExtensionInstance.forEach(persistenceExtensions::add); }
@Inject public GuidedRuleEditorRenameHelper(final @Named("ioStrategy") IOService ioService, final GuidedRuleDRLResourceTypeDefinition drlResourceType, final GuidedRuleDSLRResourceTypeDefinition dslrResourceType, final GuidedRuleEditorServiceUtilities utilities, final CommentedOptionFactory commentedOptionFactory, final DataModelService dataModelService, final Instance<RuleModelIActionPersistenceExtension> persistenceExtensionInstance) { this.ioService = ioService; this.drlResourceType = drlResourceType; this.dslrResourceType = dslrResourceType; this.utilities = utilities; this.commentedOptionFactory = commentedOptionFactory; this.dataModelService = dataModelService; persistenceExtensionInstance.forEach(persistenceExtensions::add); }
@SuppressWarnings("unchecked") private void createFixture(Instance<Properties> joynrProperties, Instance<String> joynrLocalDomain) throws Exception { Instance<RawMessagingPreprocessor> rawMessageProcessor = mock(Instance.class); when(rawMessageProcessor.get()).thenReturn(new NoOpRawMessagingPreprocessor()); BeanManager beanManager = mock(BeanManager.class); Bean<JoynrMessageProcessor> bean = mock(Bean.class); when(bean.create(Mockito.any())).thenReturn(new JoynrMessageProcessorTest()); when(beanManager.getBeans(Mockito.<Type> eq(JoynrMessageProcessor.class), Mockito.<Annotation> any())).thenReturn(Sets.newHashSet(bean)); final String mqttClientId = "someTestMqttClientId"; MqttClientIdProvider mqttClientIdProvider = mock(MqttClientIdProvider.class); when(mqttClientIdProvider.getClientId()).thenReturn(mqttClientId); Instance<MqttClientIdProvider> mqttClientIdProviderInstance = mock(Instance.class); when(mqttClientIdProviderInstance.get()).thenReturn(mqttClientIdProvider); fixture = new DefaultJoynrRuntimeFactory(joynrProperties, joynrLocalDomain, rawMessageProcessor, mqttClientIdProviderInstance, beanManager); scheduledExecutorService = mock(ScheduledExecutorService.class); Field executorField = DefaultJoynrRuntimeFactory.class.getDeclaredField("scheduledExecutorService"); executorField.setAccessible(true); executorField.set(fixture, scheduledExecutorService); }
@Inject protected JsfRequestLifecycleBroadcaster(Instance<PhaseListener> phaseListenerInstance) { Class phaseListenerClass; for (PhaseListener currentPhaseListener : phaseListenerInstance) { phaseListenerClass = ProxyUtils.getUnproxiedClass(currentPhaseListener.getClass()); if (phaseListenerClass.isAnnotationPresent(JsfPhaseListener.class)) { if (Deactivatable.class.isAssignableFrom(phaseListenerClass) && !ClassDeactivationUtils.isActivated(phaseListenerClass)) { continue; } this.phaseListeners.add(currentPhaseListener); } } //higher ordinals first sortDescending(this.phaseListeners); }
@Inject public ValidationServiceImpl(final org.uberfire.ext.editor.commons.service.ValidationService validationService, final PackageNameValidator packageNameValidator, final ModuleNameValidator moduleNameValidator, final JavaFileNameValidator javaFileNameValidator, final Instance<SaveValidator<?>> saveValidatorInstance, final Instance<CopyValidator<?>> copyValidatorInstance, final Instance<DeleteValidator<?>> deleteValidatorInstance) { this.validationService = validationService; this.packageNameValidator = packageNameValidator; this.moduleNameValidator = moduleNameValidator; this.javaFileNameValidator = javaFileNameValidator; saveValidatorInstance.forEach(saveValidators::add); copyValidatorInstance.forEach(copyValidators::add); deleteValidatorInstance.forEach(deleteValidators::add); }
@Inject public BuildHelper(final POMService pomService, final ExtendedM2RepoService m2RepoService, final KieModuleService moduleService, final DeploymentVerifier deploymentVerifier, final LRUBuilderCache cache, final Instance<PostBuildHandler> handlers, final Instance<User> identity) { this.pomService = pomService; this.m2RepoService = m2RepoService; this.moduleService = moduleService; this.deploymentVerifier = deploymentVerifier; this.cache = cache; this.handlers = handlers; this.identity = identity; }
@Inject public LRUBuilderCache(final @Named("ioStrategy") IOService ioService, final KieModuleService moduleService, final ProjectImportsService importsService, final @Any Instance<BuildValidationHelper> buildValidationHelperBeans, final @Named("LRUModuleDependenciesClassLoaderCache") LRUModuleDependenciesClassLoaderCache dependenciesClassLoaderCache, final @Named("LRUPomModelCache") LRUPomModelCache pomModelCache, final PackageNameWhiteListService packageNameWhiteListService, final @JavaSourceFilter Instance<Predicate<String>> classFilterBeans) { this.ioService = ioService; this.moduleService = moduleService; this.importsService = importsService; this.buildValidationHelperBeans = buildValidationHelperBeans; this.dependenciesClassLoaderCache = dependenciesClassLoaderCache; this.pomModelCache = pomModelCache; this.packageNameWhiteListService = (PackageNameWhiteListServiceImpl) packageNameWhiteListService; this.classFilterBeans = classFilterBeans; }
@Inject public LRUDataModelOracleCache(final @Named("ioStrategy") IOService ioService, final FileDiscoveryService fileDiscoveryService, final @Named("ModuleDataModelOracleCache") LRUModuleDataModelOracleCache cacheModules, final KieModuleService moduleService, final BuildInfoService buildInfoService, final Instance<DataModelExtension> dataModelExtensionsProvider, final MVELEvaluator evaluator) { this.ioService = ioService; this.fileDiscoveryService = fileDiscoveryService; this.cacheModules = cacheModules; this.moduleService = moduleService; this.buildInfoService = buildInfoService; this.dataModelExtensionsProvider = dataModelExtensionsProvider; this.evaluator = evaluator; }
@Inject public ApplicationDefinitionManager(final RegistryFactory registryFactory, final AdapterManager adapterManager, final Instance<DefinitionSetProxy<?>> definitionSetsInstances, final Instance<DefinitionSetAdapter<?>> definitionSetAdapterInstances, final Instance<DefinitionSetRuleAdapter<?>> definitionSetRuleAdapterInstances, final Instance<DefinitionAdapter<?>> definitionAdapterInstances, final Instance<PropertySetAdapter<?>> propertySetAdapterInstances, final Instance<PropertyAdapter<?, ?>> propertyAdapterInstances, final Instance<MorphAdapter<?>> morphAdapterInstances, final CloneManager cloneManager) { super(registryFactory, adapterManager, cloneManager); this.definitionSetsInstances = definitionSetsInstances; this.definitionSetAdapterInstances = definitionSetAdapterInstances; this.definitionSetRuleAdapterInstances = definitionSetRuleAdapterInstances; this.definitionAdapterInstances = definitionAdapterInstances; this.propertySetAdapterInstances = propertySetAdapterInstances; this.propertyAdapterInstances = propertyAdapterInstances; this.morphAdapterInstances = morphAdapterInstances; }
@Inject public ApplicationFactoryManager(final RegistryFactory registryFactory, final DefinitionManager definitionManager, final Instance<DefinitionFactory<?>> definitionFactoryInstances, final Instance<GraphFactory> graphFactoryInstances, final Instance<NodeFactory<?>> nodeFactoryInstances, final Instance<EdgeFactory<?>> edgeFactoryInstances, final Instance<DiagramFactory<?, ?>> diagramFactoryInstances) { super(registryFactory, definitionManager); this.definitionFactoryInstances = definitionFactoryInstances; this.graphFactoryInstances = graphFactoryInstances; this.nodeFactoryInstances = nodeFactoryInstances; this.edgeFactoryInstances = edgeFactoryInstances; this.diagramFactoryInstances = diagramFactoryInstances; }
@Inject public ProjectDiagramServiceImpl(final DefinitionManager definitionManager, final FactoryManager factoryManager, final Instance<DefinitionSetService> definitionSetServiceInstances, final BackendRegistryFactory registryFactory, final @Named("ioStrategy") IOService ioService, final SessionInfo sessionInfo, final Event<ResourceOpenedEvent> resourceOpenedEvent, final CommentedOptionFactory commentedOptionFactory) { this.ioService = ioService; this.sessionInfo = sessionInfo; this.resourceOpenedEvent = resourceOpenedEvent; this.commentedOptionFactory = commentedOptionFactory; this.controller = new ProjectDiagramServiceController(definitionManager, factoryManager, definitionSetServiceInstances, ioService, registryFactory); }
@Override public void setup() throws IOException { FormModelVisitor visitor = mock(FormModelVisitor.class); FormModelVisitorProvider provider = mock(FormModelVisitorProvider.class); when(provider.getModelType()).thenReturn(FormModel.class); when(provider.getVisitor()).thenReturn(visitor); Instance<FormModelVisitorProvider<?>> providersInstance = mock(Instance.class); List<FormModelVisitorProvider<?>> providers = Arrays.asList(provider); when(providersInstance.iterator()).thenReturn(providers.iterator()); indexer = spy(new TestFormDefinitionIndexer(new FormResourceTypeDefinition(), new FormDefinitionSerializerImpl(new FieldSerializer(), new FormModelSerializer(), new TestMetaDataEntryManager()), providersInstance)); when(indexer.getProviderForModel(any())).thenReturn(provider); super.setup(); }
@Inject public NewDeployWizard(final SelectPipelinePagePresenter selectPipelinePage, final ManagedInstance<PipelineParamsPagePresenter> pipelineParamsPageInstance, final @Any Instance<PipelineDescriptor> pipelineDescriptorInstance, final PopupHelper popupHelper, final TranslationService translationService, final Caller<RuntimeService> runtimeService, final Event<NotificationEvent> notification, final Event<RefreshRuntimeEvent> refreshRuntimeEvent) { super(translationService, notification); this.popupHelper = popupHelper; this.selectPipelinePage = selectPipelinePage; this.pipelineParamsPageInstance = pipelineParamsPageInstance; this.pipelineDescriptorInstance = pipelineDescriptorInstance; this.runtimeService = runtimeService; this.refreshRuntimeEvent = refreshRuntimeEvent; }
@Test @SuppressWarnings("unchecked") public void checkValidationWhenFactTypeIsNull() throws Exception { final Instance<DynamicValidator> validatorInstance = mock(Instance.class); final DynamicValidator validator = mock(DynamicValidator.class); when(validatorInstance.isUnsatisfied()).thenReturn(true); setupMockNotNullConstraint(validator); final AsyncPackageDataModelOracle oracle = getOracle(SmurfValidation1.class, validatorInstance); oracle.validateField(null, "name", null, (Set<ConstraintViolation<String>> violations) -> assertEquals(0, violations.size())); }
@Test @SuppressWarnings("unchecked") public void checkValidationWhenFieldNameIsNull() throws Exception { final Instance<DynamicValidator> validatorInstance = mock(Instance.class); final DynamicValidator validator = mock(DynamicValidator.class); when(validatorInstance.isUnsatisfied()).thenReturn(true); setupMockNotNullConstraint(validator); final AsyncPackageDataModelOracle oracle = getOracle(SmurfValidation1.class, validatorInstance); oracle.validateField("SmurfValidation1", null, null, (Set<ConstraintViolation<String>> violations) -> assertEquals(0, violations.size())); }
@Inject public RepositoryFactoryImpl(Instance<SurveyRepository> surveyRepository, Instance<UserRepository> userRepository, Instance<ResponseRepository> responseRepository) { this.surveyRepository = surveyRepository; this.userRepository = userRepository; this.responseRepository = responseRepository; }
@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(); }
public void addRegistryBean(@Observes AfterBeanDiscovery afterBeanDiscovery) { afterBeanDiscovery.addBean() .types(ReactorObserverRegistry.class) .produceWith((Function<Instance<Object>, Object>) f -> REGISTRY) .scope(ApplicationScoped.class); eventTypes.forEach(ip -> afterBeanDiscovery.addBean() .types(ip.getType()) .scope(Dependent.class) .produceWith((Function<Instance<Object>, Object>) inst -> { ParameterizedType type = (ParameterizedType) ip.getType(); Class<?> s = (Class<?>) type.getActualTypeArguments()[0]; Class<?> r = (Class<?>) type.getActualTypeArguments()[1]; return new ReactorEventImpl<>(s,r,ip.getQualifiers(),REGISTRY); })); }
private Type unwrapType(Type type) { if(type instanceof ParameterizedType) { Type rawType = ((ParameterizedType) type).getRawType(); if(rawType == Provider.class || rawType == Instance.class) { return ((ParameterizedType) type).getActualTypeArguments()[0]; } } return type; }
private void executeHooks(Instance<? extends Object> hooks, InventoryCount inventory) throws Exception { if (hooks != null) { for (Iterator<? extends Object> procIter = hooks.iterator(); procIter.hasNext();) { Object proc = procIter.next(); if (proc instanceof InventoryCountProcessHook) { ((InventoryCountProcessHook) proc).exec(inventory); } else { ((InventoryCountCheckHook) proc).exec(inventory); } } } }
@Inject public PersistentTranslationService(TextFlowDAO textFlowDAO, TextFlowTargetDAO textFlowTargetDAO, Instance<TranslatorBackend> translatorBackends) { this.textFlowDAO = textFlowDAO; this.textFlowTargetDAO = textFlowTargetDAO; Map<BackendID, TranslatorBackend> backendMap = new HashMap<>(); for (TranslatorBackend backend : translatorBackends) { backendMap.put(backend.getId(), backend); } translatorBackendMap = Collections.unmodifiableMap(backendMap); }
@Override public <T> InstanceFactory<T> createInstanceFactory(Class<T> clazz) throws NoSuchMethodException { LOGGER.fine("createInstanceFactory: " + clazz); Instance<T> inst = CDI.current().select(clazz); if (inst.isUnsatisfied() || inst.isAmbiguous()) { return DefaultClassIntrospector.INSTANCE.createInstanceFactory(clazz); } else { return new CdiInstanceFactory<>(inst); } }
@Produces @Default @Uri("") // Qualifiers are dynamically added in CdiCamelExtension private static ProducerTemplate producerTemplate(InjectionPoint ip, @Any Instance<CamelContext> instance, CdiCamelExtension extension) { return getQualifierByType(ip, Uri.class) .map(uri -> producerTemplateFromUri(ip, instance, extension, uri)) .orElseGet(() -> defaultProducerTemplate(ip, instance, extension)); }