I'm having a performance problem with my JSF/RichFaces/Facelets ajax requests and from what I can tell its because the entire component tree is being rebuild on each ajax request. This is happening even if I use ajaxSingle=true, wrap sections in a4j:region, declare a single section for rerendering or none at all. Our page is a dynamic page with many nested levels. The page may contain around 800-900 fields (inputText, rich calendars, selectOneMenus, etc). The initial load time is an issue, but I understand that issue, its a lot of fields. Once we have that initial build/render time though we have designed all other actions to be ajax and only reRender what is needed. From facelets debug logs I see messages like this on any ajax call:
2011-08-24 22:19:03,054 DEBUG [facelets.viewhandler] (http-0.0.0.0-8080-2) Took
24445ms to build view: /oconsole/appfile.xhtml
2011-08-24 22:19:09,377 DEBUG [facelets.viewhandler] (http-0.0.0.0-8080-2) Took
6323ms to render view: /oconsole/appfile.xhtml
I'm not sure if something we are doing is causing the rebuild of the entire component tree, or facelets is determining this need required for some reason (stale cache?). Here is our stack:
JBoss 5.1
JSF 1.2
RichFaces. 3.3.3.Final
Facelets 1.1.15
Seam 2.1.2
I have tried adding some context parameters to see if they would help, but they did nothing:
facelets.BUILD_BEFORE_RESTORE = false
facelets.REFRESH_PERIOD = -1 or 5 (as in 5min)
Is there anyway to tell if our views are being cached properly? We do not delcare a state saving method, so I believe it defaults to server side. All our requests happen within seam long running conversations. I wasn'te sure if this plays a factor as I thought views get cached at session level? Any help would be greatly appreciated, thank you.
Update after more debugging:
The AjaxViewHandler (which has a member variable of the FaceletsViewHandler) has developmentMode=true set. I'm not sure if this is causing facelets to not cache any views so any changes would be refreshed during development cycles...?? Its been very difficult to find any information on facelets/JSF caching of views and the behavior and controlling that. Furthermore, when I add config param:
<context-param>
<param-name>facelets.DEVELOPMENT</param-name>
<param-value>false</param-value>
</context-param>
This did not take! In debugger I still see true set. Since we have a lot of subviews I also tried
com.sun.faces.numberOfLogicalViews and
com.sun.faces.numberOfViewsInSession
to 1000 up from 15(default) and this had no effect.
I also tried changing to client side state saving without any luck. Running out of ideas....hope someone can help....
It seems Seam 2.1 auto-initializes RichFaces and I'm not sure if that has something to do with it.....
As with any performance problem, a profiler would help greatly in locating the bottlenecks. (Yes, you know it is the restore_view phase, but not where in the restore_view phase).
That said, the restore view phase indeed restores the entire view, not just the parts that will be processed or rendered. Quoting the RichFaces taglib documentation:
process: Id['s] (in format of call UIComponent.findComponent()) of components, processed at the phases 2-5 in case of AjaxRequest caused by this component. Can be single id, comma-separated list of Id's, or EL Expression with array or Collection
RESTORE_VIEW is phase 1. Also:
reRender: Id['s] (in format of call UIComponent.findComponent()) of components, rendered in case of AjaxRequest caused by this component. Can be single id, comma-separated list of Id's, or EL Expression with array or Collection
Moreover, I am not sure that UIComponent.findComponent() is implemented using a more suitable datastructure than a component tree. (Finding something in the component tree would boil down to linear search ...).
I have observed similar effects with JSF 2.0 (Mojarra). My conclusion was that views must not contain more than a couple dozen UIComponents, irrespective of whether they are rendered. (Put differently, AJAX is unsuitable for page navigation.) We indend to keep views small by including only components that are currently visible in the view, and switch views if many new components need to appear. That is, instead of one view with 10 tabs with 30 components each, we'd have 10 views, each only containing the content of a single tab. A drawback of that approach is that components are disposed when switching tabs, causing any state not held in backing beans to be lost.
I do not claim this to be a good solution. Alas, it was the best one I found when looking into this a couple weeks ago. I'd be happy to be shown a better one, too.
Edit
When I say restore, I mean ViewHandler.restoreView(), which called both for an initial get request and a postback. It is incorrect to say that restoreView would simply reuse an existing view as is. For instance, the JSF 2.0 spec mandates in section 7.6.2.7: ]
The restoreView() method must fulfill the following responsibilities:
All implementations must:
If no viewId could be identified, return null.
Call the restoreView() method of the associated StateManager , passing the FacesContext instance for
the current request and the calculated viewId, and return the returned UIViewRoot, which may be null.
and in section 7.7.2:
JSF implementations support two primary mechanisms for saving state, based on the value of the
javax.faces.STATE_SAVING_METHOD initialization parameter (see Section 11.1.3 “Application Configuration
Parameters”). The possible values for this parameter give a general indication of the approach to be used, while allowing
JSF implementations to innovate on the technical details:
client -- [...]
server -- Cause the saved state to be stored on the server in between requests. Implementations that wish to enable
their saved state to fail over to a different container instance must keep this in mind when implementing their server
side state saving strategy. The default implementation Serializes the view in both the client and server modes. In the
server mode, this serialized view is stored in the session and a unique key to retrieve the view is sent down to the
client. By storing the serialized view in the session, failover may happen using the usual mechanisms provided by the
container.
Put differently, the AJAX support added to JSF (both the one added by RichFaces 3 to JSF 1.2, and the one incorporated into JSF 2.0) aims to reduce network bandwith consumption, not server side cpu consumption.
From my analysis the issue is caused by the implementation of facelets. Based on debugger the following lines of FaceletViewHandler class, causes rebuild of tree on each (even AJAX) request (buildBeforeRestore is false, so buildView method is invoked):
// build view - but not if we're in "buildBeforeRestore"
// land and we've already got a populated view. Note
// that this optimizations breaks if there's a "c:if" in
// the page that toggles as a result of request processing -
// should that be handled? Or
// is this optimization simply so minor that it should just
// be trimmed altogether?
if (!this.buildBeforeRestore
|| viewToRender.getChildren().isEmpty()) {
this.buildView(context, viewToRender);
}
So in my mind to resolve the issue of tree rebuild on each request is to go deeply to facelets implementation and do reimplementation... I would rather prefer restructure the view and minimize number of components, so build tree time is low.
Related
In Java Wicket 6, I'm trying to find out how to get notified in a Page or Component when that Page / component is no longer used.
The context is I have a configuration service that can have listeners added to it to notify when configuration has changed / reloaded.
Obviously, if a page/component is no longer needed then I should remove it as a listener from the service, but I can't find a way of being notified or that fact.
onRemove() doesn't cut it, as it doesn't appear to be called on the page or components in the page since I'm not explicitly REMOVING anything. I'm just letting pages/components drift away into the ether.
Any ideas on how I can clean up my resources to make sure my listener list / memory footprint doesn't balloon over a period of time?
My pages are stateful, btw (although I'm not sure they need to be atm). The Configuration Service is injected into a Page/Component via #SpringBean.
One possible way to propagate a configuration update it to have the page listen ONLY and then fire a Wicket event to contained components. This would cut down on the number of listeners to the Service, but this doesn't FEEL very nice if the components have a reference to the Configuration Service anyway to then be told by something else that it needs to reconfigure. Maybe.
Even so, with the above solution I'd still like to clear the Page from the listener list when no longer needed.
By using #SpringBean you do not make a hard reference between the Page/Component and the real service instance!
#SpringBean injects a (serializable) Proxy that has logic to lookup the Spring bean from Spring's ApplicationContext. So I think you have nothing to clean actually.
I'm trying to make a design based on the Uncle Bob's Clean Architecture in Android.
The problem:
I'd like to solve is how to make the changes generated in one repository to be reflected in other parts of the app, like other repositories or Views.
The example
I've designed a VERY simplified example for this example. Please notice that boundary interfaces has been removed to keep the diagrams small.
Imagine an app that shows a list of videos (with title, thumnail and like count), clicking a video you can see the detail (there you can like/dislike the video).
Additionally the app has an statistics system that counts the number of videos the user liked or disliked.
The main classes for this app could be:
For the Videos part/module:
For the Stats part/module:
The target
Now imagine you check your stats, then navigate the list of videos, open the detail of one, and click the like button.
After the like is sent to the server, there are several elements of the apps that should be aware of the change:
Of course the detail view, should be updated with the changes (this can be made through callbacks so no problem)
The list of videos should update the "likes" count for the given video
The StatsRepository may want to update/invalidate the caches after voting a new video
If the list of stats is visible (imagine a split screen) it should also show the updated stats (or at least receive the event for re-query the data)
The Question
What are the common patterns to solve this kind of communication?
Please make your answer as complete as you can, specifying where the events are generated, how they get propagated though the app, etc.
Note: Bounties will be given to complete answers
Publish / Subscribe
Typically, for n:m communication (n senders may send a message to m receivers, while all senders and receivers do not know each other) you'll use a publish/subscribe pattern.
There are lots of libraries implementing such a communication style, for Java there is for example an EventBus implementation in the Guava library.
For in-app communication these libraries are typically called EventBus or EventManager and send/receive events.
Domain Events
Suppose you now created an event VideoRatedEvent, which signals that a user has either liked or disliked a video.
These type of events are referred to as Domain Events. The event class is a simple POJO and might look like this:
class VideoRatedEvent {
/** The video that was rated */
public Video video;
/** The user that triggered this event */
public User user;
/** True if the user liked the video, false if the user disliked the video */
public boolean liked;
}
Dispatch events
Now each time your users like or dislike a video, you'll need to dispatch a VideoRatedEvent.
With Guava, you'll simply pass an instantiated event object to object to EventBus.post(myVideoRatedEvent).
Ideally the events are generated in your domain objects and are dispatched within the persisting transaction (see this blog post for details).
That means that as your domain model state is persisted, the events are dispatched.
Event Listeners
In your application, all components affected by an event can now listen to the domain events.
In your particular example, the VideoDetailView or StatsRepository might be event listeners for the VideoRatedEvent.
Of course, you will need to register those to the Guava EventBus with EventBus.register(Object).
This is my personal 5cents and maybe not closely enough related to your example of "The Clean Architecure".
I usually try to force a kind of MVC upon androids activities and fragments and use publish/subscribe for communication. As components I have model classes that handle business logic and the data state. They data changing methods are only to be called by the controller classes which usually is the activity class and also handles session state. I use fragments to manage different view parts of the application and views under those fragments (obviously). All fragments subscribe to one or more topics. I use my own simple DataDistributionService which handles different topics, takes messages from registered publishers and relays them to all subscribers. (partly influenced by the OMGs DDS but MUCH MUCH more primitive) A simple application would only have a single topic e.g. "Main".
Every part of view interaction (touches etc) is handled by its fragment first. The fragment can potentially change a few things without sending notifications. E.g. switching the subrange of rendered data elements if the rest of the app does not need to know/react. Otherwise the fragment publishes a ViewRequest(...) containing the necessary parameters to the DDS.
The DDS broadcasts that message and at some point reaches a controller. This can simply be the main activity or a specific controller instance. There should be only ONE controller so that the request is only handled once. The controller basically has a long list of request handling code. When a request arrives the controller calls to the business logic in the model. The controller also handles other view related things like arranging the view (tabs) or starting dialogs for user input (overwrite file?) and other things that the model is not supposed to know about but influences (Throw new NoOverWritePermissionException())
Once the model changes are done the controller decides if an update notification has to be send. (usually it does). That way the model classes do not need to listen or send messages and only take care of busines logic and consistent state. The update notification ist broadcasted and received by the fragments which then run "updateFromModel()".
Effects:
Commands are global. Any ViewRequest or other kind of request can be send from anywhere the DDS can be accessed. Fragments do not have to provide a listener class and no higher instance has to implement listeners for their instanced fragments. If a new fragment does not require new Requests it can be added without any change to controller classes.
Model classes do not need to know about the communication at all. It can be hard enough to keep consistent state and handle all the data management. No message handling or session state handling is necessary. However the model might not be proteced against malicous calls from the view. But that is a general problem and cannot really be prevented if the model has to give out references at some point. If your app is fine with a model that only passes copies/flat data its possible. But at some point the ArrayAdapter simply needs access to the bitmaps he is supposed to draw in the gridview. If you cannot afford copies, you always have the risk of "view makes a changing call to the model". Different battlefield...
Update calls might be too simple. If the update of a fragment is expensive (OpenGL fragment reloading textures...) you want to have more detailed update information. The controler COULD send a more detailed notification however it actually should not have to/be able to know what parts of the model exactly changed. Sending update notes from the model is ugly. Not only would the model have to implement messaging but it also gets very chaotic with mixed notifications. The controler can divide update notifications and others a bit by using topics. E.g. a specific topic for changes to your video resources. That way fragments can decide which topics they subscribe to. Other than that you want to have a model that can be queried for changed values. Timestamp etc. I have an app where the user draws shapes on canvas. They get rendered to bitmaps and are used as textures in an OpenGL view. I certainly don't want to reload textures everytime "updateFromModel()" is called in the GLViewFragment.
Dependency Rule:
Probably not respected all the time. If the controller handles a tab switch it can simply call "seletTab()" on a TabHost and therefore have a dependency to outer circles. You can turn it into a message but then it is still a logical dependency. If the controller part has to organize some elements of the view (show the image-editor-fragment-tab automatically after loading an image via the image-gallery-fragmen-tab) you cannot avoid dependencies completely. Maybe you can get it done by modelling viewstate and have your view parts organize themselves from viewstate.currentUseCase or smth like that. But if you need global control over the view of your app you will get problems with this dependency rule I'd say. What if you try to save some data and your model asks for overwrite permission? You need to create some kind of UI for that. Dependency again. You can send a message to the view and hope that a DialogFragment picks it up. If it exists in the extremely modular world described at your link.
Entities:
are the model classes in my approach. That is pretty close to the link you provided.
Use Cases:
I do not have those explicitly modelled for now. Atm I am working on editors for videogame assets. Drawing shapes in one fragment, applying shading values in another fragment, saving/loading in a galleryfragment, exporting to a texture atlas in another one ... stuff like that. I would add Use Cases as some kind of Request subset. Basically a Use Case as a set of rules which request in which order are allowed/required/expected/forbidden etc. I would build them like transactions so that a Use Case can keep progressing, can be finished, can be cancelled and maybe even rolled back. E.g. a Use Case would define the order of saving a fresh drawn image. Including posting a Dialog to ask for overwrite permission and roll back if permission is not give or time out is reached. But Use Cases are defined in many different ways. Some apps have a single Use Case for an hour of active user interaction, some apps have 50 Use Cases just to get money from an atm. ;)
Interface Adapters:
Here it gets a bit complicated. To me this seems to be extremely high level for android apps. It states "The Ring of Interface Adapters contains the whole MVC architecture of a GUI". I cannot really wrap my head around that. Maybe you are building far more complicated apps than I do.
Frameworks and Drivers:
Not sure what to think of this one. "The web is a detail, the database is a detail..." and the graphic contains "UI" in this Ring as well. Too much for my little head
Lets check the other "asserts"
Independent of Frameworks. The architecture does not depend on the existence of some library of feature laden software. This allows you to use such frameworks as tools, rather than having to cram your system into their limited constraints.
Hm yeah well, if you run your own architecture that is what you get.
Testable. The business rules can be tested without the UI, Database, Web Server, or any other external element.
As in my approach model classes neither know about controllers or views nor about the message passing. One can test state consistency with just those classes alone.
Independent of UI. The UI can change easily, without changing the rest of the system. A Web UI could be replaced with a console UI, for example, without changing the business rules.
Again a bit overkill for android is it not? Independence yes. In my approach you can add or remove fragments as long as they do not require explicit handling somewhere higher up. But replacing a Web UI with a console UI and have the system run like before is a wet dream of architecture freaks. Some UI elements are integral part of the provided service. Of course i can easily swap the canvas drawing fragment for a console drawing fragment, or the classic photo fragment for a 'take picture with console' fragment but that does not mean the application still works. Technically its fine in my approach. If you implement an ascii console video player you can render the videos there and no other part of the app will necessarily care. However it COULD be that the set of requests that the controller supports does not align well with the new console UI or that a Use Case is not designed for the order in which a video needs to be accessed via a console interface. The view is not always the unimportant presenting slave that many architecture gurus like to see it as.
Independent of Database. You can swap out Oracle or SQL Server, for Mongo, BigTable, CouchDB, or something else. Your business rules are not bound to the database.
Yeah, so? How is that directly related to your architecture? Use the right adapters and abstraction and you can have that in a hello world app.
Independent of any external agency. In fact your business rules simply don’t know anything at all about the outside world.
Same here. If you want modularized independent code then write it. Hard to say anything specific about that.
I'm working on a servlet to perform some logic specific to a resourceType in sling and set information to the request to be accessible via the jsp then handing off the request to the jsp similarly to the first solution provided in this answer.
Here's some example code to represent my situation:
#SlingServlet(
resourceTypes="myapp/components/mycomponent",
methods="GET",
extensions={"html"}
)
...
#Reference
private ServletResolver serlvetResolver;
protected void doGet(....) {
setPropertiesToRequest();
Servlet servlet = servletResolver.resolveServlet(resource, "....jsp");
servlet.service(slingRequest, slingResponse);
clearPropertiesFromRequest();
}
Because of this, I've noticed that I've lost sling's selector handling (I've had to roll my own simpler version to determine which jsp to render. Full featured sling selector handling is described in more detail here). I wanted to reach out to the stack overflow community and ask what else I may be missing out on by depriving the default get handler of the request. I've scanned through the source code but I think there may be more going on.
Secondly, I'd be interested in thoughts on how and where this approach may impact performance of the request resolution.
Thanks, Thomas
Processing the business logic in Java and delegating to scripts for rendering sounds like a job for the recently released Sling Models. Using that should remove the need to implement your own handling of selectors, as those won't affect the model selection, only the rendering scripts.
Not sure what you are trying to achieve here, but the main problem seems to me that your SlingServlet handles the html extension and by itself does not have selectors to filter a bit more. Thus it of course intercepts all the requests to your component. Then you have to take care of the selectors again to be able to choose the correct JSP.
The question is, why do you use a SlingServlet for it when you anyway do the rendering by JSP?
Can't you implement your logic in the JSP or better in a bean referenced in the JSP?
In our company we use our custom tag that takes care of this, but there are public frameworks available from other Adobe Partner:
https://github.com/Cognifide/Slice
http://neba.io/index.html
We have built a Spring MVC web application that is heavily relying on the user to do things in a certain order, and while it prevents users from circumventing this (without trying very hard) in the usual case (by not offering options to “go to places” you’re not supposed to at the given moment), we’re having some problems when people open another instance of the application in a new tab or browser window.
Since the application stores the domain model in the user’s session, using the program in another window can potentially mess up the model’s data, we’ve already implemented a page-ID mechanism that validates the user using the program in the correct order and not using the browser navigation, but we’re still facing problems when things like resetting the program (this is a feature, redirecting the user to the home screen and clearing the domain model) happen in one window and the user then tries to do something relying on the domain model to be filled with valid data in another window (leading to a NullPointerException quite quickly).
Storing some user details (like id, name, email) in a session might be ok, but storing the user's state (or any data that changes often and/or significantly affects other things in your app) doesn't sound like a good idea.
Hopefully one of the following approaches will fit you:
Don't save state in the session - load it from the database whenever you need it (in your case, whenever the user tries to access one of the steps that should be done in order). If you use caching, this shouldn't have major performance consequences.
Don't save state in the database, only in the session - works for limited cases (for instance, ordering airline tickets) where you can postpone committing your domain object until the process has finished.
Use Ajax for multi-step processes and don't save state at all (except implicitly in the browser). This requires putting all the steps into one page and ajaxifying some of your code.
Regardless, if someone logs in and tries to go to step 3, they shouldn't get an exception thrown at them, but that's a different story.
If I were you, I'd let user to wander around other parts of the website - the parts that don't interfere with your wizard process. However, once they try to restart it - check if there's PageID in session, and remind them they have not finished what they started, and ask if they would like to cancel/restart or continue on from where they left it.
In case anyone ever reads this question again:
Instead of the HttpSession keeping exactly one copy of the domain model it now holds a collection and we transport a reference to a single one of the models through the requests/responses so we can get the right model to work on in our controllers and views.
I want to do something like this: index.xhtml -> createPerson.xhtml -> addAddress.xhtml -> index.xhtml.
In Managed-Bean CreatePerson a new Person-Object will be created, filled and saved, in Managed-Bean AddAddress I need the Person-Object in order to add an address to this person and after this, it should navigate back to the starting point. I think, the Managed-Bean CreatePerson should be #SessionScoped, because I have to inject the Person-Object into AddAdress (here #ViewScoped).
I want to have a loop or rather the possibility to create more than one person, but how can I do this if I have a SessionScoped-Bean, that lives longer than I need it? Is there any command or annotation to destroy it? How do you handle such workflows related to the scopes?
I know about MyFaces Orchestra with conversation-scope, but I will, if possible, do it only with Eclipse/Tomcat (7.0.11)/Mojarra (2.0.3).
Use a single view and make use of the rendered attribute to show/hide included views with "subforms" depending on each other. This way you can go with a #ViewScoped bean.
Alternatively, just save the Person in the DB after create and pass its id as request parameter to the next view and let it load from the DB again.
If you only want (or can) use Tomcat and Mojarra then both solutions mentioned by BalusC work perfectly, although with the limitations that you have to stay on a single page or redo queries between page navigation. Your use case is exactly what the conversation scope in Java EE 6 (through CDI) is made for. You can add this too to Tomcat via the Weld reference implementation.
When using the method BalusC outlined for staying on a single page, to give the user a tiny bit the impression of dealing with separate pages, it might be an option to display the rendered parts of the page using 'dialogs' (floating, css, ...). If using a third party component library is an option for you, you could add RichFaces or PrimeFaces that both contain ready to use dialog components.