XMLHttpRequest with Pentaho Data Integration to get the response header - http

i'm working with Pentaho Data Integration and i need a step which gives me a response header of a http request. What i would really need is an implementatione of the HEAD Method of a http call because i have to see the last-modified field of a resorce on internet. I tried using the REST Client step but it doesn't work. So i would like to write a script that makes everything i need.
I actually created a Modified Java Script Value and i put this code inside:
var req = new XMLHttpRequest();
req.open('GET', 'URL', false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
When i run it it doesn't gives me any error but there's anything in "headers".
Any suggestions? I would appreciate a different solution to

If the URL you're requesting is on a different domain then I can tell you that the server is not sending the correct headers to allow cross-domain resource sharing.
Access-Control-Allow-Origin: *
Without the server sending that header the only way to access any of the response (including headers) is if your script is running on the same domain (and protocol) or if you setup a proxy on your own server to get the data from the remote server.
If I open up the JS console on this page and run:
var req = new XMLHttpRequest();
req.open('GET', 'http://dati.toscana.it/it/storage/f/2012-07-26T160139/intoscana-arte-e-cultura.csv', false);
req.send(null);
console.log(req.getAllResponseHeaders());
I get the following output:
XMLHttpRequest cannot load http://dati.toscana.it/it/storage/f/2012-07-26T160139/intoscana-arte-e-cultura.csv. Origin http://stackoverflow.com is not allowed by Access-Control-Allow-Origin.
NetworkError: A network error occurred.

But if i put an alert in the end:
var req = new XMLHttpRequest();
req.open('GET', 'http://dati.toscana.it/it/storage/f/2012-07-26T160139/intoscana-arte-e-cultura.csv', false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);
it gives me the response.
It gives me this too:
Error: Failure
req.send(null);
I'm using Firebug.

I had a similar problem. In my case was to detect a redirection, something that could happens in services that uses third part storage (like Amazon S3). First time I tried with XMLHttpRequest but apparently that is not implemented in the JavaScript available in Kettle, just in browsers. To workaround this, I follow the instructions from http://type-exit.org/adventures-with-open-source-bi/2010/06/using-java-in-pentaho-kettle/ to reference another Java Class, mentioned in http://www.mkyong.com/java/how-to-get-http-response-header-in-java/, inside a Modified Javascript Value Step. The limitation is that you need to do a primary request to get the header, it is not a "just one request" solution.
//Get the location of a link that has a 301 permanent redirection
var pathurl=documentourl; //URL to lookup. It must be a valid address, otherwise will give error
var location; //final location in case of redirect
//fake import of the Java Classes
var HTTPRequest=javax.servlet.http.HttpServletRequest;
var url=java.net.URL;
//open a url connection
var conn= new url(pathurl).openConnection();
//if you yant to watch all the headers uncomment the following lines
//var headerobj= conn.getHeaderFields();
var status=conn.getResponseCode(); //get status code
if (status == 301){ //ie: permanent redirection
location=conn.getHeaderField("Location");
}
else{
//return the same url
location=pathurl;
}
I hope it helps to anyone with this problem!

Related

Getting storage item without CORS configured

I fetched an item from my Firebase storage bucket via this technique (generally):
const url = await firebase.storage().ref('my/ref').getDownloadURL();
const filename = 'filename.ext';
const a = document.getElementById('link');
a.href = url;
a.download = filename;
a.click();
I did it the above way prior to trying the example from the docs:
storageRef.child('images/stars.jpg').getDownloadURL().then(function(url) {
// `url` is the download URL for 'images/stars.jpg'
// This can be downloaded directly:
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(event) {
var blob = xhr.response;
};
xhr.open('GET', url);
xhr.send();
});
When trying it this way, I hit the CORS error. After adding the CORS config to my bucket, it then worked as expected. However, I cannot determine why I was able to successfully fetch it via the first technique prior to configuring CORS.
I tested it again by removing the GET method from my CORS config and uploading the config file again via gsutil. I was still able to successfully obtain the file via the first technique described above.
If this is possible to do without configuring CORS, how can I prevent it to restrict access? Odds are no one will be able to figure out the required ref to build the link, anyways, because the actual ref has multiple unique IDs that will be all but impossible to figure out. This is mainly a question out of curiosity.
I cannot determine why I was able to successfully fetch it via the first technique prior to configuring CORS.
Because same-origin policy doesn't apply when the Javascript can't access the data. In your first example, the JS tweaks the document and the document accesses the data. In the second example, the JS accesses the cross-origin data, and the absence of CORS prevents such access.
If this is possible to do without configuring CORS, how can I prevent it to restrict access?
CORS isn't designed to restrict access. (Wait, what?) CORS is designed to permit access that would otherwise be assumed to be something the user would not want -- for scripts on one page to have access to data from another origin, including, potentially, handing over use of the user's credentials to scripts on the current page when accessing the foreign site. CORS allows site B to tell the browser that it expects to be contacted by scripts from site A, and therefore such access should not be unexpected or assumed unauthorized. It has no impact on requests that don't fall under the same origin policy.
The solution -- and I apologize if I am stating the patently obvious -- is that getDownloadUrl() should not be able to fetch a usable URL for the object, if the object should not in fact be accessible. You can't trust code running on the browser, so whatever credentials are in play here should not be able to be used in this way, if the object is not intended to be accessible... otherwise you have a misconfiguration that is allowing access that should not be allowed.

Connecting to a Website with Google Apps Script

I've been trying to use GAS's URLFetchApp to connect to an external website. However, the website redirects me to a "select country" page with a HTTP 302 error no matter what web address I use.
var options = {
'muteHttpExceptions':true
};
var response = UrlFetchApp.fetch("http://www.idtdna.com/site/account", options);
Logger.log(response.getAllHeaders());
Logger.log(response.getContentText());
var cookie = response.getAllHeaders()['Set-Cookie']+', CN=US&DateSet=7/28/2015 5:48:55 PM; Path=/; Domain=www.idtdna.com';
Logger.log(cookie);
var header = {'Cookie':cookie};
var o2 = {
'headers':header,
'muteHttpExceptions':true
};
var r2 = UrlFetchApp.fetch("https://www.idtdna.com/country.aspx", o2);
Logger.log(r2.getAllHeaders());
Logger.log(r2.getContentText());
Here is my code. I've been trying to send the cookie but either I've formatted it wrong or am sending it incorrectly because I keep getting redirected regardless.
After setting the muteHttpExceptions option to 'true' and further investigating the website you mentioned, I think it all happens because of the cookies for the website.
So when we first access the website, there is no valid cookie. SO it creates a session and sets the cookie. THis might store the session details with the country as well.
You can try setting the cookie while fetching the url by passing the cookie values in the request header. Check this page for details on how to send the cookie through header.
Hope that helps!

Http request in sencha touch 2

I am very new to sencha touch 2.
I want to make a http request. basically I want to connect to google (http://www.google.com) and then check the http response if it's ok or not.
I have checked this code but I always get failure...
Ext.Ajax.request({
url : 'http://www.google.com',
success : function(response, options) {
Ext.Msg.alert("Success");
},
failure : function(response, options) {
Ext.Msg.alert("Failure" + response.responseText + " "
+ options.responseText);
}
});
Later on, I want to use this functionality to implement log-in for the application.
I appreciate your help in advance.
You can switch on Chrome with params --disable-web-security. Next you have to possibility to make Ajax request ( without cross domain policy). On device you use web container not the browser to make a request.
whene I try your code it's give me success alert.
but in console I get this error
XMLHttpRequest cannot load http://www.google.com/?_dc=1330926850434. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
This error is because of that google sever not allowed ajax request from domin localhost.
If you want to send requset on this url you have to use Jsonp .
There is a Cross Domain policy which restricts user to fetch data by AJAX requests directly. So, from javascript if you want to do that, you have to use a ScriptTagProxy here.
If you are going to make a login mechanism and the data resides in same server (localhost for your case), you will not get any issue because you will be making the AJAX request from "localhost" to "localhost" ie, to same domain and then there will be no issue like this.
Otherwise, if you really want it to be cross domain, you can just write a server side code (I am showing in php - you should use cURL) to connect and get data - which doesn't require JSONP.
Filename: action.php
<?php
print file_get_contents(http://www.google.com);
?>
File name: Your js file
Ext.Ajax.request({
url : 'action.php',
success : function(response, options) {
console.log(response);
Ext.Msg.alert("Success");
},
failure : function(response, options) {
Ext.Msg.alert("Failure" + response.responseText + " "
+ options.responseText);
}
});

URLRequestDefaults.setLoginCredentialsForHost not setting the user & pwd in authorization header

I want to access html files which are protected by basic authentication.
I am trying to load this html page using htmlloader and sending the request by urlRequest.
I am using URLRequestDefaults class to set the credentials but when I see the request being send in the fiddler I don't see any authorization header being set by this.
Am I doing something wrong here. My code is below.
URLRequestDefaults.authenticate = false;
URLRequestDefaults.setLoginCredentialsForHost("www.xyz.com", "madhur", "sharma");
var req:URLRequest = new URLRequest("http://bazinga.xyz.com/MyHtml/index.html");
htmlControl.htmlLoader.load(urlRequest);
You should read the API more carefully:
Note that "example.com", "www.example.com", and "sales.example.com" are each considered unique hosts.
In this case, the domains don't match.

Detecting a redirect in Flash/Actionscript?

I have a flash video player which requests a flv file from a central server. That server might redirect the request to a server from the user's country if possible, a lot like a CDN.
This video player also reports usage stats. One thing I'd like to report is the true server/location from which the player is streaming the video from. So basically, if it gets redirected I want to know about it.
It seems that you can't extract the url from a URLLoader, you can only keep a copy of the URLRequest that you constructed it with.
I notice that you can listen for HTTP status events, which would include a 302 or similar. But unfortunately, the HTTPStatusEvent object doesn't show the redirected location.
Any ideas about how to monitor for a redirect, and get the redirected location?
I'm a bit surprised Flash allows you to redirect a video request at all. I did a bit of digging and it looks like you can get the info:
Handling Crossdomain.xml and 302 Redirects Using NetStream
His post specifically talks about the trouble of security issues that arise because of the fact some operations fail if data is from an untrusted server. Since he doesn't know where his video is coming from (302 redirect) the Flash Player doesn't trust it and prevents some operations on the loaded content.
How he gets the server the content was actually loaded from is to do an operation on the file that should not be allowed and he parses the domain information from the error message:
try
{
var bit:BitmapData = new BitmapData(progressiveVideoPlayer.measuredWidth, progressiveVideoPlayer.measuredHeight, false, 0x000000);
bit.draw(progressiveVideoPlayer);
}
catch(error:SecurityError)
{
var list:Array = error.toString().split(" ");
var swfURL:String = list[7] as String;
var domain:String = list[10] as String;
domain = domain.substring(0, domain.length - 1);
var domainList:Array = domain.split("/");
var protocol:String = domainList[0] as String;
var address:String = domainList[2];
var policyFileURL:String = protocol + "//" + address + "/crossdomain.xml";
Security.loadPolicyFile(policyFileURL);
}
Notice he is doing it so that he can load the policy file (to allow the security restricted operations on the file). I'm not sure it will be helpful to you but at least read the article and have a think about it. You may contact the blog author directly too - he is pretty active in the general Flash community.

Resources