Running a background process - multithreading

I have a requirement where I am planning to run a background process.
Once user logs in into application, I need to have two processes done.
1. authenticate user and go to homepage
2. Get some data and put it in session.
If I do both at same time its going to take 10 minutes to get to homepage. Instead I want second process to run in background while authentication is being processed.
I don't need data from second process in homepage. I need it in some other page which i could access from session.
Can someone put me in right direction?
Thanks

Create a class which extends Thread or implements Runnable and run it. You can learn at the Sun tutorial how to do it. Reference it in a session scoped managed bean so that you can access it from other pages.
That said, it sounds like as if you're hauling some database table entirely into Java's memory which lasts 10 minutes. I strongly recommend to not do so. This is very memory-inefficient and it may blow up whenever multiple users accesses your application concurrently. Add some search/filter/paging logic and just write code accordingly that it queries only the data of interest based on the current request. Google also doesn't query zillions of records to store it in the session and display only 10 of them in the current request. Don't let Java take over the role of the DB and also don't underestimate the powers of the DB. It's very fast when properly modeled and indexed.

Related

How to persist session to share across multiple browser

I have gone through many documents and answer's but my question remains unanswered and therefore I decided to post here.
Scenario:
I am trying to share session on multiple browsers or you could say computers. Now I know this isn't possible as each browser will have its own session. However, I can probably persist the session in a database or memory and share that same session via a URL parameter so that different users can access that particular session.
So far so good, but I actually want to share the page scroll position lets say if on Chrome Page A was scrolled down to PosY-500 then Page A opened on Firefox should also be scrolled down to PosY-500.
Question:
Maybe this could be achievable by the above given session solution, But how can I save such data to session which is changing continuously and also being read on Page A. Sockets? or API calls? service worker? is it even possible?
I would really appreciate if someone can share their insights on it.

Rest API real time Tricky Question- Need Answer

I was recently interviewed by a MNC technical panel and they asked me different questions related to RestAPI , i was able to answer all but below 2 questions though i answered but not sure if those are correct answers. Can somebody answer my queries with real time examples
1) How can i secure my Rest API when somebody send request from Postman.The user provides all the correct information in the header like session id, Token etc.
My answer was: The users token sent in the header of the request should be associated with the successfully authenticated user info then only the user will be granted access if the Request either comes from Postman or application calls these API.(The panel said no to my answer)
2) How can i handle concurrency in Rest API Means if multiple users are trying to access the API at the same given time (For e.g multiple post request are coming to update data in a table) how will you make sure one request is served at one time and accordingly the values are updated as requested by different user request.
2) My answer was: In Entitiy framework we have a class called DbUpdateConcurrencyException, This class takes of handling concurrency and serves one request is served at a time.
I am not sure about my both the above answers and i did not find any specific answer on Googling also.
Your expert help is appreciated.
Thanks
1) It is not possible, requests from Postman or any other client or proxy (Burp, ZAP, etc) are indistinguishable from browser requests, if the user has appropriate credentials (like for example can observe and copy normal requests). It is not possible to authenticate the client application, only the client user.
2) It would be really bad if a web application could only serve one client at a time. Think of large traffic like Facebook. :) In many (maybe most?) stacks, each request gets its own thread (or similar) to run, and that finishes when the request-response ends. These threads are not supposed to directly communicate with each other while running. Data consistency is a requirement of the persistence technology, ie. if you are using a database for example, it must guarantee that database queries are run one after the other. Note that if an application runs multiple queries, database transactions or locks need to be used on the database level to maintain consistency. But this is not at all about client requests, it's about how you use your persistence technology to achieve consistent data. With traditional RDBMS it's mostly easy, with other persistence technologies (like for example using plaintext files for storage) it's much harder, because file operations typically don't support a facility similar to transactions (but they do support locks, which you have to manage manually).

XPages cluster and state variables

We are about to make another server for XPages applications. In front of it there will be fail over/load balance component (Microsoft Forefront, IBM Web server) that will redirect HTTP request to one of two cluster servers.
I suppose that scoped variables will be reinitialized in case of fail over - user is redirected to other server which will initialize XPage from scratch (GET) or subset of data (POST). Anything binded to beans/scoped variables will be lost (pager state, application specific data). This can cause odd behaviour to users: loss of entered data or opening of unexpected page. I am aware of fact, that this is highly depending on application design.
The situation can be very similar to expired session on one server - how to prevent loss of data in such case.
Are there any coding best practices how to avoid side effects of fail over from server to server?
While not a code best code best practise, you first need to configure your load balancer to keep users on the same session once started (probably_ using a cookie, so failover only happens when your box really goes down.
Secondly don't take scope variables to be there, always test for them - which is a good practice anyway since a session can timeout and loose its variables on a single server too.
POST will fail due to a lack of x-session, so you might resort to posting only via Ajax that can have an error handler.
You could consider to use cookies to capture state information.

Session timeout on multiple tabs

I am using Spring acegi security for single sign on on multiple applications. I need to extend session timeout at client side if user writing something on browser too. If user opended multiple sessions or browsers then i need to consider active session on all the sessions he opened. If he is active then i should not log off him eventhough he is inactive in another sessions.
Please suggest me any ideas how to track and know at the client side too.
Any idea is greatly appreaciated. Thank you.
Running application app1 in two tabs say tab1 and tab2.Timeout is 10 minutes. So we implemented timeout functionalit in java script which is at client side. This code gives Confirm box after 10 min. If user says continue, we are extending the session by firing the alive url. This working if application running in a single tab. Same applciation app1 open in multiple tabs say tab1,tab2. Here applicaiton app1 opened in two tabs but single session. We are woking the application which is opened in tab2 and not using applciation in tab1. So application in tab1 is inactive for 10 min.then application in tab1 giving confirm box and we dont answer to that confirm box tab2 will make applciation to log out. So what is the solution for not making logout as we are working application on Tab2. Any ideas? How to track whether application in active in other tabs?
This is not straigt forword answer. (Since I do not think there is a solution for that)
you could try to fire a pixel(*) between the application and by that extends the session time.
lets say that you have:
app1, app2, app3
the user logged in to app1 and app2 and he is working only on app1. if you fire a pixel from his browser to app2 every http request he made on app1, he suppose to be alive on app 2 as well.
I think that if you fire the pixel every 2 minutes between the applications app1,2 and 3 you can save the session alive between the apps.
I have done this twick in PHP application, it wans'nt so easy, but it is doable.
*pixel - it is a hidden http request that runs a script in the serverside. can do it via ajax, img, script src="", iframe and more.
You should be able to store a lastActivity timestamp in localStorage
User activity in any tab updates the lastActivity timestamp
Whenever the timer expires in any tab it should check the lastActivity value before prompting the user. If lastActivity is older than timeout, prompt the user. If not, adjust the remaining time to show prompt
The simplest thing would be to associate the sign-in session with a shared domain. Say you have app1.domain.com, app2.domain.com, app3.domain.com, BUT you have the SSO take place on domain.com, and they all share that session cookie. This is just a matter of setting the domain on the session cookie-- I believe you can do this in the configuration. Anyway, this pretty easy to do, so if this works with your problem, go for it. (Maybe there's some tricky way to do this without that domain hierarchy, but I'm not sure what it is.)
If that isn't workable, you may need a different way to store sessions. My first thought would be to put the sessions in the database. With these, you can synchronize and centrally manage the timeouts. This may require a little bit of custom code-- but it shouldn't be that much.
Not sure this is applicable, but I wrote my thoughts on implementing timeout on the client side as well.
Modified code in javascript to fire ajax request to server and finding the latest activity.
If latest activity is less than 10 mins then there is no logout.

Should Domain Entities always be loaded in their entirety?

I have a custom ASP.NET Membership Provider that I am trying to add password history functionality to. User's passwords expire after X days. Then they have to change their password to one that has not been used in their past X changes.
I already had the User entity, which has a password attribute for their current password. This maps to the User table in the db. Since I needed a list of previous passwords I created a UserPassword table to store this information with a FK reference to the UserId.
Since passwords are value objects, and have no meaning outside of the user, they belong inside the User aggregate, with the User as the root. But here in lies my dilemma. When I retrieve a User from the repository do I always have to get all of their previously used passwords? 99% of the time I don't care about their old passwords, so retrieving them each time I need a User entity seems like a dumb thing to do for db performance. I can't use lazy loading because the User entity is disconnected from the context.
I was thinking of creating a PasswordHistory entity but for the reason stated above, passwords aren't really entities.
How would you DDD experts out there handle this situation?
Thanks.
Edit 1: After considering this some more, I realized this is essentially a question about Lazy Loading. More specifically, how do you handle lazy-loading in a disconnected entity?
Edit 2: I am using LINQ to SQL. The entities are completely detached from the context using this from CodePlex.
It is hard to fully answer this question because you do not specify a platform, so I cannot be exactly sure what you even mean by "disconnected". With Hibernate "disconnected" means you have an object in a valid session but the database connection is not currently open. That is trivial, you simply reconnect and lazy load. The more complicated situation is where you have an object which is "detached" i.e no longer associated with an active session at all and in that case you cannot simply reconnect, you have to either get a new object or attach the one you have to an active session.
Either way, even in the more complicated scenarios, there is still not a whole lot to lazy loading strategies because the requirements are so inflexible: You have to be "connected" to load anything, lazy or otherwise. Period. I will assume "disconnected" means the same thing as detached. Your strategy comes down to two basic scenarios: is this a situation where you probably need to just reconnect/attach on the fly to lazy load, or is it a scenario where you want to make a decision to sometimes conditionally load additional objects before you disconnect in the first place?
Sometimes you may in fact need to code for both possibilities.
In your case you also have to be connected not only to lazy load the old passwords but to update the User object in the first place. Also since this is ASP.NET you might be using session per request, in which case your option is now basically down to only one - conditionally lazy load before your disconnect and that is about it.
The most common scenario would be a person logs in and the system determines they are required to change their password, and asks them to do so before proceeding. In that case you might as well just take care of it immediately after login and keep the User connected. But you are probably using session per request, so what you could do is in the first request process the time limit and if it is expired, you are still connected here so go ahead and return a fully loaded User (assuming you are using the historic passwords in some kind of client side script validation). Then on the submit trip you could reattach or just get a new User instance and update that.
Then there is always the possibility you also have to provide them with the option to change their password at any time. They are already logged in. Does not matter much here, you have a User but the request ended long ago and it does not have passwords loaded. Here, I would probably just write a service method where when they invoke a change password function the service gets a second copy of the User object with the full history for update purposes only, then updates the password, and then discards that object without ever even using it for session or authentication purposes. Or if you are using Session per request you have to do the equivalent - get a fully initialized object for client side validation purposes, then when the data is submitted you can either reattach either one you already have or just get yet a third instance to actually do the update.
If the password is needed after beginning an authenticated session, you could still do the same things and either replace the local User or update the local User's in memory password version as well.
If you have too much stuff going on with multiple levels of authentication most likely you are going to have to require them to logoff and do a full log back in after a password change anyway, so the state of the User does not matter much once they request a password change.
In any case if you are using session per request and your objects become fully detached after every request, in the first scenario you can still lazy load while you are on the server on the original request to return data for client side validation. In the second scenario you have to make another trip (there really is no such thing as lazy loading here). In both case though you have to weigh your two update options because you are always disconnected before an update. You can either just get a second instance from the database on the submit trip to update, or you can reattach the one you already have. It depends on what is optimal/easiest - does saving a db round trip for an uncommon event really matter? Does reattaching using your ORM of choice possibly hit the database again anyway? I would probably not bother to reattach and instead just get a new instance for the actual update as I needed it.

Resources