managing state with jboss seam
DESCRIPTION
Introduction to JBoss Seam and state management problems in Java-based web applications.TRANSCRIPT
Managing State with JBoss SeamRichmond Java Users GroupFebruary 2007Chris Wash
Agenda
� What are the problems in managing state?� How do they manifest themselves?� Why is managing state so difficult?� How would you solve them on your own?� How could a framework help?
� What is Seam? � How does Seam manage state?� How does Seam compare to other stateful frameworks?� What is seam-gen?
What is conversational state?
� State is the data involved at any point during process execution.
� Think of instance variables storing data over different instance method calls.
� Some processes cannot exist in a single request/response lifecycle, but need to be thought of as a conversation.
� A process is either stateful or not!� Some occur over a period of time, or take a while to complete.� Some cannot be completed in just one step.� Some involve complex interactions with other pieces of the
system.
How Healthy Is Your State Management?
� Ever had problems with...?� The back button� New browser windows or tabs
� General data inconsistencies � Stale data in pageflows� Database� Logs
Symptoms
Session bloat
Concurrency Issues
Improperly handling Redundant Posts
Heartburn from Multiple Windows/Tabs
Session Bloat
� HttpSession attributes are an easy way to store state data between requests
� There is no mechanism to clean data from the Session� Early in development, this may not be a problem. � Late in development, this will be a problem!
Concurrency Issues
� Conflicts over editing objects, session attributes, etc.� Think of two clients trying to edit the same object
concurrently, e.g. Version Control� AJAX finer-grained requests can cause more problems
The Redundant Posts Problem
� Consider a client issuing multiple posts� Common DoS vulnerability� Javascript form.submit() from an onclick event handler� Clicking the “Back” and resubmitting a form� What if this submitted a payment? Is it ever acceptable
to submit redundant payments?
The Multiple Browser Windows Problem
� Using session scoped attributes to store state between requests is dangerous
� A new browser window hijack the state of the previous browser window
� Two browser windows doing different things with the same session attribute is bad!
Treating the symptoms vs. Curing the disease
� Some of our treatment options are useful, but can’t we get a little help from a framework?
� Problem space is purely technical in nature� Time spent solving these problems is NOT time well-
spent to a paying business customer� Any proactive approach will pay for itself in savings later� Worst case, you can’t use a framework to help you –
let’s explore treatment options
Treating Session Bloat
� Without proper state management, most applications develop session bloat.
� Hard to replicate/reproduce – even harder to solve� Only option is to reduce the session’s size
� Really points to a lack of conversation
Treating Concurrency Problems
� Clients’ changes conflict – which one wins?� Higher probability of conflict when transactions span
multiple requests� Follow Martin Fowler’s Offline-Locking Patterns
� Pessimistic Offline-Locking – Lock/Wait� Assumes conflicts are common� Not desirable from a performance perspective!
� Optimistic Offline-Locking – Copy, Edit, Merge� Assumes conflicts are rare� More conflicts = more merges� User experience tradeoff
Treating Redundant Posts
� Javascript solutions are not the way to go!� Use the Synchronizer Token pattern� For sensitive data submission, use the Redirect After
Post pattern� Can’t return a 200/OK -- the browser will cache the Post!
Treating Multiple Window Heartburn
� We need the concept of a workspace� Organizes tasks and what data they are operating on� Prefix or suffix on session attributes� State machine to tell which actions are valid
� This is not easy to implement on your own!
Why are these problems so hard to solve?
� The technologies we use were not designed to handle stateful web applications
� HTTP is a connectionless, stateless protocol� Session IDs/Cookies
� Large numbers of clients arriving/leaving unexpectedly� The browser navigation model aggravates concurrency and
synchronization issues� AJAX techniques make state management harder� Most MVC frameworks don’t address these problems
� The diagnosis – current frameworks lack features to manage conversational state
Where do we need a framework’s help?
� The concept of a conversation.� Scopes conversational state rather than storing state in session
attributes� Provides more transaction-oriented features like freeing
resources when complete
� Managing pageflows� Handling starting new conversations when:
� A conversation doesn’t exist� A new browser window opens
Seam Cures State Management Problems!
� What is it?� Java EE 5 “Meta” framework� Gavin King’s new brainchild� Stitches together new Java EE 5 Specs
� JSR 127 - JSF� Sychronizer Token is baked in� You can specify a redirect on a JSF Navigation Rule
� JSR 220 - EJB 3.0� Makes development much easier
� Seam gives you constructs to properly manage state “out of the box”
� Takes heed of lightweight principles
� Seam exposes a richer context model� Two more contexts added to Servlet API contexts
� Seam Components� Annotated POJO that encapsulates state data� Have a specific lifetime by binding to a context
Seam’s Approach
Paymentfloat amount
Seam Component
Seam Conversation Context
@Name(“payment”)@Scope(CONVERSATION)
context variable “payment”
#{payment.amount}
Seam Components
� Add a few Seam annotations to your POJO� You have a Seam component!
� Access it in JSF� Use it in jBPM� Bind it to a context� PDF/Email generation
� Use EJB3/JPA annotations on your POJO� Or write your own!
� Atomic unit for state management
Let’s take a peek at a Seam component
� ... and jump over to Eclipse
Uniform, POJO Based Component Model
� Container Managed Services� Transaction/security management� Persistence Context management
� Annotated POJOs� Inherently unit testable/injectable� No need for separate domain/presentation components� Annotations!
� Minimize XML configuration� No JSF Managed Beans!� “Configuration by exception”� Clean DI metadata
� Drastically reduces the amount of configuration overhead
Bind Components to Contexts
� @Scope binds your component to a context� Method level annotations control your process
� @Begin starts a process (conversation, process)� @End ends process associated with the current
thread
Seam Contexts
� (Stateless)� Event� Page� Conversation� Session� Business process� Application
Context Search Order
Seam’s Conversation Context
� Melding of three concepts/scenarios:� Implementing the idea of a “workspace” in Struts� “Application Transaction with Optimistic Semantics”� Providing a construct for executing a “workflow task”
� Abstracts the difficulty in managing state� Provides more powerful mechanisms than simple “get/
set”� Integration of JSF and jBPM event handling mechanisms� “Bijection” of components (more in a minute)
Conversations, continued
� Most useful for tasks that span multiple requests� Each request is bound to a temporary conversation
When spanning multiple requests, a conversation is “promoted” to long-running with @BeginEach conversation executes serially as its requests arrive
� Use a SFSB and bind to conversation scope� Conversations may be nested� Discrete life span (will timeout)� Configuration change can store state on the client side
Keeping track of conversations
� You’ll notice a cid request parameter� Seam tacks this on and keeps track of it� Needed to implement workspace functionality � Allows for conversations happening in different tabs/
windows to work in isolation� Helps Seam handle starting, stalling, restarting, nesting
any long-running conversation
Bijection
� Dependency injection works great for stateless components, but Seam focuses on stateful components
� Essentially we need an aliasing mechanism from context variables to instance variables on components
� Wires components together� Dramatically cleans your action code
� No more getAttribute() calls at the beginning� No more setAttribute() calls at the end
Bijection
� Seam’s bijection allows stateful components to be:� Contextual - wider contexts can reach into narrower contexts to
assemble stateful components� Bidirectional
� Context variables can be injected into component instance variables
� You can “outject” your instance variables back into context variables
� Dynamic - occurs on every invocation of a component!
� Just remember two annotations: @In and @Out
Hey! You forgot about Concurrency!
� Conversations run serially per request� Optimistic Locking is pretty trivial to add with Seam
� This isn’t really a Seam feature, it’s a JPA feature
� Add @Version or @Timestamp to a property on your component that needs concurrent access
� If someone changes it “underneath” you (ticks the timestamp or version column in the database) then a OptimisticLockException is thrown.
� Catch and direct to an appropriate “merge” page.� You can add optimistic locking easily to any EJB
managed transaction as well.
Comparisons to other WASM frameworks
� BEA/Beehive Pageflow Controllers� Current state of the pageflow lives in a session attribute� Only one can be active at a time (no multiple browser support!)� Can be nested, but rules are different� Can be “longLived”, but lives the full length of your session
� Spring Pageflow� Only true rival to Seam in terms of conversational state
management� Planned to be a plug-in integration to Struts 2.0/Spring MVC
� Other frameworks assume you know all of this stuff, and how to handle it the right way on your own!
� Seam guides you toward proper usage
Other Features
� We’ve only seen the tip of the iceberg� EL/Annotations are a powerful 1-2 combo!
� JSF Presentation� iText PDF Generation� Email Templates� Log Statements
� jBPM - Business Process� jPDL - Pageflow� AJAX/Remoting Layer� Security� Lots of cool integration work still going on
� Support on major application servers
Extras
� Helpful Links� Seam Wiki Home - http://wiki.jboss.org/wiki/Wiki.jsp?page=JBossSeam� Seam Home - http://www.jboss.com/products/seam� Seam Docs - http://docs.jboss.com/seam/latest/reference/en/html/index.html� Seam Forum - http://jboss.com/index.html?module=bb&op=viewforum&f=231� JPA - http://www.hibernate.org/hib_docs/annotations/reference/en/html/entity.html
� References and Further Reading� Synchronizer Token -
� http://www.javaworld.com/javaworld/javatips/jw-javatip136.html� Redirect After Post -
� http://www.theserverside.com/tt/articles/article.tss?l=RedirectAfterPost� Optimistic Offline Lock -
� http://www.martinfowler.com/eaaCatalog/optimisticOfflineLock.html� Pessimistic Offline Lock -
� http://www.martinfowler.com/eaaCatalog/pessimisticOfflineLock.html