Worklight XSL transformation after getting response - xslt

I am novice to Worklight. I was trying XSL transformation using:
transformation : { type : "xslFile", xslFile : "filtered.xsl",
}
But for some reason if adapter fails to get response(status code != 200). Then it dumps the whole XSL in "errors".
So is it possible to do transformation of the response only if status code == 200?
Thanks in advance.

There are two ways you can solve this issue
1) in the adapter JavaScript you can check the returned status code
function getStoriesFiltered() {
var input = {
method : 'get',
returnedContentType : 'xml',
path : 'rss/edition.rss',
transformation : {
type : 'xslFile',
xslFile : 'filtered.xsl'
}
};
var response = WL.Server.invokeHttp(input);
if (response.statusCode !== 200) {
return {'statusCode' : 'something went wrong'};
}
return response;
}
Or you can check it in the adapter xsl with a <xsl:if> element depending on what is returned from your backend.

Related

SutieScript RESTlet 'Missing a required argument: MapReduceScriptTask.scriptId'

I have a RESTlet that I am working to use to call a Map Reduce Script. However, I am getting the following error:
SSS_MISSING_REQD_ARGUMENT, message:task.submit: Missing a required argument: MapReduceScriptTask.scriptId
Here is the code for this particular Function:
function bulkUpdate( request ) {
// Call Map/Reduce Script
var mapReduceScriptTask = task.create({
taskType: task.TaskType.MAP_REDUCE,
scriptID : 'customscript_transaction_bulk_update',
deploymentId : 'customdeploy_transaction_bulk_update',
params : {
"custscript_requestbody" : request['recList']
}
});
var mapReduceScriptTaskId = mapReduceScriptTask.submit();
var taskStatus = task.checkStatus({
taskID : mapReduceScriptTaskId
});
I tried the numeric id as well as the string, and with no luck.
Any help is appreciated.
scriptID : 'customscript_transaction_bulk_update',
vs
scriptId : 'customscript_transaction_bulk_update',

how to get the error response from MoyaError

similar to this but this time i need to retrieve the JSOn response of the server.
here is my existing code:
return Observable.create{ observer in
let _ = self.provider
.request(.getMerchantDetails(qrId: qrId))
.filterSuccessfulStatusCodes()
.mapJSON()
.subscribe(onNext: { response in
observer.onNext(RQRMerchant(json: JSON(response)))
}, onError: { error in
observer.onError(error)
})
return Disposables.create()
my question is: I can get the error response code 404 by error.localizedDescription But I also want to get the JSON response of the 404 HTTP request.
I've been faced with the same problem, and for me the easiest and cleanest solution was to extend MoyaError to include a property for the decoded error object. In my case I'm using Decodable objects, so you could write something like this for a decodable BackendError representing the error you may get from your server:
extension MoyaError {
public var backendError: BackendError? {
return response.flatMap {
try? $0.map(BackendError.self)
}
}
}
If you instead prefer to directly deal with JSON you can invoke the mapJSONmethod instead of mapping to a Decodable.
Then you just have to do the following to get the error information for non successful status codes:
onError: { error in
let backendError = (error as? MoyaError).backendError
}
Since the response of your server is also contained in a JSON, that means that your onNext emissions can be successful JSON responses or invalid JSON responses.
Check the validity of the response using do operator
You can check for the validity of the response by doing the following:
return Observable.create{ observer in
let _ = self.provider
.request(.getMerchantDetails(qrId: qrId))
.filterSuccessfulStatusCodes()
.mapJSON()
.do(onNext: { response in
let isValidResponse : Bool = false // check if response is valid
if !isValidResponse {
throw CustomError.reason
}
})
.subscribe(onNext: { response in
observer.onNext(RQRMerchant(json: JSON(response)))
}, onError: { error in
observer.onError(error)
})
return Disposables.create()
Use the do operator
Check if the onNext emission is indeed a valid emission
Throw an error if it is invalid, signifying that the observable operation has failed.
Response validation
To keep your response validation code in the right place, you can define a class function within your response class definition that verifies if it is valid or not:
class ResponseOfTypeA {
public class func isValid(response: ResponseOfTypeA) throws {
if errorConditionIsTrue {
throw CustomError.reason
}
}
}
So that you can do the following:
// Your observable sequence
.mapJSON()
.do(onNext: ResponseOfTypeA.isValid)
.subscribe(onNext: { response in
// the rest of your code
})

Cannot call value of non-function type HTTPURLResponse?

I am working with Alamofire 4, in Swift 3.
I am getting an error saying
Cannot call value of non-function type HTTPURLResponse?
I'm trying to download an image and store it in cache, here is my code below, can anyone help?
request = Alamofire.request(post.imageUrl!).validate(contentType: ["image/*"]).response(completionHandler: { request,data, err in
if err == nil {
let image = UIImage(data: data!)!
self.showcaseImage.image = image
FeedVC.imageCache.setObject(image, forKey: self.post.imageUrl!)
}
})
i found that i had to change the top part to just .response. but when i do that I cannot go to if err == nil bloc and set image as data. is there away to fix this. code below.
request = Alamofire.request( post.imageUrl!).validate(contentType: ["application/json"]).response { response in
debugPrint(response)
if error == nil {
let image = UIImage(data: data!)!
all the best
Tony
I looked at the documentation and was able to solve this. By changing the code to.
request = Alamofire.request(post.imageUrl!).validate(contentType: ["image/*"])
.response { response in
print(response.error)
if response.error == nil {
let image = UIImage(data: response.data!)!
I wrote response.error and then response.data, this was the same as calling request, response, data, error that solved my problem of moving on with the error and data.

Need help to use node-soap module

I have to make a server to update some device.
They asked me to use node.js and the device send a soap request.
I need to check the parameters to verify the version. So I decided to use the node-soap module. (The WSDL file I use is a local file)
But I can't find how to recover the value of those parameters.
I read the node-soap spec, but I couldn't find how to do that. :/
Here is my code (I didn't do much yet because I'm stuck because of this) :
var myService = {
ActiaProxyAPI: { //MyService
ActiaProxyAPI: { //MyPort
GetData: function(args) { //MyFunction
if (args.i-uiType == "11") {
var ID = args.i-pcIdentifiant;
var reg=new RegExp("[ $]+", "g"); //parse the string (actually works)
var tableau=ID.split(reg);
console.log(tableau[4] );
}
return {
name: args.o-poData
};
}
}
}
};
var xml = require('fs').readFileSync('./wsdl/ActiaProxyAPI.wsdl', 'utf8'),
server = http.createServer(function(request,response) {
response.end("404: Not Found: "+request.url);
});
server.listen(8080);
soap.listen(server, '/wsdl', myService, xml);
I've found how to retrieve the arguments' value : instead of args.i-uiType I used args["i-uiType"] , and instead of name: args.o-poData :
'tns:GetDataResponse': {'o-poData': result}
Well I hope this can help other people, because it works for me !

Refresh a webpage just once after 5 seconds

I'm looking for a JavaScript solution (or whatever else) that will refresh a webpage ONLY once, after 5 seconds it has been opened. Is this possible without being stuck in a refresh loop?
try this:
setTimeout(function ()
{
if (self.name != '_refreshed_'){
self.name = '_refreshed_';
self.location.reload(true);
} else {
self.name = '';
}
}, 5000);
You could do this in many different ways, but I think the easiest would be to add a query string to the url after the refresh, allowing us to tell if the refresh has already occurred:
//Function to get query string value. Source: http://www.bloggingdeveloper.com/post/JavaScript-QueryString-ParseGet-QueryString-with-Client-Side-JavaScript.aspx
function getQuerystring(key, default_){
if (default_==null) default_="";
key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
var qs = regex.exec(window.location.href);
if(qs == null)
return default_;
else
return qs[1];
}
//check if our query string is already set:
if(getQuerystring(r) !== 1){
setTimeout(function(){window.location.href = window.location.href + '?r=1'},5000)
}
If there is the possibility that a query string is already present, you will have to account for that and change the '?' to an '&'.
Sure, if you don't mind using jquery you can do it via an ajax call after waiting 5 seconds. Just throwing you some sample code:
How to wait 5 seconds with jQuery?
$(document).ready(function() {
// Get data
$.ajax({
url : '/tommyStockExchange/Data',
dataType : 'html',
data : {
'format' : 'H',
'type' : 'E'
},
success : function(data) {
$("#executions").html(data);
},
statusCode : {
404 : function() {
alert('executions url 404 :(');
}
}
});
});
Make it redirect to the same page with a different #hash and in JS only register the redirect if the hash isn't set.
You just need to pass some sort of data between page loads. This can be done in a multitude of ways — use a cookie, a URL query parameter, or something on the server side. Query parameter example:
if (!location.search.match(/(\?|&|^)stopRefreshing(=|&|$)/))
{
setTimeout(function ()
{
var search = location.search;
location.search = search ? search + '&stopRefreshing' : 'stopRefreshing';
}, 5000);
}
Demo: http://jsbin.com/ofawuz/edit