-
-
Notifications
You must be signed in to change notification settings - Fork 179
/
XMLUtil.java
executable file
·1525 lines (1384 loc) · 48.4 KB
/
XMLUtil.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
*
* Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
**/
package lucee.runtime.text.xml;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.io.StringWriter;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMResult;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.ccil.cowan.tagsoup.Parser;
import org.w3c.dom.Attr;
import org.w3c.dom.CDATASection;
import org.w3c.dom.CharacterData;
import org.w3c.dom.Comment;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
import lucee.commons.io.CharsetUtil;
import lucee.commons.io.IOUtil;
import lucee.commons.io.SystemUtil;
import lucee.commons.io.log.Log;
import lucee.commons.io.log.LogUtil;
import lucee.commons.io.res.Resource;
import lucee.commons.io.res.util.ResourceUtil;
import lucee.commons.lang.ClassUtil;
import lucee.commons.lang.ExceptionUtil;
import lucee.commons.lang.StringUtil;
import lucee.runtime.PageContext;
import lucee.runtime.config.ConfigImpl;
import lucee.runtime.engine.ThreadLocalPageContext;
import lucee.runtime.exp.ExpressionException;
import lucee.runtime.exp.PageException;
import lucee.runtime.exp.XMLException;
import lucee.runtime.listener.ApplicationContextSupport;
import lucee.runtime.op.Caster;
import lucee.runtime.op.Decision;
import lucee.runtime.osgi.EnvClassLoader;
import lucee.runtime.text.xml.struct.XMLMultiElementStruct;
import lucee.runtime.text.xml.struct.XMLStruct;
import lucee.runtime.text.xml.struct.XMLStructFactory;
import lucee.runtime.type.Array;
import lucee.runtime.type.ArrayImpl;
import lucee.runtime.type.Collection;
import lucee.runtime.type.Collection.Key;
import lucee.runtime.type.KeyImpl;
import lucee.runtime.type.Struct;
/**
*
*/
public final class XMLUtil {
public static final short UNDEFINED_NODE = -1;
public static final Collection.Key XMLCOMMENT = KeyImpl.intern("xmlcomment");
public static final Collection.Key XMLTEXT = KeyImpl.intern("xmltext");
public static final Collection.Key XMLCDATA = KeyImpl.intern("xmlcdata");
public static final Collection.Key XMLCHILDREN = KeyImpl.intern("xmlchildren");
public static final Collection.Key XMLNODES = KeyImpl.intern("xmlnodes");
public static final Collection.Key XMLNSURI = KeyImpl.intern("xmlnsuri");
public static final Collection.Key XMLNSPREFIX = KeyImpl.intern("xmlnsprefix");
public static final Collection.Key XMLROOT = KeyImpl.intern("xmlroot");
public static final Collection.Key XMLPARENT = KeyImpl.intern("xmlparent");
public static final Collection.Key XMLNAME = KeyImpl.intern("xmlname");
public static final Collection.Key XMLTYPE = KeyImpl.intern("xmltype");
public static final Collection.Key XMLVALUE = KeyImpl.intern("xmlvalue");
public static final Collection.Key XMLATTRIBUTES = KeyImpl.intern("xmlattributes");
public static final Collection.Key KEY_FEATURE_SECURE = KeyImpl.intern("secure");
public static final Collection.Key KEY_FEATURE_DISALLOW_DOCTYPE_DECL = KeyImpl.intern("disallowDoctypeDecl");
public static final Collection.Key KEY_FEATURE_EXTERNAL_GENERAL_ENTITIES = KeyImpl.intern("externalGeneralEntities");
// public final static String
// DEFAULT_SAX_PARSER="org.apache.xerces.parsers.SAXParser";
/*
* private static final Collection.Key = KeyImpl.getInstance(); private static final Collection.Key
* = KeyImpl.getInstance(); private static final Collection.Key = KeyImpl.getInstance(); private
* static final Collection.Key = KeyImpl.getInstance(); private static final Collection.Key =
* KeyImpl.getInstance(); private static final Collection.Key = KeyImpl.getInstance();
*/
// static DOMParser parser = new DOMParser();
private static DocumentBuilder docBuilder;
// private static DocumentBuilderFactory factory;
private static TransformerFactory transformerFactory;
// private static DocumentBuilderFactory documentBuilderFactory;
private static SAXParserFactory saxParserFactory;
private static URL transformerFactoryResource;
public static String unescapeXMLString(String str) {
StringBuffer rtn = new StringBuffer();
int posStart = -1;
int posFinish = -1;
while ((posStart = str.indexOf('&', posStart)) != -1) {
int last = posFinish + 1;
posFinish = str.indexOf(';', posStart);
if (posFinish == -1) break;
rtn.append(str.substring(last, posStart));
if (posStart + 1 < posFinish) {
rtn.append(unescapeXMLEntity(str.substring(posStart + 1, posFinish)));
}
else {
rtn.append("&;");
}
posStart = posFinish + 1;
}
rtn.append(str.substring(posFinish + 1));
return rtn.toString();
}
public static String unescapeXMLString2(String str) {
StringBuffer sb = new StringBuffer();
int index, last = 0, indexSemi;
while ((index = str.indexOf('&', last)) != -1) {
sb.append(str.substring(last, index));
indexSemi = str.indexOf(';', index + 1);
if (indexSemi == -1) {
sb.append('&');
last = index + 1;
}
else if (index + 1 == indexSemi) {
sb.append("&;");
last = index + 2;
}
else {
sb.append(unescapeXMLEntity(str.substring(index + 1, indexSemi)));
last = indexSemi + 1;
}
}
sb.append(str.substring(last));
return sb.toString();
}
private static String unescapeXMLEntity(String str) {
if ("lt".equals(str)) return "<";
if ("gt".equals(str)) return ">";
if ("amp".equals(str)) return "&";
if ("apos".equals(str)) return "'";
if ("quot".equals(str)) return "\"";
return "&" + str + ";";
}
public static String escapeXMLString(String xmlStr) {
char c;
StringBuffer sb = new StringBuffer();
int len = xmlStr.length();
for (int i = 0; i < len; i++) {
c = xmlStr.charAt(i);
if (c == '<') sb.append("<");
else if (c == '>') sb.append(">");
else if (c == '&') sb.append("&");
// else if(c=='\'') sb.append("&");
else if (c == '"') sb.append(""");
// else if(c>127) sb.append("&#"+((int)c)+";");
else sb.append(c);
}
return sb.toString();
}
/**
* @return returns a singelton TransformerFactory
*/
public static TransformerFactory getTransformerFactory() {
if (transformerFactory == null) transformerFactory = _newTransformerFactory();
return transformerFactory;
}
public static String getTransformerFactoryName() {
return getTransformerFactory().getClass().getName();
}
public static URL getTransformerFactoryResource() throws IOException {
if (transformerFactoryResource == null) {
String name = getTransformerFactoryName();
Resource localFile = SystemUtil.getTempDirectory().getRealResource(name.replace('\\', '_').replace('/', '_'));
IOUtil.write(localFile, name.getBytes());
transformerFactoryResource = ((File) localFile).toURI().toURL();
}
return transformerFactoryResource;
}
private static TransformerFactory _newTransformerFactory() {
Thread.currentThread().setContextClassLoader(new EnvClassLoader((ConfigImpl) ThreadLocalPageContext.getConfig()));
TransformerFactory factory = null;
Class clazz = null;
try {
clazz = ClassUtil.loadClass("com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
}
catch (Exception e) {
try {
clazz = ClassUtil.loadClass("org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl");
}
catch (Exception ee) {}
}
if (clazz != null) {
try {
factory = (TransformerFactory) ClassUtil.loadInstance(clazz);
}
catch (Exception e) {}
}
if (factory == null) return factory = TransformerFactory.newInstance();
LogUtil.log(null, Log.LEVEL_INFO, "application", "xml", factory.getClass().getName() + " is used as TransformerFactory");
return factory;
}
public static final Document parse(InputSource xml, InputSource validator, boolean isHtml) throws SAXException, IOException {
return parse(xml, validator, new XMLEntityResolverDefaultHandler(validator), isHtml);
}
/**
* parse XML/HTML String to a XML DOM representation
*
* @param xml XML InputSource
* @param isHtml is a HTML or XML Object
* @return parsed Document
* @throws SAXException
* @throws IOException
* @throws ParserConfigurationException
*/
public static final Document parse(InputSource xml, InputSource validator, EntityResolver entRes, boolean isHtml) throws SAXException, IOException {
if (!isHtml) {
DocumentBuilderFactory factory = newDocumentBuilderFactory(validator);
try {
DocumentBuilder builder = factory.newDocumentBuilder();
if (entRes != null) builder.setEntityResolver(entRes);
builder.setErrorHandler(new ThrowingErrorHandler(true, true, false));
return builder.parse(xml);
}
catch (ParserConfigurationException e) {
throw new SAXException(e);
}
}
XMLReader reader = new Parser();
reader.setFeature(Parser.namespacesFeature, true);
reader.setFeature(Parser.namespacePrefixesFeature, true);
try {
Transformer transformer = TransformerFactory.newInstance().newTransformer();
DOMResult result = new DOMResult();
transformer.transform(new SAXSource(reader, xml), result);
return XMLUtil.getDocument(result.getNode());
}
catch (Exception e) {
throw new SAXException(e);
}
}
private static DocumentBuilderFactory newDocumentBuilderFactory(InputSource validator) {
DocumentBuilderFactory factory;
if (validator != null) {
factory = _newDocumentBuilderFactory();// DocumentBuilderFactory.newInstance();
XMLUtil.setAttributeEL(factory, XMLConstants.VALIDATION_SCHEMA, Boolean.TRUE);
XMLUtil.setAttributeEL(factory, XMLConstants.VALIDATION_SCHEMA_FULL_CHECKING, Boolean.TRUE);
factory.setNamespaceAware(true);
factory.setValidating(true);
}
else {
factory = _newDocumentBuilderFactory();// DocumentBuilderFactory.newInstance();
XMLUtil.setAttributeEL(factory, XMLConstants.NON_VALIDATING_DTD_EXTERNAL, Boolean.FALSE);
XMLUtil.setAttributeEL(factory, XMLConstants.NON_VALIDATING_DTD_GRAMMAR, Boolean.FALSE);
factory.setNamespaceAware(true);
factory.setValidating(false);
}
PageContext pc = ThreadLocalPageContext.get();
if (pc != null) {
ApplicationContextSupport ac = ((ApplicationContextSupport) pc.getApplicationContext());
Struct features = ac == null ? null : ac.getXmlFeatures();
if (features != null) {
try { // handle feature aliases, e.g. secure
Object obj;
boolean featureValue;
obj = features.get(KEY_FEATURE_SECURE, null);
if (obj != null) {
featureValue = Caster.toBoolean(obj);
if (featureValue) {
// set features per
// https://cheatsheetseries.owasp.org/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.html
factory.setFeature(XMLConstants.FEATURE_DISALLOW_DOCTYPE_DECL, true);
factory.setFeature(XMLConstants.FEATURE_EXTERNAL_GENERAL_ENTITIES, false);
factory.setFeature(XMLConstants.FEATURE_EXTERNAL_PARAMETER_ENTITIES, false);
factory.setFeature(XMLConstants.FEATURE_NONVALIDATING_LOAD_EXTERNAL_DTD, false);
factory.setXIncludeAware(false);
factory.setExpandEntityReferences(false);
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
factory.setAttribute(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
}
features.remove(KEY_FEATURE_SECURE);
}
obj = features.get(KEY_FEATURE_DISALLOW_DOCTYPE_DECL, null);
if (obj != null) {
featureValue = Caster.toBoolean(obj);
factory.setFeature(XMLConstants.FEATURE_DISALLOW_DOCTYPE_DECL, featureValue);
features.remove(KEY_FEATURE_DISALLOW_DOCTYPE_DECL);
}
obj = features.get(KEY_FEATURE_EXTERNAL_GENERAL_ENTITIES, null);
if (obj != null) {
featureValue = Caster.toBoolean(obj);
factory.setFeature(XMLConstants.FEATURE_EXTERNAL_GENERAL_ENTITIES, featureValue);
features.remove(KEY_FEATURE_EXTERNAL_GENERAL_ENTITIES);
}
}
catch (PageException | ParserConfigurationException ex) {
throw new RuntimeException(ex);
}
features.forEach((k, v) -> {
try {
factory.setFeature(k.toString().toLowerCase(), Caster.toBoolean(v));
}
catch (PageException | ParserConfigurationException ex) {
throw new RuntimeException(ex);
}
});
}
}
return factory;
}
private static Class<DocumentBuilderFactory> dbf;
private static URL documentBuilderFactoryResource;
private static URL saxParserFactoryResource;
private static Class<DocumentBuilderFactory> _newDocumentBuilderFactoryClass() {
if (dbf == null) {
Thread.currentThread().setContextClassLoader(new EnvClassLoader((ConfigImpl) ThreadLocalPageContext.getConfig()));
Class<DocumentBuilderFactory> clazz = null;
try {
clazz = ClassUtil.loadClass("com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
}
catch (Exception e) {
try {
clazz = ClassUtil.loadClass("org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
}
catch (Exception ee) {}
}
if (clazz != null) {
dbf = clazz;
LogUtil.log(null, Log.LEVEL_INFO, "application", "xml", clazz.getName() + " is used as DocumentBuilderFactory");
}
}
return dbf;
}
public static String getXMLParserConfigurationName() {
String value = "org.apache.xerces.parsers.XIncludeAwareParserConfiguration";
System.setProperty("org.apache.xerces.xni.parser.XMLParserConfiguration", value);
return value; // TODO better impl, still used?
}
public static String getDocumentBuilderFactoryName() {
Class<DocumentBuilderFactory> clazz = _newDocumentBuilderFactoryClass();
if (clazz != null) return clazz.getName();
return DocumentBuilderFactory.newInstance().getClass().getName();
}
public static URL getDocumentBuilderFactoryResource() throws IOException {
if (documentBuilderFactoryResource == null) {
String name = getDocumentBuilderFactoryName();
Resource localFile = SystemUtil.getTempDirectory().getRealResource(name.replace('\\', '_').replace('/', '_'));
IOUtil.write(localFile, name.getBytes());
documentBuilderFactoryResource = ((File) localFile).toURI().toURL();
}
return documentBuilderFactoryResource;
}
private static DocumentBuilderFactory _newDocumentBuilderFactory() {
Class<DocumentBuilderFactory> clazz = _newDocumentBuilderFactoryClass();
DocumentBuilderFactory factory = null;
if (clazz != null) {
try {
factory = (DocumentBuilderFactory) ClassUtil.loadInstance(clazz);
}
catch (Exception e) {}
}
if (factory == null) factory = DocumentBuilderFactory.newInstance();
return factory;
}
private static SAXParserFactory newSAXParserFactory() {
if (saxParserFactory == null) {
Thread.currentThread().setContextClassLoader(new EnvClassLoader((ConfigImpl) ThreadLocalPageContext.getConfig()));
saxParserFactory = SAXParserFactory.newInstance();
}
return saxParserFactory;
}
public static String getSAXParserFactoryName() {
return newSAXParserFactory().getClass().getName();
}
public static URL getSAXParserFactoryResource() throws IOException {
if (saxParserFactoryResource == null) {
String name = getSAXParserFactoryName();
Resource localFile = SystemUtil.getTempDirectory().getRealResource(name.replace('\\', '_').replace('/', '_'));
IOUtil.write(localFile, name.getBytes());
saxParserFactoryResource = ((File) localFile).toURI().toURL();
}
return saxParserFactoryResource;
}
public static XMLReader createXMLReader() throws SAXException {
Thread.currentThread().setContextClassLoader(new EnvClassLoader((ConfigImpl) ThreadLocalPageContext.getConfig()));
try {
return XMLReaderFactory.createXMLReader("com.sun.org.apache.xerces.internal.parsers.SAXParser");
}
catch (Exception e) {}
try {
return XMLReaderFactory.createXMLReader("org.apache.xerces.internal.parsers.SAXParser");
}
catch (Exception ee) {}
try {
return XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
}
catch (Exception ee) {}
try {
return newSAXParserFactory().newSAXParser().getXMLReader();
}
catch (ParserConfigurationException pce) {
throw new RuntimeException(pce);
}
}
private static void setAttributeEL(DocumentBuilderFactory factory, String name, Object value) {
try {
factory.setAttribute(name, value);
}
catch (Throwable t) {
ExceptionUtil.rethrowIfNecessary(t);
}
}
/**
* sets a node to a node (Expression Less)
*
* @param node
* @param key
* @param value
* @return Object set
*/
public static Object setPropertyEL(Node node, Collection.Key key, Object value) {
try {
return setProperty(node, key, value);
}
catch (PageException e) {
return null;
}
}
public static Object setProperty(Node node, Collection.Key key, Object value, boolean caseSensitive, Object defaultValue) {
try {
return setProperty(node, key, value, caseSensitive);
}
catch (PageException e) {
return defaultValue;
}
}
/**
* sets a node to a node
*
* @param node
* @param k
* @param value
* @return Object set
* @throws PageException
*/
public static Object setProperty(Node node, Collection.Key k, Object value) throws PageException {
return setProperty(node, k, value, isCaseSensitve(node));
}
public static Object setProperty(Node node, Collection.Key k, Object value, boolean caseSensitive) throws PageException {
Document doc = getDocument(node);
boolean isXMLChildren;
// Comment
if (k.equals(XMLCOMMENT)) {
removeChildren(XMLCaster.toRawNode(node), Node.COMMENT_NODE, false);
node.appendChild(XMLCaster.toRawNode(XMLCaster.toComment(doc, value)));
}
// NS URI
else if (k.equals(XMLNSURI)) {
// TODO impl
throw new ExpressionException("XML NS URI can't be set", "not implemented");
}
// Prefix
else if (k.equals(XMLNSPREFIX)) {
// TODO impl
throw new ExpressionException("XML NS Prefix can't be set", "not implemented");
// node.setPrefix(Caster.toString(value));
}
// Root
else if (k.equals(XMLROOT)) {
doc.appendChild(XMLCaster.toNode(doc, value, false));
}
// Parent
else if (k.equals(XMLPARENT)) {
Node parent = getParentNode(node, caseSensitive);
Key name = KeyImpl.init(parent.getNodeName());
parent = getParentNode(parent, caseSensitive);
if (parent == null) throw new ExpressionException("there is no parent element, you are already on the root element");
return setProperty(parent, name, value, caseSensitive);
}
// Name
else if (k.equals(XMLNAME)) {
throw new XMLException("You can't assign a new value for the property [xmlname]");
}
// Type
else if (k.equals(XMLTYPE)) {
throw new XMLException("You can't change type of a xml node [xmltype]");
}
// value
else if (k.equals(XMLVALUE)) {
node.setNodeValue(Caster.toString(value));
}
// Attributes
else if (k.equals(XMLATTRIBUTES)) {
Element parent = XMLCaster.toElement(doc, node);
Attr[] attres = XMLCaster.toAttrArray(doc, value);
// print.ln("=>"+value);
for (int i = 0; i < attres.length; i++) {
if (attres[i] != null) {
parent.setAttributeNode(attres[i]);
// print.ln(attres[i].getName()+"=="+attres[i].getValue());
}
}
}
// Text
else if (k.equals(XMLTEXT)) {
removeChildCharacterData(XMLCaster.toRawNode(node), false);
node.appendChild(XMLCaster.toRawNode(XMLCaster.toText(doc, value)));
}
// CData
else if (k.equals(XMLCDATA)) {
removeChildCharacterData(XMLCaster.toRawNode(node), false);
node.appendChild(XMLCaster.toRawNode(XMLCaster.toCDATASection(doc, value)));
}
// Children
else if ((isXMLChildren = k.equals(XMLCHILDREN)) || k.equals(XMLNODES)) {
Node[] nodes = XMLCaster.toNodeArray(doc, value);
removeChildren(XMLCaster.toRawNode(node), isXMLChildren ? Node.ELEMENT_NODE : XMLUtil.UNDEFINED_NODE, false);
for (int i = 0; i < nodes.length; i++) {
if (nodes[i] == node) throw new XMLException("can't assign a XML Node to himself");
if (nodes[i] != null) node.appendChild(XMLCaster.toRawNode(nodes[i]));
}
}
else {
boolean isIndex = false;
Node child = XMLCaster.toNode(doc, value, false);
if (!k.getString().equalsIgnoreCase(child.getNodeName()) && !(isIndex = Decision.isInteger(k))) {
throw new XMLException("if you assign a XML Element to a XMLStruct , assignment property must have same name like XML Node Name",
"Property Name is " + k.getString() + " and XML Element Name is " + child.getNodeName());
}
Node n;
// by index
if (isIndex) {
NodeList list = XMLUtil.getChildNodes(node.getParentNode(), Node.ELEMENT_NODE, true, node.getNodeName());
int len = list.getLength();
int index = Caster.toIntValue(k);
if (index > len || index < 1) {
String detail = len > 1 ? "your index is " + index + ", but there are only " + len + " child elements"
: "your index is " + index + ", but there is only " + len + " child element";
throw new XMLException("index is out of range", detail);
}
n = list.item(index - 1);
XMLUtil.replaceChild(child, n);
return value;
}
NodeList list = XMLUtil.getChildNodes(node, Node.ELEMENT_NODE);
int len = list.getLength();
// by name
for (int i = 0; i < len; i++) {
n = list.item(i);
if (nameEqual(n, k.getString(), caseSensitive)) {
XMLUtil.replaceChild(child, n);
return value;
}
}
node.appendChild(XMLCaster.toRawNode(child));
}
return value;
}
public static void replaceChild(Node newChild, Node oldChild) {
Node nc = XMLCaster.toRawNode(newChild);
Node oc = XMLCaster.toRawNode(oldChild);
Node p = oc.getParentNode();
if (nc != oc) p.replaceChild(nc, oc);
}
public static Object getProperty(Node node, Collection.Key key, Object defaultValue) {
return getProperty(node, key, isCaseSensitve(node), defaultValue);
}
/**
* returns a property from a XMl Node (Expression Less)
*
* @param node
* @param k
* @param caseSensitive
* @return Object matching key
*/
public static Object getProperty(Node node, Collection.Key k, boolean caseSensitive, Object defaultValue) {
try {
return getProperty(node, k, caseSensitive);
}
catch (SAXException e) {
return defaultValue;
}
}
public static Object getProperty(Node node, Collection.Key key) throws SAXException {
return getProperty(node, key, isCaseSensitve(node));
}
/**
* returns a property from a XMl Node
*
* @param node
* @param k
* @param caseSensitive
* @return Object matching key
* @throws SAXException
*/
public static Object getProperty(Node node, Collection.Key k, boolean caseSensitive) throws SAXException {
// String lcKey=StringUtil.toLowerCase(key);
if (k.getLowerString().startsWith("xml")) {
// Comment
if (k.equals(XMLCOMMENT)) {
StringBuffer sb = new StringBuffer();
NodeList list = node.getChildNodes();
int len = list.getLength();
for (int i = 0; i < len; i++) {
Node n = list.item(i);
if (n instanceof Comment) {
sb.append(((Comment) n).getData());
}
}
return sb.toString();
}
// NS URI
if (k.equals(XMLNSURI)) {
undefinedInRoot(k, node);
return param(node.getNamespaceURI(), "");
}
// Prefix
if (k.equals(XMLNSPREFIX)) {
undefinedInRoot(k, node);
return param(node.getPrefix(), "");
}
// Root
else if (k.equals(XMLROOT)) {
Element re = getRootElement(node, caseSensitive);
if (re == null) throw new SAXException("Attribute [" + k.getString() + "] not found in XML, XML is empty");
return param(re, "");
}
// Parent
else if (k.equals(XMLPARENT)) {
Node parent = getParentNode(node, caseSensitive);
if (parent == null) {
if (node.getNodeType() == Node.DOCUMENT_NODE)
throw new SAXException("Attribute [" + k.getString() + "] not found in XML, there is no parent element, you are already at the root element");
throw new SAXException("Attribute [" + k.getString() + "] not found in XML, there is no parent element");
}
return parent;
}
// Name
else if (k.equals(XMLNAME)) {
return node.getNodeName();
}
// Value
else if (k.equals(XMLVALUE)) {
return StringUtil.toStringEmptyIfNull(node.getNodeValue());
}
// Type
else if (k.equals(XMLTYPE)) {
return getTypeAsString(node, true);
}
// Attributes
else if (k.equals(XMLATTRIBUTES)) {
NamedNodeMap attr = node.getAttributes();
if (attr == null) throw undefined(k, node);
return new XMLAttributes(node, caseSensitive);
}
// Text
else if (k.equals(XMLTEXT)) {
undefinedInRoot(k, node);
if (node instanceof Text || node instanceof CDATASection) return ((CharacterData) node).getData();
StringBuilder sb = new StringBuilder();
NodeList list = node.getChildNodes();
int len = list.getLength();
for (int i = 0; i < len; i++) {
Node n = list.item(i);
if (n instanceof Text || n instanceof CDATASection) {
sb.append(((CharacterData) n).getData());
}
}
return sb.toString();
}
// CData
else if (k.equals(XMLCDATA)) {
undefinedInRoot(k, node);
StringBuffer sb = new StringBuffer();
NodeList list = node.getChildNodes();
int len = list.getLength();
for (int i = 0; i < len; i++) {
Node n = list.item(i);
if (n instanceof Text || n instanceof CDATASection) {
sb.append(((CharacterData) n).getData());
}
}
return sb.toString();
}
// Children
else if (k.equals(XMLCHILDREN)) {
return new XMLNodeList(node, caseSensitive, Node.ELEMENT_NODE);
}
// Nodes
else if (k.equals(XMLNODES)) {
return new XMLNodeList(node, caseSensitive, XMLUtil.UNDEFINED_NODE);
}
}
if (node instanceof Document) {
node = ((Document) node).getDocumentElement();
if (node == null) throw new SAXException("Attribute [" + k.getString() + "] not found in XML, XML is empty");
// if((!caseSensitive && node.getNodeName().equalsIgnoreCase(k.getString())) ||
// (caseSensitive &&
// node.getNodeName().equals(k.getString()))) {
if (nameEqual(node, k.getString(), caseSensitive)) {
return XMLStructFactory.newInstance(node, caseSensitive);
}
}
else if (node.getNodeType() == Node.ELEMENT_NODE && Decision.isInteger(k)) {
int index = Caster.toIntValue(k, 0);
int count = 0;
Node parent = node.getParentNode();
String nodeName = node.getNodeName();
Element[] children = XMLUtil.getChildElementsAsArray(parent);
for (int i = 0; i < children.length; i++) {
if (XMLUtil.nameEqual(children[i], nodeName, caseSensitive)) count++;
if (count == index) return XMLCaster.toXMLStruct(children[i], caseSensitive);
}
String detail;
if (count == 0) detail = "there are no Elements with this name";
else if (count == 1) detail = "there is only 1 Element with this name";
else detail = "there are only " + count + " Elements with this name";
throw new SAXException("invalid index [" + k.getString() + "] for Element with name [" + node.getNodeName() + "], " + detail);
}
else {
List<Node> children = XMLUtil.getChildNodesAsList(node, Node.ELEMENT_NODE, caseSensitive, null);
int len = children.size();
Array array = null;// new ArrayImpl();
Element el;
XMLStruct sct = null, first = null;
for (int i = 0; i < len; i++) {
el = (Element) children.get(i);// XMLCaster.toXMLStruct(getChildNode(index),caseSensitive);
if (XMLUtil.nameEqual(el, k.getString(), caseSensitive)) {
sct = XMLCaster.toXMLStruct(el, caseSensitive);
if (array != null) {
array.appendEL(sct);
}
else if (first != null) {
array = new ArrayImpl();
array.appendEL(first);
array.appendEL(sct);
}
else {
first = sct;
}
}
}
if (array != null) {
try {
return new XMLMultiElementStruct(array, false);
}
catch (PageException e) {}
}
if (first != null) return first;
}
throw new SAXException("Attribute [" + k.getString() + "] not found");
}
private static SAXException undefined(Key key, Node node) {
if (node.getNodeType() == Node.DOCUMENT_NODE) return new SAXException(
"you cannot address [" + key + "] on the Document Object, to address [" + key + "] from the root Node use [{variable-name}.xmlRoot." + key + "]");
return new SAXException(key + " is undefined");
}
private static void undefinedInRoot(Key key, Node node) throws SAXException {
if (node.getNodeType() == Node.DOCUMENT_NODE) throw undefined(key, node);
}
/**
* check if given name is equal to name of the element (with and without namespace)
*
* @param node
* @param name
* @param caseSensitive
* @return
*/
public static boolean nameEqual(Node node, String name, boolean caseSensitive) {
if (name == null) return false;
if (caseSensitive) {
return name.equals(node.getNodeName()) || name.equals(node.getLocalName());
}
return name.equalsIgnoreCase(node.getNodeName()) || name.equalsIgnoreCase(node.getLocalName());
}
public static boolean isCaseSensitve(Node node) {
if (node instanceof XMLStruct) return ((XMLStruct) node).isCaseSensitive();
return true;
}
/**
* removes child from a node
*
* @param node
* @param k
* @param caseSensitive
* @return removed property
*/
public static Object removeProperty(Node node, Collection.Key k, boolean caseSensitive) {
boolean isXMLChildren;
// String lcKeyx=k.getLowerString();
if (k.getLowerString().startsWith("xml")) {
// Comment
if (k.equals(XMLCOMMENT)) {
StringBuffer sb = new StringBuffer();
NodeList list = node.getChildNodes();
int len = list.getLength();
for (int i = 0; i < len; i++) {
Node n = list.item(i);
if (n instanceof Comment) {
sb.append(((Comment) n).getData());
node.removeChild(XMLCaster.toRawNode(n));
}
}
return sb.toString();
}
// Text
else if (k.equals(XMLTEXT)) {
if (node instanceof Text || node instanceof CDATASection) return ((CharacterData) node).getData();
StringBuilder sb = new StringBuilder();
NodeList list = node.getChildNodes();
int len = list.getLength();
for (int i = 0; i < len; i++) {
Node n = list.item(i);
if (n instanceof Text || n instanceof CDATASection) {
sb.append(((CharacterData) n).getData());
node.removeChild(XMLCaster.toRawNode(n));
}
}
return sb.toString();
}
// children
else if ((isXMLChildren = k.equals(XMLCHILDREN)) || k.equals(XMLNODES)) {
NodeList list = node.getChildNodes();
Node child;
for (int i = list.getLength() - 1; i >= 0; i--) {
child = XMLCaster.toRawNode(list.item(i));
if (isXMLChildren && child.getNodeType() != Node.ELEMENT_NODE) continue;
node.removeChild(child);
}
return list;
}
}
NodeList nodes = node.getChildNodes();
Array array = new ArrayImpl();
for (int i = nodes.getLength() - 1; i >= 0; i--) {
Object o = nodes.item(i);
if (o instanceof Element) {
Element el = (Element) o;
if (nameEqual(el, k.getString(), caseSensitive)) {
array.appendEL(XMLCaster.toXMLStruct(el, caseSensitive));
node.removeChild(XMLCaster.toRawNode(el));
}
}
}
if (array.size() > 0) {
try {
return new XMLMultiElementStruct(array, false);
}
catch (PageException e) {}
}
return null;
}
private static Object param(Object o1, Object o2) {
if (o1 == null) return o2;
return o1;
}
/**
* return the root Element from a node
*
* @param node node to get root element from
* @param caseSensitive
* @return Root Element
*/
public static Element getRootElement(Node node, boolean caseSensitive) {
Document doc = XMLUtil.getDocument(node);
Element el = doc.getDocumentElement();
if (el == null) return null;
return (Element) XMLStructFactory.newInstance(el, caseSensitive);
}