Debian Codegraph @

rhino/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLLibImpl.java

raw symbols SCIP
1 /* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
2 *
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 package org.mozilla.javascript.xmlimpl;
8
9 import java.io.Serializable;
10
11 import org.mozilla.javascript.*;
12 import org.mozilla.javascript.xml.*;
13 import org.xml.sax.SAXException;
14
15 public final class XMLLibImpl extends XMLLib implements Serializable {
16 private static final long serialVersionUID = 1L;
17
18 //
19 // EXPERIMENTAL Java interface
20 //
21
22 /**
23 This experimental interface is undocumented.
24 */
25 public static org.w3c.dom.Node toDomNode(Object xmlObject) {
26 // Could return DocumentFragment for XMLList
27 // Probably a single node for XMLList with one element
28 if (xmlObject instanceof XML) {
29 return ((XML)xmlObject).toDomNode();
30 } else {
31 throw new IllegalArgumentException(
32 "xmlObject is not an XML object in JavaScript.");
33 }
34 }
35
36 public static void init(Context cx, Scriptable scope, boolean sealed) {
37 XMLLibImpl lib = new XMLLibImpl(scope);
38 XMLLib bound = lib.bindToScope(scope);
39 if (bound == lib) {
40 lib.exportToScope(sealed);
41 }
42 }
43
44 @Override
45 public void setIgnoreComments(boolean b) {
46 options.setIgnoreComments(b);
47 }
48
49 @Override
50 public void setIgnoreWhitespace(boolean b) {
51 options.setIgnoreWhitespace(b);
52 }
53
54 @Override
55 public void setIgnoreProcessingInstructions(boolean b) {
56 options.setIgnoreProcessingInstructions(b);
57 }
58
59 @Override
60 public void setPrettyPrinting(boolean b) {
61 options.setPrettyPrinting(b);
62 }
63
64 @Override
65 public void setPrettyIndent(int i) {
66 options.setPrettyIndent(i);
67 }
68
69 @Override
70 public boolean isIgnoreComments() {
71 return options.isIgnoreComments();
72 }
73
74 @Override
75 public boolean isIgnoreProcessingInstructions() {
76 return options.isIgnoreProcessingInstructions();
77 }
78
79 @Override
80 public boolean isIgnoreWhitespace() {
81 return options.isIgnoreWhitespace();
82 }
83
84 @Override
85 public boolean isPrettyPrinting() {
86 return options.isPrettyPrinting();
87 }
88
89 @Override
90 public int getPrettyIndent() {
91 return options.getPrettyIndent();
92 }
93
94
95 private Scriptable globalScope;
96
97 private XML xmlPrototype;
98 private XMLList xmlListPrototype;
99 private Namespace namespacePrototype;
100 private QName qnamePrototype;
101
102 private XmlProcessor options = new XmlProcessor();
103
104 private XMLLibImpl(Scriptable globalScope) {
105 this.globalScope = globalScope;
106 }
107
108 /** @deprecated */
109 @Deprecated
110 QName qnamePrototype() {
111 return qnamePrototype;
112 }
113
114 /** @deprecated */
115 @Deprecated
116 Scriptable globalScope() {
117 return globalScope;
118 }
119
120 XmlProcessor getProcessor() {
121 return options;
122 }
123
124 private void exportToScope(boolean sealed) {
125 xmlPrototype = newXML(XmlNode.createText(options, ""));
126 xmlListPrototype = newXMLList();
127 namespacePrototype = Namespace.create(this.globalScope, null,
128 XmlNode.Namespace.GLOBAL);
129 qnamePrototype = QName.create(this, this.globalScope, null,
130 XmlNode.QName.create(XmlNode.Namespace.create(""), ""));
131
132 xmlPrototype.exportAsJSClass(sealed);
133 xmlListPrototype.exportAsJSClass(sealed);
134 namespacePrototype.exportAsJSClass(sealed);
135 qnamePrototype.exportAsJSClass(sealed);
136 }
137
138 /** @deprecated */
139 @Deprecated
140 XMLName toAttributeName(Context cx, Object nameValue) {
141 if (nameValue instanceof XMLName) {
142 // TODO Will this always be an XMLName of type attribute name?
143 return (XMLName)nameValue;
144 } else if (nameValue instanceof QName) {
145 return XMLName.create( ((QName)nameValue).getDelegate(), true, false );
146 } else if (nameValue instanceof Boolean
147 || nameValue instanceof Number
148 || nameValue == Undefined.instance
149 || nameValue == null) {
150 throw badXMLName(nameValue);
151 } else {
152 // TODO Not 100% sure that putting these in global namespace is the right thing to do
153 String localName = null;
154 if (nameValue instanceof String) {
155 localName = (String)nameValue;
156 } else {
157 localName = ScriptRuntime.toString(nameValue);
158 }
159 if (localName != null && localName.equals("*")) localName = null;
160 return XMLName.create(XmlNode.QName.create(
161 XmlNode.Namespace.create(""), localName), true, false);
162 }
163 }
164
165 private static RuntimeException badXMLName(Object value)
166 {
167 String msg;
168 if (value instanceof Number) {
169 msg = "Can not construct XML name from number: ";
170 } else if (value instanceof Boolean) {
171 msg = "Can not construct XML name from boolean: ";
172 } else if (value == Undefined.instance || value == null) {
173 msg = "Can not construct XML name from ";
174 } else {
175 throw new IllegalArgumentException(value.toString());
176 }
177 return ScriptRuntime.typeError(msg+ScriptRuntime.toString(value));
178 }
179
180 XMLName toXMLNameFromString(Context cx, String name) {
181 return XMLName.create(getDefaultNamespaceURI(cx), name);
182 }
183
184 /* TODO: Marked deprecated by original author */
185 XMLName toXMLName(Context cx, Object nameValue) {
186 XMLName result;
187
188 if (nameValue instanceof XMLName) {
189 result = (XMLName)nameValue;
190 } else if (nameValue instanceof QName) {
191 QName qname = (QName)nameValue;
192 result = XMLName.formProperty(qname.uri(), qname.localName());
193 } else if (nameValue instanceof String) {
194 result = toXMLNameFromString(cx, (String)nameValue);
195 } else if (nameValue instanceof Boolean
196 || nameValue instanceof Number
197 || nameValue == Undefined.instance
198 || nameValue == null) {
199 throw badXMLName(nameValue);
200 } else {
201 String name = ScriptRuntime.toString(nameValue);
202 result = toXMLNameFromString(cx, name);
203 }
204
205 return result;
206 }
207
208 /**
209 * If value represents Uint32 index, make it available through
210 * ScriptRuntime.lastUint32Result(cx) and return null.
211 * Otherwise return the same value as toXMLName(cx, value).
212 */
213 XMLName toXMLNameOrIndex(Context cx, Object value)
214 {
215 XMLName result;
216
217 if (value instanceof XMLName) {
218 result = (XMLName)value;
219 } else if (value instanceof String) {
220 String str = (String)value;
221 long test = ScriptRuntime.testUint32String(str);
222 if (test >= 0) {
223 ScriptRuntime.storeUint32Result(cx, test);
224 result = null;
225 } else {
226 result = toXMLNameFromString(cx, str);
227 }
228 } else if (value instanceof Number) {
229 double d = ((Number)value).doubleValue();
230 long l = (long)d;
231 if (l == d && 0 <= l && l <= 0xFFFFFFFFL) {
232 ScriptRuntime.storeUint32Result(cx, l);
233 result = null;
234 } else {
235 throw badXMLName(value);
236 }
237 } else if (value instanceof QName) {
238 QName qname = (QName)value;
239 String uri = qname.uri();
240 boolean number = false;
241 result = null;
242 if (uri != null && uri.length() == 0) {
243 // Only in this case qname.toString() can resemble uint32
244 long test = ScriptRuntime.testUint32String(uri);
245 if (test >= 0) {
246 ScriptRuntime.storeUint32Result(cx, test);
247 number = true;
248 }
249 }
250 if (!number) {
251 result = XMLName.formProperty(uri, qname.localName());
252 }
253 } else if (value instanceof Boolean
254 || value == Undefined.instance
255 || value == null)
256 {
257 throw badXMLName(value);
258 } else {
259 String str = ScriptRuntime.toString(value);
260 long test = ScriptRuntime.testUint32String(str);
261 if (test >= 0) {
262 ScriptRuntime.storeUint32Result(cx, test);
263 result = null;
264 } else {
265 result = toXMLNameFromString(cx, str);
266 }
267 }
268
269 return result;
270 }
271
272 Object addXMLObjects(Context cx, XMLObject obj1, XMLObject obj2)
273 {
274 XMLList listToAdd = newXMLList();
275
276 if (obj1 instanceof XMLList) {
277 XMLList list1 = (XMLList)obj1;
278 if (list1.length() == 1) {
279 listToAdd.addToList(list1.item(0));
280 } else {
281 // Might be xmlFragment + xmlFragment + xmlFragment + ...;
282 // then the result will be an XMLList which we want to be an
283 // rValue and allow it to be assigned to an lvalue.
284 listToAdd = newXMLListFrom(obj1);
285 }
286 } else {
287 listToAdd.addToList(obj1);
288 }
289
290 if (obj2 instanceof XMLList) {
291 XMLList list2 = (XMLList)obj2;
292 for (int i = 0; i < list2.length(); i++) {
293 listToAdd.addToList(list2.item(i));
294 }
295 } else if (obj2 instanceof XML) {
296 listToAdd.addToList(obj2);
297 }
298
299 return listToAdd;
300 }
301
302 private Ref xmlPrimaryReference(Context cx, XMLName xmlName, Scriptable scope) {
303 XMLObjectImpl xmlObj;
304 XMLObjectImpl firstXml = null;
305 for (;;) {
306 // XML object can only present on scope chain as a wrapper
307 // of XMLWithScope
308 if (scope instanceof XMLWithScope) {
309 xmlObj = (XMLObjectImpl)scope.getPrototype();
310 if (xmlObj.hasXMLProperty(xmlName)) {
311 break;
312 }
313 if (firstXml == null) {
314 firstXml = xmlObj;
315 }
316 }
317 scope = scope.getParentScope();
318 if (scope == null) {
319 xmlObj = firstXml;
320 break;
321 }
322 }
323
324 // xmlObj == null corresponds to undefined as the target of
325 // the reference
326 if (xmlObj != null) {
327 xmlName.initXMLObject(xmlObj);
328 }
329 return xmlName;
330 }
331
332 Namespace castToNamespace(Context cx, Object namespaceObj) {
333 return this.namespacePrototype.castToNamespace(namespaceObj);
334 }
335
336 private String getDefaultNamespaceURI(Context cx) {
337 return getDefaultNamespace(cx).uri();
338 }
339
340 Namespace newNamespace(String uri) {
341 return this.namespacePrototype.newNamespace(uri);
342 }
343
344 Namespace getDefaultNamespace(Context cx) {
345 if (cx == null) {
346 cx = Context.getCurrentContext();
347 if (cx == null) {
348 return namespacePrototype;
349 }
350 }
351
352 Object ns = ScriptRuntime.searchDefaultNamespace(cx);
353 if (ns == null) {
354 return namespacePrototype;
355 } else {
356 if (ns instanceof Namespace) {
357 return (Namespace)ns;
358 } else {
359 // TODO Clarify or remove the following comment
360 // Should not happen but for now it could
361 // due to bad searchDefaultNamespace implementation.
362 return namespacePrototype;
363 }
364 }
365 }
366
367 Namespace[] createNamespaces(XmlNode.Namespace[] declarations) {
368 Namespace[] rv = new Namespace[declarations.length];
369 for (int i=0; i<declarations.length; i++) {
370 rv[i] = this.namespacePrototype.newNamespace(
371 declarations[i].getPrefix(), declarations[i].getUri());
372 }
373 return rv;
374 }
375
376 // See ECMA357 13.3.2
377 QName constructQName(Context cx, Object namespace, Object name) {
378 return this.qnamePrototype.constructQName(this, cx, namespace, name);
379 }
380
381 QName newQName(String uri, String localName, String prefix) {
382 return this.qnamePrototype.newQName(this, uri, localName, prefix);
383 }
384
385 QName constructQName(Context cx, Object nameValue) {
386 // return constructQName(cx, Undefined.instance, nameValue);
387 return this.qnamePrototype.constructQName(this, cx, nameValue);
388 }
389
390 QName castToQName(Context cx, Object qnameValue) {
391 return this.qnamePrototype.castToQName(this, cx, qnameValue);
392 }
393
394 QName newQName(XmlNode.QName qname) {
395 return QName.create(this, this.globalScope, this.qnamePrototype, qname);
396 }
397
398 XML newXML(XmlNode node) {
399 return new XML(this, this.globalScope, this.xmlPrototype, node);
400 }
401
402 /* TODO: Can this can be replaced by ecmaToXml below?
403 */
404 final XML newXMLFromJs(Object inputObject) {
405 String frag;
406
407 if (inputObject == null || inputObject == Undefined.instance) {
408 frag = "";
409 } else if (inputObject instanceof XMLObjectImpl) {
410 // todo: faster way for XMLObjects?
411 frag = ((XMLObjectImpl) inputObject).toXMLString();
412 } else {
413 frag = ScriptRuntime.toString(inputObject);
414 }
415
416 if (frag.trim().startsWith("<>")) {
417 throw ScriptRuntime.typeError("Invalid use of XML object anonymous tags <></>.");
418 }
419
420 if (frag.indexOf("<") == -1) {
421 // Solo text node
422 return newXML(XmlNode.createText(options, frag));
423 }
424 return parse(frag);
425 }
426
427 private XML parse(String frag) {
428 try {
429 return newXML(XmlNode.createElement(options,
430 getDefaultNamespaceURI(Context.getCurrentContext()), frag));
431 } catch (SAXException e) {
432 throw ScriptRuntime.typeError("Cannot parse XML: " + e.getMessage());
433 }
434 }
435
436 final XML ecmaToXml(Object object) {
437 // See ECMA357 10.3
438 if (object == null || object == Undefined.instance) {
439 throw ScriptRuntime.typeError("Cannot convert " + object + " to XML");
440 }
441 if (object instanceof XML) return (XML)object;
442 if (object instanceof XMLList) {
443 XMLList list = (XMLList)object;
444 if (list.getXML() != null) {
445 return list.getXML();
446 } else {
447 throw ScriptRuntime.typeError("Cannot convert list of >1 element to XML");
448 }
449 }
450 // TODO Technically we should fail on anything except a String, Number or Boolean
451 // See ECMA357 10.3
452 // Extension: if object is a DOM node, use that to construct the XML
453 // object.
454 if (object instanceof Wrapper) {
455 object = ((Wrapper) object).unwrap();
456 }
457 if (object instanceof org.w3c.dom.Node) {
458 org.w3c.dom.Node node = (org.w3c.dom.Node) object;
459 return newXML(XmlNode.createElementFromNode(node));
460 }
461 // Instead we just blindly cast to a String and let them convert anything.
462 String s = ScriptRuntime.toString(object);
463 // TODO Could this get any uglier?
464 if (s.length() > 0 && s.charAt(0) == '<') {
465 return parse(s);
466 } else {
467 return newXML(XmlNode.createText(options, s));
468 }
469 }
470
471 final XML newTextElementXML(XmlNode reference, XmlNode.QName qname, String value) {
472 return newXML(XmlNode.newElementWithText(options, reference, qname, value));
473 }
474
475 XMLList newXMLList() {
476 return new XMLList(this, this.globalScope, this.xmlListPrototype);
477 }
478
479 final XMLList newXMLListFrom(Object inputObject) {
480 XMLList rv = newXMLList();
481
482 if (inputObject == null || inputObject instanceof Undefined) {
483 return rv;
484 } else if (inputObject instanceof XML) {
485 XML xml = (XML) inputObject;
486 rv.getNodeList().add(xml);
487 return rv;
488 } else if (inputObject instanceof XMLList) {
489 XMLList xmll = (XMLList) inputObject;
490 rv.getNodeList().add(xmll.getNodeList());
491 return rv;
492 } else {
493 String frag = ScriptRuntime.toString(inputObject).trim();
494
495 if (!frag.startsWith("<>")) {
496 frag = "<>" + frag + "</>";
497 }
498
499 frag = "<fragment>" + frag.substring(2);
500 if (!frag.endsWith("</>")) {
501 throw ScriptRuntime.typeError("XML with anonymous tag missing end anonymous tag");
502 }
503
504 frag = frag.substring(0, frag.length() - 3) + "</fragment>";
505
506 XML orgXML = newXMLFromJs(frag);
507
508 // Now orphan the children and add them to our XMLList.
509 XMLList children = orgXML.children();
510
511 for (int i = 0; i < children.getNodeList().length(); i++) {
512 // Copy here is so that they'll be orphaned (parent() will be undefined)
513 rv.getNodeList().add(((XML) children.item(i).copy()));
514 }
515 return rv;
516 }
517 }
518
519 XmlNode.QName toNodeQName(Context cx, Object namespaceValue, Object nameValue) {
520 // This is duplication of constructQName(cx, namespaceValue, nameValue)
521 // but for XMLName
522
523 String localName;
524
525 if (nameValue instanceof QName) {
526 QName qname = (QName)nameValue;
527 localName = qname.localName();
528 } else {
529 localName = ScriptRuntime.toString(nameValue);
530 }
531
532 XmlNode.Namespace ns;
533 if (namespaceValue == Undefined.instance) {
534 if ("*".equals(localName)) {
535 ns = null;
536 } else {
537 ns = getDefaultNamespace(cx).getDelegate();
538 }
539 } else if (namespaceValue == null) {
540 ns = null;
541 } else if (namespaceValue instanceof Namespace) {
542 ns = ((Namespace)namespaceValue).getDelegate();
543 } else {
544 ns = this.namespacePrototype.constructNamespace(namespaceValue).getDelegate();
545 }
546
547 if (localName != null && localName.equals("*")) localName = null;
548 return XmlNode.QName.create(ns, localName);
549 }
550
551 XmlNode.QName toNodeQName(Context cx, String name, boolean attribute) {
552 XmlNode.Namespace defaultNamespace = getDefaultNamespace(cx).getDelegate();
553 if (name != null && name.equals("*")) {
554 return XmlNode.QName.create(null, null);
555 } else {
556 if (attribute) {
557 return XmlNode.QName.create(XmlNode.Namespace.GLOBAL, name);
558 } else {
559 return XmlNode.QName.create(defaultNamespace, name);
560 }
561 }
562 }
563
564 /*
565 TODO: Too general; this should be split into overloaded methods.
566 Is that possible?
567 */
568 XmlNode.QName toNodeQName(Context cx, Object nameValue, boolean attribute) {
569 if (nameValue instanceof XMLName) {
570 return ((XMLName)nameValue).toQname();
571 } else if (nameValue instanceof QName) {
572 QName qname = (QName)nameValue;
573 return qname.getDelegate();
574 } else if (
575 nameValue instanceof Boolean
576 || nameValue instanceof Number
577 || nameValue == Undefined.instance
578 || nameValue == null
579 ) {
580 throw badXMLName(nameValue);
581 } else {
582 String local = null;
583 if (nameValue instanceof String) {
584 local = (String)nameValue;
585 } else {
586 local = ScriptRuntime.toString(nameValue);
587 }
588 return toNodeQName(cx, local, attribute);
589 }
590 }
591
592 //
593 // Override methods from XMLLib
594 //
595
596 @Override
597 public boolean isXMLName(Context _cx, Object nameObj) {
598 return XMLName.accept(nameObj);
599 }
600
601 @Override
602 public Object toDefaultXmlNamespace(Context cx, Object uriValue) {
603 return this.namespacePrototype.constructNamespace(uriValue);
604 }
605
606 @Override
607 public String escapeTextValue(Object o) {
608 return options.escapeTextValue(o);
609 }
610
611 @Override
612 public String escapeAttributeValue(Object o) {
613 return options.escapeAttributeValue(o);
614 }
615
616 @Override
617 public Ref nameRef(Context cx, Object name, Scriptable scope, int memberTypeFlags) {
618 if ((memberTypeFlags & Node.ATTRIBUTE_FLAG) == 0) {
619 // should only be called for cases like @name or @[expr]
620 throw Kit.codeBug();
621 }
622 XMLName xmlName = toAttributeName(cx, name);
623 return xmlPrimaryReference(cx, xmlName, scope);
624 }
625
626 @Override
627 public Ref nameRef(Context cx, Object namespace, Object name, Scriptable scope, int memberTypeFlags) {
628 XMLName xmlName = XMLName.create(toNodeQName(cx, namespace, name), false, false);
629
630 // No idea what is coming in from the parser in this case; is it detecting the "@"?
631 if ((memberTypeFlags & Node.ATTRIBUTE_FLAG) != 0) {
632 if (!xmlName.isAttributeName()) {
633 xmlName.setAttributeName();
634 }
635 }
636
637 return xmlPrimaryReference(cx, xmlName, scope);
638 }
639 }