PageRenderTime 52ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/hippo/src/main/webapp/yui/datasource/datasource.js

http://hdbc.googlecode.com/
JavaScript | 1983 lines | 1148 code | 131 blank | 704 comment | 188 complexity | e15c2d16753b7e4339e210a3d6696a1d MD5 | raw file
  1. /*
  2. Copyright (c) 2009, Yahoo! Inc. All rights reserved.
  3. Code licensed under the BSD License:
  4. http://developer.yahoo.net/yui/license.txt
  5. version: 2.7.0
  6. */
  7. (function () {
  8. var lang = YAHOO.lang,
  9. util = YAHOO.util,
  10. Ev = util.Event;
  11. /**
  12. * The DataSource utility provides a common configurable interface for widgets to
  13. * access a variety of data, from JavaScript arrays to online database servers.
  14. *
  15. * @module datasource
  16. * @requires yahoo, event
  17. * @optional json, get, connection
  18. * @title DataSource Utility
  19. */
  20. /****************************************************************************/
  21. /****************************************************************************/
  22. /****************************************************************************/
  23. /**
  24. * Base class for the YUI DataSource utility.
  25. *
  26. * @namespace YAHOO.util
  27. * @class YAHOO.util.DataSourceBase
  28. * @constructor
  29. * @param oLiveData {HTMLElement} Pointer to live data.
  30. * @param oConfigs {object} (optional) Object literal of configuration values.
  31. */
  32. util.DataSourceBase = function(oLiveData, oConfigs) {
  33. if(oLiveData === null || oLiveData === undefined) {
  34. return;
  35. }
  36. this.liveData = oLiveData;
  37. this._oQueue = {interval:null, conn:null, requests:[]};
  38. this.responseSchema = {};
  39. // Set any config params passed in to override defaults
  40. if(oConfigs && (oConfigs.constructor == Object)) {
  41. for(var sConfig in oConfigs) {
  42. if(sConfig) {
  43. this[sConfig] = oConfigs[sConfig];
  44. }
  45. }
  46. }
  47. // Validate and initialize public configs
  48. var maxCacheEntries = this.maxCacheEntries;
  49. if(!lang.isNumber(maxCacheEntries) || (maxCacheEntries < 0)) {
  50. maxCacheEntries = 0;
  51. }
  52. // Initialize interval tracker
  53. this._aIntervals = [];
  54. /////////////////////////////////////////////////////////////////////////////
  55. //
  56. // Custom Events
  57. //
  58. /////////////////////////////////////////////////////////////////////////////
  59. /**
  60. * Fired when a request is made to the local cache.
  61. *
  62. * @event cacheRequestEvent
  63. * @param oArgs.request {Object} The request object.
  64. * @param oArgs.callback {Object} The callback object.
  65. * @param oArgs.caller {Object} (deprecated) Use callback.scope.
  66. */
  67. this.createEvent("cacheRequestEvent");
  68. /**
  69. * Fired when data is retrieved from the local cache.
  70. *
  71. * @event cacheResponseEvent
  72. * @param oArgs.request {Object} The request object.
  73. * @param oArgs.response {Object} The response object.
  74. * @param oArgs.callback {Object} The callback object.
  75. * @param oArgs.caller {Object} (deprecated) Use callback.scope.
  76. */
  77. this.createEvent("cacheResponseEvent");
  78. /**
  79. * Fired when a request is sent to the live data source.
  80. *
  81. * @event requestEvent
  82. * @param oArgs.request {Object} The request object.
  83. * @param oArgs.callback {Object} The callback object.
  84. * @param oArgs.tId {Number} Transaction ID.
  85. * @param oArgs.caller {Object} (deprecated) Use callback.scope.
  86. */
  87. this.createEvent("requestEvent");
  88. /**
  89. * Fired when live data source sends response.
  90. *
  91. * @event responseEvent
  92. * @param oArgs.request {Object} The request object.
  93. * @param oArgs.response {Object} The raw response object.
  94. * @param oArgs.callback {Object} The callback object.
  95. * @param oArgs.tId {Number} Transaction ID.
  96. * @param oArgs.caller {Object} (deprecated) Use callback.scope.
  97. */
  98. this.createEvent("responseEvent");
  99. /**
  100. * Fired when response is parsed.
  101. *
  102. * @event responseParseEvent
  103. * @param oArgs.request {Object} The request object.
  104. * @param oArgs.response {Object} The parsed response object.
  105. * @param oArgs.callback {Object} The callback object.
  106. * @param oArgs.caller {Object} (deprecated) Use callback.scope.
  107. */
  108. this.createEvent("responseParseEvent");
  109. /**
  110. * Fired when response is cached.
  111. *
  112. * @event responseCacheEvent
  113. * @param oArgs.request {Object} The request object.
  114. * @param oArgs.response {Object} The parsed response object.
  115. * @param oArgs.callback {Object} The callback object.
  116. * @param oArgs.caller {Object} (deprecated) Use callback.scope.
  117. */
  118. this.createEvent("responseCacheEvent");
  119. /**
  120. * Fired when an error is encountered with the live data source.
  121. *
  122. * @event dataErrorEvent
  123. * @param oArgs.request {Object} The request object.
  124. * @param oArgs.callback {Object} The callback object.
  125. * @param oArgs.caller {Object} (deprecated) Use callback.scope.
  126. * @param oArgs.message {String} The error message.
  127. */
  128. this.createEvent("dataErrorEvent");
  129. /**
  130. * Fired when the local cache is flushed.
  131. *
  132. * @event cacheFlushEvent
  133. */
  134. this.createEvent("cacheFlushEvent");
  135. var DS = util.DataSourceBase;
  136. this._sName = "DataSource instance" + DS._nIndex;
  137. DS._nIndex++;
  138. };
  139. var DS = util.DataSourceBase;
  140. lang.augmentObject(DS, {
  141. /////////////////////////////////////////////////////////////////////////////
  142. //
  143. // DataSourceBase public constants
  144. //
  145. /////////////////////////////////////////////////////////////////////////////
  146. /**
  147. * Type is unknown.
  148. *
  149. * @property TYPE_UNKNOWN
  150. * @type Number
  151. * @final
  152. * @default -1
  153. */
  154. TYPE_UNKNOWN : -1,
  155. /**
  156. * Type is a JavaScript Array.
  157. *
  158. * @property TYPE_JSARRAY
  159. * @type Number
  160. * @final
  161. * @default 0
  162. */
  163. TYPE_JSARRAY : 0,
  164. /**
  165. * Type is a JavaScript Function.
  166. *
  167. * @property TYPE_JSFUNCTION
  168. * @type Number
  169. * @final
  170. * @default 1
  171. */
  172. TYPE_JSFUNCTION : 1,
  173. /**
  174. * Type is hosted on a server via an XHR connection.
  175. *
  176. * @property TYPE_XHR
  177. * @type Number
  178. * @final
  179. * @default 2
  180. */
  181. TYPE_XHR : 2,
  182. /**
  183. * Type is JSON.
  184. *
  185. * @property TYPE_JSON
  186. * @type Number
  187. * @final
  188. * @default 3
  189. */
  190. TYPE_JSON : 3,
  191. /**
  192. * Type is XML.
  193. *
  194. * @property TYPE_XML
  195. * @type Number
  196. * @final
  197. * @default 4
  198. */
  199. TYPE_XML : 4,
  200. /**
  201. * Type is plain text.
  202. *
  203. * @property TYPE_TEXT
  204. * @type Number
  205. * @final
  206. * @default 5
  207. */
  208. TYPE_TEXT : 5,
  209. /**
  210. * Type is an HTML TABLE element. Data is parsed out of TR elements from all TBODY elements.
  211. *
  212. * @property TYPE_HTMLTABLE
  213. * @type Number
  214. * @final
  215. * @default 6
  216. */
  217. TYPE_HTMLTABLE : 6,
  218. /**
  219. * Type is hosted on a server via a dynamic script node.
  220. *
  221. * @property TYPE_SCRIPTNODE
  222. * @type Number
  223. * @final
  224. * @default 7
  225. */
  226. TYPE_SCRIPTNODE : 7,
  227. /**
  228. * Type is local.
  229. *
  230. * @property TYPE_LOCAL
  231. * @type Number
  232. * @final
  233. * @default 8
  234. */
  235. TYPE_LOCAL : 8,
  236. /**
  237. * Error message for invalid dataresponses.
  238. *
  239. * @property ERROR_DATAINVALID
  240. * @type String
  241. * @final
  242. * @default "Invalid data"
  243. */
  244. ERROR_DATAINVALID : "Invalid data",
  245. /**
  246. * Error message for null data responses.
  247. *
  248. * @property ERROR_DATANULL
  249. * @type String
  250. * @final
  251. * @default "Null data"
  252. */
  253. ERROR_DATANULL : "Null data",
  254. /////////////////////////////////////////////////////////////////////////////
  255. //
  256. // DataSourceBase private static properties
  257. //
  258. /////////////////////////////////////////////////////////////////////////////
  259. /**
  260. * Internal class variable to index multiple DataSource instances.
  261. *
  262. * @property DataSourceBase._nIndex
  263. * @type Number
  264. * @private
  265. * @static
  266. */
  267. _nIndex : 0,
  268. /**
  269. * Internal class variable to assign unique transaction IDs.
  270. *
  271. * @property DataSourceBase._nTransactionId
  272. * @type Number
  273. * @private
  274. * @static
  275. */
  276. _nTransactionId : 0,
  277. /////////////////////////////////////////////////////////////////////////////
  278. //
  279. // DataSourceBase public static methods
  280. //
  281. /////////////////////////////////////////////////////////////////////////////
  282. /**
  283. * Executes a configured callback. For object literal callbacks, the third
  284. * param determines whether to execute the success handler or failure handler.
  285. *
  286. * @method issueCallback
  287. * @param callback {Function|Object} the callback to execute
  288. * @param params {Array} params to be passed to the callback method
  289. * @param error {Boolean} whether an error occurred
  290. * @param scope {Object} the scope from which to execute the callback
  291. * (deprecated - use an object literal callback)
  292. * @static
  293. */
  294. issueCallback : function (callback,params,error,scope) {
  295. if (lang.isFunction(callback)) {
  296. callback.apply(scope, params);
  297. } else if (lang.isObject(callback)) {
  298. scope = callback.scope || scope || window;
  299. var callbackFunc = callback.success;
  300. if (error) {
  301. callbackFunc = callback.failure;
  302. }
  303. if (callbackFunc) {
  304. callbackFunc.apply(scope, params.concat([callback.argument]));
  305. }
  306. }
  307. },
  308. /**
  309. * Converts data to type String.
  310. *
  311. * @method DataSourceBase.parseString
  312. * @param oData {String | Number | Boolean | Date | Array | Object} Data to parse.
  313. * The special values null and undefined will return null.
  314. * @return {String} A string, or null.
  315. * @static
  316. */
  317. parseString : function(oData) {
  318. // Special case null and undefined
  319. if(!lang.isValue(oData)) {
  320. return null;
  321. }
  322. //Convert to string
  323. var string = oData + "";
  324. // Validate
  325. if(lang.isString(string)) {
  326. return string;
  327. }
  328. else {
  329. return null;
  330. }
  331. },
  332. /**
  333. * Converts data to type Number.
  334. *
  335. * @method DataSourceBase.parseNumber
  336. * @param oData {String | Number | Boolean} Data to convert. Note, the following
  337. * values return as null: null, undefined, NaN, "".
  338. * @return {Number} A number, or null.
  339. * @static
  340. */
  341. parseNumber : function(oData) {
  342. if(!lang.isValue(oData) || (oData === "")) {
  343. return null;
  344. }
  345. //Convert to number
  346. var number = oData * 1;
  347. // Validate
  348. if(lang.isNumber(number)) {
  349. return number;
  350. }
  351. else {
  352. return null;
  353. }
  354. },
  355. // Backward compatibility
  356. convertNumber : function(oData) {
  357. return DS.parseNumber(oData);
  358. },
  359. /**
  360. * Converts data to type Date.
  361. *
  362. * @method DataSourceBase.parseDate
  363. * @param oData {Date | String | Number} Data to convert.
  364. * @return {Date} A Date instance.
  365. * @static
  366. */
  367. parseDate : function(oData) {
  368. var date = null;
  369. //Convert to date
  370. if(!(oData instanceof Date)) {
  371. date = new Date(oData);
  372. }
  373. else {
  374. return oData;
  375. }
  376. // Validate
  377. if(date instanceof Date) {
  378. return date;
  379. }
  380. else {
  381. return null;
  382. }
  383. },
  384. // Backward compatibility
  385. convertDate : function(oData) {
  386. return DS.parseDate(oData);
  387. }
  388. });
  389. // Done in separate step so referenced functions are defined.
  390. /**
  391. * Data parsing functions.
  392. * @property DataSource.Parser
  393. * @type Object
  394. * @static
  395. */
  396. DS.Parser = {
  397. string : DS.parseString,
  398. number : DS.parseNumber,
  399. date : DS.parseDate
  400. };
  401. // Prototype properties and methods
  402. DS.prototype = {
  403. /////////////////////////////////////////////////////////////////////////////
  404. //
  405. // DataSourceBase private properties
  406. //
  407. /////////////////////////////////////////////////////////////////////////////
  408. /**
  409. * Name of DataSource instance.
  410. *
  411. * @property _sName
  412. * @type String
  413. * @private
  414. */
  415. _sName : null,
  416. /**
  417. * Local cache of data result object literals indexed chronologically.
  418. *
  419. * @property _aCache
  420. * @type Object[]
  421. * @private
  422. */
  423. _aCache : null,
  424. /**
  425. * Local queue of request connections, enabled if queue needs to be managed.
  426. *
  427. * @property _oQueue
  428. * @type Object
  429. * @private
  430. */
  431. _oQueue : null,
  432. /**
  433. * Array of polling interval IDs that have been enabled, needed to clear all intervals.
  434. *
  435. * @property _aIntervals
  436. * @type Array
  437. * @private
  438. */
  439. _aIntervals : null,
  440. /////////////////////////////////////////////////////////////////////////////
  441. //
  442. // DataSourceBase public properties
  443. //
  444. /////////////////////////////////////////////////////////////////////////////
  445. /**
  446. * Max size of the local cache. Set to 0 to turn off caching. Caching is
  447. * useful to reduce the number of server connections. Recommended only for data
  448. * sources that return comprehensive results for queries or when stale data is
  449. * not an issue.
  450. *
  451. * @property maxCacheEntries
  452. * @type Number
  453. * @default 0
  454. */
  455. maxCacheEntries : 0,
  456. /**
  457. * Pointer to live database.
  458. *
  459. * @property liveData
  460. * @type Object
  461. */
  462. liveData : null,
  463. /**
  464. * Where the live data is held:
  465. *
  466. * <dl>
  467. * <dt>TYPE_UNKNOWN</dt>
  468. * <dt>TYPE_LOCAL</dt>
  469. * <dt>TYPE_XHR</dt>
  470. * <dt>TYPE_SCRIPTNODE</dt>
  471. * <dt>TYPE_JSFUNCTION</dt>
  472. * </dl>
  473. *
  474. * @property dataType
  475. * @type Number
  476. * @default YAHOO.util.DataSourceBase.TYPE_UNKNOWN
  477. *
  478. */
  479. dataType : DS.TYPE_UNKNOWN,
  480. /**
  481. * Format of response:
  482. *
  483. * <dl>
  484. * <dt>TYPE_UNKNOWN</dt>
  485. * <dt>TYPE_JSARRAY</dt>
  486. * <dt>TYPE_JSON</dt>
  487. * <dt>TYPE_XML</dt>
  488. * <dt>TYPE_TEXT</dt>
  489. * <dt>TYPE_HTMLTABLE</dt>
  490. * </dl>
  491. *
  492. * @property responseType
  493. * @type Number
  494. * @default YAHOO.util.DataSourceBase.TYPE_UNKNOWN
  495. */
  496. responseType : DS.TYPE_UNKNOWN,
  497. /**
  498. * Response schema object literal takes a combination of the following properties:
  499. *
  500. * <dl>
  501. * <dt>resultsList</dt> <dd>Pointer to array of tabular data</dd>
  502. * <dt>resultNode</dt> <dd>Pointer to node name of row data (XML data only)</dd>
  503. * <dt>recordDelim</dt> <dd>Record delimiter (text data only)</dd>
  504. * <dt>fieldDelim</dt> <dd>Field delimiter (text data only)</dd>
  505. * <dt>fields</dt> <dd>Array of field names (aka keys), or array of object literals
  506. * such as: {key:"fieldname",parser:YAHOO.util.DataSourceBase.parseDate}</dd>
  507. * <dt>metaFields</dt> <dd>Object literal of keys to include in the oParsedResponse.meta collection</dd>
  508. * <dt>metaNode</dt> <dd>Name of the node under which to search for meta information in XML response data</dd>
  509. * </dl>
  510. *
  511. * @property responseSchema
  512. * @type Object
  513. */
  514. responseSchema : null,
  515. /**
  516. * Additional arguments passed to the JSON parse routine. The JSON string
  517. * is the assumed first argument (where applicable). This property is not
  518. * set by default, but the parse methods will use it if present.
  519. *
  520. * @property parseJSONArgs
  521. * @type {MIXED|Array} If an Array, contents are used as individual arguments.
  522. * Otherwise, value is used as an additional argument.
  523. */
  524. // property intentionally undefined
  525. /////////////////////////////////////////////////////////////////////////////
  526. //
  527. // DataSourceBase public methods
  528. //
  529. /////////////////////////////////////////////////////////////////////////////
  530. /**
  531. * Public accessor to the unique name of the DataSource instance.
  532. *
  533. * @method toString
  534. * @return {String} Unique name of the DataSource instance.
  535. */
  536. toString : function() {
  537. return this._sName;
  538. },
  539. /**
  540. * Overridable method passes request to cache and returns cached response if any,
  541. * refreshing the hit in the cache as the newest item. Returns null if there is
  542. * no cache hit.
  543. *
  544. * @method getCachedResponse
  545. * @param oRequest {Object} Request object.
  546. * @param oCallback {Object} Callback object.
  547. * @param oCaller {Object} (deprecated) Use callback object.
  548. * @return {Object} Cached response object or null.
  549. */
  550. getCachedResponse : function(oRequest, oCallback, oCaller) {
  551. var aCache = this._aCache;
  552. // If cache is enabled...
  553. if(this.maxCacheEntries > 0) {
  554. // Initialize local cache
  555. if(!aCache) {
  556. this._aCache = [];
  557. }
  558. // Look in local cache
  559. else {
  560. var nCacheLength = aCache.length;
  561. if(nCacheLength > 0) {
  562. var oResponse = null;
  563. this.fireEvent("cacheRequestEvent", {request:oRequest,callback:oCallback,caller:oCaller});
  564. // Loop through each cached element
  565. for(var i = nCacheLength-1; i >= 0; i--) {
  566. var oCacheElem = aCache[i];
  567. // Defer cache hit logic to a public overridable method
  568. if(this.isCacheHit(oRequest,oCacheElem.request)) {
  569. // The cache returned a hit!
  570. // Grab the cached response
  571. oResponse = oCacheElem.response;
  572. this.fireEvent("cacheResponseEvent", {request:oRequest,response:oResponse,callback:oCallback,caller:oCaller});
  573. // Refresh the position of the cache hit
  574. if(i < nCacheLength-1) {
  575. // Remove element from its original location
  576. aCache.splice(i,1);
  577. // Add as newest
  578. this.addToCache(oRequest, oResponse);
  579. }
  580. // Add a cache flag
  581. oResponse.cached = true;
  582. break;
  583. }
  584. }
  585. return oResponse;
  586. }
  587. }
  588. }
  589. else if(aCache) {
  590. this._aCache = null;
  591. }
  592. return null;
  593. },
  594. /**
  595. * Default overridable method matches given request to given cached request.
  596. * Returns true if is a hit, returns false otherwise. Implementers should
  597. * override this method to customize the cache-matching algorithm.
  598. *
  599. * @method isCacheHit
  600. * @param oRequest {Object} Request object.
  601. * @param oCachedRequest {Object} Cached request object.
  602. * @return {Boolean} True if given request matches cached request, false otherwise.
  603. */
  604. isCacheHit : function(oRequest, oCachedRequest) {
  605. return (oRequest === oCachedRequest);
  606. },
  607. /**
  608. * Adds a new item to the cache. If cache is full, evicts the stalest item
  609. * before adding the new item.
  610. *
  611. * @method addToCache
  612. * @param oRequest {Object} Request object.
  613. * @param oResponse {Object} Response object to cache.
  614. */
  615. addToCache : function(oRequest, oResponse) {
  616. var aCache = this._aCache;
  617. if(!aCache) {
  618. return;
  619. }
  620. // If the cache is full, make room by removing stalest element (index=0)
  621. while(aCache.length >= this.maxCacheEntries) {
  622. aCache.shift();
  623. }
  624. // Add to cache in the newest position, at the end of the array
  625. var oCacheElem = {request:oRequest,response:oResponse};
  626. aCache[aCache.length] = oCacheElem;
  627. this.fireEvent("responseCacheEvent", {request:oRequest,response:oResponse});
  628. },
  629. /**
  630. * Flushes cache.
  631. *
  632. * @method flushCache
  633. */
  634. flushCache : function() {
  635. if(this._aCache) {
  636. this._aCache = [];
  637. this.fireEvent("cacheFlushEvent");
  638. }
  639. },
  640. /**
  641. * Sets up a polling mechanism to send requests at set intervals and forward
  642. * responses to given callback.
  643. *
  644. * @method setInterval
  645. * @param nMsec {Number} Length of interval in milliseconds.
  646. * @param oRequest {Object} Request object.
  647. * @param oCallback {Function} Handler function to receive the response.
  648. * @param oCaller {Object} (deprecated) Use oCallback.scope.
  649. * @return {Number} Interval ID.
  650. */
  651. setInterval : function(nMsec, oRequest, oCallback, oCaller) {
  652. if(lang.isNumber(nMsec) && (nMsec >= 0)) {
  653. var oSelf = this;
  654. var nId = setInterval(function() {
  655. oSelf.makeConnection(oRequest, oCallback, oCaller);
  656. }, nMsec);
  657. this._aIntervals.push(nId);
  658. return nId;
  659. }
  660. else {
  661. }
  662. },
  663. /**
  664. * Disables polling mechanism associated with the given interval ID.
  665. *
  666. * @method clearInterval
  667. * @param nId {Number} Interval ID.
  668. */
  669. clearInterval : function(nId) {
  670. // Remove from tracker if there
  671. var tracker = this._aIntervals || [];
  672. for(var i=tracker.length-1; i>-1; i--) {
  673. if(tracker[i] === nId) {
  674. tracker.splice(i,1);
  675. clearInterval(nId);
  676. }
  677. }
  678. },
  679. /**
  680. * Disables all known polling intervals.
  681. *
  682. * @method clearAllIntervals
  683. */
  684. clearAllIntervals : function() {
  685. var tracker = this._aIntervals || [];
  686. for(var i=tracker.length-1; i>-1; i--) {
  687. clearInterval(tracker[i]);
  688. }
  689. tracker = [];
  690. },
  691. /**
  692. * First looks for cached response, then sends request to live data. The
  693. * following arguments are passed to the callback function:
  694. * <dl>
  695. * <dt><code>oRequest</code></dt>
  696. * <dd>The same value that was passed in as the first argument to sendRequest.</dd>
  697. * <dt><code>oParsedResponse</code></dt>
  698. * <dd>An object literal containing the following properties:
  699. * <dl>
  700. * <dt><code>tId</code></dt>
  701. * <dd>Unique transaction ID number.</dd>
  702. * <dt><code>results</code></dt>
  703. * <dd>Schema-parsed data results.</dd>
  704. * <dt><code>error</code></dt>
  705. * <dd>True in cases of data error.</dd>
  706. * <dt><code>cached</code></dt>
  707. * <dd>True when response is returned from DataSource cache.</dd>
  708. * <dt><code>meta</code></dt>
  709. * <dd>Schema-parsed meta data.</dd>
  710. * </dl>
  711. * <dt><code>oPayload</code></dt>
  712. * <dd>The same value as was passed in as <code>argument</code> in the oCallback object literal.</dd>
  713. * </dl>
  714. *
  715. * @method sendRequest
  716. * @param oRequest {Object} Request object.
  717. * @param oCallback {Object} An object literal with the following properties:
  718. * <dl>
  719. * <dt><code>success</code></dt>
  720. * <dd>The function to call when the data is ready.</dd>
  721. * <dt><code>failure</code></dt>
  722. * <dd>The function to call upon a response failure condition.</dd>
  723. * <dt><code>scope</code></dt>
  724. * <dd>The object to serve as the scope for the success and failure handlers.</dd>
  725. * <dt><code>argument</code></dt>
  726. * <dd>Arbitrary data that will be passed back to the success and failure handlers.</dd>
  727. * </dl>
  728. * @param oCaller {Object} (deprecated) Use oCallback.scope.
  729. * @return {Number} Transaction ID, or null if response found in cache.
  730. */
  731. sendRequest : function(oRequest, oCallback, oCaller) {
  732. // First look in cache
  733. var oCachedResponse = this.getCachedResponse(oRequest, oCallback, oCaller);
  734. if(oCachedResponse) {
  735. DS.issueCallback(oCallback,[oRequest,oCachedResponse],false,oCaller);
  736. return null;
  737. }
  738. // Not in cache, so forward request to live data
  739. return this.makeConnection(oRequest, oCallback, oCaller);
  740. },
  741. /**
  742. * Overridable default method generates a unique transaction ID and passes
  743. * the live data reference directly to the handleResponse function. This
  744. * method should be implemented by subclasses to achieve more complex behavior
  745. * or to access remote data.
  746. *
  747. * @method makeConnection
  748. * @param oRequest {Object} Request object.
  749. * @param oCallback {Object} Callback object literal.
  750. * @param oCaller {Object} (deprecated) Use oCallback.scope.
  751. * @return {Number} Transaction ID.
  752. */
  753. makeConnection : function(oRequest, oCallback, oCaller) {
  754. var tId = DS._nTransactionId++;
  755. this.fireEvent("requestEvent", {tId:tId, request:oRequest,callback:oCallback,caller:oCaller});
  756. /* accounts for the following cases:
  757. YAHOO.util.DataSourceBase.TYPE_UNKNOWN
  758. YAHOO.util.DataSourceBase.TYPE_JSARRAY
  759. YAHOO.util.DataSourceBase.TYPE_JSON
  760. YAHOO.util.DataSourceBase.TYPE_HTMLTABLE
  761. YAHOO.util.DataSourceBase.TYPE_XML
  762. YAHOO.util.DataSourceBase.TYPE_TEXT
  763. */
  764. var oRawResponse = this.liveData;
  765. this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId);
  766. return tId;
  767. },
  768. /**
  769. * Receives raw data response and type converts to XML, JSON, etc as necessary.
  770. * Forwards oFullResponse to appropriate parsing function to get turned into
  771. * oParsedResponse. Calls doBeforeCallback() and adds oParsedResponse to
  772. * the cache when appropriate before calling issueCallback().
  773. *
  774. * The oParsedResponse object literal has the following properties:
  775. * <dl>
  776. * <dd><dt>tId {Number}</dt> Unique transaction ID</dd>
  777. * <dd><dt>results {Array}</dt> Array of parsed data results</dd>
  778. * <dd><dt>meta {Object}</dt> Object literal of meta values</dd>
  779. * <dd><dt>error {Boolean}</dt> (optional) True if there was an error</dd>
  780. * <dd><dt>cached {Boolean}</dt> (optional) True if response was cached</dd>
  781. * </dl>
  782. *
  783. * @method handleResponse
  784. * @param oRequest {Object} Request object
  785. * @param oRawResponse {Object} The raw response from the live database.
  786. * @param oCallback {Object} Callback object literal.
  787. * @param oCaller {Object} (deprecated) Use oCallback.scope.
  788. * @param tId {Number} Transaction ID.
  789. */
  790. handleResponse : function(oRequest, oRawResponse, oCallback, oCaller, tId) {
  791. this.fireEvent("responseEvent", {tId:tId, request:oRequest, response:oRawResponse,
  792. callback:oCallback, caller:oCaller});
  793. var xhr = (this.dataType == DS.TYPE_XHR) ? true : false;
  794. var oParsedResponse = null;
  795. var oFullResponse = oRawResponse;
  796. // Try to sniff data type if it has not been defined
  797. if(this.responseType === DS.TYPE_UNKNOWN) {
  798. var ctype = (oRawResponse && oRawResponse.getResponseHeader) ? oRawResponse.getResponseHeader["Content-Type"] : null;
  799. if(ctype) {
  800. // xml
  801. if(ctype.indexOf("text/xml") > -1) {
  802. this.responseType = DS.TYPE_XML;
  803. }
  804. else if(ctype.indexOf("application/json") > -1) { // json
  805. this.responseType = DS.TYPE_JSON;
  806. }
  807. else if(ctype.indexOf("text/plain") > -1) { // text
  808. this.responseType = DS.TYPE_TEXT;
  809. }
  810. }
  811. else {
  812. if(YAHOO.lang.isArray(oRawResponse)) { // array
  813. this.responseType = DS.TYPE_JSARRAY;
  814. }
  815. // xml
  816. else if(oRawResponse && oRawResponse.nodeType && oRawResponse.nodeType == 9) {
  817. this.responseType = DS.TYPE_XML;
  818. }
  819. else if(oRawResponse && oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table
  820. this.responseType = DS.TYPE_HTMLTABLE;
  821. }
  822. else if(YAHOO.lang.isObject(oRawResponse)) { // json
  823. this.responseType = DS.TYPE_JSON;
  824. }
  825. else if(YAHOO.lang.isString(oRawResponse)) { // text
  826. this.responseType = DS.TYPE_TEXT;
  827. }
  828. }
  829. }
  830. switch(this.responseType) {
  831. case DS.TYPE_JSARRAY:
  832. if(xhr && oRawResponse && oRawResponse.responseText) {
  833. oFullResponse = oRawResponse.responseText;
  834. }
  835. try {
  836. // Convert to JS array if it's a string
  837. if(lang.isString(oFullResponse)) {
  838. var parseArgs = [oFullResponse].concat(this.parseJSONArgs);
  839. // Check for YUI JSON Util
  840. if(lang.JSON) {
  841. oFullResponse = lang.JSON.parse.apply(lang.JSON,parseArgs);
  842. }
  843. // Look for JSON parsers using an API similar to json2.js
  844. else if(window.JSON && JSON.parse) {
  845. oFullResponse = JSON.parse.apply(JSON,parseArgs);
  846. }
  847. // Look for JSON parsers using an API similar to json.js
  848. else if(oFullResponse.parseJSON) {
  849. oFullResponse = oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1));
  850. }
  851. // No JSON lib found so parse the string
  852. else {
  853. // Trim leading spaces
  854. while (oFullResponse.length > 0 &&
  855. (oFullResponse.charAt(0) != "{") &&
  856. (oFullResponse.charAt(0) != "[")) {
  857. oFullResponse = oFullResponse.substring(1, oFullResponse.length);
  858. }
  859. if(oFullResponse.length > 0) {
  860. // Strip extraneous stuff at the end
  861. var arrayEnd =
  862. Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}"));
  863. oFullResponse = oFullResponse.substring(0,arrayEnd+1);
  864. // Turn the string into an object literal...
  865. // ...eval is necessary here
  866. oFullResponse = eval("(" + oFullResponse + ")");
  867. }
  868. }
  869. }
  870. }
  871. catch(e1) {
  872. }
  873. oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
  874. oParsedResponse = this.parseArrayData(oRequest, oFullResponse);
  875. break;
  876. case DS.TYPE_JSON:
  877. if(xhr && oRawResponse && oRawResponse.responseText) {
  878. oFullResponse = oRawResponse.responseText;
  879. }
  880. try {
  881. // Convert to JSON object if it's a string
  882. if(lang.isString(oFullResponse)) {
  883. var parseArgs = [oFullResponse].concat(this.parseJSONArgs);
  884. // Check for YUI JSON Util
  885. if(lang.JSON) {
  886. oFullResponse = lang.JSON.parse.apply(lang.JSON,parseArgs);
  887. }
  888. // Look for JSON parsers using an API similar to json2.js
  889. else if(window.JSON && JSON.parse) {
  890. oFullResponse = JSON.parse.apply(JSON,parseArgs);
  891. }
  892. // Look for JSON parsers using an API similar to json.js
  893. else if(oFullResponse.parseJSON) {
  894. oFullResponse = oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1));
  895. }
  896. // No JSON lib found so parse the string
  897. else {
  898. // Trim leading spaces
  899. while (oFullResponse.length > 0 &&
  900. (oFullResponse.charAt(0) != "{") &&
  901. (oFullResponse.charAt(0) != "[")) {
  902. oFullResponse = oFullResponse.substring(1, oFullResponse.length);
  903. }
  904. if(oFullResponse.length > 0) {
  905. // Strip extraneous stuff at the end
  906. var objEnd = Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}"));
  907. oFullResponse = oFullResponse.substring(0,objEnd+1);
  908. // Turn the string into an object literal...
  909. // ...eval is necessary here
  910. oFullResponse = eval("(" + oFullResponse + ")");
  911. }
  912. }
  913. }
  914. }
  915. catch(e) {
  916. }
  917. oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
  918. oParsedResponse = this.parseJSONData(oRequest, oFullResponse);
  919. break;
  920. case DS.TYPE_HTMLTABLE:
  921. if(xhr && oRawResponse.responseText) {
  922. var el = document.createElement('div');
  923. el.innerHTML = oRawResponse.responseText;
  924. oFullResponse = el.getElementsByTagName('table')[0];
  925. }
  926. oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
  927. oParsedResponse = this.parseHTMLTableData(oRequest, oFullResponse);
  928. break;
  929. case DS.TYPE_XML:
  930. if(xhr && oRawResponse.responseXML) {
  931. oFullResponse = oRawResponse.responseXML;
  932. }
  933. oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
  934. oParsedResponse = this.parseXMLData(oRequest, oFullResponse);
  935. break;
  936. case DS.TYPE_TEXT:
  937. if(xhr && lang.isString(oRawResponse.responseText)) {
  938. oFullResponse = oRawResponse.responseText;
  939. }
  940. oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
  941. oParsedResponse = this.parseTextData(oRequest, oFullResponse);
  942. break;
  943. default:
  944. oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback);
  945. oParsedResponse = this.parseData(oRequest, oFullResponse);
  946. break;
  947. }
  948. // Clean up for consistent signature
  949. oParsedResponse = oParsedResponse || {};
  950. if(!oParsedResponse.results) {
  951. oParsedResponse.results = [];
  952. }
  953. if(!oParsedResponse.meta) {
  954. oParsedResponse.meta = {};
  955. }
  956. // Success
  957. if(oParsedResponse && !oParsedResponse.error) {
  958. // Last chance to touch the raw response or the parsed response
  959. oParsedResponse = this.doBeforeCallback(oRequest, oFullResponse, oParsedResponse, oCallback);
  960. this.fireEvent("responseParseEvent", {request:oRequest,
  961. response:oParsedResponse, callback:oCallback, caller:oCaller});
  962. // Cache the response
  963. this.addToCache(oRequest, oParsedResponse);
  964. }
  965. // Error
  966. else {
  967. // Be sure the error flag is on
  968. oParsedResponse.error = true;
  969. this.fireEvent("dataErrorEvent", {request:oRequest, response: oRawResponse, callback:oCallback,
  970. caller:oCaller, message:DS.ERROR_DATANULL});
  971. }
  972. // Send the response back to the caller
  973. oParsedResponse.tId = tId;
  974. DS.issueCallback(oCallback,[oRequest,oParsedResponse],oParsedResponse.error,oCaller);
  975. },
  976. /**
  977. * Overridable method gives implementers access to the original full response
  978. * before the data gets parsed. Implementers should take care not to return an
  979. * unparsable or otherwise invalid response.
  980. *
  981. * @method doBeforeParseData
  982. * @param oRequest {Object} Request object.
  983. * @param oFullResponse {Object} The full response from the live database.
  984. * @param oCallback {Object} The callback object.
  985. * @return {Object} Full response for parsing.
  986. */
  987. doBeforeParseData : function(oRequest, oFullResponse, oCallback) {
  988. return oFullResponse;
  989. },
  990. /**
  991. * Overridable method gives implementers access to the original full response and
  992. * the parsed response (parsed against the given schema) before the data
  993. * is added to the cache (if applicable) and then sent back to callback function.
  994. * This is your chance to access the raw response and/or populate the parsed
  995. * response with any custom data.
  996. *
  997. * @method doBeforeCallback
  998. * @param oRequest {Object} Request object.
  999. * @param oFullResponse {Object} The full response from the live database.
  1000. * @param oParsedResponse {Object} The parsed response to return to calling object.
  1001. * @param oCallback {Object} The callback object.
  1002. * @return {Object} Parsed response object.
  1003. */
  1004. doBeforeCallback : function(oRequest, oFullResponse, oParsedResponse, oCallback) {
  1005. return oParsedResponse;
  1006. },
  1007. /**
  1008. * Overridable method parses data of generic RESPONSE_TYPE into a response object.
  1009. *
  1010. * @method parseData
  1011. * @param oRequest {Object} Request object.
  1012. * @param oFullResponse {Object} The full Array from the live database.
  1013. * @return {Object} Parsed response object with the following properties:<br>
  1014. * - results {Array} Array of parsed data results<br>
  1015. * - meta {Object} Object literal of meta values<br>
  1016. * - error {Boolean} (optional) True if there was an error<br>
  1017. */
  1018. parseData : function(oRequest, oFullResponse) {
  1019. if(lang.isValue(oFullResponse)) {
  1020. var oParsedResponse = {results:oFullResponse,meta:{}};
  1021. return oParsedResponse;
  1022. }
  1023. return null;
  1024. },
  1025. /**
  1026. * Overridable method parses Array data into a response object.
  1027. *
  1028. * @method parseArrayData
  1029. * @param oRequest {Object} Request object.
  1030. * @param oFullResponse {Object} The full Array from the live database.
  1031. * @return {Object} Parsed response object with the following properties:<br>
  1032. * - results (Array) Array of parsed data results<br>
  1033. * - error (Boolean) True if there was an error
  1034. */
  1035. parseArrayData : function(oRequest, oFullResponse) {
  1036. if(lang.isArray(oFullResponse)) {
  1037. var results = [],
  1038. i, j,
  1039. rec, field, data;
  1040. // Parse for fields
  1041. if(lang.isArray(this.responseSchema.fields)) {
  1042. var fields = this.responseSchema.fields;
  1043. for (i = fields.length - 1; i >= 0; --i) {
  1044. if (typeof fields[i] !== 'object') {
  1045. fields[i] = { key : fields[i] };
  1046. }
  1047. }
  1048. var parsers = {}, p;
  1049. for (i = fields.length - 1; i >= 0; --i) {
  1050. p = (typeof fields[i].parser === 'function' ?
  1051. fields[i].parser :
  1052. DS.Parser[fields[i].parser+'']) || fields[i].converter;
  1053. if (p) {
  1054. parsers[fields[i].key] = p;
  1055. }
  1056. }
  1057. var arrType = lang.isArray(oFullResponse[0]);
  1058. for(i=oFullResponse.length-1; i>-1; i--) {
  1059. var oResult = {};
  1060. rec = oFullResponse[i];
  1061. if (typeof rec === 'object') {
  1062. for(j=fields.length-1; j>-1; j--) {
  1063. field = fields[j];
  1064. data = arrType ? rec[j] : rec[field.key];
  1065. if (parsers[field.key]) {
  1066. data = parsers[field.key].call(this,data);
  1067. }
  1068. // Safety measure
  1069. if(data === undefined) {
  1070. data = null;
  1071. }
  1072. oResult[field.key] = data;
  1073. }
  1074. }
  1075. else if (lang.isString(rec)) {
  1076. for(j=fields.length-1; j>-1; j--) {
  1077. field = fields[j];
  1078. data = rec;
  1079. if (parsers[field.key]) {
  1080. data = parsers[field.key].call(this,data);
  1081. }
  1082. // Safety measure
  1083. if(data === undefined) {
  1084. data = null;
  1085. }
  1086. oResult[field.key] = data;
  1087. }
  1088. }
  1089. results[i] = oResult;
  1090. }
  1091. }
  1092. // Return entire data set
  1093. else {
  1094. results = oFullResponse;
  1095. }
  1096. var oParsedResponse = {results:results};
  1097. return oParsedResponse;
  1098. }
  1099. return null;
  1100. },
  1101. /**
  1102. * Overridable method parses plain text data into a response object.
  1103. *
  1104. * @method parseTextData
  1105. * @param oRequest {Object} Request object.
  1106. * @param oFullResponse {Object} The full text response from the live database.
  1107. * @return {Object} Parsed response object with the following properties:<br>
  1108. * - results (Array) Array of parsed data results<br>
  1109. * - error (Boolean) True if there was an error
  1110. */
  1111. parseTextData : function(oRequest, oFullResponse) {
  1112. if(lang.isString(oFullResponse)) {
  1113. if(lang.isString(this.responseSchema.recordDelim) &&
  1114. lang.isString(this.responseSchema.fieldDelim)) {
  1115. var oParsedResponse = {results:[]};
  1116. var recDelim = this.responseSchema.recordDelim;
  1117. var fieldDelim = this.responseSchema.fieldDelim;
  1118. if(oFullResponse.length > 0) {
  1119. // Delete the last line delimiter at the end of the data if it exists
  1120. var newLength = oFullResponse.length-recDelim.length;
  1121. if(oFullResponse.substr(newLength) == recDelim) {
  1122. oFullResponse = oFullResponse.substr(0, newLength);
  1123. }
  1124. if(oFullResponse.length > 0) {
  1125. // Split along record delimiter to get an array of strings
  1126. var recordsarray = oFullResponse.split(recDelim);
  1127. // Cycle through each record
  1128. for(var i = 0, len = recordsarray.length, recIdx = 0; i < len; ++i) {
  1129. var bError = false,
  1130. sRecord = recordsarray[i];
  1131. if (lang.isString(sRecord) && (sRecord.length > 0)) {
  1132. // Split each record along field delimiter to get data
  1133. var fielddataarray = recordsarray[i].split(fieldDelim);
  1134. var oResult = {};
  1135. // Filter for fields data
  1136. if(lang.isArray(this.responseSchema.fields)) {
  1137. var fields = this.responseSchema.fields;
  1138. for(var j=fields.length-1; j>-1; j--) {
  1139. try {
  1140. // Remove quotation marks from edges, if applicable
  1141. var data = fielddataarray[j];
  1142. if (lang.isString(data)) {
  1143. if(data.charAt(0) == "\"") {
  1144. data = data.substr(1);
  1145. }
  1146. if(data.charAt(data.length-1) == "\"") {
  1147. data = data.substr(0,data.length-1);
  1148. }
  1149. var field = fields[j];
  1150. var key = (lang.isValue(field.key)) ? field.key : field;
  1151. // Backward compatibility
  1152. if(!field.parser && field.converter) {
  1153. field.parser = field.converter;
  1154. }
  1155. var parser = (typeof field.parser === 'function') ?
  1156. field.parser :
  1157. DS.Parser[field.parser+''];
  1158. if(parser) {
  1159. data = parser.call(this, data);
  1160. }
  1161. // Safety measure
  1162. if(data === undefined) {
  1163. data = null;
  1164. }
  1165. oResult[key] = data;
  1166. }
  1167. else {
  1168. bError = true;
  1169. }
  1170. }
  1171. catch(e) {
  1172. bError = true;
  1173. }
  1174. }
  1175. }
  1176. // No fields defined so pass along all data as an array
  1177. else {
  1178. oResult = fielddataarray;
  1179. }
  1180. if(!bError) {
  1181. oParsedResponse.results[recIdx++] = oResult;
  1182. }
  1183. }
  1184. }
  1185. }
  1186. }
  1187. return oParsedResponse;
  1188. }
  1189. }
  1190. return null;
  1191. },
  1192. /**
  1193. * Overridable method parses XML data for one result into an object literal.
  1194. *
  1195. * @method parseXMLResult
  1196. * @param result {XML} XML for one result.
  1197. * @return {Object} Object literal of data for one result.
  1198. */
  1199. parseXMLResult : function(result) {
  1200. var oResult = {},
  1201. schema = this.responseSchema;
  1202. try {
  1203. // Loop through each data field in each result using the schema
  1204. for(var m = schema.fields.length-1; m >= 0 ; m--) {
  1205. var field = schema.fields[m];
  1206. var key = (lang.isValue(field.key)) ? field.key : field;
  1207. var data = null;
  1208. // Values may be held in an attribute...
  1209. var xmlAttr = result.attributes.getNamedItem(key);
  1210. if(xmlAttr) {
  1211. data = xmlAttr.value;
  1212. }
  1213. // ...or in a node
  1214. else {
  1215. var xmlNode = result.getElementsByTagName(key);
  1216. if(xmlNode && xmlNode.item(0)) {
  1217. var item = xmlNode.item(0);
  1218. // For IE, then DOM...
  1219. data = (item) ? ((item.text) ? item.text : (item.textContent) ? item.textContent : null) : null;
  1220. // ...then fallback, but check for multiple child nodes
  1221. if(!data) {
  1222. var datapieces = [];
  1223. for(var j=0, len=item.childNodes.length; j<len; j++) {
  1224. if(item.childNodes[j].nodeValue) {
  1225. datapieces[datapieces.length] = item.childNodes[j].nodeValue;
  1226. }
  1227. }
  1228. if(datapieces.length > 0) {
  1229. data = datapieces.join("");
  1230. }
  1231. }
  1232. }
  1233. }
  1234. // Safety net
  1235. if(data === null) {
  1236. data = "";
  1237. }
  1238. // Backward compatibility
  1239. if(!field.parser && field.converter) {
  1240. field.parser = field.converter;
  1241. }
  1242. var parser = (typeof field.parser === 'function') ?
  1243. field.parser :
  1244. DS.Parser[field.parser+''];
  1245. if(parser) {
  1246. data = parser.call(this, data);
  1247. }
  1248. // Safety measure
  1249. if(data === undefined) {
  1250. data = null;
  1251. }
  1252. oResult[key] = data;
  1253. }
  1254. }
  1255. catch(e) {
  1256. }
  1257. return oResult;
  1258. },
  1259. /**
  1260. * Overridable method parses XML data into a response object.
  1261. *
  1262. * @method parseXMLData
  1263. * @param oRequest {Object} Request object.
  1264. * @param oFullResponse {Object} The full XML response from the live database.
  1265. * @return {Object} Parsed response object with the following properties<br>
  1266. * - results (Array) Array of parsed data results<br>
  1267. * - error (Boolean) True if there was an error
  1268. */
  1269. parseXMLData : function(oRequest, oFullResponse) {
  1270. var bError = false,
  1271. schema = this.responseSchema,
  1272. oParsedResponse = {meta:{}},
  1273. xmlList = null,
  1274. metaNode = schema.metaNode,
  1275. metaLocators = schema.metaFields || {},
  1276. i,k,loc,v;
  1277. // In case oFullResponse is something funky
  1278. try {
  1279. xmlList = (schema.resultNode) ?
  1280. oFullResponse.getElementsByTagName(schema.resultNode) :
  1281. null;
  1282. // Pull any meta identified
  1283. metaNode = metaNode ? oFullResponse.getElementsByTagName(metaNode)[0] :
  1284. oFullResponse;
  1285. if (metaNode) {
  1286. for (k in metaLocators) {
  1287. if (lang.hasOwnProperty(metaLocators, k)) {
  1288. loc = metaLocators[k];
  1289. // Look for a node
  1290. v = metaNode.getElementsByTagName(loc)[0];
  1291. if (v) {
  1292. v = v.firstChild.nodeValue;
  1293. } else {
  1294. // Look for an attribute
  1295. v = metaNode.attributes.getNamedItem(loc);
  1296. if (v) {
  1297. v = v.value;
  1298. }
  1299. }
  1300. if (lang.isValue(v)) {
  1301. oParsedResponse.meta[k] = v;
  1302. }
  1303. }
  1304. }
  1305. }
  1306. }
  1307. catch(e) {
  1308. }
  1309. if(!xmlList || !lang.isArray(schema.fields)) {
  1310. bError = true;
  1311. }
  1312. // Loop through each result
  1313. else {
  1314. oParsedResponse.results = [];
  1315. for(i = xmlList.length-1; i >= 0 ; --i) {
  1316. var oResult = this.parseXMLResult(xmlList.item(i));
  1317. // Capture each array of values into an array of results
  1318. oParsedResponse.results[i] = oResult;
  1319. }
  1320. }
  1321. if(bError) {
  1322. oParsedResponse.error = true;
  1323. }
  1324. else {
  1325. }
  1326. return oParsedResponse;
  1327. },
  1328. /**
  1329. * Overridable method parses JSON data into a response object.
  1330. *
  1331. * @method parseJSONData
  1332. * @param oRequest {Object} Request object.
  1333. * @param oFullResponse {Object} The full JSON from the live database.
  1334. * @return {Object} Parsed response object with the following properties<br>
  1335. * - results (Array) Array of parsed data results<br>
  1336. * - error (Boolean) True if there was an error
  1337. */
  1338. parseJSONData : function(oRequest, oFullResponse) {
  1339. var oParsedResponse = {results:[],meta:{}};
  1340. if(lang.isObject(oFullResponse) && this.responseSchema.resultsList) {
  1341. var schema = this.responseSchema,
  1342. fields = schema.fields,
  1343. resultsList = oFullResponse,
  1344. results = [],
  1345. metaFields = schema.metaFields || {},
  1346. fieldParsers = [],
  1347. fieldPaths = [],
  1348. simpleFields = [],
  1349. bError = false,
  1350. i,len,j,v,key,parser,path;
  1351. // Function to convert the schema's fields into walk paths
  1352. var buildPath = function (needle) {
  1353. var path = null, keys = [], i = 0;
  1354. if (needle) {
  1355. // Strip the ["string keys"] and [1] array indexes
  1356. needle = needle.
  1357. replace(/\[(['"])(.*?)\1\]/g,
  1358. function (x,$1,$2) {keys[i]=$2;return '.@'+(i++);}).
  1359. replace(/\[(\d+)\]/g,
  1360. function (x,$1) {keys[i]=parseInt($1,10)|0;return '.@'+(i++);}).
  1361. replace(/^\./,''); // remove leading dot
  1362. // If the cleaned needle contains invalid characters, the
  1363. // path is invalid
  1364. if (!/[^\w\.\$@]/.test(needle)) {
  1365. path = needle.split('.');
  1366. for (i=path.length-1; i >= 0; --i) {
  1367. if (path[i].charAt(0) === '@') {
  1368. path[i] = keys[parseInt(path[i].substr(1),10)];
  1369. }
  1370. }
  1371. }
  1372. else {
  1373. }
  1374. }
  1375. return path;
  1376. };
  1377. // Function to walk a path and return the pot of gold
  1378. var walkPath = function (path, origin) {
  1379. var v=origin,i=0,len=path.length;
  1380. for (;i<len && v;++i) {
  1381. v = v[path[i]];
  1382. }
  1383. return v;
  1384. };
  1385. // Parse the response
  1386. // Step 1. Pull the resultsList from oFullResponse (default assumes
  1387. // oFullResponse IS the resultsList)
  1388. path = buildPath(schema.resultsList);
  1389. if (path) {
  1390. resultsList = walkPath(path, oFullResponse);
  1391. if (resultsList === undefined) {
  1392. bError = true;
  1393. }
  1394. } else {
  1395. bError = true;
  1396. }
  1397. if (!resultsList) {
  1398. resultsList = [];
  1399. }
  1400. if (!lang.isArray(resultsList)) {
  1401. resultsList = [resultsList];
  1402. }
  1403. if (!bError) {
  1404. // Step 2. Parse out field data if identified
  1405. if(schema.fields) {
  1406. var field;
  1407. // Build the field parser map and location paths
  1408. for (i=0, len=fields.length; i<len; i++) {
  1409. field = fields[i];
  1410. key = field.key || field;
  1411. parser = ((typeof field.parser === 'function') ?
  1412. field.parser :
  1413. DS.Parser[field.parser+'']) || field.converter;
  1414. path = buildPath(key);
  1415. if (parser) {
  1416. fieldParsers[fieldParsers.length] = {key:key,parser:parser};
  1417. }
  1418. if (path) {
  1419. if (path.length > 1) {
  1420. fieldPaths[fieldPaths.length] = {key:key,path:path};
  1421. } else {
  1422. simpleFields[simpleFields.length] = {key:key,path:path[0]};
  1423. }
  1424. } else {
  1425. }
  1426. }
  1427. // Process the results, flattening the records and/or applying parsers if needed
  1428. for (i = resultsList.length - 1; i >= 0; --i) {
  1429. var r = resultsList[i], rec = {};
  1430. if(r) {
  1431. for (j = simpleFields.length - 1; j >= 0; --j) {
  1432. // Bug 1777850: data might be held in an array
  1433. rec[simpleFields[j].key] =
  1434. (r[simpleFields[j].path] !== undefined) ?
  1435. r[simpleFields[j].path] : r[j];
  1436. }
  1437. for (j = fieldPaths.length - 1; j >= 0; --j) {
  1438. rec[fieldPaths[j].key] = walkPath(fieldPaths[j].path,r);
  1439. }
  1440. for (j = fieldParsers.length - 1; j >= 0; --j) {
  1441. var p = fieldParsers[j].key;
  1442. rec[p] = fieldParsers[j].parser(rec[p]);
  1443. if (rec[p] === undefined) {
  1444. rec[p] = null;
  1445. }
  1446. }
  1447. }
  1448. results[i] = rec;
  1449. }
  1450. }
  1451. else {
  1452. results = resultsList;
  1453. }
  1454. for (key in metaFields) {
  1455. if (lang.hasOwnProperty(metaFields,key)) {
  1456. path = buildPath(metaFields[key]);
  1457. if (path) {
  1458. v = walkPath(path, oFullResponse);
  1459. oParsedResponse.meta[key] = v;
  1460. }
  1461. }
  1462. }
  1463. } else {
  1464. oParsedResponse.error = true;
  1465. }
  1466. oParsedResponse.results = results;
  1467. }
  1468. else {
  1469. oParsedResponse.error = true;
  1470. }
  1471. return oParsedResponse;
  1472. },
  1473. /**
  1474. * Overridable method parses an HTML TABLE element reference into a response object.
  1475. * Data is parsed out of TR elements from all TBODY elements.
  1476. *
  1477. * @method parseHTMLTableData
  1478. * @param oRequest {Object} Request object.
  1479. * @param oFullResponse {Object} The full HTML element reference from the live database.
  1480. * @return {Object} Parsed response object with the following properties<br>
  1481. * - results (Array) Array of parsed data results<br>
  1482. * - error (Boolean) True if there was an error
  1483. */
  1484. parseHTMLTableData : function(oRequest, oFullResponse) {
  1485. var bError = false;
  1486. var elTable = oFullResponse;
  1487. var fields = this.responseSchema.fields;
  1488. var oParsedResponse = {results:[]};
  1489. if(lang.isArray(fields)) {
  1490. // Iterate through each TBODY
  1491. for(var i=0; i<elTable.tBodies.length; i++) {
  1492. var elTbody = elTable.tBodies[i];
  1493. // Iterate through each TR
  1494. for(var j=elTbody.rows.length-1; j>-1; j--) {
  1495. var elRow = elTbody.rows[j];
  1496. var oResult = {};
  1497. for(var k=fields.length-1; k>-1; k--) {
  1498. var field = fields[k];
  1499. var key = (lang.isValue(field.key)) ? field.key : field;
  1500. var data = elRow.cells[k].innerHTML;
  1501. // Backward compatibility
  1502. if(!field.parser && field.converter) {
  1503. field.parser = field.converter;
  1504. }
  1505. var parser = (typeof field.parser === 'function') ?
  1506. field.parser :
  1507. DS.Parser[field.parser+''];
  1508. if(parser) {
  1509. data = parser.call(this, data);
  1510. }
  1511. // Safety measure
  1512. if(data === undefined) {
  1513. data = null;
  1514. }
  1515. oResult[key] = data;
  1516. }
  1517. oParsedResponse.results[j] = oResult;
  1518. }
  1519. }
  1520. }
  1521. else {
  1522. bError = true;
  1523. }
  1524. if(bError) {
  1525. oParsedResponse.error = true;
  1526. }
  1527. else {
  1528. }
  1529. return oParsedResponse;
  1530. }
  1531. };
  1532. // DataSourceBase uses EventProvider
  1533. lang.augmentProto(DS, util.EventProvider);
  1534. /****************************************************************************/
  1535. /****************************************************************************/
  1536. /****************************************************************************/
  1537. /**
  1538. * LocalDataSource class for in-memory data structs including JavaScript arrays,
  1539. * JavaScript object literals (JSON), XML documents, and HTML tables.
  1540. *
  1541. * @namespace YAHOO.util
  1542. * @class YAHOO.util.LocalDataSource
  1543. * @extends YAHOO.util.DataSourceBase
  1544. * @constructor
  1545. * @param oLiveData {HTMLElement} Pointer to live data.
  1546. * @param oConfigs {object} (optional) Object literal of configuration values.
  1547. */
  1548. util.LocalDataSource = function(oLiveData, oConfigs) {
  1549. this.dataType = DS.TYPE_LOCAL;
  1550. if(oLiveData) {
  1551. if(YAHOO.lang.isArray(oLiveData)) { // array
  1552. this.responseType = DS.TYPE_JSARRAY;
  1553. }
  1554. // xml
  1555. else if(oLiveData.nodeType && oLiveData.nodeType == 9) {
  1556. this.responseType = DS.TYPE_XML;
  1557. }
  1558. else if(oLiveData.nodeName && (oLiveData.nodeName.toLowerCase() == "table")) { // table
  1559. this.responseType = DS.TYPE_HTMLTABLE;
  1560. oLiveData = oLiveData.cloneNode(true);
  1561. }
  1562. else if(YAHOO.lang.isString(oLiveData)) { // text
  1563. this.responseType = DS.TYPE_TEXT;
  1564. }
  1565. else if(YAHOO.lang.isObject(oLiveData)) { // json
  1566. this.responseType = DS.TYPE_JSON;
  1567. }
  1568. }
  1569. else {
  1570. oLiveData = [];
  1571. this.responseType = DS.TYPE_JSARRAY;
  1572. }
  1573. util.LocalDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
  1574. };
  1575. // LocalDataSource extends DataSourceBase
  1576. lang.extend(util.LocalDataSource, DS);
  1577. // Copy static members to LocalDataSource class
  1578. lang.augmentObject(util.LocalDataSource, DS);
  1579. /****************************************************************************/
  1580. /****************************************************************************/
  1581. /****************************************************************************/
  1582. /**
  1583. * FunctionDataSource class for JavaScript functions.
  1584. *
  1585. * @namespace YAHOO.util
  1586. * @class YAHOO.util.FunctionDataSource
  1587. * @extends YAHOO.util.DataSourceBase
  1588. * @constructor
  1589. * @param oLiveData {HTMLElement} Pointer to live data.
  1590. * @param oConfigs {object} (optional) Object literal of configuration values.
  1591. */
  1592. util.FunctionDataSource = function(oLiveData, oConfigs) {
  1593. this.dataType = DS.TYPE_JSFUNCTION;
  1594. oLiveData = oLiveData || function() {};
  1595. util.FunctionDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
  1596. };
  1597. // FunctionDataSource extends DataSourceBase
  1598. lang.extend(util.FunctionDataSource, DS, {
  1599. /////////////////////////////////////////////////////////////////////////////
  1600. //
  1601. // FunctionDataSource public properties
  1602. //
  1603. /////////////////////////////////////////////////////////////////////////////
  1604. /**
  1605. * Context in which to execute the function. By default, is the DataSource
  1606. * instance itself. If set, the function will receive the DataSource instance
  1607. * as an additional argument.
  1608. *
  1609. * @property scope
  1610. * @type Object
  1611. * @default null
  1612. */
  1613. scope : null,
  1614. /////////////////////////////////////////////////////////////////////////////
  1615. //
  1616. // FunctionDataSource public methods
  1617. //
  1618. /////////////////////////////////////////////////////////////////////////////
  1619. /**
  1620. * Overriding method passes query to a function. The returned response is then
  1621. * forwarded to the handleResponse function.
  1622. *
  1623. * @method makeConnection
  1624. * @param oRequest {Object} Request object.
  1625. * @param oCallback {Object} Callback object literal.
  1626. * @param oCaller {Object} (deprecated) Use oCallback.scope.
  1627. * @return {Number} Transaction ID.
  1628. */
  1629. makeConnection : function(oRequest, oCallback, oCaller) {
  1630. var tId = DS._nTransactionId++;
  1631. this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller});
  1632. // Pass the request in as a parameter and
  1633. // forward the return value to the handler
  1634. var oRawResponse = (this.scope) ? this.liveData.call(this.scope, oRequest, this) : this.liveData(oRequest);
  1635. // Try to sniff data type if it has not been defined
  1636. if(this.responseType === DS.TYPE_UNKNOWN) {
  1637. if(YAHOO.lang.isArray(oRawResponse)) { // array
  1638. this.responseType = DS.TYPE_JSARRAY;
  1639. }
  1640. // xml
  1641. else if(oRawResponse && oRawResponse.nodeType && oRawResponse.nodeType == 9) {
  1642. this.responseType = DS.TYPE_XML;
  1643. }
  1644. else if(oRawResponse && oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table
  1645. this.responseType = DS.TYPE_HTMLTABLE;
  1646. }
  1647. else if(YAHOO.lang.isObject(oRawResponse)) { // json
  1648. this.responseType = DS.TYPE_JSON;
  1649. }
  1650. else if(YAHOO.lang.isString(oRawResponse)) { // text
  1651. this.responseType = DS.TYPE_TEXT;
  1652. }
  1653. }
  1654. this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId);
  1655. return tId;
  1656. }
  1657. });
  1658. // Copy static members to FunctionDataSource class
  1659. lang.augmentObject(util.FunctionDataSource, DS);
  1660. /****************************************************************************/
  1661. /****************************************************************************/
  1662. /****************************************************************************/
  1663. /**
  1664. * ScriptNodeDataSource class for accessing remote data via the YUI Get Utility.
  1665. *
  1666. * @namespace YAHOO.util
  1667. * @class YAHOO.util.ScriptNodeDataSource
  1668. * @extends YAHOO.util.DataSourceBase
  1669. * @constructor
  1670. * @param oLiveData {HTMLElement} Pointer to live data.
  1671. * @param oConfigs {object} (optional) Object literal of configuration values.
  1672. */
  1673. util.ScriptNodeDataSource = function(oLiveData, oConfigs) {
  1674. this.dataType = DS.TYPE_SCRIPTNODE;
  1675. oLiveData = oLiveData || "";
  1676. util.ScriptNodeDataSource.superclass.constructor.call(this, oLiveData, oConfigs);
  1677. };
  1678. // ScriptNodeDataSource extends DataSourceBase
  1679. lang.extend(util.ScriptNodeDataSource, DS, {
  1680. /////////////////////////////////////////////////////////////////////////////
  1681. //
  1682. // ScriptNodeDataSource public properties
  1683. //
  1684. /////////////////////////////////////////////////////////////////////////////
  1685. /**
  1686. * Alias to YUI Get Utility, to allow implementers to use a custom class.
  1687. *
  1688. * @property getUtility
  1689. * @type Object
  1690. * @default YAHOO.util.Get
  1691. */
  1692. getUtility : util.Get,
  1693. /**
  1694. * Defines request/response management in the following manner:
  1695. * <dl>
  1696. * <!--<dt>queueRequests</dt>
  1697. * <dd>If a request is already in progress, wait until response is returned before sending the next request.</dd>
  1698. * <dt>cancelStaleRequests</dt>
  1699. * <dd>If a request is already in progress, cancel it before sending the next request.</dd>-->
  1700. * <dt>ignoreStaleResponses</dt>
  1701. * <dd>Send all requests, but handle only the response for the most recently sent request.</dd>
  1702. * <dt>allowAll</dt>
  1703. * <dd>Send all requests and handle all responses.</dd>
  1704. * </dl>
  1705. *
  1706. * @property asyncMode
  1707. * @type String
  1708. * @default "allowAll"
  1709. */
  1710. asyncMode : "allowAll",
  1711. /**
  1712. * Callback string parameter name sent to the remote script. By default,
  1713. * requests are sent to
  1714. * &#60;URI&#62;?&#60;scriptCallbackParam&#62;=callbackFunction
  1715. *
  1716. * @property scriptCallbackParam
  1717. * @type String
  1718. * @default "callback"
  1719. */
  1720. scriptCallbackParam : "callback",
  1721. /////////////////////////////////////////////////////////////////////////////
  1722. //
  1723. // ScriptNodeDataSource public methods
  1724. //
  1725. /////////////////////////////////////////////////////////////////////////////
  1726. /**
  1727. * Creates a request callback that gets appended to the script URI. Implementers
  1728. * can customize this string to match their server's query syntax.
  1729. *
  1730. * @method generateRequestCallback
  1731. * @return {String} String fragment that gets appended to script URI that
  1732. * specifies the callback function
  1733. */
  1734. generateRequestCallback : function(id) {
  1735. return "&" + this.scriptCallbackParam + "=YAHOO.util.ScriptNodeDataSource.callbacks["+id+"]" ;
  1736. },
  1737. /**
  1738. * Overridable method gives implementers access to modify the URI before the dynamic
  1739. * script node gets inserted. Implementers should take care not to return an
  1740. * invalid URI.
  1741. *
  1742. * @method doBeforeGetScriptNode
  1743. * @param {String} URI to the script
  1744. * @return {String} URI to the script
  1745. */
  1746. doBeforeGetScriptNode : function(sUri) {
  1747. return sUri;
  1748. },
  1749. /**
  1750. * Overriding method passes query to Get Utility. The returned
  1751. * response is then forwarded to the handleResponse function.
  1752. *
  1753. * @method makeConnection
  1754. * @param oRequest {Object} Request object.
  1755. * @param oCallback {Object} Callback object literal.
  1756. * @param oCaller {Object} (deprecated) Use oCallback.scope.
  1757. * @return {Number} Transaction ID.
  1758. */
  1759. makeConnection : function(oRequest, oCallback, oCaller) {
  1760. var tId = DS._nTransactionId++;
  1761. this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller});
  1762. // If there are no global pending requests, it is safe to purge global callback stack and global counter
  1763. if(util.ScriptNodeDataSource._nPending === 0) {
  1764. util.Scr