-
-
Notifications
You must be signed in to change notification settings - Fork 81
/
AttributeCollector.java
1214 lines (1105 loc) · 41.3 KB
/
AttributeCollector.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
/* Woodstox XML processor
*
* Copyright (c) 2004- Tatu Saloranta, tatu.saloranta@iki.fi
*
* Licensed under the License specified in file LICENSE, included with
* the source code.
* You may not use this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ctc.wstx.sr;
import java.io.IOException;
import java.util.Arrays;
import javax.xml.XMLConstants;
import javax.xml.stream.Location;
import javax.xml.stream.XMLStreamException;
import javax.xml.namespace.QName;
import org.codehaus.stax2.ri.typed.CharArrayBase64Decoder;
import org.codehaus.stax2.ri.typed.ValueDecoderFactory;
import org.codehaus.stax2.typed.Base64Variant;
import org.codehaus.stax2.typed.TypedArrayDecoder;
import org.codehaus.stax2.typed.TypedValueDecoder;
import org.codehaus.stax2.typed.TypedXMLStreamException;
import org.codehaus.stax2.validation.XMLValidator;
import com.ctc.wstx.api.ReaderConfig;
import com.ctc.wstx.cfg.ErrorConsts;
import com.ctc.wstx.sw.XmlWriter;
import com.ctc.wstx.util.*;
/**
* Shared base class that defines API stream reader uses to communicate
* with the attribute collector implementation, independent of whether it's
* operating in namespace-aware or non-namespace modes.
* Collector class is used to build up attribute lists; for the most part
* will just hold references to few specialized {@link TextBuilder}s that
* are used to create efficient semi-shared value Strings.
*/
public final class AttributeCollector
{
final static int INT_SPACE = 0x0020;
/**
* Threshold value that indicates minimum length for lists instances
* that need a Map structure, for fast attribute access by fully-qualified
* name.
*/
protected final static int LONG_ATTR_LIST_LEN = 4;
/**
* Expected typical maximum number of attributes for any element;
* chosen to minimize need to resize, while trying not to waste space.
* Dynamically grown; better not to set too high to avoid excessive
* overhead for small attribute-less documents.
*/
protected final static int EXP_ATTR_COUNT = 12;
protected final static int EXP_NS_COUNT = 6;
/**
* This value is used to indicate that we shouldn't keep track
* of index of xml:id attribute -- generally done when Xml:id
* support is disabled
*/
protected final static int XMLID_IX_DISABLED = -2;
protected final static int XMLID_IX_NONE = -1;
protected final static InternCache sInternCache = InternCache.getInstance();
/*
///////////////////////////////////////////////////////////
// Configuration
///////////////////////////////////////////////////////////
*/
// // Settings for matching Xml:id attribute
protected final String mXmlIdPrefix;
protected final String mXmlIdLocalName;
/*
///////////////////////////////////////////////////////////
// Collected attribute (incl namespace attrs) information:
///////////////////////////////////////////////////////////
*/
/**
* Array of attributes collected for this element.
*/
protected Attribute[] mAttributes;
/**
* Actual number of attributes collected, including attributes
* added via default values.
*/
protected int mAttrCount;
/**
* Number of attribute values actually parsed, not including
* ones created via default value expansion. Equal to or less than
* {@link #mAttrCount}.
*/
protected int mNonDefCount;
/**
* Array of namespace declaration attributes collected for this element;
* not used in non-namespace-aware mode
*/
protected Attribute[] mNamespaces;
/**
* Number of valid namespace declarations in {@link #mNamespaces}.
*/
protected int mNsCount;
/**
* Flag to indicate whether the default namespace has already been declared
* for the current element.
*/
protected boolean mDefaultNsDeclared = false;
/**
* Index of "xml:id" attribute, if one exists for the current
* element; {@link #XMLID_IX_NONE} if none.
*/
protected int mXmlIdAttrIndex;
/*
///////////////////////////////////////////////////////////
// Attribute (and ns) value builders
///////////////////////////////////////////////////////////
*/
/**
* TextBuilder into which values of all attributes are appended
* to, including default valued ones (defaults are added after
* explicit ones).
* Constructed lazily, if and when needed (not needed
* for short attribute-less docs)
*/
protected TextBuilder mValueBuilder = null;
/**
* TextBuilder into which values of namespace URIs are added (including
* URI for the default namespace, if one defined).
*/
private final TextBuilder mNamespaceBuilder = new TextBuilder(EXP_NS_COUNT);
/*
//////////////////////////////////////////////////////////////
// Information that defines "Map-like" data structure used for
// quick access to attribute values by fully-qualified name
//////////////////////////////////////////////////////////////
*/
/**
* Encoding of a data structure that contains mapping from
* attribute names to attribute index in main attribute name arrays.
*<p>
* Data structure contains two separate areas; main hash area (with
* size <code>mAttrHashSize</code>), and remaining spillover area
* that follows hash area up until (but not including)
* <code>mAttrSpillEnd</code> index.
* Main hash area only contains indexes (index+1; 0 signifying empty slot)
* to actual attributes; spillover area has both hash and index for
* any spilled entry. Spilled entries are simply stored in order
* added, and need to be searched using linear search. In case of both
* primary hash hits and spills, eventual comparison with the local
* name needs to be done with actual name array.
*/
protected int[] mAttrMap = null;
/**
* Size of hash area in <code>mAttrMap</code>; generally at least 20%
* more than number of attributes (<code>mAttrCount</code>).
*/
protected int mAttrHashSize;
/**
* Pointer to int slot right after last spill entr, in
* <code>mAttrMap</code> array.
*/
protected int mAttrSpillEnd;
protected int mMaxAttributesPerElement;
// protected int mMaxAttributeSize;
/*
///////////////////////////////////////////////
// Life-cycle:
///////////////////////////////////////////////
*/
protected AttributeCollector(ReaderConfig cfg, boolean nsAware)
{
mXmlIdAttrIndex = cfg.willDoXmlIdTyping() ? XMLID_IX_NONE : XMLID_IX_DISABLED;
if (nsAware) {
mXmlIdPrefix = "xml";
mXmlIdLocalName = "id";
} else {
mXmlIdPrefix = null;
mXmlIdLocalName = "xml:id";
}
mMaxAttributesPerElement = cfg.getMaxAttributesPerElement();
// mMaxAttributeSize = cfg.getMaxAttributeSize();
}
/**
* Method called to allow reusing of collector, usually right before
* starting collecting attributes for a new start tag.
*/
/**
* Method called to allow reusing of collector, usually right before
* starting collecting attributes for a new start tag.
*<p>
* Note: public only so that it can be called by unit tests.
*/
public void reset()
{
if (mNsCount > 0) {
mNamespaceBuilder.reset();
mDefaultNsDeclared = false;
mNsCount = 0;
}
/* No need to clear attr name, or NS prefix Strings; they are
* canonicalized and will be referenced by symbol table in any
* case... so we can save trouble of cleaning them up. This Object
* will get GC'ed soon enough, after parser itself gets disposed of.
*/
if (mAttrCount > 0) {
mValueBuilder.reset();
mAttrCount = 0;
if (mXmlIdAttrIndex >= 0) {
mXmlIdAttrIndex = XMLID_IX_NONE;
}
}
/* Note: attribute values will be cleared later on, when validating
* namespaces. This so that we know how much to clean up; and
* occasionally can also just avoid clean up (when resizing)
*/
}
/**
* Method that can be called to force space normalization (remove
* leading/trailing spaces, replace non-spaces white space with
* spaces, collapse spaces to one) on specified attribute.
* Currently called by {@link InputElementStack} to force
* normalization of Xml:id attribute
*/
public void normalizeSpacesInValue(int index)
{
// StringUtil has a method, but it works on char arrays...
char[] attrCB = mValueBuilder.getCharBuffer();
String normValue = StringUtil.normalizeSpaces
(attrCB, getValueStartOffset(index), getValueStartOffset(index+1));
if (normValue != null) {
mAttributes[index].setValue(normValue);
}
}
/*
///////////////////////////////////////////////
// Public accesors (for stream reader)
///////////////////////////////////////////////
*/
/**
* @return Number of namespace declarations collected, including
* possible default namespace declaration
*/
protected int getNsCount() {
return mNsCount;
}
public boolean hasDefaultNs() {
return mDefaultNsDeclared;
}
// // // Direct access to attribute/NS prefixes/localnames/URI
public final int getCount() {
return mAttrCount;
}
/**
* @return Number of attributes that were explicitly specified; may
* be less than the total count due to attributes created using
* attribute default values
*/
public int getSpecifiedCount() {
return mNonDefCount;
}
public String getNsPrefix(int index) {
if (index < 0 || index >= mNsCount) {
throwIndex(index);
}
// for NS decls, local name is stored in prefix
return mNamespaces[index].mLocalName;
}
public String getNsURI(int index) {
if (index < 0 || index >= mNsCount) {
throwIndex(index);
}
return mNamespaces[index].mNamespaceURI;
}
// // // Direct access to attribute/NS prefixes/localnames/URI
public String getPrefix(int index) {
if (index < 0 || index >= mAttrCount) {
throwIndex(index);
}
return mAttributes[index].mPrefix;
}
public String getLocalName(int index) {
if (index < 0 || index >= mAttrCount) {
throwIndex(index);
}
return mAttributes[index].mLocalName;
}
public String getURI(int index) {
if (index < 0 || index >= mAttrCount) {
throwIndex(index);
}
return mAttributes[index].mNamespaceURI;
}
public QName getQName(int index) {
if (index < 0 || index >= mAttrCount) {
throwIndex(index);
}
return mAttributes[index].getQName();
}
/**
*<p>
* Note: the main reason this method is defined at this level, and
* made final, is performance. JIT may be able to fully inline this
* method, even when reference is via this base class. This is important
* since this is likely to be the most often called method of the
* collector instances.
*/
public final String getValue(int index)
{
if (index < 0 || index >= mAttrCount) {
throwIndex(index);
}
String full = mValueBuilder.getAllValues();
Attribute attr = mAttributes[index];
++index;
if (index < mAttrCount) { // not last
int endOffset = mAttributes[index].mValueStartOffset;
return attr.getValue(full, endOffset);
}
// last can be optimized bit more:
return attr.getValue(full);
}
public String getValue(String nsURI, String localName)
{
// Primary hit?
int hashSize = mAttrHashSize;
if (hashSize == 0) { // sanity check, for 'no attributes'
return null;
}
int hash = localName.hashCode();
if (nsURI != null) {
if (nsURI.length() == 0) {
nsURI = null;
} else {
hash ^= nsURI.hashCode();
}
}
int ix = mAttrMap[hash & (hashSize-1)];
if (ix == 0) { // nothing in here; no spills either
return null;
}
--ix;
// Is primary candidate match?
if (mAttributes[ix].hasQName(nsURI, localName)) {
return getValue(ix);
}
// Nope, need to traverse spill list, which has 2 entries for
// each spilled attribute id; first for hash value, second index.
for (int i = hashSize, len = mAttrSpillEnd; i < len; i += 2) {
if (mAttrMap[i] != hash) {
continue;
}
// Note: spill indexes are not off-by-one, since there's no need
// to mask 0
ix = mAttrMap[i+1];
if (mAttributes[ix].hasQName(nsURI, localName)) {
return getValue(ix);
}
}
return null;
}
/**
* Specialized version in which namespace information is completely ignored.
*
* @since 5.2
*/
public String getValueByLocalName(String localName)
{
// NOTE: can't use hashing, must do linear scan
switch (mAttrCount) {
case 4:
if (mAttributes[0].hasLocalName(localName)) return getValue(0);
if (mAttributes[1].hasLocalName(localName)) return getValue(1);
if (mAttributes[2].hasLocalName(localName)) return getValue(2);
if (mAttributes[3].hasLocalName(localName)) return getValue(3);
return null;
case 3:
if (mAttributes[0].hasLocalName(localName)) return getValue(0);
if (mAttributes[1].hasLocalName(localName)) return getValue(1);
if (mAttributes[2].hasLocalName(localName)) return getValue(2);
return null;
case 2:
if (mAttributes[0].hasLocalName(localName)) return getValue(0);
if (mAttributes[1].hasLocalName(localName)) return getValue(1);
return null;
case 1:
if (mAttributes[0].hasLocalName(localName)) return getValue(0);
return null;
case 0:
return null;
default:
for (int i = 0, end = mAttrCount; i < end; ++i) {
if (mAttributes[i].hasLocalName(localName)) {
return getValue(i);
}
}
return null;
}
}
public int getMaxAttributesPerElement() {
return mMaxAttributesPerElement;
}
public void setMaxAttributesPerElement(int maxAttributesPerElement) {
this.mMaxAttributesPerElement = maxAttributesPerElement;
}
public int findIndex(String localName) {
return findIndex(null, localName);
}
public int findIndex(String nsURI, String localName)
{
/* Note: most of the code is from getValue().. could refactor
* code, performance is bit of concern (one more method call
* if index access was separate).
* See comments on that method, for logics.
*/
// Primary hit?
int hashSize = mAttrHashSize;
if (hashSize == 0) { // sanity check, for 'no attributes'
return -1;
}
int hash = localName.hashCode();
if (nsURI != null) {
if (nsURI.length() == 0) {
nsURI = null;
} else {
hash ^= nsURI.hashCode();
}
}
int ix = mAttrMap[hash & (hashSize-1)];
if (ix == 0) { // nothing in here; no spills either
return -1;
}
--ix;
// Is primary candidate match?
if (mAttributes[ix].hasQName(nsURI, localName)) {
return ix;
}
/* Nope, need to traverse spill list, which has 2 entries for
* each spilled attribute id; first for hash value, second index.
*/
for (int i = hashSize, len = mAttrSpillEnd; i < len; i += 2) {
if (mAttrMap[i] != hash) {
continue;
}
/* Note: spill indexes are not off-by-one, since there's no need
* to mask 0
*/
ix = mAttrMap[i+1];
if (mAttributes[ix].hasQName(nsURI, localName)) {
return ix;
}
}
return -1;
}
public final boolean isSpecified(int index) {
return (index < mNonDefCount);
}
public final int getXmlIdAttrIndex() {
return mXmlIdAttrIndex;
}
/*
//////////////////////////////////////////////////////
// Type-safe accessors to support TypedXMLStreamReader
//////////////////////////////////////////////////////
*/
/**
* Method called to decode the whole attribute value as a single
* typed value.
* Decoding is done using the decoder provided.
*/
public final void decodeValue(int index, TypedValueDecoder tvd)
throws IllegalArgumentException
{
if (index < 0 || index >= mAttrCount) {
throwIndex(index);
}
/* Should be faster to pass the char array even if we might
* have a String
*/
// Either way, need to trim before passing:
char[] buf = mValueBuilder.getCharBuffer();
int start = mAttributes[index].mValueStartOffset;
int end = getValueStartOffset(index+1);
while (true) {
if (start >= end) {
tvd.handleEmptyValue();
return;
}
if (!StringUtil.isSpace(buf[start])) {
break;
}
++start;
}
// Trailing space?
while (--end > start && StringUtil.isSpace(buf[end])) { }
tvd.decode(buf, start, end+1);
}
/**
* Method called to decode the attribute value that consists of
* zero or more space-separated tokens.
* Decoding is done using the decoder provided.
* @return Number of tokens decoded
*/
public final int decodeValues(int index, TypedArrayDecoder tad,
InputProblemReporter rep)
throws XMLStreamException
{
if (index < 0 || index >= mAttrCount) {
throwIndex(index);
}
// Char[] faster than String... and no need to trim here:
return decodeValues(tad, rep,
mValueBuilder.getCharBuffer(),
mAttributes[index].mValueStartOffset,
getValueStartOffset(index+1));
}
public final byte[] decodeBinary(int index, Base64Variant v, CharArrayBase64Decoder dec,
InputProblemReporter rep)
throws XMLStreamException
{
if (index < 0 || index >= mAttrCount) {
throwIndex(index);
}
/* No point in trying to use String representation, even if one
* available, faster to process from char[]
*/
Attribute attr = mAttributes[index];
char[] cbuf = mValueBuilder.getCharBuffer();
int start = attr.mValueStartOffset;
int end = getValueStartOffset(index+1);
int len = end-start;
dec.init(v, true, cbuf, start, len, null);
try {
return dec.decodeCompletely();
} catch (IllegalArgumentException iae) {
// Need to convert to a checked stream exception
String lexical = new String(cbuf, start, len);
throw new TypedXMLStreamException(lexical, iae.getMessage(), rep.getLocation(), iae);
}
}
private final static int decodeValues(TypedArrayDecoder tad,
InputProblemReporter rep,
final char[] buf, int ptr, final int end)
throws XMLStreamException
{
int start = ptr;
int count = 0;
try {
decode_loop:
while (ptr < end) {
// First, any space to skip?
while (buf[ptr] <= INT_SPACE) {
if (++ptr >= end) {
break decode_loop;
}
}
// Then let's figure out non-space char (token)
start = ptr;
++ptr;
while (ptr < end && buf[ptr] > INT_SPACE) {
++ptr;
}
int tokenEnd = ptr;
++ptr; // to skip trailing space (or, beyond end)
// Ok, decode... any more room?
++count;
if (tad.decodeValue(buf, start, tokenEnd)) {
if (!checkExpand(tad)) {
break;
}
}
}
} catch (IllegalArgumentException iae) {
// Need to convert to a checked stream exception
Location loc = rep.getLocation();
String lexical = new String(buf, start, (ptr-start));
throw new TypedXMLStreamException(lexical, iae.getMessage(), loc, iae);
}
return count;
}
/**
* Internal method used to see if we can expand the buffer that
* the array decoder has. Bit messy, but simpler than having
* separately typed instances; and called rarely so that performance
* downside of instanceof is irrelevant.
*/
private final static boolean checkExpand(TypedArrayDecoder tad)
{
if (tad instanceof ValueDecoderFactory.BaseArrayDecoder) {
((ValueDecoderFactory.BaseArrayDecoder) tad).expand();
return true;
}
return false;
}
/*
///////////////////////////////////////////////
// Accessors for accessing helper objects
///////////////////////////////////////////////
*/
/**
* Method for getting start pointer within shared value buffer
* for given attribute. It is also the same as end pointer
* for preceding attribute, if any.
*/
protected int getValueStartOffset(int index)
{
if (index < mAttrCount) {
return mAttributes[index].mValueStartOffset;
}
return mValueBuilder.getCharSize();
}
protected char[] getSharedValueBuffer()
{
return mValueBuilder.getCharBuffer();
}
/**
* Method called to resolve and initialize specified collected
* namespace declaration
*
* @return Attribute that contains specified namespace declaration
*/
protected Attribute resolveNamespaceDecl(int index, boolean internURI)
{
Attribute ns = mNamespaces[index];
String full = mNamespaceBuilder.getAllValues();
String uri;
if (mNsCount == 0) {
uri = full;
} else {
++index;
if (index < mNsCount) { // not last
int endOffset = mNamespaces[index].mValueStartOffset;
uri = ns.getValue(full, endOffset);
} else { // is last
uri = ns.getValue(full);
}
}
if (internURI && uri.length() > 0) {
uri = sInternCache.intern(uri);
}
ns.mNamespaceURI = uri;
return ns;
}
/**
* Method needed by event creating code, to build a non-transient
* attribute container, to use with XMLEvent objects (specifically
* implementation of StartElement event).
*/
public ElemAttrs buildAttrOb()
{
int count = mAttrCount;
if (count == 0) {
return null;
}
// If we have actual attributes, let's first just create the
// raw array that has all attribute information:
String[] raw = new String[count << 2];
for (int i = 0; i < count; ++i) {
Attribute attr = mAttributes[i];
int ix = (i << 2);
raw[ix] = attr.mLocalName;
raw[ix+1] = attr.mNamespaceURI;
raw[ix+2] = attr.mPrefix;
raw[ix+3] = getValue(i);
}
// Do we have a "short" list?
if (count < LONG_ATTR_LIST_LEN) {
return new ElemAttrs(raw, mNonDefCount);
}
// Ok, nope; we need to also pass the Map information...
/* 02-Feb-2009, TSa: Must make a copy of the Map array now,
* otherwise could get overwritten.
*/
int amapLen = mAttrMap.length;
int[] amap = new int[amapLen];
// TODO: JDK 1.6 has Arrays.copyOf(), should use with Woodstox 6
System.arraycopy(mAttrMap, 0, amap, 0, amapLen);
return new ElemAttrs(raw, mNonDefCount,
amap, mAttrHashSize, mAttrSpillEnd);
}
protected void validateAttribute(int index, XMLValidator vld)
throws XMLStreamException
{
Attribute attr = mAttributes[index];
String normValue = vld.validateAttribute
(attr.mLocalName, attr.mNamespaceURI, attr.mPrefix,
mValueBuilder.getCharBuffer(),
getValueStartOffset(index),
getValueStartOffset(index+1));
if (normValue != null) {
attr.setValue(normValue);
}
}
/*
///////////////////////////////////////////////
// Attribute, namespace decl building
///////////////////////////////////////////////
*/
/**
* Low-level accessor method that attribute validation code may call
* for certain types of attributes; generally only for id and idref/idrefs
* attributes. It returns the underlying 'raw' attribute value buffer
* for direct access.
*/
public final TextBuilder getAttrBuilder(String attrPrefix, String attrLocalName) throws XMLStreamException
{
/* Ok: we have parsed prefixed-name of a regular
* attribute. So let's initialize the instance...
*/
if (mAttrCount == 0) {
if (mAttributes == null) {
allocBuffers();
}
mAttributes[0] = new Attribute(attrPrefix, attrLocalName, 0);
} else {
int valueStart = mValueBuilder.getCharSize();
if (mAttrCount >= mAttributes.length) {
if ((mAttrCount + mNsCount) >= mMaxAttributesPerElement) {
throw new XMLStreamException("Attribute limit ("+mMaxAttributesPerElement+") exceeded");
}
mAttributes = (Attribute[]) DataUtil.growArrayToAtMost(mAttributes,
mMaxAttributesPerElement);
}
Attribute curr = mAttributes[mAttrCount];
if (curr == null) {
mAttributes[mAttrCount] = new Attribute(attrPrefix, attrLocalName, valueStart);
} else {
curr.reset(attrPrefix, attrLocalName, valueStart);
}
}
++mAttrCount;
// 25-Sep-2006, TSa: Need to keep track of xml:id attribute?
if (attrLocalName == mXmlIdLocalName) {
if (attrPrefix == mXmlIdPrefix) {
if (mXmlIdAttrIndex != XMLID_IX_DISABLED) {
mXmlIdAttrIndex = mAttrCount - 1;
}
}
}
/* Can't yet create attribute map by name, since we only know
* name prefix, not necessarily matching URI.
*/
return mValueBuilder;
}
/**
* Method called by validator to insert an attribute that has a default
* value and wasn't yet included in collector's attribute set.
*
* @return Index of the newly added attribute, if added; -1 to indicate
* this was a duplicate
*/
public int addDefaultAttribute(String localName, String uri, String prefix,
String value) throws XMLStreamException
{
int attrIndex = mAttrCount;
if (attrIndex < 1) {
/* had no explicit attributes... better initialize now, then.
* Let's just use hash area of 4, and
*/
initHashArea();
}
/* Ok, first, since we do want to verify that we can not accidentally
* add duplicates, let's first try to add entry to Map, since that
* will catch dups.
*/
int hash = localName.hashCode();
if (uri != null && uri.length() > 0) {
hash ^= uri.hashCode();
}
int index = hash & (mAttrHashSize - 1);
int[] map = mAttrMap;
if (map[index] == 0) { // whoa, have room...
map[index] = attrIndex+1; // add 1 to get 1-based index (0 is empty marker)
} else { // nah, collision...
int currIndex = map[index]-1; // Index of primary collision entry
int spillIndex = mAttrSpillEnd;
map = spillAttr(uri, localName, map, currIndex, spillIndex,
hash, mAttrHashSize);
if (map == null) { // dup!
return -1; // could return negation (-(index+1)) of the prev index?
}
map[++spillIndex] = attrIndex; // no need to specifically avoid 0
mAttrMap = map;
mAttrSpillEnd = ++spillIndex;
}
/* Can reuse code; while we don't really need the builder,
* we need to add/reset attribute
*/
getAttrBuilder(prefix, localName);
Attribute attr = mAttributes[mAttrCount-1];
attr.mNamespaceURI = uri;
attr.setValue(value);
// attribute count has been updated; index is one less than count
return (mAttrCount-1);
}
/**
* Low-level mutator method that attribute validation code may call
* for certain types of attributes, when it wants to handle the whole
* validation and normalization process by itself. It is generally
* only called for id and idref/idrefs attributes, as those values
* are usually normalized.
*/
public final void setNormalizedValue(int index, String value)
{
mAttributes[index].setValue(value);
}
/**
* @return null if the default namespace URI has been already declared
* for the current element; TextBuilder to add URI to if not.
*/
public TextBuilder getDefaultNsBuilder() throws XMLStreamException
{
if (mDefaultNsDeclared) {
return null;
}
mDefaultNsDeclared = true;
return getNsBuilder(null);
}
/**
* @return null if prefix has been already declared; TextBuilder to
* add value to if not.
*/
public TextBuilder getNsBuilder(String prefix) throws XMLStreamException
{
// first: must verify that it's not a dup
if (mNsCount == 0) {
if (mNamespaces == null) {
mNamespaces = new Attribute[Math.min(EXP_NS_COUNT, mMaxAttributesPerElement)];
}
mNamespaces[0] = new Attribute(null, prefix, 0);
} else {
int len = mNsCount;
/* Ok: must ensure that there are no duplicate namespace
* declarations (ie. decls with same prefix being bound)
*/
if (prefix != null) { // null == default ns
for (int i = 0; i < len; ++i) {
// note: for ns decls, bound prefix is in 'local name'
if (prefix == mNamespaces[i].mLocalName) {
return null;
}
}
}
if (len >= mNamespaces.length) {
if ((mAttrCount + mNsCount) >= mMaxAttributesPerElement) {
throw new XMLStreamException("Attribute limit ("+mMaxAttributesPerElement+") exceeded");
}
mNamespaces = (Attribute[]) DataUtil.growArrayToAtMost(mNamespaces,
mMaxAttributesPerElement);
}
int uriStart = mNamespaceBuilder.getCharSize();
Attribute curr = mNamespaces[len];
if (curr == null) {
mNamespaces[len] = new Attribute(null, prefix, uriStart);
} else {
curr.reset(null, prefix, uriStart);
}
}
++mNsCount;
return mNamespaceBuilder;
}
/**
* Method called to resolve namespace URIs from attribute prefixes.
*<p>
* Note: public only so that it can be called by unit tests.
*
* @param rep Reporter to use for reporting well-formedness problems
* @param ns Namespace prefix/URI mappings active for this element
*
* @return Index of xml:id attribute, if any, -1 if not
*/
public int resolveNamespaces(InputProblemReporter rep, StringVector ns)
throws XMLStreamException
{
int attrCount = mAttrCount;
/* Let's now set number of 'real' attributes, to allow figuring
* out number of attributes created via default value expansion
*/
mNonDefCount = attrCount;
if (attrCount < 1) {
// Checked if doing access by FQN:
mAttrHashSize = mAttrSpillEnd = 0;
// And let's just bail out, too...
return mXmlIdAttrIndex;
}
for (int i = 0; i < attrCount; ++i) {
Attribute attr = mAttributes[i];
String prefix = attr.mPrefix;
// Attributes' ns URI is null after reset, so can skip setting "no namespace"
if (prefix != null) {
if (prefix == "xml") {
attr.mNamespaceURI = XMLConstants.XML_NS_URI;
} else {
String uri = ns.findLastFromMap(prefix);
if (uri == null) {
rep.throwParseError(ErrorConsts.ERR_NS_UNDECLARED_FOR_ATTR,
prefix, attr.mLocalName);
}
attr.mNamespaceURI = uri;
}
}
}
/* Ok, finally, let's create attribute map, to allow efficient
* access by prefix+localname combination. Could do it on-demand,
* but this way we can check for duplicates right away.
*/