Session management for big application (Java) - java

My Question is a bit subjective and may be out of context,so please excuse me for that.
I am working on an application where we need to use Session in various places say
Store user preferences in Session.
Store some attributes in Session.
User profile.
Storing Cart in Session.
and many other things, more over we need to provide a clean way to let other use use the Session.
I know how to inject session or use it and how it works etc, so that is not an issue with me.
I am wondering about a way to create a Service say (SessionService) and let all API's use this to Work with HTTP Session.
Have any one worked/developed such Implementation, if Yes please share how best this can be done and any reference will really be helpful.
Edit
We are using Spring Security for Authentication and Authorization

I firmly believe that the session should, wherever possible, remain as decoupled from the business logic of your system as is humanly possible.
By all means, when operating at a view layer, provide utilities to access the session but remember the following;
The session object itself is not thread safe;
Any attribute can be changed at any time
Any attribute can be modified by any piece of code
Testing anything involving the session is painful
If you are concerned with business logic then consider the following approaches;
Implement a service tier
Handles business logic immutable objects
Transforms could be handled by custom adapters or Spring convertors
Gives separation of concern between view and business logic
Better testability (if that's a word)
Manage temporary state in an in-memory object database rather than the session
Supports distributed replication so HA can be achieved
Supports transactional behaviour to allow consistency
Easily testable
Looks cool on your CV
I hope this helps. If not maybe a bit more information on your goals would help.

Related

Java Session Implementation

I am developing a multiplayer online game. I have the following issue:
When the user breaks his/her connection with the server, he needs to reconnect. At the first connection, during registration, the registration module produces a special ResponseDispatcher which holds the reference to the connection Channel. But if the user logs out, this Channel becomes invalid. Even though I can detect the problem and clean up resources, I have to store the reference to the registration module and Connection module to the game module, in order to renew the Channel when the user authorises and reconnects again. This creates a lot of interdependencies among modules and it gets really hard to maintain.
What I need is something like an HttpSession in Servlet Container, so that I can get the references to my channel and session resources from all modules of my server.
How is HttpSession implemented in Servlet? Is it a global hashmap storing all JSESSIONID, from which the container determines which attribute map to return? If it is a global sysmbol table, will it hit the performance (even though the time is O(1) for hashMap, there might be session modifications so it probably has to be synchronized)?
PS. Maybe some recommendations of design patterns for this case would also do.
I would recommend trying Shiro
Shiro can handle Session Management outside of a servlet container.
You may want to back Shiro with EhCache to provide proper caching and, if required, session persistence (and load balancing, etc...)
Have a look at the Facade Pattern
I'm not exactly sure what the question is. Why do you "have to store the reference to the registration module and connection module"?
Anyway there are two immediately sensible solutions to your problem.
1) Make the Registration module and Connection module Singletons. Whether this is useful depends entirely on what functionality these modules provide.
2) Make the Registration module and Connection module Persistent Entities, save them to a DataStore, complete with necessary references, and retrieve and rebuild them on reconnect.
I'm not quite sure why rolling your own session implementation would be something you want to do, what happens when the session times out?
Your design seems somewhat flawed. The player should not "still be online" if his connection goes down (this is a contradiction in terms, you cannot by definition be online if you are not connected to a network), regardless of whether this was intentional or not (you cannot know whether it is intentional or not), you have no idea whether the player is able to reconnect within a timely fashion or not, so you should assume the worst. More importantly, from a purely design aspect, getting killed by the game, because your internet connection is rubbish, is probably not something you want to deal with. If persisting data is such a costly affair you should reexamine your datastore options. Also, what happens in the scenario where the server crashes while he's offline?

More than one order request at the same time in online shopping

I have a question.
Currently, I'm in the project of online shopping and we will deliver the products via email.
For the scenario where there will be more than one order request from different customer at the same time, may I know how can we handle for that?
I don't have any knowledge on that and still don't have an idea.
Please kindly help me.
Thanks & Regards
If you use a Java EE application server, you don't have to care about multiple threads, or you are even not allowed to control them (at least before Java EE 7).
I would propose to read some basic manuals on how to use CDI. CDI beans are managed components living in a defined scope. With the help of them you can define your business logic on handling one request and the container will care about handling and separating multiple of them.
Alternatively, you can use (stateless) EJBs which would provide you an automatic transaction handling. In both cases, you won't have to care about creating and maintaining instances of the request handlers yourself.

spring mvc dao and service bean mapping

I am new to Spring and hibernate.
I am trying to learn the best practices and design methodoligies in j2ee apps.
I have a managed to create a basic spring mvc web app. now lookin for that
- how should i map my service beans to dao beans or should just use dao beans only.
- Is there any need to make DAO classes singleton
- If i use same dao bean for the jsp, then e.g. onSubmit if I have to enter data on multiple tables (dao beans) then how would I do that.
1 service bean to more than 1 dao beans??
and any refrence material on designing good web app using spring hibernate would appreciated ;)
thanks
You must use service bean. service logic should be there only.
DAO should only for DB related operation.
Now you can inject multiple DAO in your service bean.
FWIW - I just went through a similar learning process on Spring. The good news is, there are a lot of examples out on google; the bad news is, there are not a lot of "complete" examples that are good for rookies (also if you are going to target v3 Spring, there is a lot of pre-v3 stuff out there that can be confusing based on the new baseline). What worked for me was the following: started with the sample applications on the SpringSource site (http://www.springsource.org/documentation). Between their handful of examples, there are just about all the pieces you will need, at least in minimal form. When I found something in those examples that I needed, I googled based on similar terms (some of the # annotations etc) to find more complete information/better examples on that given topic. Many of those searches led me back to this site, which is why I started frequenting here - lots of good questions already answered. I guess this isn't an overly insightful answer, but this process got me up and working through the basics in a fairly quick amount of time.
DAO layer and service layer are different entities:
DAO is responsible for getting and putting single objects from\to DB. For example, get User(id, name, lastname) from DB.
Service layer is responsible for your business logic. It can use several DAO objects for making one action. For example, send message from one user to another and save it in sent folder of first user and in inbox of recipient.
A service is about presenting a facade to the user that exposes business functions that the user can take. Basically, if you have a set of low-level use cases, the methods on the service would line up with individual user actions. Services are transactional, generally if the user does something we want all the consequences of that action to be committed together. The separation between controller and service means we have one place to put webapp-specific functionality, like getting request parameters, doing validation, and choosing where to forward or redirect to, and a separate place to put the business logic, stuff that doesn't depend on webapp apis and is about what objects get updated with what values and get persisted using which data access objects.
I see a lot of cases where people seem to think they need one service for each dao. I think their assumption is that because Data Access Objects and Controllers and Models are fairly mechanical about how they're defined, services must be the same way, and they construct them with no regard for the use cases that are being implemented. What happens is, in addition to having a lot of useless service boilerplate code, all the business logic ends up in the controller jumbled up with the web-specific code, and the controllers become big and unmanageable. If your application is very simple you can get by with this for a while, but it is disorganized, it's hard to test, and it's generally a bad idea. Separation of concerns, keeping infrastructure code in one place and business code in another, is what we should be aiming for, and using services properly is very helpful in getting there.

What is the purpose of Managers / Transactions?

I'm building a spring application for the first time. I'm running into lots of problems with concurrency, and I suspect that there is something wrong with the way I'm managing the backend. The only difference I can see between my backend code and examples I've seen are manager classes.
In my code, I have my model (managed by hibernate) and my DAOs on top of that to do CRUD/searching/etc on the models. In example code I have looked at, they never use the DAO directly. Instead, they use manager classes that call the DAOs indirectly. To me, this just seems like pointless code duplication.
What are these manager classes for? I've read that they wrap my code in "transactions," but why would I want that?
Transactions are used to make updates "transactional".
Example) A user clicks a webpage that leads to 13 records being updated in the database. A transaction would ensure either 0 or 13 of the updates go through, an error would make it all roll back.
Managers have to do with making things easier to do. They will not magically make your code threadsafe. Using a DAO directly is not a thread safety bug in and of itself.
However, I suggest you limit the logic in your DAO, and put as much logic as you can in the business layers. See Best practice for DAO pattern?
If you post maybe a small example of your code that isn't working well with multiple threads, we can suggest some ideas... but neither transactions nor managers alone will fix your problem.
Many applications have non trivial requirements and the business logic often involves access to several resources (e.g. several DAOs), coordination of these accesses and control of transaction across these accesses (if you access DAO1 and DAO2, you want to commit or rollback the changes as an indivisible unit of work).
It is thus typical to encapsulate and hide this complexity in dedicated services components exposing business behavior in a coarse-grained manner to the clients.
And this is precisely what the managers you are referring to are doing, they constitute the Service Layer.
A Service Layer defines an application's boundary [Cockburn PloP] and its set of available operations from the perspective of interfacing client layers. It encapsulates the application's business logic, controlling transactions and coordinating responses in the implementation of its operations.
DAOs should not own transactions, because they have no way of knowing whether or not they're only a part of a larger transaction.
The service tier is where transactions belong. You're incorrect to say they're a "pointless code duplication."

Stateless EJBs: Finding the balance between performance and security

I have a JSF web client and a Java client that both use the same stateless EJB layer for their application logic. I'm unsure of how to balance the need for performance (limiting the amount of data that is transported between the presentation and application layers) with security (in the sense of ensuring all decisions are made based on up to date data).
I understand that this is a subjective topic, so perhaps I can make it more objective with concrete examples:
Do I only send the username to the EJBs, and then load the User entity on each and every EJB call, or do I send the User entity from the presentation layers?
If I need more information than just the User entity (let's say I need to load an additional entity on each EJB call), do I send the username and the other entity's key and load both the entities in the application layer, or do I send both entites from the presentation layers?
What about if I need even more information for certain EJB calls (>= 3 entities)?
When does it make sense to send the actual entity instead of just its key, or is the answer never, always reload on the application layer side? Should I be worried about performance? I've heard that Hibernate (which I'm using) employs intelligent caching meaning the User entity probably won't be reloaded from the DB every time? What if my EJB methods have a very small granularity and frontend actions might sometimes cause 3 or more EJB methods to be called, with each needing to load the User entity?
A final related question: I intend on using the JAAS principal to store the username which is loaded by the EJBs. What if my Remote facade EJBs call a bunch of Local stateless EJBs that also require the user information, do I still use the JAAS principal and load the User entity in each of them as well or is there a better way?
You should consider stateful EJBs, since it sounds like the clients need non-trivial state to answer a series of requests concerning the same state from one user. That said, stateful EJBs are kind of a bear to write and configure properly.
As a matter of design, I would not have the clients send user information to the business logic layer. One, it just punts the problem over to the client, no? to load, store and send this info? also it makes me nervous from a security perspective, to let a presumably less-secure client tier feed sensitive user data to a more-secure backend-tier which then trusts and uses that info.
But, really, I think you mentioned the best approach already: Hibernate's lazy loading. You just interact with the object and let it load data on demand. To work well with Hibernate in this regard, the User object should be small, so that loading it is fairly quick, and push all the big, heavy info into child objects or other entities. Then it doesn't matter if you have to load User a lot; it's just a bit of a 'pointer' to other info.
I don't think it changes things if you use JAAS, no. Although I might say, for what I imagine your purposes are, JAAS may or may not be worthwhile. In the time it takes you to integrate, write permissions, use those permissions, deal with consequences of the SecurityManager, etc. you probably could have just written a simple permissions framework for yourself anyhow.
if you make just one EJB, make stateless session. personally i found it humbug empty interfaces

Categories

Resources