ESPRequest.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. /*##############################################################################
  2. # HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. ############################################################################## */
  16. define([
  17. "dojo/_base/declare",
  18. "dojo/_base/array",
  19. "dojo/_base/lang",
  20. "dojo/_base/config",
  21. "dojo/_base/Deferred",
  22. "dojo/request",
  23. "dojo/request/script",
  24. "dojo/store/util/QueryResults",
  25. "dojo/store/Observable"
  26. ], function (declare, arrayUtil, lang, config, Deferred, request, script, QueryResults, Observable) {
  27. var RequestHelper = declare(null, {
  28. serverIP: null,
  29. constructor: function (args) {
  30. if (args) {
  31. declare.safeMixin(this, args);
  32. }
  33. this.serverIP = this.getParamFromURL("ServerIP");
  34. },
  35. getParamFromURL: function (key) {
  36. var value = "";
  37. if (dojo.doc.location.search) {
  38. var searchStr = dojo.doc.location.search.substr((dojo.doc.location.search.substr(0, 1) == "?" ? 1 : 0));
  39. value = searchStr ? dojo.queryToObject(searchStr)[key] : "";
  40. }
  41. if (value)
  42. return value;
  43. return config[key];
  44. },
  45. getBaseURL: function (service) {
  46. if (service === undefined) {
  47. service = "WsWorkunits";
  48. }
  49. if (this.serverIP)
  50. return "http://" + this.serverIP + ":8010/" + service;
  51. return "/" + service;
  52. },
  53. isCrossSite: function () {
  54. return this.serverIP ? true : false;
  55. },
  56. _send: function(service, action, _params) {
  57. var params = lang.mixin({
  58. load: function (response) {
  59. },
  60. error: function (error) {
  61. },
  62. event: function (evt) {
  63. }
  64. }, _params);
  65. lang.mixin(params.request, {
  66. rawxml_: true
  67. });
  68. var handleAs = params.handleAs ? params.handleAs : "json";
  69. var postfix = "";
  70. if (handleAs === "json") {
  71. postfix = ".json";
  72. }
  73. var method = params.method ? params.method : "get";
  74. var retVal = null;
  75. if (this.isCrossSite()) {
  76. retVal = script.get(this.getBaseURL(service) + "/" + action + postfix, {
  77. query: params.request,
  78. jsonp: "jsonp"
  79. });
  80. } else {
  81. retVal = request.post(this.getBaseURL(service) + "/" + action + postfix, {
  82. data: params.request,
  83. handleAs: handleAs
  84. });
  85. }
  86. return retVal.then(function (response) {
  87. params.load(response);
  88. return response;
  89. },
  90. function (error) {
  91. params.error(error);
  92. return error;
  93. },
  94. function (event) {
  95. params.event(event);
  96. return event;
  97. });
  98. },
  99. send: function (service, action, params) {
  100. if (!params)
  101. params = {};
  102. dojo.publish("hpcc/standbyBackgroundShow");
  103. var handleAs = params.handleAs ? params.handleAs : "json";
  104. return this._send(service, action, params).then(function (response) {
  105. if (!params.suppressExceptionToaster && handleAs == "json") {
  106. var deletedWorkunit = false; // Deleted WU
  107. if (lang.exists("Exceptions.Source", response)) {
  108. dojo.publish("hpcc/brToaster", {
  109. Severity: "Error",
  110. Source: service + "." + action,
  111. Exceptions: response.Exceptions.Exception
  112. });
  113. }
  114. }
  115. dojo.publish("hpcc/standbyBackgroundHide");
  116. return response;
  117. },
  118. function (error) {
  119. var message = "Unknown Error";
  120. if (lang.exists("response.text", error)) {
  121. message = error.response.text;
  122. } else if (error.message && error.stack) {
  123. message = "<h3>" + error.message + "</h3>";
  124. message += "<p>" + error.stack + "</p>";
  125. }
  126. dojo.publish("hpcc/brToaster", {
  127. Severity: "Error",
  128. Source: service + "." + action,
  129. Exceptions: [{ Message: message }]
  130. });
  131. dojo.publish("hpcc/standbyBackgroundHide");
  132. return error;
  133. });
  134. },
  135. // XML to JSON helpers ---
  136. getValue: function (domXml, tagName, knownObjectArrays) {
  137. var retVal = this.getValues(domXml, tagName, knownObjectArrays);
  138. if (retVal.length == 0) {
  139. return null;
  140. } else if (retVal.length != 1) {
  141. alert("Invalid length: " + retVal.length);
  142. }
  143. return retVal[0];
  144. },
  145. getValues: function (domXml, tagName, knownObjectArrays) {
  146. var retVal = [];
  147. var items = domXml.getElementsByTagName(tagName);
  148. var parentNode = items.length ? items[0].parentNode : null; // Prevent <Dataset><row><field><row> scenario
  149. for (var i = 0; i < items.length; ++i) {
  150. if (items[i].parentNode == parentNode)
  151. retVal.push(this.flattenXml(items[i], knownObjectArrays));
  152. }
  153. return retVal;
  154. },
  155. flattenXml: function (domXml, knownObjectArrays) {
  156. var retValArr = [];
  157. var retValStr = "";
  158. var retVal = {};
  159. for (var i = 0; i < domXml.childNodes.length; ++i) {
  160. var childNode = domXml.childNodes[i];
  161. if (childNode.childNodes) {
  162. if (childNode.nodeName && knownObjectArrays != null && dojo.indexOf(knownObjectArrays, childNode.nodeName) >= 0) {
  163. retValArr.push(this.flattenXml(childNode, knownObjectArrays));
  164. } else if (childNode.nodeName == "#text") {
  165. retValStr += childNode.nodeValue;
  166. } else if (childNode.childNodes.length == 0) {
  167. retVal[childNode.nodeName] = null;
  168. } else {
  169. var value = this.flattenXml(childNode, knownObjectArrays);
  170. if (retVal[childNode.nodeName] == null) {
  171. retVal[childNode.nodeName] = value;
  172. } else if (dojo.isArray(retVal[childNode.nodeName])) {
  173. retVal[childNode.nodeName].push(value);
  174. } else if (dojo.isObject(retVal[childNode.nodeName])) {
  175. var tmp = retVal[childNode.nodeName];
  176. retVal[childNode.nodeName] = [];
  177. retVal[childNode.nodeName].push(tmp);
  178. retVal[childNode.nodeName].push(value);
  179. }
  180. }
  181. }
  182. }
  183. if (retValArr.length)
  184. return retValArr;
  185. else if (retValStr.length)
  186. return retValStr;
  187. return retVal;
  188. }
  189. });
  190. _StoreSingletons = [];
  191. return {
  192. getURL: function (_params) {
  193. var requestHelper = new RequestHelper();
  194. var params = lang.mixin({
  195. protocol: location.protocol,
  196. hostname: requestHelper.serverIP ? requestHelper.serverIP : location.hostname,
  197. port: location.port,
  198. pathname: ""
  199. }, _params);
  200. return params.protocol + "//" + params.hostname + ":" + params.port + params.pathname;
  201. },
  202. flattenArray: function (target, arrayName, arrayID) {
  203. if (lang.exists(arrayName + ".length", target)) {
  204. var tmp = {};
  205. for (var i = 0; i < target[arrayName].length; ++i) {
  206. tmp[arrayName + "_i" + i] = target[arrayName][i][arrayID];
  207. }
  208. delete target[arrayName];
  209. return lang.mixin(target, tmp);
  210. }
  211. return target;
  212. },
  213. flattenMap: function (target, arrayName) {
  214. if (lang.exists(arrayName, target)) {
  215. var appData = target[arrayName];
  216. delete target[arrayName];
  217. var singularName = arrayName.substr(0, arrayName.length - 1);
  218. var i = 0;
  219. for (var key in appData) {
  220. target[arrayName + "." + singularName + "." + i + '.Application'] = "ESPRequest.js";
  221. target[arrayName + "." + singularName + "." + i + '.Name'] = key;
  222. target[arrayName + "." + singularName + "." + i + '.Value'] = appData[key];
  223. ++i;
  224. }
  225. target[arrayName + "." + singularName + ".itemcount"] = i;
  226. }
  227. return target;
  228. },
  229. getBaseURL: function (service) {
  230. var helper = new RequestHelper();
  231. return helper.getBaseURL(service);
  232. },
  233. send: function (service, action, params) {
  234. var helper = new RequestHelper();
  235. return helper.send(service, action, params);
  236. },
  237. Store: declare(null, {
  238. SortbyProperty: 'Sortby',
  239. DescendingProperty: 'Descending',
  240. useSingletons: true,
  241. constructor: function (options) {
  242. this.cachedArray = {};
  243. if (!this.service) {
  244. throw new Error("service: Undefined - Missing service name (eg 'WsWorkunts').");
  245. }
  246. if (!this.action) {
  247. throw new Error("action: Undefined - Missing action name (eg 'WUQuery').");
  248. }
  249. if (!this.responseQualifier) {
  250. throw new Error("responseQualifier: Undefined - Missing action name (eg 'Workunits.ECLWorkunit').");
  251. }
  252. if (!this.idProperty) {
  253. throw new Error("idProperty: Undefined - Missing ID field (eg 'Wuid').");
  254. }
  255. if (options) {
  256. declare.safeMixin(this, options);
  257. }
  258. },
  259. getIdentity: function (item) {
  260. return item[this.idProperty];
  261. },
  262. getCachedArray: function (create) {
  263. return this.useSingletons ? lang.getObject(this.service + "." + this.action, create, _StoreSingletons) : this.cachedArray;
  264. },
  265. exists: function (id) {
  266. var cachedArray = this.getCachedArray(false);
  267. if (cachedArray) {
  268. return cachedArray[id] !== undefined;
  269. }
  270. return false;
  271. },
  272. get: function (id, item) {
  273. if (!this.exists(id)) {
  274. var cachedArray = this.getCachedArray(true);
  275. cachedArray[id] = this.create(id, item);
  276. return cachedArray[id];
  277. }
  278. var cachedArray = this.getCachedArray(false);
  279. return cachedArray[id];
  280. },
  281. create: function (id, item) {
  282. var retVal = {
  283. };
  284. retVal[this.idProperty] = id;
  285. return retVal;
  286. },
  287. update: function (id, item) {
  288. lang.mixin(this.get(id), item);
  289. },
  290. _hasResponseContent: function(response) {
  291. return lang.exists(this.responseQualifier, response);
  292. },
  293. _getResponseContent: function(response) {
  294. return lang.getObject(this.responseQualifier, false, response);
  295. },
  296. query: function (query, options) {
  297. var request = query;
  298. if (options !== undefined && options.start !== undefined && options.count !== undefined) {
  299. if (this.startProperty) {
  300. request[this.startProperty] = options.start;
  301. }
  302. if (this.countProperty) {
  303. request[this.countProperty] = options.count;
  304. }
  305. }
  306. if (options !== undefined && options.sort !== undefined && options.sort[0].attribute !== undefined) {
  307. request[this.SortbyProperty] = options.sort[0].attribute;
  308. request[this.DescendingProperty] = options.sort[0].descending ? true : false;
  309. }
  310. if (this.preRequest) {
  311. this.preRequest(request);
  312. }
  313. var helper = new RequestHelper();
  314. var results = helper.send(this.service, this.action, {
  315. request: request
  316. });
  317. var deferredResults = new Deferred();
  318. var context = this;
  319. deferredResults.total = results.then(function (response) {
  320. if (context.responseTotalQualifier) {
  321. return lang.getObject(context.responseTotalQualifier, false, response);
  322. } else if (context._hasResponseContent(response)) {
  323. return context._getResponseContent(response).length;
  324. }
  325. return 0;
  326. });
  327. Deferred.when(results, function (response) {
  328. if (context.preProcessFullResponse) {
  329. context.preProcessFullResponse(response, request, query, options);
  330. }
  331. var items = [];
  332. if (context._hasResponseContent(response)) {
  333. if (context.preProcessResponse) {
  334. var responseQualiferArray = context.responseQualifier.split(".");
  335. context.preProcessResponse(lang.getObject(responseQualiferArray[0], false, response), request, query, options);
  336. }
  337. arrayUtil.forEach(context._getResponseContent(response), function (item, index) {
  338. if (context.preProcessRow) {
  339. context.preProcessRow(item, request, query, options);
  340. }
  341. var storeItem = context.get(context.getIdentity(item), item);
  342. context.update(context.getIdentity(item), item);
  343. items.push(storeItem);
  344. });
  345. }
  346. if (context.postProcessResults) {
  347. context.postProcessResults(items);
  348. }
  349. deferredResults.resolve(items);
  350. return items;
  351. });
  352. return QueryResults(deferredResults);
  353. }
  354. })
  355. };
  356. });