~andreserl/maas/packaging_precise_rebase

« back to all changes in this revision

Viewing changes to debian/extras/jslibs/yui/dataschema-xml/dataschema-xml-debug.js

  • Committer: Andres Rodriguez
  • Date: 2013-03-20 18:12:30 UTC
  • mfrom: (145.2.22 precise.sru)
  • Revision ID: andreserl@ubuntu.com-20130320181230-6l5guc0nhlv2z4p7
Re-base againts latest quantal released branch towards SRU

Show diffs side-by-side

added added

removed removed

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