How to convert an deprecated SoapService call to the new UrlFetchApp - google-apps-script

I found an example on how to call a webservice with Google drive scripts here: https://developers.google.com/apps-script/articles/soap_geoip_example
function determineCountryFromIP(ipAddress) {
var wsdl = SoapService.wsdl("http://www.webservicex.net/geoipservice.asmx?wsdl");
var geoService = wsdl.getGeoIPService();
var param = Xml.element("GetGeoIP", [
Xml.attribute("xmlns", "http://www.webservicex.net/"),
Xml.element("IPAddress", [
ipAddress
])
]);
var result = geoService.GetGeoIP(param);
return result.Envelope.Body.GetGeoIPResponse.GetGeoIPResult.CountryCode.Text;
}
However this uses the SoapService which is deprecated. the documentation says I should use UrlFetchApp
Converting the input xml is easy. But can anyone tell me how to call a webservice with the UrlFetchApp?

It turns out to be a lot more work, but after a day of googling and trying i got it to work with the UrlFetchApp
function UrlFetchAppDetermineCountryFromIP_(ipAddress) {
var xml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+"<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">"
+"<SOAP-ENV:Body>"
+"<GetGeoIP xmlns=\"http://www.webservicex.net/\">"
+"<IPAddress>"+ ipAddress +"</IPAddress>"
+"</GetGeoIP>"
+"</SOAP-ENV:Body>"
+"</SOAP-ENV:Envelope>"
var options =
{
"method" : "post",
"contentType" : "text/xml",
"payload" : xml
};
var result = UrlFetchApp.fetch("http://www.webservicex.net/geoipservice.asmx?wsdl", options);
var xmlResult = XmlService.parse(result).getRootElement();
var soapNamespace = xmlResult.getNamespace("soap");
var getGeoIPResponse = xmlResult.getChild("Body", soapNamespace).getChildren()[0];
var getGeoIPResponseNamespace = getGeoIPResponse.getNamespace();
return getGeoIPResponse
.getChild("GetGeoIPResult", getGeoIPResponseNamespace)
.getChild("CountryCode", getGeoIPResponseNamespace)
.getText();
}
It should probely be posable to build the payload xml with the XmlService, however i tryed that for a few hours and was unable to put the 4 xmlns attributes on the Evnelope element, wich caused the webservice request to fail

Related

can't access nested JSON

When I try to display the object using console log, I am getting undefined. The line of code is:
var inform = data.Payload;
// If access allowed, set redirect location
console.log(inform.token_use);
The data is a JSON object with the following values:
{
"StatusCode": 200,
"Payload": "{\"sub\":\"1234567-1234-1234-1234-123456778\",\"token_use\":\"access\",\"scope\":\"aws.cognito.signin.user.admin\",\"iss\":\"https://cognito-idp.us-east-1.amazonaws.com/us-east-1_99999999999\",\"exp\":1468310126,\"client_id\":\"xxxxxxxxxxxxx\",\"username\":\"usernam\"}"
}
I wanted to check the value of token_use.
var inform = JSON.parse(data.Payload);
You need to parson payload since its stringify
'1234567-1234-1234-1234-123456778','token_use' => 'access');
$json_data= json_encode($data);
?>
var data= '';
var res = JSON.parse(data);
var inform = res.Payload;
console.log(inform.token_use);

Adobe AIR file upload response data in complete handler is null while fiddler(web debugger) shows that json is returned as response

When uploading a file from adobe AIR to a backbone server, the response returned is not anyway accessible when using file.upload(request) function, while i can see json response in fiddler(web debugger and in task manager), also it was working fine when using URLLoader.load() instead of file.upload()
var url = "api url of backbone server ";
request = null;
file = null;
request = new air.URLRequest(url);
request.useCache = false;
var authorization = new air.URLRequestHeader("Authorization", "Bearer "+accessToken);
var contentType = new air.URLRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
var Accept = new air.URLRequestHeader("Accept", "application/json;charset=UTF-8");
request.requestHeaders.push(authorization);
request.requestHeaders.push(contentType);
request.requestHeaders.push(Accept);
file = new air.File(path);
pathNative = file.nativePath;
var directory = getDirectoryFromPath(pathNative);
params = new air.URLVariables();
params.parent_id = directory.directory_id;
params.name = file.name;
request.data = params;
request.method = air.URLRequestMethod.POST;
request.contentType = 'multipart/form-data, boundary='+boundary;
var file = new air.File(path);
file.upload(request);
file.addEventListener(air.Event.COMPLETE, function(e){
air.Introspector.Console.log(file);
air.Introspector.Console.log(e);
air.Introspector.Console.log(e.target.data);
});
This is the console for complete event as you can see returned data is null.
see console
while in fiddler shows that json is returned.
see fiddler
Seems like it's a known issue on iOS? Are you trying to do this from iOS?
https://forums.adobe.com/thread/1720117?start=0&tstart=0
I ran into the same problem. Instead of using air.Event.COMPLETE, try to use air.DataEvent.UPLOAD_COMPLETE_DATA:
file.addEventListener(air.DataEvent.UPLOAD_COMPLETE_DATA, function(e){
air.Introspector.Console.log(e.data);
});

Creating a zip file from a JSON object using adm-zip

I'm trying to create a .zip file from a JSON object in Node.js. I'm using adm-zip to do that however I'm unable to make it work with this code:
var admZip = require('adm-zip');
var zip = new admZip();
zip.addFile(Date.now() + '.json', new Buffer(JSON.stringify(jsonObject));
var willSendthis = zip.toBuffer();
fs.writeFileSync('./example.zip', willSendthis);
This code creates example.zip but I'm not able to extract it, I tried with a .zipextractor but also with this code:
var admZip = require('adm-zip');
var zip = new admZip("./example.zip");
var zipEntries = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function(zipEntry) {
console.log(zipEntry.data.toString('utf8'));
});
It returns Cannot read property 'toString' of undefined at the line with console.log.
I could use zip.writeZip() for this example but I'm sending the .zipfile to Amazon S3 thus I need to use the method .toBuffer() to do something like this after using adm-zip:
var params = {Key: 'example.zip', Body: zip.toBuffer()};
s3bucket.upload(params, function(err, data) {...});
I don't see what is wrong, am I using the package correctly?
Try use zipEntry.getData().toString('utf8') instead zipEntry.data.toString('utf8'):
var admZip = require('adm-zip');
var zip = new admZip("./example.zip");
var zipEntries = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function(zipEntry) {
console.log(zipEntry.getData().toString('utf8'));
});

How to create an object of specific type from JSON in Parse

I have a Cloud Code script that pulls some JSON from a service. That JSON includes an array of objects. I want to save those to Parse, but using a specific Parse class. How can I do it?
Here's my code.
Parse.Cloud.httpRequest({
url: 'http://myservicehost.com',
headers: {
'Authorization': 'XXX'
},
success: function(httpResponse) {
console.log("Success!");
var json = JSON.parse(httpResponse.text);
var recipes = json.results;
for(int i=0; i<recipes.length; i++) {
var Recipe = Parse.Object.extend("Recipe");
var recipeFromJSON = recipes[i];
// how do i save recipeFromJSON into Recipe without setting all the fields one by one?
}
}
});
I think I got it working. You need to set the className property in the JSON data object to your class name. (Found it in the source code) But I did only try this on the client side though.
for(int i=0; i<recipes.length; i++) {
var recipeFromJSON = recipes[i];
recipeFromJSON.className = "Recipe";
var recipeParseObject = Parse.Object.fromJSON(recipeFromJSON);
// do stuff with recipeParseObject
}
Example from this page https://parse.com/docs/js/guide
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
gameScore.save({
score: 1337,
playerName: "Sean Plott",
cheatMode: false
}, {
success: function(gameScore) {
// The object was saved successfully.
},
error: function(gameScore, error) {
// The save failed.
// error is a Parse.Error with an error code and message.
}
});
IHMO this question is not a duplicate of How to use Parse.Object fromJSON? [duplicate]
In this question the JSON has not been generated by the Parse.Object.toJSON function itself, but comes from another service.
const object = new Parse.Object('MyClass')
const asJson = object.toJSON();
// asJson.className = 'MyClass';
Parse.Object.fromJSON(asJson);
// Without L3 this results into:
// Error: Cannot create an object without a className
// It makes no sense (to me) why the Parse.Object.toJSON is not reversible

how to get value JSON in google API

I have google API, it return a JSON file
http://maps.googleapis.com/maps/api/geocode/json?latlng=10.75,106.667&sensor=false
I want to get "long_name" : "Hồ Chí Minh", "long_name" : "Việt Nam" and "short_name" : "VN"
I don't know JSON, I do like this
var API = 'http://maps.googleapis.com/maps/api/geocode/json?latlng=10.75,106.667&sensor=false';
var obj = eval("(" + API + ")");
var obj2 = eval("(" + obj + ")");
document.getElementById("City").innerHTML = obj.results[0].obj2.address_components[0].long_name;
But it not working
I think you should read a little more about javascript. You must use a http get request to obtain the json, there is 2 ways to make this, using synchronous request or ajax request.
Try this :
//the json url
var API = 'http://maps.googleapis.com/maps/api/geocode/json?atlng=10.75,106.667&sensor=false';
//this function add the long_name
function addLongName(data){
var long_name = data.results[0].address_components[5].long_name;
document.getElementById("City").appendChild(document.createTextNode(long_name));
}
Using synchronous request
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", API, false);
try {
xmlHttp.send(null);
responseText = xmlHttp.responseText;
var data = JSON.parse(responseText);
addLongName(data);
} catch (ex) {
console.error(ex);
}
Using ajax request
var ajax = $.ajax({
type : "GET",
url : API,
dataType: 'jsonp',
success: function(data) {
addLongName(data);
}
});