1 /*******************************************************************************
\r
2 * ============LICENSE_START====================================================
\r
4 * * ===========================================================================
\r
5 * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
\r
6 * * ===========================================================================
\r
7 * * Licensed under the Apache License, Version 2.0 (the "License");
\r
8 * * you may not use this file except in compliance with the License.
\r
9 * * You may obtain a copy of the License at
\r
11 * * http://www.apache.org/licenses/LICENSE-2.0
\r
13 * * Unless required by applicable law or agreed to in writing, software
\r
14 * * distributed under the License is distributed on an "AS IS" BASIS,
\r
15 * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
\r
16 * * See the License for the specific language governing permissions and
\r
17 * * limitations under the License.
\r
18 * * ============LICENSE_END====================================================
\r
20 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
\r
22 ******************************************************************************/
\r
23 package org.onap.aaf.cadi.wsse;
\r
25 import java.io.ByteArrayOutputStream;
\r
26 import java.io.IOException;
\r
27 import java.io.InputStream;
\r
28 import java.util.ArrayList;
\r
29 import java.util.HashMap;
\r
30 import java.util.List;
\r
31 import java.util.Map;
\r
32 import java.util.Stack;
\r
34 import javax.xml.stream.XMLStreamException;
\r
38 * This class works similarly as StAX, except StAX has more behavior than is needed. That would be ok, but
\r
39 * StAX also was Buffering in their code in such as way as to read most if not all the incoming stream into memory,
\r
40 * defeating the purpose of pre-reading only the Header
\r
42 * This Reader does no back-tracking, but is able to create events based on syntax and given state only, leaving the
\r
43 * Read-ahead mode of the InputStream up to the other classes.
\r
45 * At this time, we only implement the important events, though if this is good enough, it could be expanded, perhaps to
\r
46 * replace the original XMLReader from StAX.
\r
50 // @SuppressWarnings("restriction")
\r
51 public class XReader {
\r
52 private XEvent curr,another;
\r
53 private InputStream is;
\r
54 private ByteArrayOutputStream baos;
\r
55 private int state, count, last;
\r
57 private Stack<Map<String,String>> nsses;
\r
59 public XReader(InputStream is) {
\r
61 curr = another = null;
\r
62 baos = new ByteArrayOutputStream();
\r
65 nsses = new Stack<Map<String,String>>();
\r
68 public boolean hasNext() throws XMLStreamException {
\r
75 public XEvent nextEvent() {
\r
84 // Note: The State of parsing XML can be complicated. There are too many to cleanly keep in "booleans". Additionally,
\r
85 // there are certain checks that can be better made with Bitwise operations within switches
\r
86 // Keeping track of state this way also helps us to accomplish logic without storing any back characters except one
\r
87 private final static int BEGIN_DOC= 0x000001;
\r
88 private final static int DOC_TYPE= 0x000002;
\r
89 private final static int QUESTION_F= 0x000004;
\r
90 private final static int QUESTION = 0x000008;
\r
91 private final static int START_TAG = 0x000010;
\r
92 private final static int END_TAG = 0x000020;
\r
93 private final static int VALUE= 0x000040;
\r
94 private final static int COMMENT = 0x001000;
\r
95 private final static int COMMENT_E = 0x002000;
\r
96 private final static int COMMENT_D1 =0x010000;
\r
97 private final static int COMMENT_D2 =0x020000;
\r
98 private final static int COMMENT_D3 =0x040000;
\r
99 private final static int COMMENT_D4 =0x080000;
\r
100 // useful combined Comment states
\r
101 private final static int IN_COMMENT=COMMENT|COMMENT_E|COMMENT_D1|COMMENT_D2;
\r
102 private final static int COMPLETE_COMMENT = COMMENT|COMMENT_E|COMMENT_D1|COMMENT_D2|COMMENT_D3|COMMENT_D4;
\r
105 private XEvent parse() throws XMLStreamException {
\r
106 Map<String,String> nss = nsses.isEmpty()?null:nsses.peek();
\r
109 if((rv=another)!=null) { // "another" is a tag that may have needed to be created, but not
\r
110 // immediately returned. Save for next parse. If necessary, this could be turned into
\r
111 // a FIFO storage, but a single reference is enough for now.
\r
112 another = null; // "rv" is now set for the Event, and will be returned. Set to Null.
\r
118 while(go && (c=is.read())>=0) {
\r
121 case '<': // Tag is opening
\r
122 state|=~BEGIN_DOC; // remove BEGIN_DOC flag, this is possibly an XML Doc
\r
124 if(baos.size()>0) { // If there are any characters between tags, we send as Character Event
\r
125 String chars = baos.toString().trim(); // Trim out WhiteSpace before and after
\r
126 if(chars.length()>0) { // don't send if Characters were only whitespace
\r
127 cxe = new XEvent.Characters(chars);
\r
132 last = c; // make sure "last" character is set for use in "ParseTag"
\r
133 Tag t = parseTag(); // call subroutine to process the tag as a unit
\r
135 switch(t.state&(START_TAG|END_TAG)) {
\r
137 nss = getNss(nss,t); // Only Start Tags might have NS Attributes
\r
138 // Get any NameSpace elements from tag. If there are, nss will become
\r
139 // a new Map with all the previous NSs plus the new. This provides
\r
140 // scoping behavior when used with the Stack
\r
141 // drop through on purpose
\r
143 ns = t.prefix==null?"":nss.get(t.prefix); // Get the namespace from prefix (if exists)
\r
149 throw new XMLStreamException("Invalid Namespace Prefix at " + count);
\r
151 switch(t.state) { // based on
\r
153 rv = new XEvent.StartDocument();
\r
156 rv = new XEvent.Comment(t.value);
\r
159 rv = new XEvent.StartElement(ns,t.name);
\r
160 nsses.push(nss); // Change potential scope for Namespace
\r
163 rv = new XEvent.EndElement(ns,t.name);
\r
164 nss = nsses.pop(); // End potential scope for Namespace
\r
166 case START_TAG|END_TAG: // This tag is both start/end aka <myTag/>
\r
167 rv = new XEvent.StartElement(ns,t.name);
\r
168 if(last=='/')another = new XEvent.EndElement(ns,t.name);
\r
170 if(cxe!=null) { // if there is a Character Event, it actually should go first. ow.
\r
171 another = rv; // Make current Event the "another" or next event, and
\r
172 rv = cxe; // send Character Event now
\r
178 if((state&BEGIN_DOC)==BEGIN_DOC) { // if Whitespace before doc, just ignore
\r
181 // fallthrough on purpose
\r
183 if((state&BEGIN_DOC)==BEGIN_DOC) { // if there is any data at the start other than XML Tag, it's not XML
\r
184 throw new XMLStreamException("Parse Error: This is not an XML Doc");
\r
186 baos.write(c); // save off Characters
\r
188 last = c; // Some processing needs to know what the last character was, aka Escaped characters... ex \"
\r
190 } catch (IOException e) {
\r
191 throw new XMLStreamException(e); // all errors parsing will be treated as XMLStreamErrors (like StAX)
\r
193 if(c==-1 && (state&BEGIN_DOC)==BEGIN_DOC) { // Normally, end of stream is ok, however, we need to know if the
\r
194 throw new XMLStreamException("Premature End of File"); // document isn't an XML document, so we throw exception if it
\r
195 } // hasn't yet been determined to be an XML Doc
\r
203 * Parsing a Tag is somewhat complicated, so it's helpful to separate this process from the
\r
204 * higher level Parsing effort
\r
206 * @throws IOException
\r
207 * @throws XMLStreamException
\r
209 private Tag parseTag() throws IOException, XMLStreamException {
\r
213 int c, quote=0; // If "quote" is 0, then we're not in a quote. We set ' (in pretag) or " in attribs accordingly to denote quoted
\r
214 String prefix=null,name=null,value=null;
\r
217 while(go && (c=is.read())>=0) {
\r
219 if(quote!=0) { // If we're in a quote, we only end if we hit another quote of the same time, not preceded by \
\r
220 if(c==quote && last!='\\') {
\r
225 } else if((state&COMMENT)==COMMENT) { // similar to Quote is being in a comment
\r
228 switch(state) { // XML has a complicated Quote set... <!-- --> ... we keep track if each has been met with flags.
\r
229 case COMMENT|COMMENT_E:
\r
232 case COMMENT|COMMENT_E|COMMENT_D1:
\r
234 baos.reset(); // clear out "!--", it's a Comment
\r
236 case COMMENT|COMMENT_E|COMMENT_D1|COMMENT_D2:
\r
240 case COMMENT|COMMENT_E|COMMENT_D1|COMMENT_D2|COMMENT_D3:
\r
246 case '>': // Tag indicator has been found, do we have all the comment characters in line?
\r
247 if((state&COMPLETE_COMMENT)==COMPLETE_COMMENT) {
\r
248 byte ba[] = baos.toByteArray();
\r
249 tag = new Tag(null,null, new String(ba,0,ba.length-2));
\r
254 // fall through on purpose
\r
256 state&=~(COMMENT_D3|COMMENT_D4);
\r
257 if((state&IN_COMMENT)!=IN_COMMENT) state&=~IN_COMMENT; // false alarm, it's not actually a comment
\r
260 } else { // Normal Tag Processing loop
\r
263 switch(state & (QUESTION_F|QUESTION)) { // Validate the state of Doc tag... <?xml ... ?>
\r
266 state &= ~QUESTION_F;
\r
269 state |=QUESTION_F;
\r
272 throw new IOException("Bad character [?] at " + count);
\r
277 state|=COMMENT|COMMENT_E; // likely a comment, continue processing in Comment Loop
\r
282 state|=(last=='<'?END_TAG:(END_TAG|START_TAG)); // end tag indicator </xxx>, ,or both <xxx/>
\r
285 prefix=baos.toString(); // prefix indicator
\r
288 case '=': // used in Attributes
\r
289 name=baos.toString();
\r
293 case '>': // end the tag, which causes end of this subprocess as well as formulation of the found data
\r
295 // passthrough on purpose
\r
298 case '\n': // white space indicates change in internal tag state, ex between name and between attributes
\r
299 if((state&VALUE)==VALUE) {
\r
300 value = baos.toString(); // we're in VALUE state, add characters to Value
\r
301 } else if(name==null) {
\r
302 name = baos.toString(); // we're in Name state (default) add characters to Name
\r
304 baos.reset(); // we've assigned chars, reset buffer
\r
305 if(name!=null) { // Name is not null, there's a tag in the offing here...
\r
306 Tag t = new Tag(prefix,name,value);
\r
307 if(tag==null) { // Set as the tag to return, if not exists
\r
309 } else { // if we already have a Tag, then we'll treat this one as an attribute
\r
313 prefix=name=value=null; // reset these values in case we loop for attributes.
\r
315 case '\'': // is the character one of two kinds of quote?
\r
323 baos.write(c); // write any unprocessed bytes into buffer
\r
329 int type = state&(DOC_TYPE|COMMENT|END_TAG|START_TAG); // get just the Tag states and turn into Type for Tag
\r
333 tag.state|=type; // add the appropriate Tag States
\r
340 * If the tag contains some Namespace attributes, create a new nss from the passed in one, copy all into it, then add
\r
341 * This provides Scoping behavior
\r
343 * if Nss is null in the first place, create an new nss, so we don't have to deal with null Maps.
\r
349 private Map<String, String> getNss(Map<String, String> nss, Tag t) {
\r
350 Map<String,String> newnss = null;
\r
351 if(t.attribs!=null) {
\r
352 for(Tag tag : t.attribs) {
\r
353 if("xmlns".equals(tag.prefix)) {
\r
355 newnss = new HashMap<String,String>();
\r
356 if(nss!=null)newnss.putAll(nss);
\r
358 newnss.put(tag.name, tag.value);
\r
362 return newnss==null?(nss==null?new HashMap<String,String>():nss):newnss;
\r
366 * The result of the parseTag method
\r
368 * Data is split up into prefix, name and value portions. "Tags" with Values that are inside a Tag are known in XLM
\r
375 public String prefix,name,value;
\r
376 public List<Tag> attribs;
\r
378 public Tag(String prefix, String name, String value) {
\r
379 this.prefix = prefix;
\r
381 this.value = value;
\r
387 * Not all tags need attributes... lazy instantiate to save time and memory
\r
390 public void add(Tag attrib) {
\r
391 if(attribs == null) {
\r
392 attribs = new ArrayList<Tag>();
\r
394 attribs.add(attrib);
\r
397 public String toString() {
\r
398 StringBuffer sb = new StringBuffer();
\r
403 sb.append(name==null?"!!ERROR!!":name);
\r
405 char quote = ((state&DOC_TYPE)==DOC_TYPE)?'\'':'"';
\r
412 return sb.toString();
\r