Vaadin Session Management - How does it work? - java

At work, we develop a web application using Vaadin. I am a pretty advanced programmer in Java. I’m experienced with Vaadin as well. But now I've come to a point where information needs to be stored in a user session. Attributes like Locale, Username and so on.
In the Vaadin Documentation they are talking about two different types of sessions but I dont really get the difference:
VaadinServletService or VaadinPortletService described as low-level customization layer for processing requests.
VaadinSession of a UI with getSession() as lower-level session objects.
What is the difference and which one is to use when I want so store attributes during the whole UI independent user-session?

If in Vaadin 8, you have simple hierarchy of scope, on three levels.
ServletContextRepresents your entire Vaadin web app.
VaadinSessionRepresents each user's work session.
UIRepresents each web browser/tab within a session (Vaadin supports multi-window apps, pretty amazing).
The first is a standard part of every Java Servlet, defined in the spec.
The second is a wrapper around the session, also defined in the Java Servlet spec.
Vaadin is actually one huge Servlet, so it carries these features of context and session.
The UI class is unique to Vaadin. It represents the content of a web browser window/tab. Vaadin supports multi-window apps, tracking all the open windows/tabs as part of the session, a very nice feature of Vaadin.
To store state-wide app, use the standard ServletContext object. It carries a key-value collection known as "attributes". The key is of String type, and the value is of Object type. Call methods setAttribute, getAttribute, and removeAttribute. Use this collection for any objects you may need to access for any of your users, accoss their sessions. You may to learn about ServletContextListener by the way, to hook into your web app launching and exiting.
The VaadinSession class carries the same kind of key-value collection, with similar "attribute" methods. Use this to track items throughout the user’s work session, across them possibly opening/colsing multiple windows/tabs of your app. For example, in the session you would store the user’s Spirit Animal choice, their avatar image, and the fact that person has been authenticated via username/password credentials. See this page in the manual, Setting and reading session attributes.
If you want to store per-window settings, for something like their choice of background color or light/dark mode, store something on UI. Unfortunately, that class does not come with a convenient key-value store that I know of. So you'll need to add your own Map, or some other member variables to your UI subclass.
For more info, see my Answer to a similar Question. I made some nifty diagrams there. That question is about Vaadin 7, but as I vaguely recall, these concepts carry over between 7 and 8.
As for VaadinService and VaadinServletService, I have never understood exactly their role. They seem to represent various aspects of your entire Vaadin web at runtime. But neither carries a convenient key-value collection as like VaadinSession. (If you use Vaadin Flow, versions 10+, see VaadinContext, a class than does represent your entire web app, and does carry a convenient key-value collection of "attributes".)

Related

Best way to directly manipulate java-based backend objects from flex front-end?

I'm currently stuck between two options:
1) Store the object's information in the file.xml that is returned to my application at initialization to be displayed when the GUI is loaded and then perform asynchronous calls to my backend whenever the object is edited via the GUI (saving to the file.xml in the process).
-or-
2) Make the whole thing asynchronous so that when my custom object is brought up for editing by the end-user it queries the backend for the object, returns the xml to be displayed in the GUI, and then do another asynchronous call for if something was changed.
Either way I see many cons to both of these approaches. I really only need one representation of the object (on the backend) and would not like to manage the front-end version of the object as well as the conversion of my object to an xml representation and then breaking that out into another object on the flex front-end to be used in datagrids.
Is there a better way to do this that allows me to only manage my backend java object and create the interface to it on the front-end without worrying about the asynchronous nature of it and multiple representations of the same object?
You should look at Granite Data Services: http://www.graniteds.org If you are using Hibernate: it should be your first choice, as BlazeDS is not so advanced. Granite implements a great facade in Flex to access backend java objects with custom serialization in AMF, support for lazy-loading, an entity cache on the flex-side with bean validation. Globally, it is a top-down approach with generation of AS3 classes from your java classes.
If you need real-time features you can push data changes on flex client (Gravity module) and solve conflicts on the front side or implement conflict resolvers on the backend.
Still you will eventually have to deal with advanced conflicts (with some "deprecated" flex objects to work with on the server: you don't want to deal with that), a basic feature for instance is to add a version field and reject manipulation of such objects on the backend automatically (many ways to do that): you will have to implement a custom way for a flex client to update itself to the current changes implying that some work could be dropped (data lost) on the flex client.
If not so many people work on the same objects on your flex application, this will not happen a lot, like in a distributed VCS.
Depending on your real-time needs (what is the frequency of changes of your java object? This is the most important question), you can choose to "cache" changes in the flex side then updating the whole thing once (but you'll get troublesome conflicts if changes have happened) or you can check everytime the server-side (granite enables this) with less conflicts (and if one happens: it is simpler) but you'll generate probably more code to synchronize objects and more network traffic.

Best Dashboard Architecture

I need to build a dashboard for an application, the dashboard will have different dashlets and each dashlet can have any one of the following things:
Graphs (JFreeCharts and some Javascript Chart)
Table data from tables
Data from external sources
Maps
What can be a good architecture for such kind of application?
What I have currently in mind is:
Each dashlet should have its own lifecycle and when the dashboard loads it should just show the UI of the dashlets initially.
After the page load each dashlet sends a server call (based on its type) to fetch its data
After the data has been fetched, each dashlet (based on its type) renders the data.
First of all, there are plenty of front-end frameworks to get you started. Some of the more popular ones include:
Backbone
Javscript MVC
Sproutcore
A bit of Google searching can yeild pros and cons of each and I would weight your options accordingly.
That all being said, the basic problem you posed actually seems similar to ours. In the end, we built something a bit different in house. Many of the frameworks out there are optimized to display a singular canonical "view" based on a Model reflected by the DB and a Controller to manage small changes. A dashboard has, in essence, a variety of different modules that must be doing their own independent things as you've mentioned in your question. Because of the high number of independent modules, I feel like you might feel pains in some of the frameworks listed above.
I can't tell you exactly how to implement such a module architecture, but here are some rules of thumb we used when designing ours:
Module Design:
Module-based. (Login module, Map module, each Dashlet may be a module, etc.)
Modules must have one Model, may have no more than one Collection (which is-a Model), and may have one or more Views.
A module may be used in multiple places and pages. The singular Model should stay the same, but the Views are likely different.
Rendering:
Almost all HTML on the page is written and updated by javascript modules. The template files are almost empty except for headers and basic scaffolding.
All modules render their full HTML selves and replace themselves into the DOM. The module should have as complete of a static HTML representation ready to go before inserting into the DOM. This means the render functions use “.replaceWith()” instead of “.append()”.
If simple HTML replacing isn’t an option (i.e. needs to be animated) a transition function should be defined detailing how to go from one rendered state to another.
Because rendering is expensive, Views by default do not auto-refresh on all Model changes. Re-rending happens through events only. _render() is in-fact an internal method.
Orthogonality:
A single inter-module event dispatcher on the page Controller handles all cross-effects between modules.
Modules should never “reach outside” of their own DOM context. If an event in one module affects another, it should go through the page controller dispatcher.
Each module as orthogonal as possible. They depend on each other as little as possible.
Each module in its own file.
Connecting to backend:
All modules use the same global backend adapter. Modules never talk to the backend by themselves. This makes your front-end back-end agnostic.
Recursive:
Modules are commonly included in other modules.
Modules re-render recursively.
Testable:
Because modules render static HTML, they can be predictably tested.
Modules must be testable.
Standard input -> Module -> Predictable static HTML output.
Standard events -> Module -> Predictable static HTML output.
If anyone knows of other frameworks along these lines, please share!
Our web app is based exactly on this architecture and in production since end of last year. You can see it at http://beebole.com
We just optimized the calls to our own server.
There is a single call to get the common data needed by most widgets, each time a screen is loaded.
Then if a widget needs additional data, it makes a call itself to our server.
The external widgets call their own data too, but to another server.
I would advise against using a custom web framework when there are so many free ones available.
As mentioned in another answer, the traditional MVC style frameworks don't really fit well to your 'dashboard' desired style of UI. They are best used for creating static web sites based on data retrieved elsewhere. They don't handle user interaction well and you usually have to hand roll your own AJAX to do anything useful without a page request.
A better breed of web frameworks to look at are the Web 2.0 fraemworks, also known as the frameworks which help you build web applications. It is important to understand the difference between web site and web applications. They are usually differentiated by the latter being interactive and the former being mostly static. Websites which also have some interactive components are still web sites. A good way to think of it is ask yourself "Does this feel like a desktop app?".
For web application development in the Java (JVM) realm, I would use Vaadin. It lets you write Java code similar to Swing programming, with event based methods. You can even avoid writting HTML altogether if you'd like by defining your views programatically. This lets you unittest your view logic (in web apps, there is more than usual) which is not posible with regular HTML template based frameworks. The other main advantage is that it has built in methods which allow you to write Java code to handle dynamic, asynchronous functionality and it all gets translated to JavaScript automatically. No need to write 4 different languages while writing your web app, just write Java for everything! Try it out, it is fun to work with!
Another web app framework that is getting alot of attention is Lift. I do not have experience with it but many devs I have spoken with have promoted it to me. I believe it uses HTML templates with Java code as the back-end. It is also apparently really easy to get started and your web app spun up. It also has built in support for doing AJAX like functionality. Worth looking into at least.
There are probably many more web app frameworks out there that would suit your needs. These all have the advantage of being tested, independently maintained, updated, and secure*. If you roll your own framework for this project, you need to worry about everything yourself. Written a web framework that doesn't offer anything new would be like written yet another programming language that isn't innovative; it is just a waste of time.
I think what you are looking for is more along the lines of managing or controlling your dashboard. I am designing something similar. I would suggest you look at google app engine it can be used to automate and control this: https://developers.google.com/appengine/docs/whatisgoogleappengine
Also look at these open-source dashboards: https://github.com/twilio/stashboard

Update beans (I18N) for a Spring MVC Webservice

I've a webservice written with Spring MVC for a webapp.
The user could change the locale and so the language of his page, so a call to my webservice is done with this information. For information, at startup, I load few beans for my webapp configuration. These beans attributes needs to be internationalize
My question is how can I update the values of my bean directly from a user call ?
There are two things here:
One is overall i18n architecture. At best Beans (controllers, models) should not contain any translatable texts, therefore no i18n work would need to be done to make them localizable. This is ideal situation which doesn't happen to often in practice.
Another is a way to make Controllers localizable. Again, there are two possible approaches: one is to use resource keys instead of strings, messages, etc. and resolve it in your View to real translation, just before displaying it to user, another is to make Controllers read these messages from resources - you said that you know Locale, so it could be done. If you are going with latter solution, you probably need to limit your Scope to request (as different users might want to use different languages and as far as I understand what you wrote users might want to change their language on the fly).

Pagination in a REST web app

Usually, a user makes a search, get a hitlist, and can then browse it. The hitlist is an intermediate result that remains consistent throughout the browsing and is typically stored in session state. E.g. if new items are added concurrently by some other, they would appear only in a subsequent search.
In a REST application, I can't have this intermediate result easily -- neither does it belong to the client, nor the model. I have read Pagination in a REST web app, but am not completely clear with the answer. The solution there seems to assume that the model is not updated while the user browses the results.
We can of course imagine the world (the model) as series of immutable snapshot. By providing a timestamp (or a global version number), we then get a consistent view of the model at that time, which solves the problem from a conceptual point of view. It does however imply full versioning of the model. (I'm also wondering if there is a connection to draw with functional programming)
How should I deal with this issue?
Note: I'm asking because I plan to use the play framework, which has no notion of HTTP state or session at all; it's pure restful.
After you've got query result on the first search, You can save the result in a cache. For one server it can be ehcache (supported in play) or memcached (also supported by play) for a cluster environment. You can save the result by a static name + session id. So you only need session id for each request, it's saved in the client cookie and available in your play app.
You can use cached data for browsing pages. I'm also recommending ElasticSearch.
EDIT: A better way is you can use play-search http://github.com/jfp/play-search, Sample:
Query q = Search.search("object:dogs", Folder.class);
q.orderBy("object")
.page(2,5)
.reverse();
PS: Your decision with Play is perfect. I'm a professional .net developer and I can say the only (optimal) web framework in the world that can race with asp.net mvc 2 is Play framework. Grails is buggy, Django/Python, Yii/Php, Rails all are slow, not type safe and far from jvm/clr frameworks. wicket, tapestry, struts, jsf, spring mvc all are verbose and useless. spring roo is only a template generator. Asp.net mvc surpassed asp.net and became #1 development platform for .net, but sun worked for an old asp.net clone with jsf for next gen, big mistake. The only hope for java is play framework in my opinion. With scala module, it's perfect...
I'm kind of lost about what your context is, but if I have to provide a short answer, it is that search results should be part of the model. I assume you have a searchable model. What you do is index the parts you need to search and store the index info (making it part of the model, too). When you execute a search, you query the index and display results. Performing the search a second time would not contain newly added items, unless the index is regenerated.
This removes the need to use any session state and keeps it restful, as the indexing is just another operation performed on a resource. Is this what you need?

Why is the servlet request not available in the portlet API

The portlet API deos not provide any reference to the enclosing servlet request and response objects. I know it is not the preferred model of interaction with the user, but it seems draconian to remove all access.
I understand that for portlet driven interaction with the user, you want to use portlet URLs, and let the portlet container manage all the complexity.
However if you have a number of portlets which are basically showing variants of the same data, it makes sense for them to be able to use the enclosing request to drive the data.
We ended up using using a Liferay specific call to get the request, and it all seems to work as we wish.
However I do feel the guilt.
So my question really is, is there an underlying deep reason for the prohibition, or is it just to enforce the authors view of the API environment?
The portlet doesn't run right into the Servlet container, but rather what is called a Portlet container.
You should be able to access to the corresponding information, PortletRequest, PortletResponse, and PortletContext.
The reason is that two instances of the same portlet can run next to each other in the same page, but still be isolated with their own lifecycle. The portal will "multiplex" that transparently for you, and it will convert from the servlet world to the portlet world. Portlet bridges are also available to develop portlets with non-portlet technologies (e.g. JSF). I agree that all this is usually (very) complicated to use (because of the many frameworks and implementations available), but when you think of how it works conceptually, it's quite nice.
The exact details will depend on the technologies you chose to develop the portlet. But I feel like there should be a way to do what you want using the portlet API.

Categories