I build a prototype that handle pages, I successfully add (push), but can get the data, I failed:
var foundImageIndex = Pages.indexFirst(function (item) { if (item.PageID == PageID) return true; });
Here the javascript page handler:
var Pages = new Array();
PageContainer = function () //constructor for the proxy
{
// this._baseURL = url;
};
PageContainer.prototype =
{
AddPage: function (data) {
if (data == null) return;
Pages.push({ PageID: data.PageID, SegmentID: data.SegmentID });
},
GetPage: function (PageID) {
alert('getPage('+PageID+')=' + JSON.stringify(Pages));
var foundImageIndex = Pages.indexFirst(function (item) { if (item.PageID == PageID) return true; });
var dt = { PageID: Pages[foundImageIndex].PageID, SegmentID: Pages[foundImageIndex].SegmentID };
return dt;
}
};
I call from other js as following:
var gPageContainer = new PageContainer();
for (var i = 0; i < SegStruct.SegmentsCount; i++) {
var segRClass = //get from webservice
gPageContainer.AddPage({ PageID: i, SegmentID: segRClass.SegmentID });
}
I trying to call: gPageContainer.GetPage(1); but it failed in GetPage: function (PageID) it returns -1 in:
var foundImageIndex = Pages.indexFirst(function (item) { if (item.PageID == PageID) return true; });
foundImageIndex always -1
why?
Simply add the following before the constructor:
if (typeof Array.prototype.indexFirst == 'undefined') {
Array.prototype.indexFirst = function (validator) {
for (var i = 0; i <= this.length - 1; i++) {
if (validator(this[i])) {
return i;
}
}
return -1;
};
}
Related
i made a module for odoo 12 to lock the pos screen the code works fine in odoo 10, but gives error this.pos is null or this.pos.currency is undefined. in the models.js, i want to switch the orders of different cashiers but this.pos is not initialized, what should i do so that it becomes initialized?
here is my code:
odoo.define('pos_user_lock.models',
//['point_of_sale.models','point_of_sale.screens','point_of_sale.chrome'
//,'web.ajax','web.core'],
function (require) {
"use strict";
var ajax = require('web.ajax');
var screens = require('point_of_sale.screens');
var models = require('point_of_sale.models');
var chrome = require('point_of_sale.chrome');
var core = require('web.core');
var QWeb = core.qweb;
var _t = core._t;
models.Order = models.Order.extend({
initialize: function(attributes,options){
var order = models.Order.__super__.initialize.call(this,attributes,options);
if (!this.cashier)
{
this.cashier = this.pos.cashier || this.pos.user;
}
this.is_last_selected = (this.is_last_selected === undefined) ? false:this.is_last_selected;
return order;
},
finalize: function() {
var res = models.Order.__super__.finalize.call(this);
this.pos.lock_user_screen();
},
init_from_JSON: function(json) {
var user = this.get_user_by_id(json.user_id);
if (user)
this.cashier = user;
this.is_last_selected = json.is_last_selected;
models.Order.__super__.init_from_JSON.call(this, json);
},
export_as_JSON: function() {
var res = models.Order.__super__.export_as_JSON.call(this);
if (this.cashier)
res.user_id = this.cashier.id ;
if(this.pos && this.pos.get_cashier())
res.user_id = this.pos.get_cashier().id ;
res.is_last_selected = this.is_last_selected;
return res;
},
get_user_by_id: function(id) {
var users = this.pos.users;
for (var i = 0; i < users.length; i++) {
var user = users[i];
if (user.id == id)
return user;
}
},
});
models.PosModel = models.PosModel.extend({
initialize: function(session, attributes) {
models.PosModel.__super__.initialize.call(this, session, attributes);
var self = this;
alert(JSON.stringify(attributes.pos));
this.ready.then(function(){
if (self.config.auto_push_order)
self.config.iface_precompute_cash = true;
});
},
is_locked: function(){
if (
this.gui.current_popup
&& this.gui.current_popup.template == 'PasswordPinPopupWidget'
){
return true;
}
return false;
},
unlock: function(){
if (this.is_locked()){
this.gui.close_popup();
}
},
lock_user_screen: function(){
var self = this;
if (!this.config.lock_users) return;
this.gui.show_popup('passwordPin',{
'title': _t('Insert password or scan your barcode'),
});
},
get_last_order: function(){
var orders = this.get_order_list();
for (var i = 0; i < orders.length; i++) {
if (orders[i].is_last_selected) {
return orders[i];
}
}
return null;
},
set_last_order: function(order){
var orders = this.get_order_list();
for (var i = 0; i < orders.length; i++) {
if (orders[i].uid == order.uid) {
orders[i].is_last_selected = true;
}else{
orders[i].is_last_selected = false;
}
}
return null;
},
set_order: function(order){
models.PosModel.__super__.set_order.call(this, order);
this.set_last_order(order);
},
get_order_list: function(){
var orders = models.PosModel.__super__.get_order_list.call(this);
var c_orders = [];
var cashier = this.cashier || this.user;
for (var i = 0; i < orders.length; i++) {
if (cashier && orders[i].cashier.id === cashier.id) {
c_orders.push(orders[i]);
}
}
return c_orders;
},
switch_order: function(){
var self = this;
if(self.pos)
{
}
else
{
alert("self.pos is null");
}
if(self !== undefined && self != null && self.pos !== undefined && self.pos.currency != null)
{
alert("in switch order");
//console.log(this.pos.currency);
if (!self.config.lock_users) return;
var user = self.pos.get_cashier() || self.user;
var orders = self.get_order_list();
var last_order = self.get_last_order() || orders[0];
if (orders.length) {
self.set_order(last_order);
}
else {
self.add_new_order();
}
}
},
set_cashier: function(user){
models.PosModel.__super__.set_cashier.call(this,user);
if(this.pos)
{
alert("this.pos is not null in set_cashier");
}
else
{
alert("this.pos is null in set_cashier");
}
this.switch_order(this);
if (!this.table && this.config.iface_floorplan)
this.set_table(null);
},
});
return models;
});
the web page shows this.pos is null. and this.currency is null.
i found the solution by adding:
this.pos = this;
inside initialize function of PosModel.
I have a function for returning a feed which is retrieved by an AJAX-Call and now want to do something after a few of these asynchron requests have been done.
doit() is the function I call at first.
I am sorry for not providing a url, but it is an internal server.
Here is my code:
function grabFollowedCommunityPageFeed(page, cCallback) {
$.ajax({
url: "blabla.com&page=" + page,
method: "GET",
contentType: "application/atom+xml"
}).always(function(xhr, ignore, thrownMessage) {
var totalResults = 0;
if ((200 === thrownMessage.status) && (xhr)) {
totalResults = parseInt($(xhr).find("totalResults").first().text()) || -1;
}
if (cCallback && $.isFunction(cCallback)) {
cCallback({feed: xhr, resultCount: totalResults});
}
});
}
function grabFollowedCommunitiesFeeds(pagecount) {
var i = 1,
deferredArr = [];
for (i = 1; i < pagecount; i += 1) {
grabFollowedCommunityPageFeed(i, function callback(resultObj) {
deferredArr[i] = new $.Deferred();
deferredArr[i].resolve(resultObj);
});
}
return deferredArr;
}
function doit() {
var allCommunityFeedObjects = [],
allCommunityFeedObjectsCount = 0,
deferredObj = [];
(function initialReadFollowedCommunityFeedPages() {
grabFollowedCommunityPageFeed(1, function(requestObj) {
allCommunityFeedObjectsCount = requestObj.resultCount;
var tEntries = $(requestObj.communityFeed).find("entry"),
el$;
$.each(tEntries, function(ignore, el) {
el$ = $(el);
if (!($.inArray(el$, allCommunityFeedObjects) !== -1)) {
allCommunityFeedObjects.push(el$);
}
});
deferredObj = grabFollowedCommunitiesFeeds(allCommunityFeedObjectsCount) || [];
$.whenAll.apply($, deferredObj).always(function(allCommunityFeeds) {
var k = allCommunityFeeds;
// union k with allCommunityFeedObjects
});
});
})();
}
This line seems to be fine as well and I have checked it:
deferredArr[i].resolve(resultObj);
The problem is that allCommunityFeeds parameter is undefined in
$.whenAll.apply($, deferredObj).always(function(allCommunityFeeds)
and that means there is something wrong. Can you help me?
I'm using ActionHero in node.js and Angular.js.
I am trying images send to ActionHero using $http method.
but I don't know How many images are made.
so I can't define the parameter names on action in ActionHero.
below is my source.
First. images are in object, so I change object to each parameter.
insert: function (param, next) {
var url = settings.apiUrl + "/api/online/productAdd";
var vdata = {
img_objects :param.img_objects
};
angular.forEach(param.img_objects, function (v, k) {
vdata['img_file'+(k)] = v.files;
});
commonSVC.sendUrlFile("POST", url, vdata, function (state, data) {
next(state, data);
});
}
Second. make formData in sendUrlFile like source below. and then send to actionHero.
var promise = $http({
method: method,
url: url,
headers: {
'Content-Type': undefined
},
data: params,
transformRequest: function (data) {
var formData = new FormData();
angular.forEach(data, function (value, key) {
if(angular.isObject(value)){
if(value.lastModified > 0 && value.size > 0){
formData.append(key, value);
}else{
formData.append(key, JSON.stringify(value));
}
}else{
formData.append(key, value);
}
});
return formData;
}
});
Third. ActionHero is received. but parameter isn't defined so ActionHero can't receive.
exports.productAdd = {
name: 'online/productAdd',
inputs: {
I don't know How Many Images are made? 1~10? or 1~100?
},
authenticate: true,
outputExample: {
'result':'success'
}
So I have two Questions:
How can actionhero receive the parameter without inputs defined?
Can I object with Image Data send to ActionHero by Ajax?
Thank You.
I change reduceParams function in actionProcessor.js.
api.actionProcessor.prototype.reduceParams = function(){
var self = this;
var inputNames = [];
if(self.actionTemplate.inputs){
inputNames = Object.keys(self.actionTemplate.inputs);
}
// inputs * 확인 2017-01-20 Eddy
var multi = [];
var strArray;
for(var v in inputNames){
if(inputNames[v].indexOf("*") != -1){
strArray = inputNames[v].split('*');
multi.push(strArray[0]);
}
}
var multiLength = multi.length;
var flag;
if(api.config.general.disableParamScrubbing !== true){
for(var p in self.params){
flag = true;
if(multiLength > 0){
for(var i=0; i<multiLength; i++){
if(p.indexOf(multi[i]) != -1){
flag = false;
}
}
}
if(flag){
if(api.params.globalSafeParams.indexOf(p) < 0 && inputNames.indexOf(p) < 0){
delete self.params[p];
}
}
}
}
};
i can define on inputs like below.
'img_*' : {required: false}
and Then I make middleware
var actionHeroMiddleware = {
name: '-',
global: true,
priority: 1000,
preProcessor: function(data, next) {
api.actionProcessor.prototype.reduceParams = function(){
var self = this;
var inputNames = [];
if(self.actionTemplate.inputs){
inputNames = Object.keys(self.actionTemplate.inputs);
}
// inputs * 확인 2017-01-20 Eddy
var multi = [];
var strArray;
for(var v in inputNames){
if(inputNames[v].indexOf("*") != -1){
strArray = inputNames[v].split('*');
multi.push(strArray[0]);
}
}
var multiLength = multi.length;
var flag;
if(api.config.general.disableParamScrubbing !== true){
for(var p in self.params){
flag = true;
if(multiLength > 0){
for(var i=0; i<multiLength; i++){
if(p.indexOf(multi[i]) != -1){
flag = false;
}
}
}
if(flag){
if(api.params.globalSafeParams.indexOf(p) < 0 && inputNames.indexOf(p) < 0){
delete self.params[p];
}
}
}
}
};
next();
},
stop: function(api, next) {
next();
}
};
api.actions.addMiddleware(actionHeroMiddleware);
next();
Need help with the chaining. The functions work. But async calls make it hard for me to get everything. Help me think right!
My thought:
Get All Webs recursively (function works)
Get all lists from webs and iff announcementlist add to array and pass along
Get two items from all announcmentlists and sort by created.
Add ALL announcement items into one large array (to be able to sort array later.
Heres the code,
function getAllWebs(success, error) {
var ctx = SP.ClientContext.get_current();
var web = ctx.get_site().get_rootWeb();
var result = [];
var level = 0;
result.push(web);
var getAllWebsInner = function (web, result, success, error) {
level++;
var ctx = web.get_context();
var webs = web.get_webs();
ctx.load(webs, 'Include(Title,Webs,ServerRelativeUrl)');
ctx.executeQueryAsync(
function () {
for (var i = 0; i < webs.get_count() ; i++) {
var web = webs.getItemAtIndex(i);
result.push(web);
if (web.get_webs().get_count() > 0) {
getAllWebsInner(web, result, success, error);
}
}
level--;
if (level == 0 && success)
success(result);
},
error);
};
getAllWebsInner(web, result, success, error);
}
function error(sender, args) {
console.log(args.get_message());
};
function getAnnouncementLists(web, success, error) {
var dfd = $.Deferred();
var ctx = web.get_context();
var collList = web.get_lists();
var result = []
ctx.load(collList, 'Include(Title, Id, BaseTemplate)');
ctx.executeQueryAsync(function () {
for (var i = 0; i < collList.get_count() ; i++) {
var list = collList.getItemAtIndex(i);
var bTemp = list.get_baseTemplate();
if (bTemp == 104) {
result.push(list);
}
}
//success(result);
dfd.resolve(result);
}, error);
return dfd.promise();
}
function getListItems(list, success, error) {
var dfd = $.Deferred();
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><OrderBy><FieldRef Name="Created" Ascending="False"></FieldRef>'
+ '</OrderBy></Query><ViewFields><FieldRef Name="Title"/><FieldRef Name="Body"/>' +
'<FieldRef Name="Created"/></ViewFields><RowLimit>2</RowLimit></View>');
var listItems = list.getItems(camlQuery);
var result = []
var ctx = list.get_parentWeb().get_context();
ctx.load(listItems);
ctx.executeQueryAsync(function () {
for (var i = 0; i < listItems.get_count() ; i++) {
var item = listItems.getItemAtIndex(i);
result.push(item);
}
dfd.resolve(result);
//success(result);
}, error);
return dfd.promise();
}
function printResults(items) {
var sortedItems = items.sort(dynamicSort("get_created()"));
alert(sortedItems);
}
function dynamicSort(property) {
var sortOrder = 1;
if (property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a, b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
$(document).ready(function () {
var items = getAllWebs(
function (allwebs) {
var array = [];
for (var i = 0; i < allwebs.length; i++) {
getAnnouncementLists(allwebs[i]).then(function (announceLists) {
for (var i = 0; i < announceLists.length; i++) {
getListItems(announceLists[i]).then(function (items) {
array.push(items);
});
}
});
}
return array;
}
);
//getAllWebs(
// function (allwebs) {
// for (var i = 0; i < allwebs.length; i++) {
// getAnnouncementLists(allwebs[i],
// function (announceLists) {
// for (var i = 0; i < announceLists.length; i++) {
// getListItems(announceLists[i],
// function (items) {
// printResults(items);
// }, error);
// }
// }, error);
// }
// }, error);
});
Given the requirements to retrieve list items from Announcements lists located across site collection, below is demonstrated the modified example that contains some improvements such as:
the number of requests to the server is reduced
fixed the issue in getAllWebs function that prevents to return any results if site contains only a root web
Example
function getAllWebs(propertiesToRetrieve,success, error) {
var ctx = SP.ClientContext.get_current();
var web = ctx.get_site().get_rootWeb();
var result = [];
var level = 0;
ctx.load(web, propertiesToRetrieve);
result.push(web);
var getAllWebsInner = function (web, result, success, error) {
level++;
var ctx = web.get_context();
var webs = web.get_webs();
var includeExpr = 'Include(Webs,' + propertiesToRetrieve.join(',') + ')';
ctx.load(webs, includeExpr);
ctx.executeQueryAsync(
function () {
for (var i = 0; i < webs.get_count() ; i++) {
var web = webs.getItemAtIndex(i);
result.push(web);
if (web.get_webs().get_count() > 0) {
getAllWebsInner(web, result, success, error);
}
}
level--;
if (level == 0 && success)
success(result);
},
error);
};
getAllWebsInner(web, result, success, error);
}
function loadListItems(lists,query,success,error,results){
var results = results || [];
var curList = lists[0];
var ctx = curList.get_context();
var listItems = curList.getItems(query);
ctx.load(listItems);
ctx.executeQueryAsync(function () {
results.push.apply(results, listItems.get_data());
lists.shift();
if(lists.length > 0) {
loadListItems(lists,query,success,error,results);
}
if(lists.length == 0)
success(results);
}, error);
}
function dynamicSort(property) {
var sortOrder = 1;
if (property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a, b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
var propertiesToRetrieve = ['Lists.Include(BaseTemplate)','ServerRelativeUrl'];
getAllWebs(propertiesToRetrieve,
function(allwebs){
//1. get filtered lists
var allAnnouncementLists = [];
allwebs.forEach(function(w){
var announcementLists = w.get_lists().get_data().filter(function(l){
if(l.get_baseTemplate() == SP.ListTemplateType.announcements)
return l;
});
allAnnouncementLists.push.apply(allAnnouncementLists, announcementLists);
});
//2.Load list items from lists
var query = new SP.CamlQuery(); //<-set your custom query here
loadListItems(allAnnouncementLists,query,
function(allListItems){
//3.Sort and print results
var sortedItems = allListItems.sort(dynamicSort("get_created()"));
sortedItems.forEach(function(item){
console.log(item.get_item('Title'));
});
},logError);
},
logError);
function logError(sender,args){
console.log(args.get_message());
}
I would like to send an XML string as POST from javascript to server. The XML has this structure:
<?xml version="1.0" encoding="UTF-8"?>
<Devices>
<Device>
<Id>212121</Id>
<Accuracy>3</Accuracy>
<BatteryVolts>12.34</BatteryVolts>
</Device>
<Device>
<Id>212122</Id>
<Accuracy>5</Accuracy>
<BatteryVolts>12.14</BatteryVolts>
</Device>
</Devices>
In javascript I use:
var dd = '<?xml version="1.0" encoding="UTF-8"?>< ... all xml goes here '
$.ajax({
async: true,
type: "POST",
data: dd,
contentType: "application/x-www-form-urlencoded",
dataType: "xml",
url: 'api/deviceapi',
success: function (data) { var ok= 1; },
error: function (xhr) { var ok = 0; }
});
In the controller:
public int Post(object message)
{//parse message ...
return 1;
}
Once I get the xml into the controller I can parse it, no problem. Please help, thank you!
var defineClass = function () {
var inheritance = function inheritance() { };
return function defineClass(data) {
var classname = data.name,
superclass = data.extend || Object,
constructor = data.construct || function () { },
methods = data.methods || {},
statics = data.statics || {},
borrows,
provides;
if (!data.borrows) {
borrows = [];
}
else {
if (data.borrows instanceof Array) {
borrows = data.borrows;
}
else {
borrows = [data.borrows];
};
};
if (!data.provides) {
provides = [];
}
else {
if (data.provides instanceof Array) {
provides = data.provides;
}
else {
provides = [data.provides];
};
};
inheritance.prototype = superclass.prototype;
var proto = new inheritance();
for (var i = 0; i < borrows.length; i++) {
var c = borrows[i];
for (var p in c.prototype) {
if (typeof c.prototype[p] != "function") continue;
proto[p] = c.prototype[p];
}
}
for (var p in methods) {
proto[p] = methods[p];
};
proto.constructor = constructor;
constructor.superclass = superclass.prototype;
if (classname) {
proto.classname = classname;
};
for (var i = 0; i < provides.length; i++) {
var c = provides[i];
for (var p in c.prototype) {
if (typeof c.prototype[p] != "function") {
continue;
};
if (p == "constructor" || p == "superclass") {
continue;
};
if (p in proto && typeof proto[p] == "function" && proto[p].length == c.prototype[p].length) {
continue;
};
throw new Error("Class " + classname + " are not provided method " + c.classname + "." + p);
};
};
constructor.prototype = proto;
for (var p in statics) {
constructor[p] = statics[p];
};
return constructor;
}
}();
var EndPoint = (function () {
return defineClass({
name: "EndPoint",
construct: function (urlObj) {
var myUrl,
myScheme,
myDefaultScheme = "http",
myLogin,
myPassword,
myHost,
myDefaultHost = "localhost",
myIP,
myDefaultIP = "127.0.0.1",
myPort,
myDefaultPort = "80",
myPath,
myDefaultPath = "/",
myOptions,
myAnchor;
var self = this;
var parse_url = /^(?:([A-Za-z]+):)?(\/{0,3})(?:([A-Za-z]+):([A-Za-z]+)#)?([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;
var result = parse_url.exec(urlObj);
var names = ['url', 'scheme', 'slash', 'login', 'password', 'host', 'port', 'path', 'query', 'hash'];
var i;
for (i = 0; i < names.length; i += 1) {
switch (names[i]) {
case 'url':
myUrl = result[i];
break;
case 'scheme':
myScheme = result[i];
break;
case 'slash':
break;
case 'login':
myLogin = result[i];
break;
case 'password':
myPassword = result[i];
break;
case 'host':
myHost = result[i];
break;
case 'port':
myPort = result[i];
break;
case 'path':
myPath = result[i];
break;
case 'query':
myOptions = result[i];
break;
case 'hash':
myAnchor = result[i];
break;
}
}
this.scheme = myScheme;
this.login = myLogin;
this.password = myPassword;
this.host = myHost;
this.ip = myIP;
this.port = myPort;
this.path = myPath;
this.options = myOptions;
this.anchor = myAnchor;
this.url = myUrl;
},
methods: {
ValidateIP: function (ip) {
return /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ip);
},
ValidateUrl: function (url) {
return /^(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?/.test(url);
},
ValidateShortUrl: function (url) {
if (/^\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?/.test(url)) {
return true;
};
if (/^[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?/.test(url)) {
return true;
}
return false;
}
}
})
}());
var QueryType = function QueryType() {
if (!(this instanceof QueryType)) {
return new QueryType(arguments[0]);
};
this.endPoint = arguments[0]["endPoint"];
this.envelope = arguments[0]["envelope"];
this.type = arguments[0]["type"];
this.headers = arguments[0]["headers"];
this.callback_success = arguments[0]["callback_success"];
this.callback_failure = arguments[0]["callback_failure"];
this.timeout = arguments[0]["timeout"];
this.username = arguments[0]["username"];
this.password = arguments[0]["password"];
};
var TaskManager = function () {
if (!(this instanceof TaskManager)) {
return new TaskManager();
};
var instance;
TaskManager = function () {
return instance;
};
TaskManager.prototype = this;
instance = new TaskManager();
instance.constructor = TaskManager;
function Request() {
if (!(this instanceof Request)) {
return new Request();
};
var instance;
Request = function () {
return instance;
};
Request.prototype = this;
instance = new Request();
instance.constructor = Request;
var httpRequest = new XMLHttpRequest();
instance.send = function (query, callback, errorHandler) {
try { netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); } catch (e) { };
httpRequest.abort();
if ((query.username == undefined) || (query.password == undefined)) {
httpRequest.open(query.type, query.endPoint.url, true);
}
else {
httpRequest.open(query.type, query.endPoint.url, true, query.username, query.password);
};
if (query.headers != null) {
for (var i = 0; i < query.headers.length; ++i) {
httpRequest.setRequestHeader(query.headers[i][0], query.headers[i][1]);
}
}
else {
httpRequest.setRequestHeader("SOAPAction", '""');
httpRequest.setRequestHeader("Content-Type", "text/xml");
};
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
callback(httpRequest.responseText);
}
else {
if (errorHandler) {
errorHandler(httpRequest.status, httpRequest.statusText);
}
else {
callback(null);
};
};
};
};
switch (query.type) {
case "POST":
httpRequest.send(query.envelope);
break;
case "GET":
httpRequest.send(null);
break;
}
};
instance.cancel = function () {
httpRequest.abort();
};
return instance;
};
var httpHandler = Request();
var queryQueue = [];
var timeoutID = -1;
var startedFlag = false;
var currentQuery = null;
var start = function () {
if (queryQueue.length > 0) {
startedFlag = true;
currentQuery = queryQueue.shift();
httpHandler.send(currentQuery,
function (resp) {
if (timeoutID >= 0) {
clearTimeout(timeoutID);
timeoutID = -1;
};
currentQuery.callback_success(resp);
start();
},
function (resp) {
if (timeoutID >= 0) {
clearTimeout(timeoutID);
timeoutID = -1;
};
currentQuery.callback_failure(resp);
start();
}
);
}
else {
startedFlag = false;
};
};
instance.add = function (req) {
if (req instanceof QueryType) {
queryQueue.push(req);
if (!startedFlag) {
start();
};
return true;
}
else {
return false;
};
};
instance.stopCurrent = function () {
httpHandler.cancel();
timeoutID = -1;
if ((currentQuery.callback_failure != undefined) && (currentQuery.callback_failure != null)) {
currentQuery.callback_failure("<comm_error>COMM TIMEOUT</comm_error>");
};
start();
};
return instance;
};
//to send a request it must be
TaskManager().add(
new QueryType({
"endPoint": new EndPoint("http://***.***.***.***/api/deviceapi"),
"type": "POST",
"envelope": '<?xml version="1.0" encoding="UTF-8"?>< ... all xml goes here ',
"callback_success": function (wResponse) { /* here we get a response from the server */ },
"callback_failure": function (status, statusText) { },
"timeout": 60
})
);