This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes JSF and the fly likes Injection problem - not quite sure if this is something i should be using injection for Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » JSF
Bookmark "Injection problem - not quite sure if this is something i should be using injection for" Watch "Injection problem - not quite sure if this is something i should be using injection for" New topic
Author

Injection problem - not quite sure if this is something i should be using injection for

Christopher Whu
Ranch Hand

Joined: Sep 03, 2008
Posts: 80
If i was using jsp i would just set some session varibles and then pull them later from the bean.

I am trying to use cdi injection but not having luck...

i want to store an ID in this code:


and in this code i want to build some arraylists to feed a jsf...


when the page is called i get this null pointer


SEVERE: Error Rendering View[/shop/browseProductLineChosen.xhtml]
com.google.common.collect.ComputationException: java.lang.RuntimeException: java.lang.NullPointerException
at com.google.common.collect.ComputingConcurrentHashMap.compute(ComputingConcurrentHashMap.java:218)
at com.google.common.collect.ComputingConcurrentHashMap.apply(ComputingConcurrentHashMap.java:100)
at com.google.common.collect.MapMaker$ComputingMapAdapter.get(MapMaker.java:515)
at org.jboss.weld.bean.proxy.ClientProxyProvider.getClientProxy(ClientProxyProvider.java:113)
at org.jboss.weld.manager.BeanManagerImpl.getReference(BeanManagerImpl.java:681)
at org.jboss.weld.el.AbstractWeldELResolver.lookup(AbstractWeldELResolver.java:140)
at org.jboss.weld.el.AbstractWeldELResolver.getValue(AbstractWeldELResolver.java:112)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:185)
at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
at com.sun.el.parser.AstIdentifier.getValue(AstIdentifier.java:99)
at com.sun.el.parser.AstValue.getValue(AstValue.java:158)
at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:219)
at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:55)
at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
at javax.faces.component.UIComponentBase.isRendered(UIComponentBase.java:413)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:297)
at com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.encodeRecursive(HtmlBasicRenderer.java:309)
at com.sun.faces.renderkit.html_basic.GridRenderer.renderRow(GridRenderer.java:185)
at com.sun.faces.renderkit.html_basic.GridRenderer.encodeChildren(GridRenderer.java:129)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1756)
at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1756)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401)
at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:410)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1534)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:326)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:227)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:170)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:822)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:719)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1013)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.RuntimeException: java.lang.NullPointerException
at org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInstantiation(SecureReflectionAccess.java:240)
at org.jboss.weld.util.reflection.SecureReflections.newInstance(SecureReflections.java:390)
at org.jboss.weld.bean.proxy.ProxyFactory.create(ProxyFactory.java:239)
at org.jboss.weld.bean.proxy.ClientProxyProvider.createClientProxy(ClientProxyProvider.java:97)
at org.jboss.weld.bean.proxy.ClientProxyProvider.access$000(ClientProxyProvider.java:47)
at org.jboss.weld.bean.proxy.ClientProxyProvider$1.apply(ClientProxyProvider.java:61)
at org.jboss.weld.bean.proxy.ClientProxyProvider$1.apply(ClientProxyProvider.java:52)
at com.google.common.collect.ComputingConcurrentHashMap.compute(ComputingConcurrentHashMap.java:206)
... 59 more
Caused by: java.lang.NullPointerException
at PageModels.ProductLineModel.establishProductLineSetViaSession(ProductLineModel.java:76)
at PageModels.ProductLineModel.<init>(ProductLineModel.java:43)
at PageModels.org$jboss$weld$bean-web-ManagedBean-class_PageModels$ProductLineModel_$$_WeldClientProxy.<init>(org$jboss$weld$bean-web-ManagedBean-class_PageModels$ProductLineModel_$$_WeldClientProxy.java)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
at java.lang.Class.newInstance0(Class.java:355)
at java.lang.Class.newInstance(Class.java:308)
at org.jboss.weld.util.reflection.SecureReflections$16.work(SecureReflections.java:395)
at org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:54)
at org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInstantiation(SecureReflectionAccess.java:216)
... 66 more


I cant seem to get this right... I know i am missing something... Please help.

I apologize in advance if it turns out i did something stupid, lol...
Brendan Healey
Ranch Hand

Joined: May 12, 2009
Posts: 218
What import are you using for @SessionScoped? it's not shown but you
need javax.enterprise.context.SessionScoped.

Also do you need an empty beans.xml file to enable CDI (in NetBeans:
New - Other - Context & Dependency Injection - beans.xml(CDI config
file)). Getter & setter for sessionHelper property maybe?

I don't actually use CDI myself because of a lack of view scope and I've
not yet figured out conversation scope, so I'm probably off target but
there's a couple of things to check.

Regards,
Brendan.

p.s. it looks like a very convoluted way of doing things

beans.xml in WEB-INF
Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 16095
    
  21

I think what you're looking for is a Managed Property. In JSF1, you would make your managed properties be sub-elements of the managed bean element in faces-config.xml. You can still do that in JSF2, but since you're using annotations, there's a ManagedProperty annotation that does the same thing - establishes a bean/property reference to the managed property within the annotated bean so that the JSF framework can inject it.


Customer surveys are for companies who didn't pay proper attention to begin with.
Brendan Healey
Ranch Hand

Joined: May 12, 2009
Posts: 218
@Inject is the CDI equivalent of @ManagedProperty and this should work, I've used it
in some test code before without problems. I use @ManagedProperty for bean
injection like this:



I'm pretty sure that I hit a funny problem like the OP and this was caused by
there not being an empty beans.xml file., but it was a while ago. There is a
fix in Mojarra 2.1 relating to @Inject support so it might be an idea to upgrade
if not already done.

http://java.net/jira/browse/JAVASERVERFACES-1709

Brendan.
Christopher Whu
Ranch Hand

Joined: Sep 03, 2008
Posts: 80
i have the correct bean.xml file... I have the correct import for session....

When i use @named and inject on in the SessionHelper class it is passing a 0 not the value... I am definitely doing something wrong syntax wise.... I suck..
Christopher Whu
Ranch Hand

Joined: Sep 03, 2008
Posts: 80
is there an easy way to get / set session variables from my beans?

i need to call the variable from another bean
Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 16095
    
  21

For managed beans - both JSF-managed and Spring Framework managed beans, you can inject them as managed properties as long as their scope is at least as long as the destination bean.

For non-managed beans, you have to do it the hard way, chasing your way down the FacesContext and into the HttpServletRequest object, casting as needed. I keep a utility class that houses a method to do this so as to minimize the javax.faces code I have to put in the beans, but the work involved to locate a non-managed bean is the same either way.
Christopher Whu
Ranch Hand

Joined: Sep 03, 2008
Posts: 80
thank you sir! I am going to do it the hard way, lol... i have used this before....

I guess i was just trying to use CDI the wrong way..
Brendan Healey
Ranch Hand

Joined: May 12, 2009
Posts: 218

One further question, do your session scoped beans have a no-arg constructor?
If all else fails use the session map. This should be fairly self-explanatory, I include
this method as part of an abstract class that is inherited by all my backing beans
(eventually):



So just getSessionMap().put(key, value) and getSessionMap().get() as you would expect.

It's irritating that we've not been able to identify the source of your problem so far,
but this hasn't been helped by the lack of information about the platform that you're
running on, what versions etc. and also minimal code extracts. You've really got to
provide full context if you want to move forwards.

Regards,
Brendan.
Christopher Whu
Ranch Hand

Joined: Sep 03, 2008
Posts: 80
TY - i will study that...

I love that everyone on this site is so smart... I am self educated (my college did not have a very good programming dept - no java at all)... I don't have a senior programmer to consult..

My jsf book does not user the noarg constructors.... SHould i be using them for my backing beans? I use them on my object classes...
Christopher Whu
Ranch Hand

Joined: Sep 03, 2008
Posts: 80
also if anyone reads this who is new to JSF, i was basically trying to use session in lieu of passing URL vars (like i would in jsp)... And i was trying to call the methods of a session class i built to hold the info temporarily that i would have passed via url var...


I actually found a nifty way to pass URL vars. Not saying it is the right way to do it but:

on my jsf page:


in my backing bean:


Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 16095
    
  21

No, trying to force JSF to do things the non-JSF way is losing some of the benefits of JSF.

The reason JSF makes it so hard to pass parameters is because it prefers NOT to pass parameters. Instead, it does its work behind the scenes with the backing beans.

For example, suppose I have a search form. I want to collect search parameters and do a search.

To do this the JSF way, I'd create a short-scope backing bean to back the search form itself and inject the long-term bean relating to the search results into it. The "Search" button connects to an action method in the search form backing bean that initiates the search. You have your option as to whether you want the actual search function to be done in the search form bean or in the long-term bean (where the search action processor invokes a method in the injected bean). In either case, the search form action method would then ensure that the search results were posted to (or created in) the long-term bean and would return a navigation action that went to the search results view. Absolutely no form tag contortions and no javax.faces imports required. Everything can be done with simple forms and POJOs.

Inversion of Control is hard thing for most people to get used to. They're accustomed to being active or even (gag) pro-active (a word we managed to limp by without for centuries). IoC is about creating generic TinkerToys and wiring them together. The magic is in the wiring and not in explicitly-coded logic. And the IoC framework (JSF and/or things like Spring) handle the wiring.
Christopher Whu
Ranch Hand

Joined: Sep 03, 2008
Posts: 80
Ty for the advice tim....

So in lew of using the params on the tag i should be creating a short term bean with a setter to grab what i was using the params to pass. That bean would also forward the browser to the model driving page and supply the model bean with the info collected...


I think that is what you mean...
Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 16095
    
  21

Yep.

It's one of life's little ironies that the more "JSF" you have in your JSF, the less likely it is that you're properly using JSF.

Spelling tip of the day. "Lew" is a friend of mine. The spelling you wanted was "lieu". Not to be confused with Liu, who is another friend of mine.
Christopher Whu
Ranch Hand

Joined: Sep 03, 2008
Posts: 80
ok so back to getting injection to work...

I am using the latest version of glassfish running on windows... Developing on netbeans...

jsf page with navigation:


short term bean


the big bean


the null pointer occurs when we reference the injected bean



Is my helper bean uninjectable?
Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 16095
    
  21

YIPE!

This is a forest-and-trees problem. And I'd have to kill a tree (printout) to be able to follow all that.

I really recommend that you try the @ManagedBean annotation in place of @Inject. I don't know if there's anything active in your server that's scanning for and applying the @Inject annotations, much less what it's resolving references from.

There's no such thing as an "uninjectable" bean, really, although some beans are useless once injected. But it seems pretty obvious that the bean isn't being injected at all, and that means your injector mechanism is suspect. Using managedBean, if the bean wasn't resolvable as an EL expression, you'd get an injection failure, but that would pretty much prevent the app from even starting.
Christopher Whu
Ranch Hand

Joined: Sep 03, 2008
Posts: 80
trying out import javax.annotation.ManagedBean;


when clicking


i get:

javax.el.PropertyNotFoundException: /index.xhtml @17,80 action="#{modelHelper.iDToPass}": Target Unreachable, identifier 'modelHelper' resolved to null
Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 16095
    
  21

Uh-oh. Time to hit the books, big time.

You package name has upper-case letters in it. That's a violation of conventions and can cause some Java tools to complain. Or worse.

You're using static members in a JSF object. That's not a good idea at the best of times and in this particular case, I think the app will go haywire the minute more than one users attempts to work with it.

The proper name for the property on a JSF would be "idToPass", with getIdToPass() and setIdToPass() accessor methods on the backing bean. Note how JSF will manipulate the upper/lower-case characteristics.

As I've said, using parameterized methods in JSF isn't something I recommend and in this case, you're compounding the issue by attempting to use the "set" method as an action processor. My action methods are usually more like this:



You're attempting to drive JSF manually. Don't do that. JSF can drive itself just fine. Note that I didn't need any references to JSF's internals to do the above.

Also, note that my output View reference has no extension on it. That will make it default to ".jsf". ".xhtml" isn't a URL component, it's a resource file reference, and JSF wants the URL.

Oh yes, and the "submit button":
Christopher Whu
Ranch Hand

Joined: Sep 03, 2008
Posts: 80
i must be missing the point of injection...

i want to call


which is part of


from another class...

using


inside the class that needs to call it...

is this the wrong implementation?

Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 16095
    
  21

If you inject ModelHelper into another class (let's call it Modeluser), you cannot call ModelUser's getIdToPass() method in ModelHelper. ModelUser knows how to find ModelHelper's methods, but not the other way around, because injection is a one-way connection. To go the other way, you'd have to define a callback.
Christopher Whu
Ranch Hand

Joined: Sep 03, 2008
Posts: 80
But if i want to call ModelHelpers getIdToPass() from ModelUser that is correct implementation, right?

I just want to make sure i am sniffing up the right tree...

i need to use the ID contained in ModelHelper with another class...

TY for all the help...

I cant believe all i had to do was return the path to get the browser to forward itself....

i tend to make things to difficult... lol...
Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 16095
    
  21

EVERYONE tends to make JSF difficult. I guess they think it can't be that easy. And maybe because there are still some pre-release docs from when it wasn't so easy floating around on the Internet. Moral of story: put dates on technical articles!

When you inject an object into another object, the "set" method used to inject the object has an argument type, which is a class or interface (or wrapper or primitive type). So the target of the injection not only knows what type of injected object it is dealing with, but actually prevents incompatible objects from being injected through that method, since that's just basic Java object typing enforcement

So, knowing that I have my hands on (an injected) ModelHelpers object, and knowing that the ModelHelpers class implements a public getIdToPass() method, I can call it, because that's just basic Java.

The magic is that there is no magic.
Christopher Whu
Ranch Hand

Joined: Sep 03, 2008
Posts: 80
i am determined to get this right...

Going to try and mock some classes tomorrow just to try and get something simple to work... Maybe that will make it click... Do you know any really simple tutorials or examples out there?
Christopher Whu
Ranch Hand

Joined: Sep 03, 2008
Posts: 80
Finally got injection working...
I had it backwords, i was trying to do it backwards...

my next question is am i breaking the JSF drive itself rule with this...

The goal is to have links that feed data to a bean that drives a page view

first my page with links


now the page that grabs the values we need to pass to the page view bean


then we have the bean that handles the view:


finally we have our page that displays the data from the view...



on a side note, i noticed that when creating a project in netbeans there is a checkbox that asks you if you would like to use injection... Not sure if i checked that off on the code i was originally using... I am going to rebuild the project with that option checked off...

Professor Tim, do we like it?
Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 16095
    
  21

Well, I've never done anything quite like that, but it seems acceptable. The main variances from what I routinely do are the use of propertyActionListener (I had to look that one up) and the separation of the action processor into a separate bean from the View Model bean - effectively making MessageServeBean a Controller. Then again, I've never been totally happy with the standard JSF model where both UI data and action were the same bean, anyway.

IoC is an inside-out technology, and I think everyone gets it backwards at first. I did. It's not what we're used to,but it does make it a lot easier to re-use code and to wire in testing.

IDE options I'll have to leave you on your own with. Last time I used NetBeans was 2-3 name changes ago. But there are a lot of NetBeans fans here, so just any questions in the IDE forum!
Christopher Whu
Ranch Hand

Joined: Sep 03, 2008
Posts: 80
Ty for all your help... It feels good to be doing this project in a more current, professional manner.

its funny, i did not even have to use the managedbean annotations once i figured out i was doing things out of order.... Initially this morning i was trying to call the helper from the big bean that handles the view and i was getting nulls, i noticed that the viewer bean was firing off first and that made me do the switcharoo of having the helper inject the viewer bean...

i am not married to using f:setPropertyActionListener, it was one of the ways i found to do it online... If there is a better way to do it i am all ears..

For this project i am kind of married to netbeans... I am using the UPS to handle my shipping and the only IDE i was able to unwrap there wsdl files with was netbeans... Have you used UPS's back end? It made me want to headbutt my monitor...

TY again...

Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 16095
    
  21

Your IDE should not be affecting your program design, just the tools that are available to help to design your program. Otherwise, you'll end up getting burned (voice of experience, here).

Eclipse doesn't have native Web Services support, but Apache Axis did provide a plugin. Presumably they've kept it up to date. As far as web service API's go, however, I doubt UPS can do worse than Intuit did. I sold my stock, quit using Quicken, and curse every time I have to use their web services interface. They may be cheap, and they may be popular, but they're not rocket scientists.
Christopher Whu
Ranch Hand

Joined: Sep 03, 2008
Posts: 80
UPS support will only help you download the wsdl, that it...

Since my client does tens of thousands of business with them a month in shipping he was able to get me a developer... The developer was awesome but he only did dot.net...

He worsk for UPS and he told me that the people who wrote the api and wsdls where no help to him... He basically had to unrwrap he wsdl line by line..

We worked together with his C# code and it took us 3 days to finally get all the data we needed... It was an expereince...

My colleague had problems with Intuit as well... Its a shame these companies dont realize the value of third party software...
Tim Holloway
Saloon Keeper

Joined: Jun 25, 2001
Posts: 16095
    
  21

To be fair, I think Intuit does understand the value of third parties. What they don't seem to understand is the value of paying for talent that's over 10 years old.

Your UPS experiences are typical of what comes from getting cheap offshore labor. However, Intuit's stuff isn't so much about the quality and communication as such, as it is the fundamental limitation in sophistication. Even cheap offshore labor is typically more sophisticated than that. Almost everything they do is welded to Windows. When their products "export to Excel", they don't mean produce an XLS or CSV file, they expect you to actually have a copy of Excel itself installed on THAT computer! Nobody else has ever done that to me - not even Microsoft! I dropped Quicken as a personal user because the only kind of stock splits it could handle decently were ESOP, and I generally don't buy much stock in employers, on the grounds that if they take a hit, they'll lay me off and their stock will dive at the same time.

The darker side of cloud-based computing. At least when you're working in-house you can egg someone's car if they won't help you!
Brendan Healey
Ranch Hand

Joined: May 12, 2009
Posts: 218

What exacttly was is it that you did the fix the problem? backwards means nothing to me.
Christopher Whu
Ranch Hand

Joined: Sep 03, 2008
Posts: 80
Brendan Healey wrote:
What exacttly was is it that you did the fix the problem? backwards means nothing to me.


If you look at my initial problem, i was trying to call the helper bean from the viewbean... And i was missing

instead i ended up calling the calling an init type method from the helper bean... I also enabled CDI in netbeans...

the helper that i am going forward with looks like this.



doBuildView kicks off the process that builds all the arraylists that populate my page...



 
GeeCON Prague 2014
 
subject: Injection problem - not quite sure if this is something i should be using injection for