org.apache.deltaspike.core.api.provider.BeanProvider Java Examples

The following examples show how to use org.apache.deltaspike.core.api.provider.BeanProvider. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CdiQueryInvocationContext.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
public QueryInOutMapper<?> getQueryInOutMapper()
{
    if (repositoryMethodMetadata.getQueryInOutMapperClass() == null)
    {
        return null;
    }

    QueryInOutMapper<?> result = null;
    if (repositoryMethodMetadata.isQueryInOutMapperIsNormalScope())
    {
        result = BeanProvider.getContextualReference(repositoryMethodMetadata.getQueryInOutMapperClass());
    }
    else
    {
        DependentProvider<? extends QueryInOutMapper<?>> mappedProvider =
                BeanProvider.getDependent(repositoryMethodMetadata.getQueryInOutMapperClass());
        
        result = mappedProvider.get();
        
        this.addDestroyable(new DependentProviderDestroyable(mappedProvider));
    }
    
    return result;
}
 
Example #2
Source File: CdiTestRunner.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Override
protected Object createTest() throws Exception
{
    BeanManager beanManager = BeanManagerProvider.getInstance().getBeanManager();

    Class<?> type = getTestClass().getJavaClass();
    Set<Bean<?>> beans = beanManager.getBeans(type);

    Object result;
    if (!USE_TEST_CLASS_AS_CDI_BEAN || beans == null || beans.isEmpty())
    {
        result = super.createTest();
        BeanProvider.injectFields(result); //fallback to simple injection
    }
    else
    {
        Bean<Object> bean = (Bean<Object>) beanManager.resolve(beans);
        CreationalContext<Object> creationalContext = beanManager.createCreationalContext(bean);
        result = beanManager.getReference(bean, type, creationalContext);
    }
    return result;
}
 
Example #3
Source File: SecurityUtils.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
private static void processApplicationSecurityException(AccessDeniedException exception,
                                                        Class<? extends ViewConfig> errorView,
                                                        boolean allowNavigation)
{
    SecurityViolationHandler securityViolationHandler =
            BeanProvider.getContextualReference(SecurityViolationHandler.class, true);

    if (securityViolationHandler != null)
    {
        //optional (custom handler) - allows to handle custom implementations of SecurityViolation
        securityViolationHandler.processSecurityViolations(exception.getViolations());
    }
    else
    {
        addViolationsAsMessage(exception.getViolations());
    }

    if (allowNavigation)
    {
        BeanProvider.getContextualReference(ViewNavigationHandler.class).navigateTo(errorView);
    }
}
 
Example #4
Source File: CucumberObjectFactory.java    From database-rider with Apache License 2.0 6 votes vote down vote up
@Override
public <T> T getInstance(Class<T> clazz)
{
    if (definitions.get(clazz) == null)
    {
        try {
            definitions.put(clazz, BeanProvider.getContextualReference(clazz, false));
        }catch (Exception e){
            Logger.getLogger(CucumberObjectFactory.class.getName()).warning(String.format("Could not get reference of %s using BeanManager, message: %s. Falling back to newInstance()",clazz.getName(),e.getMessage()));
            try {
                definitions.put(clazz,clazz.newInstance());
            } catch (InstantiationException | IllegalAccessException e1) {
                log.log(Level.SEVERE, String.format("Could not instantiate class %s", clazz.getName()));
            }
        }
    }
    return (T) definitions.get(clazz);
}
 
Example #5
Source File: MockedRequestScopedBeanWithInjectionTest.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Test
public void mixedMocksWithInjection2()
{
    SessionScopedBean mockedSessionScopedBean = mock(SessionScopedBean.class);
    when(mockedSessionScopedBean.getCount()).thenReturn(14);
    mockManager.addMock(mockedSessionScopedBean);

    RequestScopedBean mockedRequestScopedBean = new MockedRequestScopedBeanWithInjection();
    BeanProvider.injectFields(mockedRequestScopedBean);
    mockManager.addMock(mockedRequestScopedBean);

    Assert.assertEquals(14, requestScopedBean.getCount());
    requestScopedBean.increaseCount(); //not delegated
    Assert.assertEquals(14, requestScopedBean.getCount());
    sessionScopedBean.increaseCount();
    Assert.assertEquals(14, sessionScopedBean.getCount()); //still mocked
    Assert.assertEquals(14, requestScopedBean.getCount()); //still mocked
}
 
Example #6
Source File: MockedRequestScopedBeanWithInjectionTest.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Test
public void mixedMocksWithInjection1()
{
    SessionScopedBean mockedSessionScopedBean = mock(SessionScopedBean.class);
    when(mockedSessionScopedBean.getCount()).thenReturn(7);
    mockManager.addMock(mockedSessionScopedBean);

    RequestScopedBean mockedRequestScopedBean = new MockedRequestScopedBeanWithInjection();
    BeanProvider.injectFields(mockedRequestScopedBean);
    mockManager.addMock(mockedRequestScopedBean);

    Assert.assertEquals(7, requestScopedBean.getCount());
    requestScopedBean.increaseCount(); //not delegated
    Assert.assertEquals(7, requestScopedBean.getCount());
    sessionScopedBean.increaseCount();
    Assert.assertEquals(7, sessionScopedBean.getCount()); //still mocked
    Assert.assertEquals(7, requestScopedBean.getCount()); //still mocked
}
 
Example #7
Source File: ApplicationScopedBeanTest.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@AfterClass
public static void finalCheck()
{
    int value = BeanProvider.getContextualReference(ApplicationScopedTestBean.class).getValue();
    int nextValue = BeanProvider.getContextualReference(ApplicationScopedTestBeanClient.class).getNextValue();

    if (value == 0)
    {
        throw new IllegalStateException("new application-scoped bean instance was created");
    }

    if (nextValue == 1)
    {
        throw new IllegalStateException("new application-scoped bean instance was created");
    }
}
 
Example #8
Source File: SimpleSchedulerExample.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException
{
    CdiContainer cdiContainer = CdiContainerLoader.getCdiContainer();
    cdiContainer.boot();

    ContextControl contextControl = cdiContainer.getContextControl();
    contextControl.startContext(ApplicationScoped.class);

    GlobalResultHolder globalResultHolder =
        BeanProvider.getContextualReference(GlobalResultHolder.class);

    while (globalResultHolder.getCount() < 100)
    {
        Thread.sleep(500);
        LOG.info("current count: " + globalResultHolder.getCount());
    }
    LOG.info("completed!");

    contextControl.stopContext(ApplicationScoped.class);
    cdiContainer.shutdown();
}
 
Example #9
Source File: MockAwareProducerWrapper.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Override
public T produce(CreationalContext<T> creationalContext)
{
    DynamicMockManager mockManager =
        BeanProvider.getContextualReference(this.beanManager, DynamicMockManager.class, false);

    for (Type beanType : this.beanTypes)
    {
        Object mockInstance = mockManager.getMock(
            (Class)beanType, this.qualifiers.toArray(new Annotation[this.qualifiers.size()]));

        if (mockInstance != null)
        {
            return (T)mockInstance;
        }
    }

    return wrapped.produce(creationalContext);
}
 
Example #10
Source File: SessionScopePerTestClassTest.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@AfterClass
public static void finalCheckAndCleanup()
{
    int testCount = TestUtils.getTestMethodCount(SessionScopePerTestClassTest.class);

    if (RequestScopedBean.getInstanceCount() != testCount)
    {
        throw new IllegalStateException("unexpected instance count");
    }
    RequestScopedBean.resetInstanceCount();

    if (BeanProvider.getContextualReference(ApplicationScopedBean.class).getCount() != testCount)
    {
        throw new IllegalStateException("unexpected count");
    }

    if (BeanProvider.getContextualReference(SessionScopedBean.class).getCount() != testCount)
    {
        throw new IllegalStateException("unexpected count");
    }
    BeanProvider.getContextualReference(ApplicationScopedBean.class).resetCount();
}
 
Example #11
Source File: HandlerMethodImpl.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void notify(final ExceptionEvent<T> event, BeanManager beanManager) throws Exception
{
    CreationalContext<?> ctx = null;
    try
    {
        ctx = beanManager.createCreationalContext(null);
        @SuppressWarnings("unchecked")
        Object handlerInstance = BeanProvider.getContextualReference(declaringBeanClass);
        InjectableMethod<?> im = createInjectableMethod(handler, getDeclaringBean(), beanManager);
        im.invoke(handlerInstance, ctx, new OutboundParameterValueRedefiner(event, this));
    }
    finally
    {
        if (ctx != null)
        {
            ctx.release();
        }
    }
}
 
Example #12
Source File: ViewConfigPathValidator.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Override
public void contextInitialized(ServletContextEvent sce)
{
    if (ClassDeactivationUtils.isActivated(getClass()))
    {
        ViewConfigResolver viewConfigResolver;

        try
        {
            viewConfigResolver = BeanProvider.getContextualReference(ViewConfigResolver.class);
        }
        catch (Exception e)
        {
            LOGGER.log(Level.WARNING, "Container issue detected -> can't validate view-configs. " +
                "This exception is usually the effect (but not the reason) of a failed startup. " +
                "You can deactivate " + getClass().getName() + " via a custom " +
                ClassDeactivator.class.getName() + " to verify it.", e);
            return;
        }

        List<String> supportedExtensions = new ArrayList<String>();
        supportedExtensions.add(View.Extension.XHTML);
        supportedExtensions.add(View.Extension.JSP);
        validateViewConfigPaths(sce, viewConfigResolver, supportedExtensions);
    }
}
 
Example #13
Source File: DeltaSpikePhaseListener.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
private void checkSecuredView(FacesContext facesContext)
{
    if (!this.securityModuleActivated)
    {
        return;
    }

    try
    {
        BeanProvider.getContextualReference(ViewRootAccessHandler.class).checkAccessTo(facesContext.getViewRoot());
    }
    catch (ErrorViewAwareAccessDeniedException accessDeniedException)
    {
        SecurityUtils.tryToHandleSecurityViolation(accessDeniedException);
        facesContext.renderResponse();
    }
}
 
Example #14
Source File: WindowIdHtmlRenderer.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
private void lazyInit()
{
    if (clientWindow == null)
    {
        synchronized (this)
        {
            if (clientWindow == null)
            {
                clientWindowConfig = BeanProvider.getContextualReference(ClientWindowConfig.class);
                maxWindowIdLength = ClientWindowHelper.getMaxWindowIdLength();

                clientWindow = BeanProvider.getContextualReference(ClientWindow.class);
            }
        }
    }
}
 
Example #15
Source File: DeltaSpikeLifecycleWrapper.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
private synchronized void init()
{
    // switch into paranoia mode
    if (this.initialized == null)
    {
        if (ClassDeactivationUtils.isActivated(JsfRequestBroadcaster.class))
        {
            this.jsfRequestBroadcaster =
                    BeanProvider.getContextualReference(JsfRequestBroadcaster.class, true);
        }

        clientWindow = BeanProvider.getContextualReference(ClientWindow.class, true);
        windowContext = BeanProvider.getContextualReference(WindowContext.class, true);
        contextExtension = BeanProvider.getContextualReference(DeltaSpikeContextExtension.class, true);
        
        this.initialized = true;
    }
}
 
Example #16
Source File: ManagedArtifactResolver.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
private static <T> T getContextualReference(BeanManager beanManager, Class<T> type)
{
    Set<Bean<?>> beans = beanManager.getBeans(type);

    if (beans == null || beans.isEmpty())
    {
        return null;
    }

    Bean<?> bean = beanManager.resolve(beans);

    CreationalContext<?> creationalContext = beanManager.createCreationalContext(bean);

    @SuppressWarnings({ "unchecked", "UnnecessaryLocalVariable" })
    T result = (T) beanManager.getReference(bean, type, creationalContext);

    if (bean.getScope().equals(Dependent.class))
    {
        AbstractBeanStorage beanStorage = BeanProvider.getContextualReference(RequestDependentBeanStorage.class);

        //noinspection unchecked
        beanStorage.add(new DependentBeanEntry(result, bean, creationalContext));
    }

    return result;
}
 
Example #17
Source File: SecuredAnnotationTest.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Test
public void invocationOfMultipleSecuredStereotypes()
{
    SecuredBean4 testBean = BeanProvider.getContextualReference(SecuredBean4.class, false);

    TestAccessDecisionVoter1 voter1 = BeanProvider.getContextualReference(TestAccessDecisionVoter1.class, false);
    TestAccessDecisionVoter2 voter2 = BeanProvider.getContextualReference(TestAccessDecisionVoter2.class, false);

    Assert.assertFalse(voter1.isCalled());
    Assert.assertFalse(voter2.isCalled());

    Assert.assertEquals("result", testBean.getResult());

    Assert.assertTrue(voter1.isCalled());
    Assert.assertTrue(voter2.isCalled());
}
 
Example #18
Source File: BaseConfigPropertyProducer.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
public <T> ConfigResolver.TypedResolver<T> asResolver(final String key, final String stringDefault,
                                                      final Type ipCls,
                                                      final Class<? extends ConfigResolver.Converter> converterType,
                                                      final String parameterizedBy,
                                                      final boolean projectStageAware, final boolean evaluate)
{
    final ConfigResolver.UntypedResolver<String> untypedResolver = ConfigResolver.resolve(key);
    final ConfigResolver.TypedResolver<T> resolver =
            (ConfigResolver.Converter.class == converterType ?
                    untypedResolver.as(Class.class.cast(ipCls)) :
                    untypedResolver.as(ipCls, BeanProvider.getContextualReference(converterType)))
                    .withCurrentProjectStage(projectStageAware);
    if (!ConfigProperty.NULL.equals(stringDefault))
    {
        resolver.withStringDefault(stringDefault);
    }
    if (!ConfigProperty.NULL.equals(parameterizedBy))
    {
        resolver.parameterizedBy(parameterizedBy);
    }
    return resolver.evaluateVariables(evaluate);
}
 
Example #19
Source File: ConfigExample.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args)
{
    CdiContainer cdiContainer = CdiContainerLoader.getCdiContainer();
    cdiContainer.boot();

    ContextControl contextControl = cdiContainer.getContextControl();
    contextControl.startContext(ApplicationScoped.class);

    SettingsBean settingsBean = BeanProvider.getContextualReference(SettingsBean.class, false);

    LOG.info("configured int-value #1: " + settingsBean.getIntProperty1());
    LOG.info("configured long-value #2: " + settingsBean.getProperty2());
    LOG.info("configured inverse-value #2: " + settingsBean.getInverseProperty());
    LOG.info("configured location (custom config): " + settingsBean.getLocationId().name());
    
    cdiContainer.shutdown();
}
 
Example #20
Source File: DeltaSpikePhaseListener.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
private synchronized void lazyInit()
{
    if (this.viewConfigResolver != null)
    {
        return;
    }

    this.securityModuleActivated =
        BeanProvider.getContextualReference(EditableAccessDecisionVoterContext.class, true) != null;

    this.viewConfigResolver = BeanProvider.getContextualReference(ViewConfigResolver.class);

    if (!this.securityModuleActivated)
    {
        Logger.getLogger(getClass().getName()) //it's the only case for which a logger is needed in this class
                .info("security-module-impl isn't used -> " + getClass().getName() +
                        "#checkSecuredView gets deactivated");
    }
}
 
Example #21
Source File: BeanManagedUserTransactionStrategy.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
protected UserTransaction resolveUserTransaction()
{
    //manual lookup needed because injecting UserTransactionResolver can fail (see the comment there)
    try
    {
        DependentProvider<UserTransactionResolver> provider =
            BeanProvider.getDependent(this.beanManager, UserTransactionResolver.class);

        UserTransaction userTransaction = provider.get().resolveUserTransaction();

        provider.destroy();
        return userTransaction;
    }
    catch (Exception e)
    {
        return null;
    }
}
 
Example #22
Source File: ScopedPartialBeanTest.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Test
public void testPartialBeanWithApplicationScope() throws Throwable
{
    ApplicationScopedPartialBean bean = BeanProvider.getContextualReference(ApplicationScopedPartialBean.class);
    bean.getManualResult();

    Assert.assertEquals("willFail3", bean.willFail3());

    try
    {
        bean.willFail2();

        Assert.fail("#willFail2 should actually throw a ClassNotFoundException");
    }
    catch (Exception e)
    {
        Assert.assertEquals(e.getClass(), ClassNotFoundException.class);
    }
}
 
Example #23
Source File: CdiAwareJobFactory.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Override
public Job newJob(TriggerFiredBundle bundle, Scheduler scheduler) throws SchedulerException
{
    Job result = null;
    try
    {
        Class<? extends Job> jobClass = bundle.getJobDetail().getJobClass();
        result = BeanProvider.getContextualReference(jobClass);
        scheduler.getContext().put(jobClass.getName(), Boolean.TRUE);
    }
    catch (Exception e)
    {
        if (result == null)
        {
            result = defaultFactory.newJob(bundle, scheduler);
        }
    }
    return result;
}
 
Example #24
Source File: JsfUtils.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
public static void tryToRestoreMessages(FacesContext facesContext)
{
    JsfModuleConfig jsfModuleConfig = BeanProvider.getContextualReference(JsfModuleConfig.class);

    if (!jsfModuleConfig.isAlwaysKeepMessages())
    {
        return;
    }

    try
    {
        WindowMetaData windowMetaData = BeanProvider.getContextualReference(WindowMetaData.class);

        @SuppressWarnings({ "unchecked" })
        List<FacesMessageEntry> facesMessageEntryList = windowMetaData.getFacesMessageEntryList();
        List<FacesMessage> originalMessageList = new ArrayList<FacesMessage>(facesContext.getMessageList());

        if (facesMessageEntryList != null)
        {
            for (FacesMessageEntry messageEntry : facesMessageEntryList)
            {
                if (isNewMessage(originalMessageList, messageEntry.getFacesMessage()))
                {
                    facesContext.addMessage(messageEntry.getComponentId(), messageEntry.getFacesMessage());
                }
            }
            facesMessageEntryList.clear();
        }
    }
    catch (ContextNotActiveException e)
    {
        //TODO discuss how we handle it
    }
}
 
Example #25
Source File: RequestTokenHtmlRenderer.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
private PostRequestTokenManager getPostRequestTokenManager()
{
    if (this.postRequestTokenManager == null)
    {
        synchronized (this)
        {
            if (this.postRequestTokenManager == null)
            {
                this.postRequestTokenManager = BeanProvider.getContextualReference(PostRequestTokenManager.class);
            }
        }
    }

    return this.postRequestTokenManager;
}
 
Example #26
Source File: ExcludeTest.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
/**
 * bean is excluded in any case
 */
@Test
public void excludeWithoutCondition()
{
    NoBean noBean = BeanProvider.getContextualReference(NoBean.class, true);

    Assert.assertNull(noBean);
}
 
Example #27
Source File: SecurityAwareViewHandler.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
protected void broadcastAccessDeniedException(ErrorViewAwareAccessDeniedException accessDeniedException)
{
    AccessDeniedExceptionBroadcaster exceptionBroadcaster =
        BeanProvider.getContextualReference(AccessDeniedExceptionBroadcaster.class);

    Throwable broadcastResult = exceptionBroadcaster.broadcastAccessDeniedException(accessDeniedException);

    if (broadcastResult != null)
    {
        throw ExceptionUtils.throwAsRuntimeException(broadcastResult);
    }
}
 
Example #28
Source File: MinimalMessagesTest.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
@Test
public void testExpressionLanguageIntegration()
{
    ElPickedUpMessages elMessage =
            (ElPickedUpMessages) BeanProvider.getContextualReference("elPickedUpMessages");
    Assert.assertNotNull(elMessage);
    Assert.assertEquals("Hello DeltaSpike", elMessage.sayHello("DeltaSpike"));
    Assert.assertEquals("Hello null", elMessage.sayHello(null));
    Assert.assertEquals("Text", elMessage.text());
}
 
Example #29
Source File: DisableClientWindowHtmlRenderer.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
protected synchronized void init()
{
    if (this.initialized == null)
    {
        clientWindow = BeanProvider.getContextualReference(ClientWindow.class);
        jsfModuleConfig = BeanProvider.getContextualReference(JsfModuleConfig.class);
        
        this.initialized = true;
    }
}
 
Example #30
Source File: InjectableViewAccessContextManager.java    From deltaspike with Apache License 2.0 5 votes vote down vote up
private ViewAccessContextManager getConversationManager()
{
    if (this.viewAccessContextManager == null)
    {
        this.viewAccessContextManager =
            BeanProvider.getContextualReference(DeltaSpikeContextExtension.class).getViewAccessScopedContext();
    }
    return this.viewAccessContextManager;
}