Java 类javax.enterprise.inject.Instance 实例源码

项目:Camel    文件:CdiCamelFactory.java   
@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);
    }
}
项目:sealion    文件:PermissionProvider.java   
@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();
}
项目:secret-store    文件:TokenTest.java   
@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;
}
项目:appformer    文件:PreferenceStoreImpl.java   
@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();
    }
}
项目:appformer    文件:Row.java   
@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;
}
项目:appformer    文件:CopyServiceImpl.java   
@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;
}
项目:appformer    文件:SocialSecurityConstraintsManagerTest.java   
@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;
        }
    };
}
项目:appformer    文件:PanelManagerImpl.java   
@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;
}
项目:appformer    文件:JarPathTest.java   
@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();
}
项目:ocelot    文件:MessageControllerManagerTest.java   
/**
 * 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);
}
项目:ocelot    文件:TopicAccessManagerTest.java   
/**
 * 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);
}
项目:lightblue-client    文件:AbstractLightblueProxyServletTest.java   
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;
}
项目:oxAuth    文件:CacheGrant.java   
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;
}
项目:ara-commons    文件:TemplateProcessorTest.java   
@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));

}
项目:marmotta    文件:StatisticsServiceImpl.java   
/**
 * 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();
    }
}
项目:marmotta    文件:AuthenticationServiceImpl.java   
@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();
    }
}
项目:hammock    文件:HealthCheckManager.java   
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);
    }
}
项目:drools-wb    文件:GuidedRuleEditorCopyHelper.java   
@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);
}
项目:drools-wb    文件:GuidedRuleEditorRenameHelper.java   
@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);
}
项目:joynr    文件:DefaultJoynrRuntimeFactoryTest.java   
@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);
}
项目:deltaspike    文件:JsfRequestLifecycleBroadcaster.java   
@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);
}
项目:kie-wb-common    文件:ValidationServiceImpl.java   
@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);
}
项目:kie-wb-common    文件:BuildHelper.java   
@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;
}
项目:kie-wb-common    文件:LRUBuilderCache.java   
@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;
}
项目:kie-wb-common    文件:LRUDataModelOracleCache.java   
@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;
}
项目:kie-wb-common    文件:ApplicationDefinitionManager.java   
@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;
}
项目:kie-wb-common    文件:ApplicationFactoryManager.java   
@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;
}
项目:kie-wb-common    文件:ProjectDiagramServiceImpl.java   
@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);
}
项目:kie-wb-common    文件:FormDefinitionIndexerTest.java   
@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();
}
项目:kie-wb-common    文件:NewDeployWizard.java   
@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;
}
项目:kie-wb-common    文件:PackageDataModelFactFieldsValidationsTest.java   
@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()));
}
项目:kie-wb-common    文件:PackageDataModelFactFieldsValidationsTest.java   
@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()));
}
项目:webpoll    文件:RepositoryFactoryImpl.java   
@Inject
public RepositoryFactoryImpl(Instance<SurveyRepository> surveyRepository,
                             Instance<UserRepository> userRepository,
                             Instance<ResponseRepository> responseRepository) {
    this.surveyRepository = surveyRepository;
    this.userRepository = userRepository;
    this.responseRepository = responseRepository;
}
项目:Mastering-Java-EE-Development-with-WildFly    文件:BankFactory.java   
@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();
}
项目:reactive-cdi-events    文件:ReactorExtension.java   
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);
            }));
}
项目:incubator-tamaya-sandbox    文件:JavaConfigCDIExtension.java   
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;
}
项目:openbravo-brazil    文件:InventoryCountProcess.java   
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);
      }
    }
  }
}
项目:zanata-mt    文件:PersistentTranslationService.java   
@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);
}
项目:standalone-javax-mvc    文件:CdiClassIntrospecter.java   
@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);
    }
}
项目:Camel    文件:CdiCamelFactory.java   
@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));
}