/*
Copyright (c) 2007, Yahoo! Inc. All rights reserved.
Code licensed under the BSD License:
version: 2.3.0
*/
/**
* The DataSource utility provides a common configurable interface for widgets
* to access a variety of data, from JavaScript arrays to online servers over
* XHR.
*
* @namespace YAHOO.util
* @module datasource
* @requires yahoo, event
* @optional connection
* @title DataSource Utility
* @beta
*/
/****************************************************************************/
/****************************************************************************/
/****************************************************************************/
/**
* The DataSource class defines and manages a live set of data for widgets to
* interact with. Examples of live databases include in-memory
* local data such as a JavaScript array, a JavaScript function, or JSON, or
* remote data such as data retrieved through an XHR connection.
*
* @class DataSource
* @uses YAHOO.util.EventProvider
* @constructor
* @param oLiveData {Object} Pointer to live database.
* @param oConfigs {Object} (optional) Object literal of configuration values.
*/
// Set any config params passed in to override defaults
if(sConfig) {
}
}
}
if(!oLiveData) {
"error", this.toString());
return;
}
}
}
}
}
}
}
else {
}
// Validate and initialize public configs
var maxCacheEntries = this.maxCacheEntries;
maxCacheEntries = 0;
}
// Initialize local cache
this._aCache = [];
}
/////////////////////////////////////////////////////////////////////////////
//
// Custom Events
//
/////////////////////////////////////////////////////////////////////////////
/**
* Fired when a request is made to the local cache.
*
* @event cacheRequestEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.callback {Function} The callback function.
* @param oArgs.caller {Object} The parent object of the callback function.
*/
this.createEvent("cacheRequestEvent");
/**
* Fired when data is retrieved from the local cache.
*
* @event getCachedResponseEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.response {Object} The response object.
* @param oArgs.callback {Function} The callback function.
* @param oArgs.caller {Object} The parent object of the callback function.
* @param oArgs.tId {Number} Transaction ID.
*/
this.createEvent("cacheResponseEvent");
/**
* Fired when a request is sent to the live data source.
*
* @event requestEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.callback {Function} The callback function.
* @param oArgs.caller {Object} The parent object of the callback function.
*/
this.createEvent("requestEvent");
/**
* Fired when live data source sends response.
*
* @event responseEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.response {Object} The raw response object.
* @param oArgs.callback {Function} The callback function.
* @param oArgs.caller {Object} The parent object of the callback function.
*/
this.createEvent("responseEvent");
/**
* Fired when response is parsed.
*
* @event responseParseEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.response {Object} The parsed response object.
* @param oArgs.callback {Function} The callback function.
* @param oArgs.caller {Object} The parent object of the callback function.
*/
this.createEvent("responseParseEvent");
/**
* Fired when response is cached.
*
* @event responseCacheEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.response {Object} The parsed response object.
* @param oArgs.callback {Function} The callback function.
* @param oArgs.caller {Object} The parent object of the callback function.
*/
this.createEvent("responseCacheEvent");
/**
* Fired when an error is encountered with the live data source.
*
* @event dataErrorEvent
* @param oArgs.request {Object} The request object.
* @param oArgs.callback {Function} The callback function.
* @param oArgs.caller {Object} The parent object of the callback function.
* @param oArgs.message {String} The error message.
*/
this.createEvent("dataErrorEvent");
/**
* Fired when the local cache is flushed.
*
* @event cacheFlushEvent
*/
this.createEvent("cacheFlushEvent");
};
/////////////////////////////////////////////////////////////////////////////
//
// Public constants
//
/////////////////////////////////////////////////////////////////////////////
/**
* Type is unknown.
*
* @property TYPE_UNKNOWN
* @type Number
* @final
* @default -1
*/
/**
* Type is a JavaScript Array.
*
* @property TYPE_JSARRAY
* @type Number
* @final
* @default 0
*/
/**
* Type is a JavaScript Function.
*
* @property TYPE_JSFUNCTION
* @type Number
* @final
* @default 1
*/
/**
* Type is hosted on a server via an XHR connection.
*
* @property TYPE_XHR
* @type Number
* @final
* @default 2
*/
/**
* Type is JSON.
*
* @property TYPE_JSON
* @type Number
* @final
* @default 3
*/
/**
* Type is XML.
*
* @property TYPE_XML
* @type Number
* @final
* @default 4
*/
/**
* Type is plain text.
*
* @property TYPE_TEXT
* @type Number
* @final
* @default 5
*/
/**
* Type is an HTML TABLE element.
*
* @property TYPE_HTMLTABLE
* @type Number
* @final
* @default 6
*/
/**
* Error message for invalid dataresponses.
*
* @property ERROR_DATAINVALID
* @type String
* @final
* @default "Invalid data"
*/
/**
* Error message for null data responses.
*
* @property ERROR_DATANULL
* @type String
* @final
* @default "Null data"
*/
/////////////////////////////////////////////////////////////////////////////
//
// Private variables
//
/////////////////////////////////////////////////////////////////////////////
/**
* Internal class variable to index multiple DataSource instances.
*
* @property DataSource._nIndex
* @type Number
* @private
* @static
*/
/**
* Internal class variable to assign unique transaction IDs.
*
* @property DataSource._nTransactionId
* @type Number
* @private
* @static
*/
/**
* Name of DataSource instance.
*
* @property _sName
* @type String
* @private
*/
/**
* Local cache of data result object literals indexed chronologically.
*
* @property _aCache
* @type Object[]
* @private
*/
/**
* Local queue of request connections, enabled if queue needs to be managed.
*
* @property _oQueue
* @type Object
* @private
*/
/////////////////////////////////////////////////////////////////////////////
//
// Private methods
//
/////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////
//
// Public member variables
//
/////////////////////////////////////////////////////////////////////////////
/**
* Max size of the local cache. Set to 0 to turn off caching. Caching is
* useful to reduce the number of server connections. Recommended only for data
* sources that return comprehensive results for queries or when stale data is
* not an issue.
*
* @property maxCacheEntries
* @type Number
* @default 0
*/
/**
* Pointer to live database.
*
* @property liveData
* @type Object
*/
/**
* Where the live data is held.
*
* @property dataType
* @type Number
* @default YAHOO.util.DataSource.TYPE_UNKNOWN
*
*/
/**
* Format of response.
*
* @property responseType
* @type Number
* @default YAHOO.util.DataSource.TYPE_UNKNOWN
*/
/**
* Response schema object literal takes a combination of the following properties:
*
* <dl>
* <dt>resultsList</dt> <dd>Pointer to array of tabular data</dd>
* <dt>resultNode</dt> <dd>Pointer to node name of row data (XML data only)</dd>
* <dt>recordDelim</dt> <dd>Record delimiter (text data only)</dd>
* <dt>fieldDelim</dt> <dd>Field delimiter (text data only)</dd>
* <dt>fields</dt> <dd>Array of field names (aka keys), or array of object literals
* such as: {key:"fieldname",parser:YAHOO.util.DataSource.parseDate}</dd>
* </dl>
*
* @property responseSchema
* @type Object
*/
/**
* Alias to YUI Connection Manager. Allows implementers to specify their own
* subclasses of the YUI Connection Manager utility.
*
* @property connMgr
* @type Object
* @default YAHOO.util.Connect
*/
/**
* If data is accessed over XHR via Connection Manager, this setting defines
* <dl>
* <dt>queueRequests</dt>
* <dd>If a request is already in progress, wait until response is returned
* before sending the next request.</dd>
*
* <dt>cancelStaleRequests</dt>
* <dd>If a request is already in progress, cancel it before sending the next
* request.</dd>
*
* <dt>ignoreStaleResponses</dt>
* <dd>Send all requests, but handle only the response for the most recently
* sent request.</dd>
*
* <dt>allowAll</dt>
* <dd>Send all requests and handle all responses.</dd>
*
* </dl>
*
* @property connXhrMode
* @type String
* @default "allowAll"
*/
/**
* If data is accessed over XHR via Connection Manager, true if data should be
* sent via POST, otherwise data will be sent via GET.
*
* @property connMethodPost
* @type Boolean
* @default false
*/
/**
* If data is accessed over XHR via Connection Manager, the connection timeout
* defines how many milliseconds the XHR connection will wait for a server
* response. Any non-zero value will enable the Connection utility's
* Auto-Abort feature.
*
* @property connTimeout
* @type Number
* @default 0
*/
/////////////////////////////////////////////////////////////////////////////
//
// Public static methods
//
/////////////////////////////////////////////////////////////////////////////
/**
* Converts data to type String.
*
* @method DataSource.parseString
* @param oData {String | Number | Boolean | Date | Array | Object} Data to parse.
* The special values null and undefined will return null.
* @return {Number} A string, or null.
* @static
*/
// Special case null and undefined
return null;
}
//Convert to string
// Validate
return string;
}
else {
YAHOO.log("Could not convert data " + YAHOO.lang.dump(oData) + " to type String", "warn", this.toString());
return null;
}
};
/**
* Converts data to type Number.
*
* @method DataSource.parseNumber
* @param oData {String | Number | Boolean | Null} Data to convert. Beware, null
* returns as 0.
* @return {Number} A number, or null if NaN.
* @static
*/
//Convert to number
// Validate
return number;
}
else {
YAHOO.log("Could not convert data " + YAHOO.lang.dump(oData) + " to type Number", "warn", this.toString());
return null;
}
};
// Backward compatibility
" deprecated in favor of YAHOO.util.DataSource.parseNumber()", "warn",
this.toString());
};
/**
* Converts data to type Date.
*
* @method DataSource.parseDate
* @param oData {Date | String | Number} Data to convert.
* @return {Date} A Date instance.
* @static
*/
var date = null;
//Convert to date
if(!(oData instanceof Date)) {
}
else {
return oData;
}
// Validate
if(date instanceof Date) {
return date;
}
else {
YAHOO.log("Could not convert data " + YAHOO.lang.dump(oData) + " to type Date", "warn", this.toString());
return null;
}
};
// Backward compatibility
" deprecated in favor of YAHOO.util.DataSource.parseDate()", "warn",
this.toString());
};
/////////////////////////////////////////////////////////////////////////////
//
// Public methods
//
/////////////////////////////////////////////////////////////////////////////
/**
* Public accessor to the unique name of the DataSource instance.
*
* @method toString
* @return {String} Unique name of the DataSource instance.
*/
return this._sName;
};
/**
* Overridable method passes request to cache and returns cached response if any,
* refreshing the hit in the cache as the newest item. Returns null if there is
* no cache hit.
*
* @method getCachedResponse
* @param oRequest {Object} Request object.
* @param oCallback {Function} Handler function to receive the response.
* @param oCaller {Object} The Calling object that is making the request.
* @return {Object} Cached response object or null.
*/
var oResponse = null;
// If cache is enabled...
// Loop through each cached element
var oCacheElem = aCache[i];
// Defer cache hit logic to a public overridable method
// Grab the cached response
// The cache returned a hit!
// Remove element from its original location
// Add as newest
this.fireEvent("cacheResponseEvent", {request:oRequest,response:oResponse,callback:oCallback,caller:oCaller});
break;
}
}
}
return oResponse;
};
/**
* Default overridable method matches given request to given cached request.
* Returns true if is a hit, returns false otherwise. Implementers should
* override this method to customize the cache-matching algorithm.
*
* @method isCacheHit
* @param oRequest {Object} Request object.
* @param oCachedRequest {Object} Cached request object.
* @return {Boolean} True if given request matches cached request, false otherwise.
*/
return (oRequest === oCachedRequest);
};
/**
* Adds a new item to the cache. If cache is full, evicts the stalest item
* before adding the new item.
*
* @method addToCache
* @param oRequest {Object} Request object.
* @param oResponse {Object} Response object to cache.
*/
if(!aCache) {
return;
}
//TODO: check for duplicate entries
// If the cache is full, make room by removing stalest element (index=0)
}
// Add to cache in the newest position, at the end of the array
};
/**
* Flushes cache.
*
* @method flushCache
*/
if(this._aCache) {
this._aCache = [];
this.fireEvent("cacheFlushEvent");
}
};
/**
* First looks for cached response, then sends request to live data.
*
* @method sendRequest
* @param oRequest {Object} Request object.
* @param oCallback {Function} Handler function to receive the response.
* @param oCaller {Object} The Calling object that is making the request.
* @return {Number} Transaction ID, or null if response found in cache.
*/
// First look in cache
if(oCachedResponse) {
return null;
}
// Not in cache, so forward request to live data
};
/**
* Overridable method provides default functionality to make a connection to
* live data in order to send request. The response coming back is then
* forwarded to the handleResponse function. This method should be customized
* to achieve more complex implementations.
*
* @method makeConnection
* @param oRequest {Object} Request object.
* @param oCallback {Function} Handler function to receive the response.
* @param oCaller {Object} The Calling object that is making the request.
* @return {Number} Transaction ID.
*/
var oRawResponse = null;
// How to make the connection depends on the type of data
switch(this.dataType) {
// If the live data is a JavaScript Function
// pass the request in as a parameter and
// forward the return value to the handler
break;
// If the live data is over Connection Manager
// set up the callback object and
// pass the request in as a URL query and
// forward the response to the handler
var oSelf = this;
/**
* Define Connection Manager success handler
*
* @method _xhrSuccess
* @param oResponse {Object} HTTPXMLRequest object
* @private
*/
var _xhrSuccess = function(oResponse) {
// If response ID does not match last made request ID,
// silently fail and wait for the next response
return null;
}
// Error if no response
else if(!oResponse) {
// Send error response back to the caller with the error flag on
return null;
}
// Forward to handler
else {
}
};
/**
* Define Connection Manager failure handler
*
* @method _xhrFailure
* @param oResponse {Object} HTTPXMLRequest object
* @private
*/
var _xhrFailure = function(oResponse) {
// Backward compatibility
" between the host and query parameters" +
}
// Send failure response back to the caller with the error flag on
return null;
};
/**
* Define Connection Manager callback object
*
* @property _xhrCallback
* @param oResponse {Object} HTTPXMLRequest object
* @private
*/
var _xhrCallback = {
scope: this
};
// Apply Connection Manager timeout
}
// Cancel stale requests
if(this.connXhrMode == "cancelStaleRequests") {
// Look in queue for stale requests
}
else {
}
}
}
// Get ready to send the request URL
var isPost = this.connMethodPost;
// Send the request right away
if(this.connXhrMode != "queueRequests") {
}
// Queue up then send the request
else {
// Found a request already in progress
// Add request to queue
// Interval needs to be started
// Connection is in progress
return;
}
else {
// Send next request
// Remove request from queue
}
// No more requests
else {
}
}
}, 50);
}
}
// Nothing is in progress
else {
}
}
}
else {
// Send null response back to the caller with the error flag on
}
break;
// Simply forward the entire data object to the handler
default:
/* accounts for the following cases:
YAHOO.util.DataSource.TYPE_UNKNOWN:
YAHOO.util.DataSource.TYPE_JSARRAY:
YAHOO.util.DataSource.TYPE_JSON:
YAHOO.util.DataSource.TYPE_HTMLTABLE:
YAHOO.util.DataSource.TYPE_XML:
*/
oRawResponse = this.liveData;
break;
}
return tId;
};
/**
* Handles raw data response from live data source. Sends a parsed response object
* to the callback function in this format:
*
* fnCallback(oRequest, oParsedResponse)
*
* where the oParsedResponse object literal with the following properties:
* <ul>
* <li>tId {Number} Unique transaction ID</li>
* <li>results {Array} Array of parsed data results</li>
* <li>error {Boolean} True if there was an error</li>
* </ul>
*
* @method handleResponse
* @param oRequest {Object} Request object
* @param oRawResponse {Object} The raw response from the live database.
* @param oCallback {Function} Handler function to receive the response.
* @param oCaller {Object} The calling object that is making the request.
* @param tId {Number} Transaction ID.
*/
YAHOO.util.DataSource.prototype.handleResponse = function(oRequest, oRawResponse, oCallback, oCaller, tId) {
var oParsedResponse = null;
var bError = false;
// Access to the raw response before it gets parsed
switch(this.responseType) {
}
break;
}
break;
}
break;
}
break;
}
break;
default:
//var contentType = oRawResponse.getResponseHeader["Content-Type"];
break;
}
if(oParsedResponse) {
// Last chance to touch the raw response or the parsed response
// Cache the response
}
else {
// Send response back to the caller with the error flag on
oParsedResponse = {error:true};
}
// Send the response back to the caller
};
/**
* Overridable method gives implementers access to the original raw response
* before the data gets parsed. Implementers should take care not to return an
* unparsable or otherwise invalid raw response.
*
* @method doBeforeParseData
* @param oRequest {Object} Request object.
* @param oRawResponse {Object} The raw response from the live database.
* @return {Object} Raw response for parsing.
*/
return oRawResponse;
};
/**
* Overridable method gives implementers access to the original raw response and
* the parsed response (parsed against the given schema) before the data
* is added to the cache (if applicable) and then sent back to callback function.
* response with any custom data.
*
* @method doBeforeCallback
* @param oRequest {Object} Request object.
* @param oRawResponse {Object} The raw response from the live database.
* @param oParsedResponse {Object} The parsed response to return to calling object.
* @return {Object} Parsed response object.
*/
YAHOO.util.DataSource.prototype.doBeforeCallback = function(oRequest, oRawResponse, oParsedResponse) {
return oParsedResponse;
};
/**
* Overridable method parses raw array data into a response object.
*
* @method parseArrayData
* @param oRequest {Object} Request object.
* @param oRawResponse {Object} The raw response from the live database.
* @return {Object} Parsed response object.
*/
var oParsedResponse = {results:[]};
var oResult = {};
// Backward compatibility
}
}
// Safety measure
data = null;
}
}
}
return oParsedResponse;
}
else {
return null;
}
};
/**
* Overridable method parses raw plain text data into a response object.
*
* @method parseTextData
* @param oRequest {Object} Request object.
* @param oRawResponse {Object} The raw response from the live database.
* @return {Object} Parsed response object.
*/
var oParsedResponse = {};
oParsedResponse.results = [];
// Delete the last line delimiter at the end of the data if it exists
}
// Split along record delimiter to get an array of strings
// Cycle through each record, except the first which contains header info
var oResult = {};
// Split along field delimter to get each data value
// Remove quotation marks from edges, if applicable
var data = fielddataarray[j];
}
}
// Backward compatibility
}
}
// Safety measure
data = null;
}
}
}
}
}
else {
oParsedResponse.error = true;
}
return oParsedResponse;
};
/**
* Overridable method parses raw XML data into a response object.
*
* @method parseXMLData
* @param oRequest {Object} Request object.
* @param oRawResponse {Object} The raw response from the live database.
* @return {Object} Parsed response object.
*/
var bError = false;
var oParsedResponse = {};
null;
bError = true;
}
// Loop through each result
else {
oParsedResponse.results = [];
var oResult = {};
// Loop through each data field in each result using the schema
var data = null;
// Values may be held in an attribute...
if(xmlAttr) {
}
// ...or in a node
else {
}
else {
data = "";
}
}
// Backward compatibility
}
}
// Safety measure
data = null;
}
}
// Capture each array of values into an array of results
}
}
if(bError) {
oParsedResponse.error = true;
}
else {
}
return oParsedResponse;
};
/**
* Overridable method parses raw JSON data into a response object.
*
* @method parseJSONData
* @param oRequest {Object} Request object.
* @param oRawResponse {Object} The raw response from the live database.
* @return {Object} Parsed response object.
*/
var oParsedResponse = {};
var bError = false;
oParsedResponse.results = [];
// Parse JSON object out if it's a string
// Check for latest JSON lib but divert KHTML clients
// Use the new JSON utility if available
if(!jsonObj) {
bError = true;
}
}
// Check for older JSON lib but divert KHTML clients
// Use the JSON utility if available
if(!jsonObj) {
bError = true;
}
}
// No JSON lib found so parse the string
else {
try {
// Trim leading spaces
}
// Strip extraneous stuff at the end
// Turn the string into an object literal...
// ...eval is necessary here
if(!jsonObj) {
bError = true;
}
}
else {
jsonObj = null;
bError = true;
}
}
catch(e) {
bError = true;
}
}
}
// Response must already be a JSON object
else if(oRawResponse.constructor == Object) {
}
// Not a string or an object
else {
bError = true;
}
// Now that we have a JSON object, parse a jsonList out of it
try {
// eval is necessary here since schema can be of unknown depth
}
catch(e) {
bError = true;
}
}
oParsedResponse.error = true;
}
}
else if(!jsonList) {
jsonList = [];
}
// Loop through the array of all responses...
var oResult = {};
var jsonResult = jsonList[i];
// ...and loop through each data field value of each response
// ...and capture data into an array mapped according to the schema...
// eval is necessary here since schema can be of unknown depth
//YAHOO.log("data: " + i + " value:" +j+" = "+dataFieldValue,"debug",this.toString());
// Backward compatibility
}
}
// Safety measure
data = null;
}
}
// Capture the array of data field values in an array of results
}
}
else {
oParsedResponse.error = true;
}
return oParsedResponse;
};
/**
* Overridable method parses raw HTML TABLE element data into a response object.
*
* @method parseHTMLTableData
* @param oRequest {Object} Request object.
* @param oRawResponse {Object} The raw response from the live database.
* @return {Object} Parsed response object.
*/
var bError = false;
var elTable = oRawResponse;
var oParsedResponse = {};
oParsedResponse.results = [];
// Iterate through each TBODY
// Iterate through each TR
var oResult = {};
// Backward compatibility
}
}
// Safety measure
data = null;
}
}
}
}
if(bError) {
oParsedResponse.error = true;
}
else {
}
return oParsedResponse;
};