How to inject blazor session storage in a C# class - c#-4.0

I want to inject the Blazor sessionStorage in a class like the code below.
[Inject]
Blazored.SessionStorage.ISessionStorageService _sessionStorage
A lot of examples online show or place this in the Html file.
Is there a way to inject this in a C# class? I tried with the above code and it does not work

Try this:
public partial class MyComponent
{
[Inject] Blazored.SessionStorage.ISessionStorageService _sessionStorage {get; set;}
...
}

Related

How to inject RequestScoped bean into Axis2 POJO web service?

We are currently building a web application where the backend is exposing the server functionality via REST web services (using Jersey). However, there is one web service which needs to be a SOAP service due to backwards compatibility. We have for this implemented a POJO (generated as Axis2 web service using Eclipse to get the setup right) which we deploy as an Axis2 web service on a Tomcat. The SOAP web service is defined as request scoped (done in services.xml). Calling this web service, using both Kerberos and NTLM for authentication (which one depends on the environment where the web app is deployed) works fine.
Now, we want to reuse some of the functionality of the REST services. The REST services are only used as facades and the business logic are implemented in #RequestScoped beans being injected into the REST services using CDI and #Inject. It would be perfect if we could inject a #RequestScoped bean into our POJO but this doesn't seem to work. The bean to be injected also have dependencies on other #RequestScoped beans which are also injected using CDI. Basically, it will cause an entire tree of object dependencies to be instanciated.
Now, my question is if this scenario should in general be possible, i.e. injecting a #RequestScoped bean into an Axis2 POJO using CDI? If not, do you have any suggestions of how this could be solved in a different manner, i.e. reusing #RequestScoped beans in an Axis2 POJO?
Here are some code samples of our setup:
POJO:
import javax.inject.Inject;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.transport.http.HTTPConstants;
public class MyService {
#Inject
private MyRequestScopedService mrss;
public MyResponse getSomeData(MyRequest myRequest) {
// some logic...
}
}
Bean to inject:
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
#RequestScoped
public class MyRequestScopedService {
#Inject
private MyOtherRequestScopedService morss;
[...] // a few other beans are also injected
public SomeData getSomeData(SomeRequest someRequest) {
// some logic...
}
[...]
}
services.xml
<service name="MyService" scope="request">
<messageReceivers>
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-only" class="org.apache.axis2.rpc.receivers.RPCInOnlyMessageReceiver" />
<messageReceiver mep="http://www.w3.org/2004/08/wsdl/in-out" class="org.apache.axis2.rpc.receivers.RPCMessageReceiver"/>
</messageReceivers>
<parameter name="ServiceClass" locked="false">com.domain.MyService</parameter>
</service>
If you need some more details, please let me know.

Injecting a remote EJB in a managedBean

I'm stuck since x time on how to inject a remote EJB in a managed bean of a JSF application.
I've created a simpl java application and i've come to inject the remote EJB with the lookup... and it works.
but when i come to the web application i really don't know what to do !!!
here is my EJB code:
#Stateless
public class Hello implements HelloRemote {
#Override
public String sayHello(String name) {
return "Hello, "+name;
}
}
the Remote interface is
#Remote
public interface HelloRemote {
public String sayHello(String name);
}
in my web application i vre created i managed bean :
#ManagedBean
public class MyBean {
#EJB
HelloRemote helloRemote;
}
BUT IT DOESN'T WORK :(
If you want to expose EJB locally you have to use #Local on Interface.
If you want to expose both locally and remotely you have to created 2 Interfaces, one with #Local and one with #Remote.
If your JSF ManagedBean(MyBean) is running locally ie.,Running on same App server as EJB you can directly inject it using #EJB.
If your JSF ManagedBean is running on different server, you have to use the JNDI Registry to look up and access the EJB.

Spring Integration: Inject request scoped twitter-template bean into inbound-channel-adapter

I have an annotation configured request-scoped TwitterTemplate bean and I want to inject that bean into an xml configured inbound-channel-adapter.
What is the best way to do that and are there any implications that need to be considered in case of multiple sessions accessing the same inbound-channel-adapter?
Have you got any examples of twitter inbound-channel-adapter configured through java?
Inject an ApplicationContext object into your xml configured bean, as a property.
Your xml configured bean can implement InitializingBean and override the afterPropertiesSet method, where you get an instance of your twitterBean as shown in the code below.
You context gets merged irrespective of the configuration mechanism you use.
YourXmlBean implements InitializingBean {
ApplicationContext ctx;
TwitterTemplate twitBean;
...
#Override
public void afterPropertiesSet(){
twitBean = (TwitterTemplate) ctx.getBean("twitterTemplate");
}

How do I force an application-scoped bean to instantiate at application startup?

I can't seem to find a way to force an application-scoped managed bean to be instantiated/initialized when the web app is started. It seems that application-scoped beans get lazy-instantiated the first time the bean is accessed, not when the web app is started up. For my web app this happens when the first user opens a page in the web app for the first time.
The reason I want to avoid this is because a number of time-consuming database operations happen during the initialization of my application-scoped bean. It has to retrieve a bunch of data from persistent storage and then cache some of it that will be frequently displayed to the user in the form of ListItem elements, etc. I don't want all that to happen when the first user connects and thus cause a long delay.
My first thought was to use an old style ServletContextListener contextInitialized() method and from there use an ELResolver to manually request the instance of my managed bean (thus forcing the initialization to happen). Unfortunately, I can't use an ELResolver to trigger the initialization at this stage because the ELResolver needs a FacesContext and the FacesContext only exists during the lifespan of a request.
Does anyone know of an alternate way to accomplish this?
I am using MyFaces 1.2 as the JSF implementation and cannot upgrade to 2.x at this time.
My first thought was to use an old style ServletContextListener contextInitialized() method and from there use an ELResolver to manually request the instance of my managed bean (thus forcing the initialization to happen). Unfortunately, I can't use an ELResolver to trigger the initialization at this stage because the ELResolver needs a FacesContext and the FacesContext only exists during the lifespan of a request.
It doesn't need to be that complicated. Just instantiate the bean and put it in the application scope with the same managed bean name as key. JSF will just reuse the bean when already present in the scope. With JSF on top of Servlet API, the ServletContext represents the application scope (as HttpSession represents the session scope and HttpServletRequest represents the request scope, each with setAttribute() and getAttribute() methods).
This should do,
public void contextInitialized(ServletContextEvent event) {
event.getServletContext().setAttribute("bean", new Bean());
}
where "bean" should be the same as the <managed-bean-name> of the application scoped bean in faces-config.xml.
Just for the record, on JSF 2.x all you need to do is to add eager=true to #ManagedBean on an #ApplicationScoped bean.
#ManagedBean(eager=true)
#ApplicationScoped
public class Bean {
// ...
}
It will then be auto-instantiated at application startup.
Or, when you're managing backing beans by CDI #Named, then grab OmniFaces #Eager:
#Named
#Eager
#ApplicationScoped
public class Bean {
// ...
}
Romain Manni-Bucau posted a neat solution to this that uses CDI 1.1 on his blog.
The trick is to let the bean observe the initialization of the built-in lifecycle scopes, i.e. ApplicationScoped in this case. This can also be used for shutdown cleanup. So an example looks like this:
#ApplicationScoped
public class ApplicationScopedStartupInitializedBean {
public void init( #Observes #Initialized( ApplicationScoped.class ) Object init ) {
// perform some initialization logic
}
public void destroy( #Observes #Destroyed( ApplicationScoped.class ) Object init ) {
// perform some shutdown logic
}
}
As far as I know, you can't force a managed bean to be instantiated at application startup.
Maybe you could use a ServletContextListener which, instead of instantiating your managed bean, will perform all the database operations itself?
Another solution might be to instantiate your bean manually at application startup, and then set the bean as an attribute of your ServletContext.
Here is a code sample:
public class MyServletListener extends ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {
ServletContext ctx = sce.getServletContext();
MyManagedBean myBean = new MyManagedBean();
ctx.setAttribute("myManagedBean", myManagedBean);
}
}
In my opinion, this is far from clean code, but it seems like it does the trick.
Additionally to BalusC's answer above you could use #Startup and #Singleton (CDI), e.g.
//#Named // javax.inject.Named: only needed for UI publishing
//#Eager // org.omnifaces.cdi.Eager: seems non-standard like taken #Startup below
#Startup // javax.ejb.Startup: like Eager, but more standard
#Singleton // javax.ejb.Singleton: maybe not needed if Startup is there
//#Singleton( name = "myBean" ) // useful for providing it with a defined name
#ApplicationScoped
public class Bean {
// ...
}
which is nicely explained here.
Works in JPA 2.1 at least.

Jsf custom managed bean instantination handler

Which JSF 1.2 component is responsible for instantiating managed bean specified in faces-config.xml?
I'd like to replace this component with my custom-made version which will perform some additional tasks after bean instance is successfully created.
No one component is responsible for that. It is just EL which is responsible for that. If the expression #{beanname} returns null, it will create one which is associated with the managed bean name.
In your specific case, the normal way to solve this problem is just making use of the constructor of the bean or a public method of the bean annotated with #PostConstruct.
public class Bean {
public Bean() {
// Put code here which is to be executed during construction, but before
// setting of the managed properties (<managed-property> declarations).
}
#PostConstruct
public void init() {
// Put code here which is to be executed AFTER construction
// and the setting of managed properties.
}
}
If you really want to take the EL resolving in your own hands, then best what you can do is to implement a custom ELResolver. You can find here an article about that.
Here is the JSP resolver structure detailed in the JSF 1.2 spec:
Faces ELResolver for JSP
|_ faces.ImplicitObjectELResolverForJSP
|_ faces.ManagedBeanELResolver
|_ faces.ResourceBundleELResolver
|_ ELResolvers in application configuration resources
|_ faces.VariableResolverChainWrapper (wraps deprecated API)
|_ faces.PropertyResolverChainWrapper (wraps deprecated API)
|_ ELResolvers from Application.addELResolver()
Managed beans will be instantiated by the faces.ManagedBeanELResolver (which is just a label developers can refer to it by, not the name of a public class).
The top-level ELResolver is provided via the Application (which you can provide via an ApplicationFactory). But, although the JSF specification details behaviour, the API does not expose the means by which the managed beans will be instantiated. It would be difficult to decorate the implementation to disambiguate between a newly instantiated bean and a bean that was returned from the request/session/application scope.
BalusC's post gives a couple of good strategies for approaching this problem.
Although JSF 2.0 brings changes to the managed bean facility, it does not, to the best of my knowledge, change this aspect of the API.
#PostConstruct is the way to go for JSF 1.2.
If you are using JavaEE 6 then you can also use #Produces annotation on a method to create custom factory method.
public class CustomBeanFactory {
#Produces
public Bean getBean() {
Bean bean = new Bean();
System.out.println("Created new bean.");
return bean;
}
}

Resources