source: contrib/MailArchiver/sources/src/serpro/mailarchiver/config/webroot/arcservutil/cxf-addon-cors-utils.js @ 6785

Revision 6785, 33.7 KB checked in by rafaelraymundo, 12 years ago (diff)

Ticket #2946 - Liberado codigo do MailArchiver?. Documentação na subpasta DOCS.

Line 
1<!--
2/**
3 * Licensed to the Apache Software Foundation (ASF) under one or more
4 * contributor license agreements. See the NOTICE file distributed with this
5 * work for additional information regarding copyright ownership. The ASF
6 * licenses this file to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 * License for the specific language governing permissions and limitations under
16 * the License.
17 */
18
19// This code is structured on to require a 'new' of an object of type
20// CxfApacheOrgUtil.
21// Alternative, it could be made 'static', but this allowed us to use this same
22// object to carry some state.
23var org_apache_cxf_XSI_namespace_uri = "http://www.w3.org/2001/XMLSchema-instance";
24var org_apache_cxf_XSD_namespace_uri = "http://www.w3.org/2001/XMLSchema";
25
26function cxf_apache_org_util_null_trace(message) {
27}
28
29function org_apache_cxf_trace(str){
30    this.trace = str;
31    window.alert(this.trace);
32}
33
34function CxfApacheOrgUtil() {
35        // Set up tracing if there is a trace object.
36        //if ("function" == typeof(org_apache_cxf_trace)) {
37        //      this.trace = org_apache_cxf_trace.trace;
38        //      this.trace("Javascript tracing enabled.");
39        //} else {
40                this.trace = cxf_apache_org_util_null_trace;
41        //}
42}
43
44// define a constant for the DOM node type for an element.
45CxfApacheOrgUtil.prototype.ELEMENT_NODE = 1;
46
47// compensate for Microsoft's weakness here.
48function org_apache_cxf_getNodeLocalName(node) {
49        if ("localName" in node) {
50                return node.localName;
51        } else {
52                return node.baseName;
53        }
54}
55
56CxfApacheOrgUtil.prototype.getNodeLocalName = org_apache_cxf_getNodeLocalName;
57
58// compensate for lack of namespace support in IE.
59function org_apache_cxf_getNamespaceURI(elementNode, namespacePrefix) {
60        var namespaceURI = null;
61        if (elementNode.nodeType == 9)
62                return null;
63        else {
64                namespaceURI = org_apache_cxf_findNamespace(elementNode,
65                                namespacePrefix);
66                if (namespaceURI == null)
67                        namespaceURI = org_apache_cxf_getNamespaceURI(
68                                        elementNode.parentNode, namespacePrefix);
69                else
70                        return namespaceURI;
71        }
72        return namespaceURI;
73}
74
75// Search through the attributes of one node to find a namespace prefix definition.
76function org_apache_cxf_findNamespace(elementNode, namespacePrefix) {
77        var attributes = elementNode.attributes;
78        if ((attributes != null) && (attributes.length > 0)) {
79                for (var x = 0;x < attributes.length; x++) {
80                        var attributeNodeName = attributes.item(x).nodeName;
81                        var attributeNamespacePrefix = org_apache_cxf_getPrefix(attributes
82                                        .item(x).nodeName);
83                        var attributeNamespaceSuffix = org_apache_cxf_getLocalName(attributes
84                                        .item(x).nodeName);
85
86                        if ((namespacePrefix == null) && (attributeNamespacePrefix == null)
87                                        && (attributeNamespaceSuffix == "xmlns"))
88                                return attributes.item(x).nodeValue;
89                        else if ((attributeNamespacePrefix == "xmlns")
90                                        && (attributeNamespaceSuffix == namespacePrefix))
91                                return attributes.item(x).nodeValue;
92                }
93                return null;
94        }
95}
96
97// Get namespace for a node.
98function org_apache_cxf_get_node_namespaceURI(elementNode) {
99        var prefix = org_apache_cxf_getPrefix(elementNode.nodeName);
100        return org_apache_cxf_getNamespaceURI(elementNode, prefix);
101}
102
103CxfApacheOrgUtil.prototype.getElementNamespaceURI = org_apache_cxf_get_node_namespaceURI;
104
105// Supprt functions for xsd:any start here.
106
107// Object that can test an element against an 'any' specification.
108function org_apache_cxf_any_ns_matcher(style, tns, nslist, nextLocalPart) {
109        this.style = style;
110        this.tns = tns;
111        this.nslist = nslist;
112        this.nextLocalPart = nextLocalPart;
113}
114
115org_apache_cxf_any_ns_matcher.ANY = "##any";
116org_apache_cxf_any_ns_matcher.OTHER = "##other";
117org_apache_cxf_any_ns_matcher.LOCAL = "##local";
118org_apache_cxf_any_ns_matcher.LISTED = "listed";
119
120function org_apache_cxf_any_ns_matcher_match(namespaceURI, localName) {
121        switch (this.style) {
122                // should this match local elements?
123                case org_apache_cxf_any_ns_matcher.ANY :
124                        return true;
125                case org_apache_cxf_any_ns_matcher.OTHER :
126                        return namespaceURI != this.tns;
127                case org_apache_cxf_any_ns_matcher.LOCAL :
128                        return namespaceURI == null || namespaceURI == '';
129                case org_apache_cxf_any_ns_matcher.LISTED :
130                        for (var x in this.nslist) {
131                                var ns = this.nslist[x];
132                                if (ns == "##local") {
133                                        if ((namespaceURI == null || namespaceURI == '')
134                                                        && (this.nextLocalPart != null && localName != this.nextLocalPart))
135                                                return true;
136                                } else {
137                                        if (ns == namespaceURI)
138                                                return true;
139                                }
140                        }
141                        return false;
142        }
143}
144
145org_apache_cxf_any_ns_matcher.prototype.match = org_apache_cxf_any_ns_matcher_match;
146
147function org_apache_cxf_getPrefix(tagName) {
148        var prefix;
149        var prefixIndex = tagName.indexOf(":");
150        if (prefixIndex == -1)
151                return null;
152        else
153                return prefix = tagName.substring(0, prefixIndex);
154}
155
156function org_apache_cxf_getLocalName(tagName) {
157        var suffix;
158        var prefixIndex = tagName.indexOf(":");
159
160        if (prefixIndex == -1)
161                return tagName;
162        else
163                return suffix = tagName.substring(prefixIndex + 1, tagName.length);
164}
165
166function org_apache_cxf_element_name_for_trace(node) {
167        if (node == null)
168                return "Null";
169        else if (node == undefined)
170                return "Undefined";
171        else {
172                var n = '';
173                if (node.namespaceURI != null && node.namespaceURI != '') {
174                        n = n + "{" + node.namespaceURI + "}";
175                }
176                return n + this.getNodeLocalName(node);
177        }
178}
179
180//MA 01 - TRACE ERROR
181CxfApacheOrgUtil.prototype.traceElementName = org_apache_cxf_element_name_for_trace;
182
183function org_apache_cxf_escapeXmlEntities(val) {
184        if (val == null || val == undefined)
185                return "";
186        else {
187                val = String(val);
188                return val.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g,
189                                "&gt;");
190        }
191}
192
193CxfApacheOrgUtil.prototype.escapeXmlEntities = org_apache_cxf_escapeXmlEntities;
194
195// Is an element xsi:nil? Note, in IE this requires the use of the prefix 'xsi', literally.
196function org_apache_cxf_isElementNil(node) {
197        if (node == null)
198                throw "null node passed to isElementNil";
199        // we need to look for an attribute xsi:nil, where xsi is
200        // http://www.w3.org/2001/XMLSchema-instance. we have the usual
201        // problem here with namespace-awareness.
202        if ('function' == typeof node.getAttributeNS) {
203                var nillness = node.getAttributeNS(
204                                "http://www.w3.org/2001/XMLSchema-instance", "nil");
205                return nillness != null && nillness == "true";
206        } else { // we assume the standard prefix and hope for the best.
207                var nillness = node.getAttribute("xsi:nil");
208                return nillness != null && nillness == "true";
209        }
210}
211
212CxfApacheOrgUtil.prototype.isElementNil = org_apache_cxf_isElementNil;
213
214function org_apache_cxf_getFirstElementChild(node) {
215        if (node == undefined)
216                throw "undefined node to getFirstElementChild";
217
218        var n;
219        for (n = node.firstChild;n != null && n.nodeType != this.ELEMENT_NODE; n = n.nextSibling) {
220        }
221
222        return n;
223}
224
225CxfApacheOrgUtil.prototype.getFirstElementChild = org_apache_cxf_getFirstElementChild;
226
227function org_apache_cxf_getNextElementSibling(node) {
228        if (node == undefined)
229                throw "undefined node to getNextElementSibling";
230        if (node == null)
231                throw "null node to getNextElementSibling";
232        var n;
233        for (n = node.nextSibling;n != null && n.nodeType != this.ELEMENT_NODE; n = n.nextSibling);
234        return n;
235}
236
237CxfApacheOrgUtil.prototype.getNextElementSibling = org_apache_cxf_getNextElementSibling;
238
239function org_apache_cxf_isNodeNamedNS(node, namespaceURI, localName) {
240        if (node == undefined)
241                throw "undefined node to isNodeNamedNS";
242
243        if (namespaceURI == '' || namespaceURI == null) {
244                if (node.namespaceURI == '' || node.namespaceURI == null) {
245                        return localName == org_apache_cxf_getNodeLocalName(node);
246                } else
247                        return false;
248        } else {
249                return namespaceURI == node.namespaceURI
250                                && localName == org_apache_cxf_getNodeLocalName(node);
251        }
252}
253
254CxfApacheOrgUtil.prototype.isNodeNamedNS = org_apache_cxf_isNodeNamedNS;
255
256// Firefox splits large text regions into multiple Text objects (4096 chars in
257// each). Glue it back together.
258function org_apache_cxf_getNodeText(node) {
259        var r = "";
260        for (var x = 0;x < node.childNodes.length; x++) {
261                r = r + node.childNodes[x].nodeValue;
262        }
263        return r;
264}
265
266CxfApacheOrgUtil.prototype.getNodeText = org_apache_cxf_getNodeText;
267
268// This always uses soap-env, soap, and xsi as prefixes.
269function org_apache_cxf_begin_soap11_message(namespaceAttributes) {
270        var value = '<?xml version="1.0" encoding="UTF-8"?>'
271                        + '<soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/"'
272                        + ' xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"'
273                        + ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
274                        + '><soap-env:Body ' + namespaceAttributes + '>';
275        return value;
276}
277
278CxfApacheOrgUtil.prototype.beginSoap11Message = org_apache_cxf_begin_soap11_message;
279
280function org_apache_cxf_end_soap11_message() {
281        return '</soap-env:Body></soap-env:Envelope>';
282}
283
284CxfApacheOrgUtil.prototype.endSoap11Message = org_apache_cxf_end_soap11_message;
285
286var org_apache_cxf_base64_keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
287
288function org_apache_cxf_base64_encode64array(input) {
289        var output = "";
290        var chr1, chr2, chr3;
291        var enc1, enc2, enc3, enc4;
292        var i = 0;
293
294        do {
295                var count = 1;
296                chr1 = chr2 = chr3 = 0;
297
298                chr1 = input[i++];
299                if (i < input.length) {
300                        chr2 = input[i++];
301                        count++;
302                }
303
304                if (i < input.length) {
305                        chr3 = input[i++];
306                        count++;
307                }
308
309                enc1 = chr1 >> 2;
310                enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
311                if (count > 1) {
312                        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
313                        if (count > 2)
314                                enc4 = chr3 & 63;
315                        else
316                                enc4 = 64;
317                } else
318                        enc3 = enc4 = 64;
319
320                output = output + org_apache_cxf_base64_keyStr.charAt(enc1)
321                                + org_apache_cxf_base64_keyStr.charAt(enc2)
322                                + org_apache_cxf_base64_keyStr.charAt(enc3)
323                                + org_apache_cxf_base64_keyStr.charAt(enc4);
324        } while (i < input.length);
325
326        return output;
327}
328
329function org_apache_cxf_base64_encode64Unicode(input) {
330        var data = new Array(2 + (input.length * 2));
331        data[0] = 0xff;
332        data[1] = 0xfe;
333        for (var x = 0;x < input.length; x++) {
334                var c = input.charCodeAt(x);
335                data[2 + (x * 2)] = c & 0xff;
336                data[3 + (x * 2)] = (c >> 8) & 0xff;
337        }
338        return encode64array(data);
339}
340
341// we may be able to do this more cleanly with unescape( encodeURIComponent(
342// input ) );
343function org_apache_cxf_base64_encode64UTF8(input) {
344
345        // determine how many bytes are needed for the complete conversion
346        var bytesNeeded = 0;
347        for (var i = 0;i < input.length; i++) {
348                if (input.charCodeAt(i) < 0x80) {
349                        ++bytesNeeded;
350                } else if (input.charCodeAt(i) < 0x0800) {
351                        bytesNeeded += 2;
352                } else if (input.charCodeAt(i) < 0x10000) {
353                        bytesNeeded += 3;
354                } else {
355                        bytesNeeded += 4;
356                }
357        }
358
359        // allocate a byte[] of the necessary size
360        var data = new Array(bytesNeeded);
361        // do the conversion from character code points to utf-8
362        var bytes = 0;
363        for (var i = 0;i < input.length; i++) {
364                if (input.charCodeAt(i) < 0x80) {
365                        data[bytes++] = input.charCodeAt(i);
366                } else if (input.charCodeAt(i) < 0x0800) {
367                        data[bytes++] = ((input.charCodeAt(i) >> 6) | 0xC0);
368                        data[bytes++] = ((input.charCodeAt(i) & 0x3F) | 0x80);
369                } else if (input.charCodeAt(i) < 0x10000) {
370                        data[bytes++] = ((input.charCodeAt(i) >> 12) | 0xE0);
371                        data[bytes++] = (((input.charCodeAt(i) >> 6) & 0x3F) | 0x80);
372                        data[bytes++] = ((input.charCodeAt(i) & 0x3F) | 0x80);
373                } else {
374                        data[bytes++] = ((input.charCodeAt(i) >> 18) | 0xF0);
375                        data[bytes++] = (((input.charCodeAt(i) >> 12) & 0x3F) | 0x80);
376                        data[bytes++] = (((input.charCodeAt(i) >> 6) & 0x3F) | 0x80);
377                        data[bytes++] = ((input.charCodeAt(i) & 0x3F) | 0x80);
378                }
379        }
380        return encode64array(data);
381}
382
383function org_apache_cxf_base64_decode64array(input) {
384        var output = new Array();
385        var chr1, chr2, chr3;
386        var enc1, enc2, enc3, enc4;
387        var i = 0;
388
389        // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
390        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
391
392        do {
393                enc1 = org_apache_cxf_base64_keyStr.indexOf(input.charAt(i++));
394                enc2 = org_apache_cxf_base64_keyStr.indexOf(input.charAt(i++));
395                enc3 = org_apache_cxf_base64_keyStr.indexOf(input.charAt(i++));
396                enc4 = org_apache_cxf_base64_keyStr.indexOf(input.charAt(i++));
397
398                chr1 = (enc1 << 2) | (enc2 >> 4);
399                chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
400                chr3 = ((enc3 & 3) << 6) | enc4;
401
402                output[output.length] = chr1;
403
404                if (enc3 != 64) {
405                        output[output.length] = chr2;
406                }
407                if (enc4 != 64) {
408                        output[output.length] = chr3;
409                }
410        } while (i < input.length);
411
412        return output;
413}
414
415var org_apache_cxf_base64_hD = "0123456789ABCDEF";
416function org_apache_cxf_base64_d2h(d) {
417        var h = org_apache_cxf_base64_hD.substr(d & 15, 1);
418        while (d > 15) {
419                d >>= 4;
420                h = org_apache_cxf_base64_hD.substr(d & 15, 1) + h;
421        }
422        return h;
423}
424
425function org_apache_cxf_base64_decode64Unicode(input) {
426        var bytes = org_apache_cxf_base64_decode64array(input);
427        var swap;
428        var output = "";
429        if (bytes[0] == 0xff && bytes[1] == 0xfe) {
430                swap = true;
431        } else if (bytes[0] == 0xfe && bytes[1] == 0xff) {
432                swap = false;
433        } else {
434                confirm("Problem with decoding utf-16");
435        }
436        for (var x = 2;x < bytes.length; x = x + 2) {
437                var c;
438                if (swap)
439                        c = (bytes[x + 1] << 8) | bytes[x];
440                else
441                        c = (bytes[x] << 8) | bytes[x + 1];
442
443                output = output + String.fromCharCode(c);
444        }
445        return output;
446}
447
448// we may be able to do this more cleanly with decodeURIComponent( escape( input
449// ) );
450function org_apache_cxf_base64_decode64UTF8(input) {
451        var utftext = org_apache_cxf_base64_decode64array(input);
452        var plaintext = "";
453        var cRay = new Array();
454        var i = 0;
455        var c;
456        var c2;
457        var c3;
458        while (i < utftext.length) {
459                c = utftext[i];
460                if (c < 128) {
461                        plaintext += String.fromCharCode(c);
462                        i++;
463                } else if ((c > 191) && (c < 224)) {
464                        c2 = utftext[i + 1];
465                        plaintext += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
466                        i += 2;
467                } else {
468                        c2 = utftext[i + 1];
469                        c3 = utftext[i + 2];
470                        plaintext += String.fromCharCode(((c & 15) << 12)
471                                        | ((c2 & 63) << 6) | (c3 & 63));
472                        i += 3;
473                }
474        }
475        return plaintext;
476}
477
478// MTOM deserialization.
479// This assumes that the only content type it will be asked to deal with is text/plain;charset=utf-8.
480// This only handles cid: xop URNs.
481
482var org_apache_cxf_XOP_NS = 'http://www.w3.org/2004/08/xop/include';
483
484function org_apache_cxf_deserialize_MTOM_or_base64(element) {
485        var elementChild = this.getFirstElementChild(element);
486        if (elementChild == null) { // no MTOM, assume base64
487                var base64Text = this.getNodeText(element);
488                // we assume this is text/plain;charset=utf-8. We could check for the
489                // xmime attribute.
490                return org_apache_cxf_base64_decode64UTF8(base64Text);
491        }
492        //
493        if (!org_apache_cxf_isNodeNamedNS(elementChild, org_apache_cxf_XOP_NS, 'Include')) {
494                this.trace('Invalid child element of base64 element');
495                return ''; // we don't knoww what this is, so we throw it out. We could
496                                        // throw.
497        }
498        var href = elementChild.getAttribute('href');
499        if(!href) {
500                this.trace('missing href for xop:Include');
501                return ''; // we don't knoww what this is, so we throw it out. We could
502                                        // throw.
503        }
504        // we only support cid:, not URLs.
505        if(href.length < 4 || href.substr(0, 4) != 'cid:') {
506                this.trace('Non-cid href in xop:Include: ' + href);
507                return '';
508        }
509        var cid = href.substr(4);
510        var partobject = this.client.parts[cid];
511        if(!partobject) {
512                this.trace('xop:Include href points to missing attachment: ' + href);
513                return '';
514        }
515        // success.
516        return partobject.data;
517}
518
519CxfApacheOrgUtil.prototype.deserializeBase64orMom = org_apache_cxf_deserialize_MTOM_or_base64;
520
521/*
522 * Client object sends requests and calls back with responses.
523 */
524function CxfApacheOrgClient(utils) {
525        utils.trace("Client constructor");
526        this.utils = utils;
527        utils.client = this; // we aren't worried about multithreading!
528        this.mtomparts = [];
529        this.soapAction = "";
530        this.messageType = "CALL";
531        // handler functions
532        this.onsuccess = null;
533        this.onerror = null;
534        // Firefox is noncompliant with respect to the defined constants,
535        // so we define our own.
536        this.READY_STATE_UNINITIALIZED = 0;
537        this.READY_STATE_LOADING = 1;
538        this.READY_STATE_LOADED = 2;
539        this.READY_STATE_INTERACTIVE = 3;
540        this.READY_STATE_DONE = 4;
541}
542
543var org_apache_cxf_pad_string_PAD_LEFT = 0;
544var org_apache_cxf_pad_string_PAD_RIGHT = 1;
545var org_apache_cxf_pad_string_PAD_BOTH = 2;
546
547function org_apache_cxf_pad_string(string, len, pad, type) {
548        var append = new String();
549
550        len = isNaN(len) ? 0 : len - string.length;
551        pad = typeof(pad) == 'string' ? pad : ' ';
552
553        if (type == org_apache_cxf_pad_string_PAD_BOTH) {
554                string = org_apache_cxf_pad_sring(Math.floor(len / 2) + string.length,
555                                pad, org_apache_cxf_pad_string_PAD_LEFT);
556                return (org_apache_cxf_pad_string(Math.ceil(len / 2) + string.length,
557                                pad, org_apache_cxf_pad_string_PAD_RIGHT));
558        }
559
560        while ((len -= pad.length) > 0)
561                append += pad;
562        append += pad.substr(0, len + pad.length);
563
564        return (type == org_apache_cxf_pad_string_PAD_LEFT
565                        ? append.concat(string)
566                        : string.concat(append));
567}
568
569/*
570 * Generate a uniformly distributed random integer within the range <min> ..
571 * <max>. (min) - Lower limit: random >= min (default: 0) (max) - Upper limit:
572 * random <= max (default: 1)
573 */
574function org_apache_cxf_random_int(min, max) {
575        if (!isFinite(min))
576                min = 0;
577        if (!isFinite(max))
578                max = 1;
579        return Math.floor((Math.random() % 1) * (max - min + 1) + min);
580}
581
582function org_apache_cxf_random_hex_string(len) {
583        var random = org_apache_cxf_random_int(0, Math.pow(16, len) - 1);
584        return org_apache_cxf_pad_string(random.toString(16), len, '0',
585                        org_apache_cxf_pad_string_PAD_LEFT);
586}
587
588function org_apache_cxf_make_uuid(type) {
589        switch ((type || 'v4').toUpperCase()) {
590                // Version 4 UUID (Section 4.4 of RFC 4122)
591                case 'V4' :
592                        var tl = org_apache_cxf_random_hex_string(8);
593                        // time_low
594                        var tm = org_apache_cxf_random_hex_string(4);
595                        // time_mid
596                        var thav = '4' + org_apache_cxf_random_hex_string(3);
597                        // time_hi_and_version
598                        var cshar = org_apache_cxf_random_int(0, 0xFF);
599                        // clock_seq_hi_and_reserved
600                        cshar = ((cshar & ~(1 << 6)) | (1 << 7)).toString(16);
601                        var csl = org_apache_cxf_random_hex_string(2);
602                        // clock_seq_low
603                        var n = org_apache_cxf_random_hex_string(12);
604                        // node
605
606                        return (tl + '-' + tm + '-' + thav + '-' + cshar + csl + '-' + n);
607
608                        // Nil UUID (Section 4.1.7 of RFC 4122)
609                case 'NIL' :
610                        return '00000000-0000-0000-0000-000000000000';
611        }
612        return null;
613}
614
615//
616// Returns XMLHttpRequest object.
617//
618var ORG_APACHE_CXF_XMLHTTPREQUEST_MS_PROGIDS = new Array(
619    "Msxml2.XMLHTTP.7.0",
620    "Msxml2.XMLHTTP.6.0",
621    "Msxml2.XMLHTTP.5.0",
622    "Msxml2.XMLHTTP.4.0",
623    "MSXML2.XMLHTTP.3.0",
624    "MSXML2.XMLHTTP",
625    "Microsoft.XMLHTTP"
626    );
627
628function org_apache_cxf_getXMLHttpRequest()
629{
630    var httpRequest = null;
631
632    // Create the appropriate HttpRequest object for the browser.
633    try {
634       //CORS ADD ON
635       //httpRequest = new XMLHttpRequest();
636       //return httpRequest;
637
638       //CORS ADDON: XHR or XDR request handler
639       /*var RequestHandler = Cxf_Transport();
640       RequestHandler.handler = Cxf_Transport_Handler();
641       httpRequest = RequestHandler.handler;
642        */
643       //var RequestHandler = new Cxf_Transport_Cors();
644       var RequestHandler = new cxf_cors_request_object();
645       RequestHandler.init();
646       httpRequest = RequestHandler.handler;
647       //window.alert('Cliente tipo = ' + RequestHandler.type);
648       if(!httpRequest)
649           throw "CXF-UTILS-CORS fails to create CORS XMLHttpRequest object";
650    } catch(ex) {
651        window.alert('CORS failure:' + ex.description);
652    }
653    /*
654    if (window.ActiveXObject != null) {
655        // Must be IE, find the right ActiveXObject.
656
657        var success = false;
658        //
659        // Define a list of Microsoft XML HTTP ProgIDs.
660        //
661        for (var i = 0;
662             i < ORG_APACHE_CXF_XMLHTTPREQUEST_MS_PROGIDS.length && !success;
663             i++)
664        {
665            try
666            {
667                httpRequest = new ActiveXObject(ORG_APACHE_CXF_XMLHTTPREQUEST_MS_PROGIDS[i]);
668                success = true;
669            }
670            catch (ex)
671            {
672                // no reason to log unless we come up empty.
673            }
674        }
675        if(!success) {
676            this.utils.trace("Unable to get any Microsoft XML HttpRequest object.");
677            throw "org_apache_cxf no Microsoft XMLHttpRequest";
678        }
679    }*/
680
681    // Return it.
682    //return httpRequest;
683    return RequestHandler;
684}
685
686CxfApacheOrgClient.prototype.getXMLHttpRequest = org_apache_cxf_getXMLHttpRequest;
687
688var ORG_APACHE_CXF_MTOM_REQUEST_HEADER = 'Content-Type: application/xop+xml; type="text/xml"; charset=utf-8\r\n';
689
690// Caller must avoid stupid mistakes like 'GET' with a request body.
691// This does not support attempts to cross-script.
692// This imposes a relatively straightforward set of HTTP options.
693function org_apache_cxf_client_request(url, requestXML, method, sync, headers)
694{
695        this.utils.trace("request " + url);
696
697        this.url = url;
698        this.sync = sync;
699
700        this.req = null;
701
702        if (method) {
703                this.method = method;
704        } else {
705                if (requestXML)
706                        this.method = "POST";
707                else
708                        this.method = "GET";
709        }
710
711        try {
712                this.req = this.getXMLHttpRequest();
713                //window.alert('this.req getted: ' + this.req.type);
714        } catch (err) {
715                this.utils.trace("Error creating XMLHttpRequest: " + err);
716                this.req = null;
717        }
718
719        if (this.req.handler == null) {
720                this.utils.trace("Unable to create request object.");
721                throw "ORG_APACHE_CXF_NO_REQUEST_OBJECT";
722        }
723
724        this.utils.trace("about to open " + this.method + " " + this.url);
725        this.req.handler.open(this.method, this.url, !this.sync);
726
727        var mimeBoundary;
728
729        // we can't do binary MTOM, but we can do 'text/plain' !
730        if (this.mtomparts.length > 0) {
731                var uuid = org_apache_cxf_make_uuid('v4');
732                mimeBoundary = '@_bOuNDaRy_' + uuid;
733                var ctHeader = 'multipart/related; start-info="text/xml"; type="application/xop+xml"; boundary="'
734                                + mimeBoundary + '"';
735                this.req.handler.setRequestHeader("Content-Type", ctHeader);
736
737        } else {
738        // for now, assume SOAP 1.1. 1.2 calls for application/xml.
739        // also assume we're talking Unicode here.
740                //CORS
741                //XDR does not support setRequestHeader. Discarting it
742                //if(this.req.type != 'XDR')
743                    this.req.handler.setRequestHeader("Content-Type", "text/xml;charset=utf-8");
744        }
745
746    if (headers) { // must be array indexed by header field.
747        // avoid extra properties on the headers.
748        for (var h in headers) {
749            if(headers.hasOwnProperty(h)) {
750                //CORS
751                //XDR does not support setRequestHeader. Discarting it
752                //if(this.req.type != 'XDR')
753                    this.req.handler.setRequestHeader(h, headers[h]);
754            }
755        }
756    }
757
758        //CORS
759        //XDR does not support setRequestHeader. Discarting it
760       // if(this.req.type != 'XDR'){
761            this.req.handler.setRequestHeader("SOAPAction", this.soapAction);
762     //   }
763
764        var requester = this; /* setup a closure */
765
766        if(this.req.type != 'MS-XDR'){
767            //this.req.handler.onreadystatechange = function() {
768            this.req.handler.onload = function() {
769                          requester.onReadyState();
770            }
771        }
772        else if(this.req.type == 'MS-XDR'){
773            this.req.handler.onload = function() {
774                          requester.onReadyState();
775            }
776        }
777        //window.alert('request onreadystatechange = ' + this.req.onreadystatechange);
778
779        // NOTE: we do not call the onerror callback for a synchronous error
780        // at request time. We let the request object throw as it will.
781        // onError will only be called for asynchronous errors.
782        this.utils.trace("about to send data" + this.method + " " + this.url);
783        var dataToSend;
784        if (this.mtomparts.length == 0) {
785                dataToSend = requestXML;
786        } else {
787                dataToSend = "--" + mimeBoundary + "\r\n";
788                dataToSend = dataToSend + ORG_APACHE_CXF_MTOM_REQUEST_HEADER + "\r\n";
789                dataToSend = dataToSend + requestXML;
790                for (var bx in this.mtomparts) {
791                        var part = this.mtomparts[bx];
792                        dataToSend += "\r\n\r\n--" + mimeBoundary + "\r\n";
793                        dataToSend += part;
794                }
795                dataToSend += "--" + mimeBoundary + "--\r\n";
796        }
797  //window.alert('will send data now:\n' + dataToSend);
798        this.req.handler.send(dataToSend);
799}
800
801CxfApacheOrgClient.prototype.request = org_apache_cxf_client_request;
802
803function org_apache_cxf_trim_string(str) {
804        return str.replace(/^\s+|\s+$/g, '');
805}
806
807// this gets an array of a=b strings, and produces a dictionary of x[a]=b;
808function org_apache_cxf_parse_mime_keyword_value_pairs(strings) {
809        var result = [];
810        for (var x = 1;x < strings.length; x = x + 1) {
811                var str = strings[x];
812                var valequal = str.indexOf("=");
813                if (valequal != -1) {
814                        var k = str.substr(0, valequal);
815                        var v = str.substr(valequal + 1);
816                        v = org_apache_cxf_trim_string(v);
817                        if (v.charAt(0) == '"') {
818                                v = v.substr(1, v.length - 2);
819                        }
820                        if (v.charAt(0) == "'") {
821                                v = v.substr(1, v.length - 2);
822                        }
823
824                        result[org_apache_cxf_trim_string(k.toLowerCase())] = v;
825                }
826        }
827        return result;
828}
829
830function org_apache_cxf_regexp_escape(text) {
831        if (!arguments.callee.sRE) {
832                var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{',
833                                '}', '\\'];
834                arguments.callee.sRE = new RegExp('(\\' + specials.join('|\\') + ')',
835                                'g');
836        }
837        return text.replace(arguments.callee.sRE, '\\$1');
838}
839
840// Called when we don't have response XML.
841// returns true if we have multipart-related, false if we don't or can't parse
842// it.
843function org_apache_cxf_parse_multipart_related() {
844  if(this.req.type == 'MZ-XHR')
845         var contentType = this.req.handler.getResponseHeader("content-type");
846        else
847         var contentType = this.req.handler.contentType;
848
849        window.alert('contenttype = ' + contentType);
850
851        if (!contentType)
852                return false; // not bloody likely.
853        var ctPart = contentType.split(/\s*;\s*/);
854        var ctMain = ctPart[0].toLowerCase();
855        if (ctMain != "multipart/related")
856                return false;
857        // now we have keyword-value pairs.
858        var params = org_apache_cxf_parse_mime_keyword_value_pairs(ctPart);
859        // there is a lot of noise we don't care about. all we really want is the
860        // boundary.
861        var boundary = params['boundary'];
862        if (!boundary)
863                return false;
864        boundary = "--" + boundary; // the annoying 'extra-dash' convention.
865        // var boundarySplitter = org_apache_cxf_regexp_escape(boundary);
866        var text = this.req.responseText;
867        // we are willing to use a lot of memory here.
868        var parts = text.split(boundary);
869        // now we have the parts.
870        // now we have to pull headers off the parts.
871        this.parts = [];
872        // the first one is noise due to the initial boundary. The last will just be
873        // -- due to MIME.
874        for (var px = 1;px < parts.length - 1; px++) {
875                var seenOneHeader = false;
876                var x = 0; // misc index.
877                var parttext = parts[px];
878                var headers = [];
879                nextHeaderLine : for (var endX = parttext.indexOf('\r', x);endX != -1; x = endX
880                                + 1, endX = parttext.indexOf('\r', x)) {
881                        var headerLine = parttext.slice(x, endX);
882                        if (headerLine == "") {
883                                if (parttext.charAt(endX + 1) == '\n')
884                                        endX++;
885                                if (seenOneHeader) {
886                                        break nextHeaderLine;
887                                } else {
888                                        continue nextHeaderLine;
889                                }
890                        }
891                        seenOneHeader = true;
892
893                        var colonIndex = headerLine.indexOf(":");
894            var headerName = headerLine.slice(0, colonIndex).toLowerCase();
895            var headerValue = headerLine.substr(colonIndex+1);
896                        headers[headerName] = org_apache_cxf_trim_string(headerValue);
897
898                        if (parttext.charAt(endX + 1) == '\n')
899                                endX++;
900                }
901
902                // Now, see about the mime type (if any) and the ID.
903                var thispart = new Object(); // a constructor seems excessive.
904                // at exit, x indicates the start of the blank line.
905                if (parttext.charAt(x + 1) == '\n')
906                        x = x + 1;
907                thispart.data = parttext.substr(x);
908                thispart.contentType = headers['content-type'];
909                if (px > 1) {
910                        var cid = headers['content-id'];
911                        // take of < and >
912                        cid = cid.substr(1, cid.length - 2);
913                        thispart.cid = cid;
914                        this.parts[cid] = thispart;
915                } else {
916                        // the first part.
917                        var doc;
918                        if (window.ActiveXObject) {
919                                doc = new ActiveXObject("Microsoft.XMLDOM");
920                                doc.async = "false";
921                                doc.loadXML(thispart.data);
922                        } else {
923                                var parser = new DOMParser();
924                                doc = parser.parseFromString(thispart.data, "text/xml");
925                        }
926                        this.mpResponseXML = doc;
927                }
928        }
929        return true;
930
931}
932
933CxfApacheOrgClient.prototype.parseMultipartRelated = org_apache_cxf_parse_multipart_related;
934
935function org_apache_cxf_client_onReadyState() {
936        var req = this.req;
937        //only XHR has "readyState" property
938  if (req.type == 'MZ-XHR'){
939    var ready = req.handler.readyState;
940    this.utils.trace("onreadystatechange " + ready);
941
942          if (ready == this.READY_STATE_DONE) {
943                  var httpStatus;
944                  try {
945                         httpStatus = req.handler.status;
946                  } catch (e) {
947                         // Firefox throws when there was an error here.
948                         this.utils
949                                        .trace("onreadystatechange DONE ERROR retrieving status (connection error?)");
950                         if (this.onerror != null) {
951                                 this.onerror(e);
952                         }
953                         return;
954      }
955
956                  this.utils.trace("onreadystatechange DONE " + httpStatus);
957
958                  if (httpStatus == 200 || httpStatus == 0) {
959                         if (this.onsuccess != null) {
960                                // the onSuccess function is generated, and picks apart the
961                                // response.
962                                if (!req.handler.responseXML) {
963                                        if (this.parseMultipartRelated()) {
964                                                this.onsuccess(this, this.mpResponseXML);
965                                                return;
966                                        }
967                                        if (this.onerror != null) {
968                                                this.onerror("Could not handle content of response.");
969                                                return;
970                                        }
971                                }
972                                this.onsuccess(this, req.handler.responseXML);
973                         }
974                  } else {
975                         this.utils.trace("onreadystatechange DONE ERROR "
976                                        + req.handler.getAllResponseHeaders() + " " + req.handler.statusText + " "
977                                        + req.handler.responseText);
978                        if (this.onerror != null)
979                                this.onerror(this);
980                  }
981          }
982         }
983         //XDR success/error callbacks
984         else{
985                 // the onSuccess function is generated, and picks apart the
986                 // response.
987                 if (req.handler.contentType != 'text/xml') {
988                  if (this.parseMultipartRelated()) {
989        this.onsuccess(this, this.mpResponseXML);
990                                return;
991                        }
992                        if (this.onerror != null) {
993                                        this.onerror("Could not handle content of response.");
994                                        return;
995                        }
996                 }
997                 //Creates data as XML doc, once XDomainRequest does not provide responseXML
998     var xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
999     xmlDoc.async="false";
1000     xmlDoc.loadXML(req.handler.responseText);
1001
1002                 this.onsuccess(this, xmlDoc);
1003   }
1004}
1005
1006CxfApacheOrgClient.prototype.onReadyState = org_apache_cxf_client_onReadyState;
1007
1008function org_apache_cxf_package_mtom(value) {
1009        var uuid = org_apache_cxf_make_uuid('v4');
1010        var placeholder = '<xop:Include xmlns:xop="http://www.w3.org/2004/08/xop/include" '
1011                        + 'href="cid:' + uuid + '" />';
1012        var mtomObject = 'Content-Type: text/plain; charset="utf-8";\r\nContent-ID: <'
1013                        + uuid + '>\r\n\r\n' + value + '\r\n';
1014        this.client.mtomparts.push(mtomObject);
1015        return placeholder;
1016}
1017
1018CxfApacheOrgUtil.prototype.packageMtom = org_apache_cxf_package_mtom;
1019
1020// Holder object used for xs:any
1021// The namespaceURI and localName identify the global element from the schema.
1022// The object to go with it goes into object.
1023// If the Any is an array, put the array into the object slot.
1024
1025function org_apache_cxf_any_holder(namespaceURI, localName, object) {
1026        this.typeMarker = "org_apache_cxf_any_holder";
1027        this.namespaceURI = namespaceURI;
1028        this.localName = localName;
1029        this.qname = "{" + namespaceURI + "}" + localName;
1030        this.object = object;
1031        this.raw = false;
1032}
1033
1034// the following will simply dump the supplied XML into the message.
1035function org_apache_cxf_raw_any_holder(xml) {
1036        this.typeMarker = "org_apache_cxf_raw_any_holder";
1037        this.xml = xml;
1038        this.raw = true;
1039        this.xsiType = false;
1040}
1041
1042// The following will get an xsi:type attribute in addition to dumping the XML
1043// into
1044// the message.
1045function org_apache_cxf_raw_typed_any_holder(namespaceURI, localName, xml) {
1046        this.typeMarker = "org_apache_cxf_raw_any_holder";
1047        this.namespaceURI = namespaceURI;
1048        this.localName = localName;
1049        this.xml = xml;
1050        this.raw = true;
1051        this.xsiType = true;
1052}
1053
1054function org_apache_cxf_get_xsi_type(elementNode) {
1055        var attributes = elementNode.attributes;
1056        if ((attributes != null) && (attributes.length > 0)) {
1057                for (var x = 0;x < attributes.length; x++) {
1058                        var attributeNodeName = attributes.item(x).nodeName;
1059                        var attributeNamespacePrefix = org_apache_cxf_getPrefix(attributes
1060                                        .item(x).nodeName);
1061                        var attributeNamespaceSuffix = org_apache_cxf_getLocalName(attributes
1062                                        .item(x).nodeName);
1063                        if (attributeNamespaceSuffix == 'type') {
1064                                // perhaps this is ours
1065                                var ns = org_apache_cxf_getNamespaceURI(elementNode,
1066                                                attributeNamespacePrefix);
1067                                if (ns == org_apache_cxf_XSI_namespace_uri) {
1068                                        return attributes.item(x).nodeValue;
1069                                }
1070                        }
1071                }
1072                return null;
1073        }
1074}
1075
1076// Return an object if we can deserialize an object, otherwise return the
1077// element itself.
1078function org_apache_cxf_deserialize_anyType(cxfjsutils, element) {
1079        var type = org_apache_cxf_get_xsi_type(element);
1080        if (type != null) {
1081                // type is a :-qualified name.
1082                var namespacePrefix = org_apache_cxf_getPrefix(type);
1083                var localName = org_apache_cxf_getLocalName(type);
1084                var uri = org_apache_cxf_getNamespaceURI(element, namespacePrefix);
1085                if (uri == org_apache_cxf_XSD_namespace_uri) {
1086                        // we expect a Text node below
1087                        var textNode = element.firstChild;
1088                        if (textNode == null)
1089                                return null;
1090                        var text = textNode.nodeValue;
1091                        if (text == null)
1092                                return null;
1093                        // For any of the basic types, assume that the nodeValue is what the
1094                        // doctor ordered,
1095                        // converted to the appropriate type.
1096                        // For some of the more interesting types this needs more work.
1097                        if (localName == "int" || localName == "unsignedInt"
1098                                        || localName == "long" || localName == "unsignedLong") {
1099                                return parseInt(text);
1100                        }
1101                        if (localName == "float" || localName == "double")
1102                                return parseFloat(text);
1103                        if (localName == "boolean")
1104                                return text == 'true';
1105                        return text;
1106                }
1107                var qname = "{" + uri + "}" + localName;
1108                var deserializer = cxfjsutils.interfaceObject.globalElementDeserializers[qname];
1109                if (deserializer != null) {
1110                        return deserializer(cxfjsutils, element);
1111                }
1112        }
1113        return element;
1114}
1115-->
Note: See TracBrowser for help on using the repository browser.