inner working of JSF 1.2 - java

I'm trying to understand the inner workings of JSF 1.2 sun implementation.
I have the following questions.
It is stated that Lifecycle class manages the processing of the entire lifecycle of a particular JavaServer Faces request. It has execute and render methods but its a abstract class. How is it really implemented?
In this blog, he states that the ViewHandler will eventually call the following:
stateManager.saveView(context);
Is this correct? I couldn't find anywhere this line of code.
In which class would I find the code that parses the JSF tags and created component tree, (xml -> tree)?
In which class would I find the code that does the reverse of (3) i.e. renders the component tree. (tree -> xml)?
It would also be infinitely great if someone could point me to any resource that provides explanation about JSF 1.2 implementation.

It's been a few years since I've been in the guts of JSF 1.2, but if memory serves the class implementing Lifecycle was always LifecycleImpl.
Regarding the conversion between xml->tree and tree->xhtml (for me, anyways), I always thought that was done by the Components / Renderers / Converters. Based on a tag, a Component is created and populated in the tree. The Renderer attached to the Component (based in the tag definition) is responsible for rendering the output (by default html, but you can have multiple renderers attached to a component based on the desired output), and the Converter is responsible for the String <-> Object conversions.
I always had good luck reading the source (can be found at http://javaserverfaces.java.net/download.html), although it took a few tries to get my head around some of it.
Hope this helps

Related

Restoring from component rendering failures in Wicket

Let's consider the case:
Wicket page contains several components and rendering of one of them fails with some common runtime exception (like NullPointerException).
The result I see by default is: the whole page fails to render.
How to recover from this error in Wicket? What should be done, not render or replace the failing component only?
A custom IRequestCycleListener is the solution you are looking for. Read Carl-Eric's answer here:
How to handle exceptions thrown in Wicket custom model?
In a "classical" wicket application where pages and components are instantiated by code in constructors and initializers you probably have to add try-catch blocks manually to each and every possible constructor call. Wicket is not a managed framework, meaning there isn't a central component factory that could be decorated by such functionality. That does not mean though that you can't create such a component factory yourself.
In a CMS-like application we've been developing since 2006 all wicket components are instantiated by builders that themselves are created from xml or json documents (so the full layout and configuration of the app is externalized and the wicket components are just small building boxes that can be mixed and matched together like lego pieces) - so I know such an approach works and performs well. In our case each builder method that creates a component has a try-catch block that creates an empty Label instead if any RuntimeException happens.
This is weird requirement, in my humble opinion.
What is the rendering of the replacement component fails too ? Add extra logic ?! Or let it fail with stack overflow error ?
What if half of the components in the page fail ? You will show half page with proper content and the other with "Oopsies" ?!
If there is an error then it should be fixed!

Tapestry XML output

I'm interested in the Tapestry framework put have some problems with it due to several reasons:
The output I have to generate has to be XML. According to http://tapestry.apache.org/content-type-and-markup.html this is no big deal.
But when it comes down to use actionlink, components or all the other Tapestry goodies, the resulting code should not be anchor or div but some custom xml elements/attributes.
Is it possible to archieve this without alot of pain?
Workarounds or insides to the background mechanismn of Tapestry are welcome.
while actionlink will always render as an anchor (a) tag, the Any component can render as any arbitrary xml element, and it and many other tapestry components will render arbitrary (informal) parameters depending on their definition.
for example, (assuming you have a java method called 'getTheTime' in your class, mine returns System.currentTimeMillis())
<xyz t:type="actionlink" t:id="someaction">
a element</xyz>
<xyz t:type="any"
attribute1="${theTime}"
attribute2="prop:theTime"
attribute3="theTime">
xyz element</xyz>
will render as:
a element
<xyz attribute1="1338418847753" attribute2="1338418847753"
attribute3="theTime">xyz element</xyz>
In order to get a combination of the two, you will need to roll your own component. This is pretty simple once you understand tapestry a little better.
Have a look at the source of ActionLink.java (and its super classes) and you should be able to figure it out.

Decorating a multi-client webapp

I have a web-app in Java, Spring, Struts 2 and Hibernate, that servers multiple clients. Each client with multiple users. To create a personal feel for each client, i would like to customize the header for each client.
I'm using sitemesh as decorator, and am looking for tips or examples or someone who can point me in the right direction as to how to acomplish this in the best practice.
What would you think? Should i just code it direct in the header.jsp? Extracting the info about the logged in user and from that create a custom header by code? Or is there a more clever solution out there?
Thanks!
Update:
To further clearify what i want:
Different properties-files for each client is not an option. We are looking at potentionally hundreds of clients. It needs to be database-driven. But thats the easy part. There is no problem storing the information in db and extracting it when needed.
What im trying to figure out is if there is some sort of standard way of doing this. Some sort of filter or Action that is run before the sitemesh decorator that will provide the decorator with the correct info?
Struts2 provides application scope, for variables which are global to the application.
Load all the customer specific strings into #application scope (I would use spring to do this when the application starts up). From there referencing the strings would be pretty obvious: #application.greeting I don't like the idea of using an interceptor because there is nothing to intercept. I would say for what you are doing application scope is the perfect place. If it is a single client system I can see no reason why anything would be stored in application scope.
Aside: Tiles uses a different template paradigm than site mesh, and they have slightly different purposes. As such the two can be complimentary. Tiles relying on XML definitions can have it's definitions stored in a DB and is definitely less computationally intensive, however where there is interplay between different UI components... or disparate elements appearing on the page you need to use sitemesh. So for basic template needs tiles does everything and is quite easy to understand but say you wanted to make add a certain widget in the middle of the page which relies on JS which needs to be added to the header it would be tricky to do this in Tiles (although the obvious solution is to just roll the JS functionality into one JS file for all possible uses in a particular part of the site).
Asside 2: By using a view technology such as velocity or freemarker in conjunction with tiles it is conceivable to move the entire view layer into a database. I just thought I would mention that as for some maintenance issues that could be extremely beneficial.
Sitemesh makes it's decisions about what decoration to use based upon the requested URL string, so unless you have a reference to the client in every url - either as part of the main url string or as a known parameter, then Sitemesh out of the box is not going to help.
This leaves a few possibilities to achieve what you want;
1) Write a filter that runs before Sitemesh that adds, for example, "&clientId="xx" to every incoming request.
2) Dive into the source code for Sitemesh & look for where Sitemesh finally makes it's decision about which decorators to use and override it. I've never tried this so I don't know how practical this might be.
3) Make the style sheet definition in your jsp pages an OGNL expression and provide that information in a base action class that all your actions extend. In this way you end up with (potentially) a different CSS file for each client and you provide your customisation via CSS.
Hope that this helps.

Confused: Role of Beans in JSF2 in comparison to classical MVC Controllers

i have a question that is more design and architecture related. I am coming from a classical MVC based background and have to get my hands dirty on JSF2. I read the IBM articles on JSF2 (http://www.ibm.com/developerworks/library/j-jsf1/) and think i understand the overall concept.
I started to get in touch with JSF2 trough ROO. I have the feeling that ROO (maybe this is true for any JSF2-Type App, or maybe not) is making very strange/unclear use of beans. It is in general really not clear to me what the actual role of a Bean is! For example, if i have a view with a form that is for editing a single user-entry, i would initialize the user in a, lets call it UserBean (maybe store in in a member variable) and access this variable trough getters. If i now want to overview all users, i would again render the view in in the UserBean hold a collection of users and again access this collection trough getters. The previous description is actually the way i would do things with jsf. This means i would user the UserBean more as a statefull-service as a controller.
In a typical controller situation i would create for every type of action (list user, edit user, view user, etc) a separate controller, with specific initialized data and this way i would separated the context of the logic by controllers.
I often make use of context specific services, e.g. if i handle user's often an spread over the application, i create a user-service that handles user specific logic that is maybe to complex to be put into the itself. If i now for example look into roo generated Beans, i would find methods that programatically render forms, input fields, labels, that again store list's of users, boolean fields that indicate if data had already been loaded, single user members and a lot of methods that more look like to be put into a UserService (or whatever). I am wondering if this is the way JSF2 is intended to be used, in words: pushing everything that is related to one context into on bean, not making use of service and writing "super-controller-beans" that handle everything.
I don't really know if you get the question right, but what would maybe help me is, a hint to
a very exemplary and commendable example application that makes use of beans the way they where intended to be used in combination with jsf2 features and usecases that for example implement basic CRUD usecases around a given type of entity. (One big confusing point is, that in my case ROO always makes use of AJAX and javascript stuff like Modal-Dialogs to implement CRUD logic. I wonder if with JSF there is a more classical way to to this?[With 'classical' i mean for example URL-Based views and separated views for listing, editing and viewing entities])
a resource that enlightens typical "thats-the-way-the-good-guys-do-it" JSF-Patterns (maybe this is J2EE Patterns?).
Thanks you so much!
Please feel free the push me to concretize specific points if i am not clear!
The link for JSF2 you have posted points to JSF1.2 article. In case you want to start of with JSF2 or JSF I suggest following links.
JSF 2.0 Tutorial # mkYong.com
BalusC JSF blog
Stackoverflow wiki for jsf
I'll suggest start with plain vanilla JSF rather than ROO with JSF to get a hang of JSF.
To answer your question
First link provides you with simple jsf examples, in JSF you can have both ajax based and classical way of submitting form. In JSF 1.x versions ajax was not part and parcel of JSF it was implemented by third party component library mainly RichFaces and PrimeFaces to name few. In JSF2 there is inbuilt support for ajax, this does not apply third party components are no longer required, they still provide some extended features. I'll suggest go through this link to find differences between JSF 1.x and JSF 2.
Patterns I am not aware of as such as specific to JSF apart code can be categorized in model - view - controller. Typical case Person represents model, PersonMangedBean plays role of controller which plays central role of getting data from view(jsp/facelets) and after processing data in bean itself or service beans handles navigation to classic views may be listPersons.xhtml.
JSF managed beans are not "super-controller-beans" handling every thing in that bean. I try to categorize things the way you mentioned i.e. have a service layer where we have all business logic may be EJB or Spring managed bean and it decouples at-least business logic away from view technology JSF whereby it(service) can be reused somewhere else as a library if designed properly.
Tip: JSF is component based framework not an action based and it has lifecycle of its own, do get a grip of that life-cycle will save lots of time and proper understanding of the framework. This link though for JSF 1.x holds good for JSF2 too, for basic understanding of life-cycle.
Hope this helps.

JSF Lifecycle and Custom components

There are a couple of things that I am having a difficult time understanding with regards to developing custom components in JSF. For the purposes of these questions, you can assume that all of the custom controls are using valuebindings/expressions (not literal bindings), but I'm interested in explanations on them as well.
Where do I set the value for the valuebinding? Is this supposed to happen in decode? Or should decode do something else and then have the value set in encodeBegin?
Read from the Value Binding - When do I read data from the valuebinding vs. reading it from submittedvalue and putting it into the valuebinding?
When are action listeners on forms called in relation to all of this? The JSF lifecycle pages all mention events happening at various steps, but its not completely clear to me when just a simple listener for a commandbutton is being called
I've tried a few combinations, but always end up with hard to find bugs that I believe are coming from basic misunderstandings of the event lifecycle.
There is a pretty good diagram in the JSF specification that shows the request lifecycle - essential for understanding this stuff.
The steps are:
Restore View. The UIComponent tree is rebuilt.
Apply Request Values. Editable components should implement EditableValueHolder. This phase walks the component tree and calls the processDecodes methods. If the component isn't something complex like a UIData, it won't do much except call its own decode method. The decode method doesn't do much except find its renderer and invokes its decode method, passing itself as an argument. It is the renderer's job to get any submitted value and set it via setSubmittedValue.
Process Validations. This phase calls processValidators which will call validate. The validate method takes the submitted value, converts it with any converters, validates it with any validators and (assuming the data passes those tests) calls setValue. This will store the value as a local variable. While this local variable is not null, it will be returned and not the value from the value binding for any calls to getValue.
Update Model Values. This phase calls processUpdates. In an input component, this will call updateModel which will get the ValueExpression and invoke it to set the value on the model.
Invoke Application. Button event listeners and so on will be invoked here (as will navigation if memory serves).
Render Response. The tree is rendered via the renderers and the state saved.
If any of these phases fail (e.g. a value is invalid), the lifecycle skips to Render Response.
Various events can be fired after most of these phases, invoking listeners as appropriate (like value change listeners after Process Validations).
This is a somewhat simplified version of events. Refer to the specification for more details.
I would question why you are writing your own UIComponent. This is a non-trivial task and a deep understanding of the JSF architecture is required to get it right. If you need a custom control, it is better to create a concrete control that extends an exisiting UIComponent (like HtmlInputText does) with an equivalent renderer.
If contamination isn't an issue, there is an open-source JSF implementation in the form of Apache MyFaces.
Action listeners, such as for a CommandButton, are called during the Invoke Application phase, which is the last phase before the final Render Response phase. This is shown in The JSF Lifecycle - figure 1.
It is the only framework that I've
ever used where component creation is
a deep intricate process like this.
None of the other web frameworks
(whether in the .net world or not)
make this so painful, which is
completely inexplicable to me.
Some of the design decisions behind JSF start to make a little more sense when you consider the goals. JSF was designed to be tooled - it exposes lots of metadata for IDEs. JSF is not a web framework - it is a MVP framework that can be used as a web framework. JSF is highly extensible and configurable - you can replace 90% of the implementation on a per-application basis.
Most of this stuff just makes your job more complicated if all you want to do is slip in an extra HTML control.
The component is a composition of
several inputtext (and other) base
components, btw.
I'm assuming JSP-includes/tooling-based page fragments don't meet your requirements.
I would consider using your UIComponentELTag.createComponent to create a composite control with a UIPanel base and creating all its children from existing implementations. (I'm assuming you're using JSPs/taglibs and making a few other guesses.) You'd probably want a custom renderer if none of the existing UIPanel renderers did the job, but renderers are easy.
The best article I've found is Jsf Component Writing,
as for 2 where do I read the value for a value binding in your component you have a getter that looks like this
public String getBar() {
if (null != this.bar) {
return this.bar ;
}
ValueBinding _vb = getValueBinding("bar");
return (_vb != null) ? (bar) _vb.getValue(getFacesContext()) : null;
}
how did this get into the getValueBinding?
In your tag class setProperties method
if (bar!= null) {
if (isValueReference(bar)) {
ValueBinding vb = Util.getValueBinding(bar);
foo.setValueBinding("bar", vb);
} else {
throw new IllegalStateException("The value for 'bar' must be a ValueBinding.");
}
}

Categories