What does flash.discard do? What's the difference from flash.clear()? - java

I haven't found any documentation on flash.discard(). What does it do?

After looking at the code, this is what I understand:
The Flash data is ultimately for storing data between requests.
Since Play is stateless, that state is saved in a session cookie, which is send to the client and send back with the next request.
The data Map is the data that comes from the client via the cookie.
The out Map is the data that the Play app writes to the Flash instance.
If the data changed, the data in the out Map is used to build the content of the cookie to send back to the client.
So from this, I would say, that flash.discard() is used to throw away everything that would go to the client, and flash.clear() is used to throw away everything that came from the client...

That's a good question. While I don't know the answer either, the source code at github should help:
https://github.com/playframework/play/blob/master/framework/src/play/mvc/Scope.java
A quick glance shows the Scope keeps two hashmaps, one named data and other named out.
They both store the same information. But the flash.clear() is acting upon data and flash.discard() is acting upon out... Funny...
Better call both, just in case =)

Related

netty: redirecting requests with serialization inbetween

I'm building a proxy with two endpoints and with a custom protocol in between.
Means, I'll receive the original request on one site, serialize it for the custom protocol, de-serialize it on the other end and send it to a defined target server. Same back with the response.
The thing looks about like this:
This all works wonderful. The thing is, that the custom protocol in the middle has a max size of about 5 MB. Although I need to be able to post files bigger than this.
I now had an idea, which I'm not sure if it is possible and I would be very happy about some advice.
Right now, I'm collecting all the HttpObjects and send the whole request at once over the custom protocol. On the other end, I'm parsing a FullHttpRequest, modify the Host, URI and so one and send it to the target server. Here again, same procedure with the response. This is of course a waste of memory and time.
Now with this I'm not sure:
I could immediately send all the HttpObjects that I receive, over the custom protocol without collecting the whole request first and send it in a whole.
On the other end, I still could manipulate the one HttpRequest object and the just pump all the HttpObjects, one after the other, into the outgoing channel until the HttpLastContent object. Would this work?
I thought I'd rather ask first, before putting too much effort in it just to find out it's a stupid idea.

Combine two http responses into one

Is it possible to send extra data attached to a http response via Java or Php?
My Website is a homework-platform: One User enters homeworks into a database, and all users can then see the homeworks on the website. The current load is very inefficient, as the browser makes two requests for eveything to load: One for the index file and one for the homeworks. For the homeworks request the client also sends settings of the user to the server, based on which the returned homeworks are generated by a Php script.
Now, I wonder, if it is possible, to combine those two requests into one? Is it maybe possible to detect the http request with Java or Php on the server, read the cookies (where the settings are saved), then get the homeworks from the database and send the data attached to the http response to the client? Or, even better, firstly only return the index file and as soon as possible and the homework data afterwards as a second response, because the client needs some time to parse the Html & build the DOM-tree when it can't show the homeworks anyway.
While browsing the web I stumbled across terms like "Server-side rendering" and "SPDY", but I don't know if those are the right starting points.
Any help is highly appreciated, as I'm personally very interested in a solution and it would greatly improve the load time of my website.
A simple solution to your problem is to initialize your data in the index file.
You would create a javascript object, and embed it right into the html, rendered by your server. You could place this object in the global namespace (such as under window.initData), so that it can be accessed by the code in your script.
<scipt>
window.initData = {
someVariable: 23,
}; // you could use json_encode if you use php, or Jackson if you use java
</script>
However, it is not a huge problem if your data is fetched in a separate server request. Especially when it takes more time to retrieve the data from the database/web services, you can provide better user experience by first fetching the static content very quickly and displaying a spinner while the (slower) data is being loaded.

How to parse big data (XML) in GWT

In my GWT application I am retrieving the XML data from a REST server. I am using Piriti XML parser https://code.google.com/p/piriti/wiki/Xml for deserializing the object and display in a table. As long as we are returning upto 1000 records everything is fine but with the big result it just hang and gives user message to stop the java script running in the back. Could someone please help me to find the best way to handle big data in GWT OR more precisely the best approach to parse big XML file in GWT.
Thanks a lot for all your suggestions.
The problem is that parsing a big XML document slows down the browser. And you need enough memory to hold the whole DOM plus your mapped objects in memory. The only solution is to avoid such situation. You have to adapt your REST service to be able to send only small chunks of data to the browser. So if you already have a paged table you only retrieve the data for the first page at the beginning. If the user wants to change the page you do another REST call to retrieve the data for the next page.
If you cannot change the the REST service itself you can create another server side service (on a server controlled by you) as a proxy. At first access you call the original REST service, store the XML at your own server and allow the client to retrieve only parts of that XML.

Do you always REDIRECT after POST? If yes, How do you manage it?

Say, you are submitting a form, which affects your database (adding records/ deleting them/ updating them) and this is how your request looks like:
POST /application/action=update
Now, say, you are done with your update, so you would like to take the user to the home page.
Response.sendRedirect /application/action=home
This works wonderfully well. User is sent a redirect after POST, so even if the user tries to refresh the page by hitting F5, you are good. However, this will not work if you did this:
requestDispatcher.forward(/application/action=home)
Given that there is a scenario where you have to display different kinds of error / success messages after you are done with your update, you are most likely doing a forward after POST. In such a scenario, how do you avoid update actions from happening twice?
I find it rather amusing that many secure sites (banks) / payment gateways tend to inform the user by placing text on screen, such as "Please don't press back / refresh buttons".
Is there no better way to handling this? Other than requesting the user not to press these buttons? When I last checked, there was something called the 'Vertical Response Cache'. A Filter that would identify uniqueness of your request in a session and tries to send a cached response if the request is duplicate. Are there any simpler ways to solving this classic problem?
Here is a link to the vertical response cache solution I was talking about: http://www.fingo.info/en/articles/_1.html. I am, However, not sure as to how well this really works.
Yes, I believe that you should redirect after a POST, with the exception of API requests. Without doing this not only do you have to worry about getting duplicate POSTs when the user uses the back button, but the browser will also give the user annoying dialogs when they try to use the back button.
Response.sendRedirect works in practice, but tecnically speaking this is sending the wrong HTTP response code for this purpose. sendRedirect sends a 302, but the correct code to use to transform a POST into a GET is 303. (most browsers will treat a 302 just like a 303 if they get it in response to a POST, however)
In general you want the redirect to send the user to whatever view will display the effect of their change. For example, if they edit a widget, they should be redirected to the view of that widget. If they delete a widget, they should be redirected to the view that the widget would have appeared in when it existed (perhaps the widget list).
Sometimes it's nice to have a status message to further drive home the fact that an action occurred. A simple way to do this is to have a common parameter to your views that, when set, will display an action completed message. eg:
/widget?id=12345&msg=Widget+modified.
Here the "msg" parameter contains the message "Widget modified". The one downside to this approach is that it may be possible for malicious sites to give your users confusing/misleading messages. eg:
/account?msg=Foo+Corp.+hates+you.
If you're really worried about this you could include an expiring signature for the message as an additional parameter. If the signature is invalid or has expired, simply don't display the message.
The best solution to solve the problem of showing status messages to the users after a POST to GET redirect is to use user sessions.
How
Add attributes to user session with value as set of messages to be displayed. for eg.
userSession.put("success_messages", new HashSet<String>(){"Success", "Check your account balance"});
userSession.put("warning_messages", new HashSet<String>(){"Your account balance is low. Recharge immediately"});
And have a filter which scans the user session for these particular attributes and outputs the messages. The filter should delete the attributes after reading once, as the status messages are generally displayed only once.
One thought that I've had is to embed a unique ID (probably a random string) as a hidden form field in the form that is being POST-submitted. The ID string can be put in the database as a "transaction ID". Now, when you go to update the database, first check whether there's an existing record with the submitted transaction ID, and if so, assume it's a duplicate and don't change the database.
Of course, as I said, this is just a thought. I don't know what methods are actually used in practice. (I suspect that a lot of less-critical sites just ignore the problem and hope their users will be smart... a losing proposition if I ever saw one ;-)
EDIT: as pointed out in the comments, storing transaction IDs in the database might take up a lot of space, but if that's an issue, you could keep an in-memory cache of all transaction IDs processed in the last 5 minutes/1 hour/1 day/whatever. That should work unless you're up against a determined hacker...
I find it rather amusing that many secure sites (banks) / payment gateways tend to inform the user by placing text on screen, such as "Please don't press back / refresh buttons".
some people find its better to "disable all Back, Refresh event on this critical pages";
I'm not sure if this is good or not.
But your addressed solution "vertical response cache" sounds nice
Its a little non-obvious but:
create a keyed-object in the user session.
the value is a Request + java Future for the result
return immediately with a client-side redirect.
while the client-side redirect is being handled, have a worker thread work on producing the answer.
So by the time the client browser completes the redirect, getting the new page's images, etc... the results are waiting for the user.
The alternative is to make the user painfully aware of how long the database is taking.
Security Update (2011 Jan 24 ) :
The key is vulnerable to attack since it is part of the response to the client, so
Generate a random key
Use user's session id as a salt to create a SHA-1
Store both the random key and the SHA-1 in the database with (, ) as the primary key. (no separate indexing on the RANDOMKEY.
Use both RANDOMKEY and the SHA-1 as the db lookup.
Do not store the Session Id (avoid privacy issues with being able to corollate many entries to the same user)
Expire the results after 2-3 days. ( Allows a daily batch job to do the clean up and avoids creating problems for user sessions that are semi-long lasting )
This method requires any hacker to know both the session id and the random key.
This approach may seem overkill, but a redirect-hardened mechanism can be used for situations like password resets.
If you are working with java server side scripting and also using struts 2 then you refer this link which talks about on using token .
http://www.xinotes.org/notes/note/369/
A token should be generated and kept in session for the initial page render, when the request is submitted along with the token for the first time , in struts action run a thread with thread name as the token id and run the logic whatever the client has requested for , when client submit again the same request, check whether the thread is still running(thread.getcurrentthread().interrupted) if still running then send a client redirect 503.
Please look at the ExecuteAndWaitInterceptor of struts 2code, the logic of this combined with token will help out fast click

Multiple questions in Java (Validating URLs, adding applications to startup, etc.)

I have an application to build in Java, and I've got some questions to put.
Is there some way to know if one URL of a webpage is real? The user enters the URL and I have to test if it's real, or not.
How can I konw if one webpage has changes since one date, or what is the date of the last update?
In java how can I put an application running on pc boot, the application must run since the user turns on the computer.
I'm not sure what kind of application you want to build. I'll assume it's a desktop application. In order to check if a URL exists, you should make a HTTP HEAD Request, and parse the results. HEAD can be used to check if the page has been modified. In order for an application to start when the PC boots, you have to add a registry entry under Windows; this process is explained here
To check whether a url is valid you could try using a regular expression (regex for urls).
To know if a webpage has changed you can take a look at the http headers (reading http headers in java).
You can't make the program startup automatically on boot, the user must do that. However, you can write code to help the user set the program as startup app; this however depends on the operating system.
I'm not sure what you mean by "real". If you mean "valid", then you can just construct a java.net.URL from a String and catch the resulting MalformedURLException if it's not valid. If you mean that there's actually something there, you could issue an HTTP HEAD request like Geo says, or you could just retrieve the content. HTTPUnit is particularly handy for retrieving web content.
HTTP headers may indicate when the content has changed, as nan suggested above. If you don't want to count on that you can just retrieve the page and store it, or even better, store a hash of the page content. See DigestOutputStream for generating a hash. On a subsequent check for changes you would simply compare the new hash with the the one you stored last time.
Nan is right about start on boot. What OS are you targeting?

Categories