django: invoking browser's save as from an ajax invoked view - ajax

In my django app I want to both render a template and invoke the browser's save as. I’ve implemented this using ajax – I have a view that renders a template. In that template is some javascript that invokes another view with ajax. That view returns a response that should trigger the save as. But when returned from the ajax invoked view it does not. If I invoke the same view by cutting and pasting the URL generated by the ajax call into my browser’s address bar the save as is invoked, but when called from ajax it is not. I have verified from the python side using pdb that the view is invoked and the proper response is being returned. I have verified from the browser side that it received the response.
This is the response I return (cut and pasted from the browser's debug window):
HTTP/1.1 200 OK
Date: Tue, 26 Mar 2013 13:07:47 GMT
Server: Apache/2.2.21 (Unix) mod_ssl/2.2.21 OpenSSL/1.0.0f DAV/2 mod_wsgi/3.3 Python/2.6.7
Vary: Cookie
Content-Disposition: Attachment; filename=SF69.xml
Keep-Alive: timeout=5, max=98
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/xml
Any idea why that could be happening? Why would this behave differenly when being returned from ajax vs. 'normal' way?

Related

ruby mechanize: How to retrieve an attachment from a GET

I'm trying to download transactions from a bank account (mine).
Step 1: a form is filled and submitted (POST).
Step 2. subsequent to that, the browser sends a GET
https://accountinfo.corp.xxxxxxx.com.au/AIWeb/ExportAccounts/DownloadExport?OfficeId=201012249&ScheduleId=&FileFormat=CSV-Tran&IsAccountExport=False
The browser receives the file and saves it (default action).
The http response is:
(Status-Line) HTTP/1.1 200 OK
Content-Length 73
Content-Type application/AIUsers
Date Thu, 24 Dec 2015 03:24:22 GMT
p3p CP="NON CUR OTPi OUR NOR UNI"
x-frame-options SAMEORIGIN
x-aspnetmvc-version 1.0
Cache-Control private
Content-Disposition attachment; filename=Accounts_24-12-2015_91456974_T.CSV
I emulate the form submission (with ruby mechanize), wait a few seconds, and agent.get the URL above, as in:
url = "https://accountinfo.corp.westpac.com.au/AIWeb/ExportAccounts/DownloadExport?OfficeId=201012249&ScheduleId=&FileFormat=CSV-Tran&IsAccountExport=False"
download_page = agent.get(url)
The result is incorrect:
<html><body><script>window.parent.location = '/AIWeb/ExportAccounts/ShowErrorMessage?errorCode=3';</script></body></html>
Would appreciate some guidance on how to get the result of the GET.
Regards
There must be something that server expects in headers (and/or) cookies. You can check that using chrome inspector or firebug and add to your request if mechanize supports it (no idea what that is).

Redirect from a Servlet filter, when an AJAX request is made [duplicate]

While trying to redirect user to a URL, it works with GET requests but not with postback requests.
Through firebug's Network window, I can see the redirect response received by browser after the postback request (that should cause redirect) completes. The browser seemingly initiates a GET request for the redirect URL but doesn't actually successfully redirect. It remains there on the same page.
 I use JSF server side. The initiated GET request is not received at all by the server. However initiated by the browser on server's demand. I guess problem is somewhere client side only 
Can anyone please explain how to make redirect work successfully ? Let me know incase I should provide any more information.
Edit:
Request header for redirect:
GET /Px10Application/welcome.xhtml HTTP/1.1
Host: localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 6.2; rv:20.0) Gecko/20100101 Firefox/20.0
Accept: application/xml, text/xml, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Referer: http://localhost:8080/Px10Application/channelPages.xhtml?channelId=-3412&type=Group
X-Requested-With: XMLHttpRequest
Faces-Request: partial/ajax
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Cookie: hb8=wq::db6a8873-f1dc-4dcc-a784-4514ee9ef83b; JSESSIONID=d40337b14ad665f4ec02f102bb41; oam.Flash.RENDERMAP.TOKEN=-1258fu7hp9
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Response header for redirect:
HTTP/1.1 200 OK
X-Powered-By: Servlet/3.0 JSP/2.2 (GlassFish Server Open Source Edition 3.1 Java/Sun Microsystems Inc./1.6)
Server: GlassFish Server Open Source Edition 3.1
Set-Cookie: oam.Flash.RENDERMAP.TOKEN=-1258fu7hp8; Path=/Px10Application
Pragma: no-cache
Cache-Control: no-cache
Expires: -1
Content-Type: text/xml;charset=UTF-8
Content-Length: 262
Date: Wed, 22 May 2013 17:18:56 GMT
X-Requested-With: XMLHttpRequest
Faces-Request: partial/ajax
You're thus attempting to send a redirect on a JSF ajax request using "plain vanilla" Servlet API's HttpServletResponse#sendRedirect(). This is not right. The XMLHttpRequest does not treat a 302 response as a new window.location, but just as a new ajax request. However as you're returning a complete plain vanilla HTML page as ajax response instead of a predefined XML document with instructions which HTML parts to update, the JSF ajax engine has no clues what to do with the response of the redirected ajax request. You end up with a JS error (didn't you see it in the JS console?) and no form of visual feedback if you don't have the jsf.ajax.onError() handler configured.
In order to instruct the JSF ajax engine to change the window.location, you need to return a special XML response. If you have used ExternalContext#redirect() instead, then it would have taken place fully transparently.
externalContext.redirect(redirectURL);
However, if you're not inside JSF context, e.g. in a servlet filter or so, and thus don't have the FacesContext at hands, then you should be manually creating and returning the special XML response.
if ("partial/ajax".equals(request.getHeader("Faces-Request"))) {
response.setContentType("text/xml");
response.getWriter()
.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
.printf("<partial-response><redirect url=\"%s\"></redirect></partial-response>", redirectURL);
} else {
response.sendRedirect(redirectURL);
}
If you happen to use JSF utility library OmniFaces, then you can also use Servlets#facesRedirect() for the job:
Servlets.facesRedirect(request, response, redirectURL);
See also:
Authorization redirect on session expiration does not work on submitting a JSF form, page stays the same
JSF Filter not redirecting After Initial Redirect

Does if-no-match need to be set programmatically in ajax request, if server sends Etag

My question is pretty simple. Although while searching over, I have not found a simple satisfying answer.
I am using Jquery ajax request to get the data from a server. Server
hosts a rest API that sets the Etag and Cach-control headers to the GET requests. The Server also sets CORS headers to allow the Etag.
The client of the Api is a browser web app. I am using Ajax request to call the Api. Here are the response headers from server after a simple GET request:
Status Code: 200 OK
Access-Control-Allow-Origin: *
Cache-Control: no-transform, max-age=86400
Connection: Keep-Alive
Content-Encoding: gzip
Content-Type: application/json
Date: Sun, 30 Aug 2015 13:23:41 GMT
Etag: "-783704964"
Keep-Alive: timeout=15, max=99
Server: Apache-Coyote/1.1
Transfer-Encoding: chunked
Vary: Accept-Encoding
access-control-allow-headers: X-Requested-With, Content-Type, Etag,Authorization
access-control-allow-methods: GET, POST, DELETE, PUT
All I want to know is:
Do I need to manually collect the Etag from response headers sent from the server and attach an if-no-match header to ajax request?OR the Browser sends it by-default in a conditional get request when it has an 'Etag'
I have done debugging over the network console in the browser and It
seems the browser is doing the conditional GET automatically and
sets the if-no-match header.
if it is right, Suppose, I created a new resource, and then I called the get request. It gives me the past cached data for the first time. But when I reload the page, It gives the updated one. So I am confused that, If the dataset on the server-side has changed and it sends a different Etag, Why doesn't the browser get an updated data set from the server unless I have to reload
Also in case of pagination. Suppose I have a URL /users?next=0. next is a query param where the value for the next changes for every new request. Since each response will get its own 'Etag'. Will the browser store the 'Etag' based on request or it just stores the lastest Etag of the previous get request, irrespective of the URL.
Well, I have somehow figured out the solution myself:
The browser sends the if-no-match header itself when it sees url had the e-tag header on a previous request. Browser saves the e-tag with respect to that URL, so it does not matter how many requests with different URLs happen.
Also, a trick to force the browser to fetch a conditional-get to check the e-tag:
Set the max-age header to the lowest (for me 60s works great)
once the cache expires, thebrowser will send a conditional-get to check if the expired cached resource is valid. If the if-no-match header matches with e-tag. The server sends the response back with 304: Not-Modified header. This means the expired cached resource is valid and can be used.

Will ETag work without cache-control header set by web server

My server returns the following headers for a file:
Accept-Ranges:bytes
Connection:Keep-Alive
Content-Length:155
Content-Type:text/css
Date:Thu, 06 Feb 2014 18:32:44 GMT
ETag:"99000000061b06-9b-4f1c118fdd2f1"
Keep-Alive:timeout=5, max=100
Last-Modified:Thu, 06 Feb 2014 18:32:37 GMT
As you can see, it doesn't return cache-control header, however it returns ETag and Last-Modified headers.
My question is whether browser is going to cache the requested file? I can observr that during the following requests the browser sends ETag:"99000000061b06-9b-4f1c118fdd2f1" in headers and server returns status code 304.
And second question: Will browser cache resource and request it with ETag if Cache-control is set to no-cache?
For first part of question - It is up to your browser (its implementation and configuration) if the response will be cached and when will be revalidated. The only (standardized) difference between browser behaviour with validation headers and behaviour without validation headers is that former one can reduce traffic with server using validation.
Second question: Yes. Browser will cache resource but every time you open the page browser will ask origin server if resource was not modified. If not modified server will respond 304 and browser will display cached content. Otherwise server will send new content.
My guess would be ETag can serve as cache-control: no-cache.

What would cause SmartCloud to redirect a REST call to a login page?

I am not using the SBT, but making direct REST calls with Abdera to the current version of Connections on IBM SmartCloud. REST URL in question: https://apps.na.collabserv.com/search/serviceconfigs
Observations
When testing from my laptop (using Firefox and the REST client add-on,) this works as expected. I get back an ATOM feed.
When testing from a server (on a different network,) using the same method (Firefox + REST client,) I get back HTML that is a log-in page.
In addition, I get this same result when I call the URL from a Java program on the same server.
In all cases, I am using the same credentials with basic authentication.
Update: If I log into SmartCloud first, on a separate tab in Firefox on the server, then call the URL as before, from another tab, it works. I get the ATOM feed as desired. Naturally, this is unsuitable as a solution, but I present it as additional information that could lead to an actual solution.
Update: Further testing shows that the local (laptop) log-in exhibits the same behavior as the server. A form-based log-in is required from the same browser, then subsequent REST calls work.
Update: Here is a relevant simplified code snippet:
private static Abdera ABDERA = new Abdera();
private static AbderaClient ABDERA_CLIENT = new AbderaClient(ABDERA);
...
String host = "https://apps.na.collabserv.com";
ABDERA_CLIENT.addCredentials(host, AuthScope.ANY_REALM, "basic", new UsernamePasswordCredentials("user", "password"));
...
ClientResponse response = ABDERA_CLIENT.get("https://apps.na.collabserv.com/search/serviceconfigs");
Summary
It appears that something about the originating server or the call is causing SmartCloud to respond with a log-in page. Whereas, the same call and credentials from my laptop, work as expected.
Question
Where should I start to trouble-shoot this? How can I build the client credentials to allow programmatic log-in?
Response Headers
If it helps, here are the response headers that I get back in each case.
Unsuccessful
Status Code: 200 OK
Cache-Control: no-cache
Connection: keep-alive
Content-Encoding: gzip
Content-Length: 1850
Content-Type: text/html
Date: Tue, 08 Oct 2013 14:15:03 GMT
Pragma: no-cache
Server: WebSEAL/6.1.1.3 (Build 110428)
Set-Cookie: PD-H-SESSION-ID=4_0_IR4***masked***oRKlJI;secure; Path=/; HttpOnly BIGipServerE3A-WebSEAL-80-fe=2132806922.20480.0000;secure; path=/
Vary: Accept-Encoding
p3p: CP="NON CUR OTPi OUR NOR UNI"
Successful
Status Code: 200 OK
Cache-Control: public, max-age=86400, s-maxage=86400, no-cache=set-cookie, private, must-revalidate
Content-Encoding: gzip
Content-Language: en-US
Content-Length: 1164
Content-Type: application/atom+xml; charset=UTF-8
Date: Mon, 07 Oct 2013 17:21:12 GMT
Expires: Tue, 08 Oct 2013 17:21:12 GMT
Server: WebSphere Application Server/8.0
Vary: Accept-Encoding
p3p: CP="NON CUR OTPi OUR NOR UNI"
x-lconn-auth: true
x-powered-by: Servlet/3.0
#Grant is your login using SAML? I could see this redirect happening. also could be TFIM related... maybe you should grab the auth on a different page, store the cookies, and then try connecting to the endpoint above.

Resources