src/cm/media/js/lib/yui/yui3-3.15.0/build/dataschema-xml/dataschema-xml-debug.js
changeset 602 e16a97fb364a
equal deleted inserted replaced
601:d334a616c023 602:e16a97fb364a
       
     1 YUI.add('dataschema-xml', function (Y, NAME) {
       
     2 
       
     3 /**
       
     4 Provides a DataSchema implementation which can be used to work with XML data.
       
     5 
       
     6 @module dataschema
       
     7 @submodule dataschema-xml
       
     8 **/
       
     9 
       
    10 /**
       
    11 Provides a DataSchema implementation which can be used to work with XML data.
       
    12 
       
    13 See the `apply` method for usage.
       
    14 
       
    15 @class DataSchema.XML
       
    16 @extends DataSchema.Base
       
    17 @static
       
    18 **/
       
    19 var Lang = Y.Lang,
       
    20 
       
    21     okNodeType = {
       
    22         1 : true,
       
    23         9 : true,
       
    24         11: true
       
    25     },
       
    26 
       
    27     SchemaXML;
       
    28 
       
    29 SchemaXML = {
       
    30 
       
    31     ////////////////////////////////////////////////////////////////////////////
       
    32     //
       
    33     // DataSchema.XML static methods
       
    34     //
       
    35     ////////////////////////////////////////////////////////////////////////////
       
    36     /**
       
    37     Applies a schema to an XML data tree, returning a normalized object with
       
    38     results in the `results` property. Additional information can be parsed out
       
    39     of the XML for inclusion in the `meta` property of the response object.  If
       
    40     an error is encountered during processing, an `error` property will be
       
    41     added.
       
    42 
       
    43     Field data in the nodes captured by the XPath in _schema.resultListLocator_
       
    44     is extracted with the field identifiers described in _schema.resultFields_.
       
    45     Field identifiers are objects with the following properties:
       
    46 
       
    47       * `key`    : <strong>(required)</strong> The desired property name to use
       
    48             store the retrieved value in the result object.  If `locator` is
       
    49             not specified, `key` is also used as the XPath locator (String)
       
    50       * `locator`: The XPath locator to the node or attribute within each
       
    51             result node found by _schema.resultListLocator_ containing the
       
    52             desired field data (String)
       
    53       * `parser` : A function or the name of a function on `Y.Parsers` used
       
    54             to convert the input value into a normalized type.  Parser
       
    55             functions are passed the value as input and are expected to
       
    56             return a value.
       
    57       * `schema` : Used to retrieve nested field data into an array for
       
    58             assignment as the result field value.  This object follows the same
       
    59             conventions as _schema_.
       
    60 
       
    61     If no value parsing or nested parsing is needed, you can use XPath locators
       
    62     (strings) instead of field identifiers (objects) -- see example below.
       
    63 
       
    64     `response.results` will contain an array of objects with key:value pairs.
       
    65     The keys are the field identifier `key`s, and the values are the data
       
    66     values extracted from the nodes or attributes found by the field `locator`
       
    67     (or `key` fallback).
       
    68 
       
    69     To extract additional information from the XML, include an array of
       
    70     XPath locators in _schema.metaFields_.  The collected values will be
       
    71     stored in `response.meta` with the XPath locator as keys.
       
    72 
       
    73     @example
       
    74         var schema = {
       
    75                 resultListLocator: '//produce/item',
       
    76                 resultFields: [
       
    77                     {
       
    78                         locator: 'name',
       
    79                         key: 'name'
       
    80                     },
       
    81                     {
       
    82                         locator: 'color',
       
    83                         key: 'color',
       
    84                         parser: function (val) { return val.toUpperCase(); }
       
    85                     }
       
    86                 ]
       
    87             };
       
    88 
       
    89         // Assumes data like
       
    90         // <inventory>
       
    91         //   <produce>
       
    92         //     <item><name>Banana</name><color>yellow</color></item>
       
    93         //     <item><name>Orange</name><color>orange</color></item>
       
    94         //     <item><name>Eggplant</name><color>purple</color></item>
       
    95         //   </produce>
       
    96         // </inventory>
       
    97 
       
    98         var response = Y.DataSchema.JSON.apply(schema, data);
       
    99 
       
   100         // response.results[0] is { name: "Banana", color: "YELLOW" }
       
   101 
       
   102     @method apply
       
   103     @param {Object} schema Schema to apply.  Supported configuration
       
   104         properties are:
       
   105       @param {String} [schema.resultListLocator] XPath locator for the
       
   106           XML nodes that contain the data to flatten into `response.results`
       
   107       @param {Array} [schema.resultFields] Field identifiers to
       
   108           locate/assign values in the response records. See above for
       
   109           details.
       
   110       @param {Array} [schema.metaFields] XPath locators to extract extra
       
   111           non-record related information from the XML data
       
   112     @param {XMLDocument} data XML data to parse
       
   113     @return {Object} An Object with properties `results` and `meta`
       
   114     @static
       
   115     **/
       
   116     apply: function(schema, data) {
       
   117         var xmldoc = data, // unnecessary variables
       
   118             data_out = { results: [], meta: {} };
       
   119 
       
   120         if (xmldoc && okNodeType[xmldoc.nodeType] && schema) {
       
   121             // Parse results data
       
   122             data_out = SchemaXML._parseResults(schema, xmldoc, data_out);
       
   123 
       
   124             // Parse meta data
       
   125             data_out = SchemaXML._parseMeta(schema.metaFields, xmldoc, data_out);
       
   126         } else {
       
   127             Y.log("XML data could not be schema-parsed: " + Y.dump(data) + " " + Y.dump(data), "error", "dataschema-xml");
       
   128             data_out.error = new Error("XML schema parse failure");
       
   129         }
       
   130 
       
   131         return data_out;
       
   132     },
       
   133 
       
   134     /**
       
   135      * Get an XPath-specified value for a given field from an XML node or document.
       
   136      *
       
   137      * @method _getLocationValue
       
   138      * @param field {String | Object} Field definition.
       
   139      * @param context {Object} XML node or document to search within.
       
   140      * @return {Object} Data value or null.
       
   141      * @static
       
   142      * @protected
       
   143      */
       
   144     _getLocationValue: function(field, context) {
       
   145         var locator = field.locator || field.key || field,
       
   146             xmldoc = context.ownerDocument || context,
       
   147             result, res, value = null;
       
   148 
       
   149         try {
       
   150             result = SchemaXML._getXPathResult(locator, context, xmldoc);
       
   151             while ((res = result.iterateNext())) {
       
   152                 value = res.textContent || res.value || res.text || res.innerHTML || res.innerText || null;
       
   153             }
       
   154 
       
   155             // FIXME: Why defer to a method that is mixed into this object?
       
   156             // DSchema.Base is mixed into DSchema.XML (et al), so
       
   157             // DSchema.XML.parse(...) will work.  This supports the use case
       
   158             // where DSchema.Base.parse is changed, and that change is then
       
   159             // seen by all DSchema.* implementations, but does not support the
       
   160             // case where redefining DSchema.XML.parse changes behavior. In
       
   161             // fact, DSchema.XML.parse is never even called.
       
   162             return Y.DataSchema.Base.parse.call(this, value, field);
       
   163         } catch (e) {
       
   164             Y.log('SchemaXML._getLocationValue failed: ' + e.message);
       
   165         }
       
   166 
       
   167         return null;
       
   168     },
       
   169 
       
   170     /**
       
   171      * Fetches the XPath-specified result for a given location in an XML node
       
   172      * or document.
       
   173      *
       
   174      * @method _getXPathResult
       
   175      * @param locator {String} The XPath location.
       
   176      * @param context {Object} XML node or document to search within.
       
   177      * @param xmldoc {Object} XML document to resolve namespace.
       
   178      * @return {Object} Data collection or null.
       
   179      * @static
       
   180      * @protected
       
   181      */
       
   182     _getXPathResult: function(locator, context, xmldoc) {
       
   183         // Standards mode
       
   184         if (! Lang.isUndefined(xmldoc.evaluate)) {
       
   185             return xmldoc.evaluate(locator, context, xmldoc.createNSResolver(context.ownerDocument ? context.ownerDocument.documentElement : context.documentElement), 0, null);
       
   186 
       
   187         }
       
   188         // IE mode
       
   189         else {
       
   190             var values=[], locatorArray = locator.split(/\b\/\b/), i=0, l=locatorArray.length, location, subloc, m, isNth;
       
   191 
       
   192             // XPath is supported
       
   193             try {
       
   194                 // this fixes the IE 5.5+ issue where childnode selectors begin at 0 instead of 1
       
   195                 try {
       
   196                    xmldoc.setProperty("SelectionLanguage", "XPath");
       
   197                 } catch (e) {}
       
   198 
       
   199                 values = context.selectNodes(locator);
       
   200             }
       
   201             // Fallback for DOM nodes and fragments
       
   202             catch (e) {
       
   203                 // Iterate over each locator piece
       
   204                 for (; i<l && context; i++) {
       
   205                     location = locatorArray[i];
       
   206 
       
   207                     // grab nth child []
       
   208                     if ((location.indexOf("[") > -1) && (location.indexOf("]") > -1)) {
       
   209                         subloc = location.slice(location.indexOf("[")+1, location.indexOf("]"));
       
   210                         //XPath is 1-based while DOM is 0-based
       
   211                         subloc--;
       
   212                         context = context.children[subloc];
       
   213                         isNth = true;
       
   214                     }
       
   215                     // grab attribute value @
       
   216                     else if (location.indexOf("@") > -1) {
       
   217                         subloc = location.substr(location.indexOf("@"));
       
   218                         context = subloc ? context.getAttribute(subloc.replace('@', '')) : context;
       
   219                     }
       
   220                     // grab that last instance of tagName
       
   221                     else if (-1 < location.indexOf("//")) {
       
   222                         subloc = context.getElementsByTagName(location.substr(2));
       
   223                         context = subloc.length ? subloc[subloc.length - 1] : null;
       
   224                     }
       
   225                     // find the last matching location in children
       
   226                     else if (l != i + 1) {
       
   227                         for (m=context.childNodes.length-1; 0 <= m; m-=1) {
       
   228                             if (location === context.childNodes[m].tagName) {
       
   229                                 context = context.childNodes[m];
       
   230                                 m = -1;
       
   231                             }
       
   232                         }
       
   233                     }
       
   234                 }
       
   235 
       
   236                 if (context) {
       
   237                     // attribute
       
   238                     if (Lang.isString(context)) {
       
   239                         values[0] = {value: context};
       
   240                     }
       
   241                     // nth child
       
   242                     else if (isNth) {
       
   243                         values[0] = {value: context.innerHTML};
       
   244                     }
       
   245                     // all children
       
   246                     else {
       
   247                         values = Y.Array(context.childNodes, 0, true);
       
   248                     }
       
   249                 }
       
   250             }
       
   251 
       
   252             // returning a mock-standard object for IE
       
   253             return {
       
   254                 index: 0,
       
   255 
       
   256                 iterateNext: function() {
       
   257                     if (this.index >= this.values.length) {return undefined;}
       
   258                     var result = this.values[this.index];
       
   259                     this.index += 1;
       
   260                     return result;
       
   261                 },
       
   262 
       
   263                 values: values
       
   264             };
       
   265         }
       
   266     },
       
   267 
       
   268     /**
       
   269      * Schema-parsed result field.
       
   270      *
       
   271      * @method _parseField
       
   272      * @param field {String | Object} Required. Field definition.
       
   273      * @param result {Object} Required. Schema parsed data object.
       
   274      * @param context {Object} Required. XML node or document to search within.
       
   275      * @static
       
   276      * @protected
       
   277      */
       
   278     _parseField: function(field, result, context) {
       
   279         var key = field.key || field,
       
   280             parsed;
       
   281 
       
   282         if (field.schema) {
       
   283             parsed = { results: [], meta: {} };
       
   284             parsed = SchemaXML._parseResults(field.schema, context, parsed);
       
   285 
       
   286             result[key] = parsed.results;
       
   287         } else {
       
   288             result[key] = SchemaXML._getLocationValue(field, context);
       
   289         }
       
   290     },
       
   291 
       
   292     /**
       
   293      * Parses results data according to schema
       
   294      *
       
   295      * @method _parseMeta
       
   296      * @param xmldoc_in {Object} XML document parse.
       
   297      * @param data_out {Object} In-progress schema-parsed data to update.
       
   298      * @return {Object} Schema-parsed data.
       
   299      * @static
       
   300      * @protected
       
   301      */
       
   302     _parseMeta: function(metaFields, xmldoc_in, data_out) {
       
   303         if(Lang.isObject(metaFields)) {
       
   304             var key,
       
   305                 xmldoc = xmldoc_in.ownerDocument || xmldoc_in;
       
   306 
       
   307             for(key in metaFields) {
       
   308                 if (metaFields.hasOwnProperty(key)) {
       
   309                     data_out.meta[key] = SchemaXML._getLocationValue(metaFields[key], xmldoc);
       
   310                 }
       
   311             }
       
   312         }
       
   313         return data_out;
       
   314     },
       
   315 
       
   316     /**
       
   317      * Schema-parsed result to add to results list.
       
   318      *
       
   319      * @method _parseResult
       
   320      * @param fields {Array} Required. A collection of field definition.
       
   321      * @param context {Object} Required. XML node or document to search within.
       
   322      * @return {Object} Schema-parsed data.
       
   323      * @static
       
   324      * @protected
       
   325      */
       
   326     _parseResult: function(fields, context) {
       
   327         var result = {}, j;
       
   328 
       
   329         // Find each field value
       
   330         for (j=fields.length-1; 0 <= j; j--) {
       
   331             SchemaXML._parseField(fields[j], result, context);
       
   332         }
       
   333 
       
   334         return result;
       
   335     },
       
   336 
       
   337     /**
       
   338      * Schema-parsed list of results from full data
       
   339      *
       
   340      * @method _parseResults
       
   341      * @param schema {Object} Schema to parse against.
       
   342      * @param context {Object} XML node or document to parse.
       
   343      * @param data_out {Object} In-progress schema-parsed data to update.
       
   344      * @return {Object} Schema-parsed data.
       
   345      * @static
       
   346      * @protected
       
   347      */
       
   348     _parseResults: function(schema, context, data_out) {
       
   349         if (schema.resultListLocator && Lang.isArray(schema.resultFields)) {
       
   350             var xmldoc = context.ownerDocument || context,
       
   351                 fields = schema.resultFields,
       
   352                 results = [],
       
   353                 node, nodeList, i=0;
       
   354 
       
   355             if (schema.resultListLocator.match(/^[:\-\w]+$/)) {
       
   356                 nodeList = context.getElementsByTagName(schema.resultListLocator);
       
   357 
       
   358                 // loop through each result node
       
   359                 for (i = nodeList.length - 1; i >= 0; --i) {
       
   360                     results[i] = SchemaXML._parseResult(fields, nodeList[i]);
       
   361                 }
       
   362             } else {
       
   363                 nodeList = SchemaXML._getXPathResult(schema.resultListLocator, context, xmldoc);
       
   364 
       
   365                 // loop through the nodelist
       
   366                 while ((node = nodeList.iterateNext())) {
       
   367                     results[i] = SchemaXML._parseResult(fields, node);
       
   368                     i += 1;
       
   369                 }
       
   370             }
       
   371 
       
   372             if (results.length) {
       
   373                 data_out.results = results;
       
   374             } else {
       
   375                 data_out.error = new Error("XML schema result nodes retrieval failure");
       
   376             }
       
   377         }
       
   378         return data_out;
       
   379     }
       
   380 };
       
   381 
       
   382 Y.DataSchema.XML = Y.mix(SchemaXML, Y.DataSchema.Base);
       
   383 
       
   384 
       
   385 }, '@VERSION@', {"requires": ["dataschema-base"]});