Update project structure for aaf/cadi
[aaf/cadi.git] / core / src / main / java / org / onap / aaf / cadi / wsse / XReader.java
1 /*******************************************************************************\r
2  * ============LICENSE_START====================================================\r
3  * * org.onap.aaf\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
10  * * \r
11  *  *      http://www.apache.org/licenses/LICENSE-2.0\r
12  * * \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
19  * *\r
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.\r
21  * *\r
22  ******************************************************************************/\r
23 package org.onap.aaf.cadi.wsse;\r
24 \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
33 \r
34 import javax.xml.stream.XMLStreamException;\r
35 \r
36 /**\r
37  * XReader\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
41  * \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
44  * \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
47  * \r
48  *\r
49  */\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
56         \r
57         private Stack<Map<String,String>> nsses;\r
58         \r
59         public XReader(InputStream is) {\r
60                 this.is = is;\r
61                 curr = another = null;\r
62                 baos = new ByteArrayOutputStream();\r
63                 state = BEGIN_DOC; \r
64                 count = 0;\r
65                 nsses = new Stack<Map<String,String>>();\r
66         }\r
67         \r
68         public boolean hasNext() throws XMLStreamException {\r
69                 if(curr==null) {\r
70                         curr = parse();\r
71                 }\r
72                 return curr!=null;\r
73         }\r
74 \r
75         public XEvent nextEvent() {\r
76                 XEvent xe = curr;\r
77                 curr = null;\r
78                 return xe;\r
79         }\r
80 \r
81         // \r
82         // State Flags\r
83         //\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
103         \r
104         \r
105         private XEvent parse() throws XMLStreamException {\r
106                 Map<String,String> nss = nsses.isEmpty()?null:nsses.peek();\r
107 \r
108                 XEvent rv;\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
113                 } else {\r
114                         boolean go = true;\r
115                         int c=0;\r
116                         \r
117                         try {\r
118                                 while(go && (c=is.read())>=0) {\r
119                                         ++count;\r
120                                         switch(c) {\r
121                                                 case '<': // Tag is opening\r
122                                                         state|=~BEGIN_DOC; // remove BEGIN_DOC flag, this is possibly an XML Doc\r
123                                                         XEvent cxe = null;\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
128                                                                         baos.reset();\r
129                                                                         go = false;\r
130                                                                 }\r
131                                                         }\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
134                                                         String ns;\r
135                                                         switch(t.state&(START_TAG|END_TAG)) {\r
136                                                                 case START_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
142                                                                 case END_TAG:\r
143                                                                         ns = t.prefix==null?"":nss.get(t.prefix); // Get the namespace from prefix (if exists)\r
144                                                                         break;\r
145                                                                 default:\r
146                                                                         ns = "";\r
147                                                         }\r
148                                                         if(ns==null)\r
149                                                                 throw new XMLStreamException("Invalid Namespace Prefix at " + count);\r
150                                                         go = false;\r
151                                                         switch(t.state) { // based on \r
152                                                           case DOC_TYPE: \r
153                                                                   rv = new XEvent.StartDocument();\r
154                                                                   break;\r
155                                                           case COMMENT:\r
156                                                                   rv = new XEvent.Comment(t.value);\r
157                                                                   break;\r
158                                                           case START_TAG:\r
159                                                                   rv = new XEvent.StartElement(ns,t.name);\r
160                                                                   nsses.push(nss);                              // Change potential scope for Namespace\r
161                                                                   break;\r
162                                                           case END_TAG:\r
163                                                                   rv = new XEvent.EndElement(ns,t.name);\r
164                                                                   nss = nsses.pop();                    // End potential scope for Namespace\r
165                                                                   break;\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
169                                                         }\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
173                                                         }\r
174                                                         break;\r
175                                                 case ' ':\r
176                                                 case '\t':\r
177                                                 case '\n':\r
178                                                         if((state&BEGIN_DOC)==BEGIN_DOC) { // if Whitespace before doc, just ignore \r
179                                                                 break;\r
180                                                         }\r
181                                                         // fallthrough on purpose\r
182                                                 default:\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
185                                                         }\r
186                                                         baos.write(c); // save off Characters\r
187                                         }\r
188                                         last = c; // Some processing needs to know what the last character was, aka Escaped characters... ex \"\r
189                                 }\r
190                         } catch (IOException e) {\r
191                                 throw new XMLStreamException(e); // all errors parsing will be treated as XMLStreamErrors (like StAX)\r
192                         }\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
196                 }\r
197                 return rv;\r
198         }\r
199         \r
200         /**\r
201          * parseTag\r
202          * \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
205          * @return\r
206          * @throws IOException\r
207          * @throws XMLStreamException\r
208          */\r
209         private Tag parseTag() throws IOException, XMLStreamException {\r
210                 Tag tag = null;\r
211                 boolean go = true;\r
212                 state = 0;\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
215                 baos.reset();\r
216                 \r
217                 while(go && (c=is.read())>=0) {\r
218                         ++count;\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
221                                         quote=0;\r
222                                 } else {\r
223                                         baos.write(c);\r
224                                 }\r
225                         } else if((state&COMMENT)==COMMENT) { // similar to Quote is being in a comment\r
226                                 switch(c) {\r
227                                         case '-':\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
230                                                                 state|=COMMENT_D1;\r
231                                                                 break;\r
232                                                         case COMMENT|COMMENT_E|COMMENT_D1:\r
233                                                                 state|=COMMENT_D2;\r
234                                                                 baos.reset();                           // clear out "!--", it's a Comment\r
235                                                                 break;\r
236                                                         case COMMENT|COMMENT_E|COMMENT_D1|COMMENT_D2:\r
237                                                                 state|=COMMENT_D3;\r
238                                                                 baos.write(c);\r
239                                                                 break;\r
240                                                         case COMMENT|COMMENT_E|COMMENT_D1|COMMENT_D2|COMMENT_D3:\r
241                                                                 state|=COMMENT_D4;\r
242                                                                 baos.write(c);\r
243                                                                 break;\r
244                                                 }\r
245                                                 break;\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
250                                                         baos.reset();\r
251                                                         go = false;\r
252                                                         break;\r
253                                                 }\r
254                                                 // fall through on purpose\r
255                                         default:\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
258                                                 baos.write(c);\r
259                                 }\r
260                         } else { // Normal Tag Processing loop\r
261                                 switch(c) {\r
262                                         case '?': \r
263                                                 switch(state & (QUESTION_F|QUESTION)) {  // Validate the state of Doc tag... <?xml ... ?>\r
264                                                         case QUESTION_F:\r
265                                                                 state |= DOC_TYPE;\r
266                                                                 state &= ~QUESTION_F;\r
267                                                                 break;\r
268                                                         case 0:\r
269                                                                 state |=QUESTION_F;\r
270                                                                 break;\r
271                                                         default:\r
272                                                                 throw new IOException("Bad character [?] at " + count);\r
273                                                 }\r
274                                                 break;\r
275                                         case '!':\r
276                                                 if(last=='<') { \r
277                                                         state|=COMMENT|COMMENT_E; // likely a comment, continue processing in Comment Loop\r
278                                                 }\r
279                                                 baos.write(c);\r
280                                                 break;\r
281                                         case '/':\r
282                                                 state|=(last=='<'?END_TAG:(END_TAG|START_TAG));  // end tag indicator </xxx>, ,or both <xxx/>\r
283                                                 break;\r
284                                         case ':':\r
285                                                 prefix=baos.toString(); // prefix indicator\r
286                                                 baos.reset();\r
287                                                 break;\r
288                                         case '=':                                       // used in Attributes\r
289                                                 name=baos.toString();\r
290                                                 baos.reset();\r
291                                                 state|=VALUE;\r
292                                                 break;\r
293                                         case '>': // end the tag, which causes end of this subprocess as well as formulation of the found data\r
294                                                 go = false;\r
295                                                 // passthrough on purpose\r
296                                         case ' ':\r
297                                         case '\t':\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
303                                                 }\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
308                                                                 tag = t;\r
309                                                         } else {                                        // if we already have a Tag, then we'll treat this one as an attribute\r
310                                                                 tag.add(t);\r
311                                                         }\r
312                                                 }\r
313                                                 prefix=name=value=null;                 // reset these values in case we loop for attributes.\r
314                                                 break;\r
315                                         case '\'':                                                      // is the character one of two kinds of quote?\r
316                                         case '"':\r
317                                                 if(last!='\\') {\r
318                                                         quote=c;\r
319                                                         break;\r
320                                                 }\r
321                                                 // Fallthrough ok\r
322                                         default:\r
323                                                 baos.write(c);                                  // write any unprocessed bytes into buffer\r
324                                                 \r
325                                 }\r
326                         }\r
327                         last = c;\r
328                 }\r
329                 int type = state&(DOC_TYPE|COMMENT|END_TAG|START_TAG); // get just the Tag states and turn into Type for Tag\r
330                 if(type==0) {\r
331                         type=START_TAG;\r
332                 }\r
333                 tag.state|=type;        // add the appropriate Tag States\r
334                 return tag;\r
335         }\r
336 \r
337         /**\r
338          * getNSS\r
339          * \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
342          * \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
344          * \r
345          * @param nss\r
346          * @param t\r
347          * @return\r
348          */\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
354                                         if(newnss==null) {\r
355                                                 newnss = new HashMap<String,String>();\r
356                                                 if(nss!=null)newnss.putAll(nss);\r
357                                         }\r
358                                         newnss.put(tag.name, tag.value);\r
359                                 }\r
360                         }\r
361                 }\r
362                 return newnss==null?(nss==null?new HashMap<String,String>():nss):newnss;\r
363         }\r
364 \r
365         /**\r
366          * The result of the parseTag method\r
367          * \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
369          * as Attributes.  \r
370          * \r
371          *\r
372          */\r
373         public class Tag {\r
374                 public int state;\r
375                 public String prefix,name,value;\r
376                 public List<Tag> attribs;\r
377 \r
378                 public Tag(String prefix, String name, String value) {\r
379                         this.prefix = prefix;\r
380                         this.name = name;\r
381                         this.value = value;\r
382                         attribs = null;  \r
383                 }\r
384 \r
385                 /**\r
386                  * add an attribute\r
387                  * Not all tags need attributes... lazy instantiate to save time and memory\r
388                  * @param tag\r
389                  */\r
390                 public void add(Tag attrib) {\r
391                         if(attribs == null) {\r
392                                 attribs = new ArrayList<Tag>();\r
393                         }\r
394                         attribs.add(attrib);\r
395                 }\r
396                 \r
397                 public String toString() {\r
398                         StringBuffer sb = new StringBuffer();\r
399                         if(prefix!=null) {\r
400                                 sb.append(prefix);\r
401                                 sb.append(':');\r
402                         }\r
403                         sb.append(name==null?"!!ERROR!!":name);\r
404 \r
405                         char quote = ((state&DOC_TYPE)==DOC_TYPE)?'\'':'"';\r
406                         if(value!=null) {\r
407                                 sb.append('=');\r
408                                 sb.append(quote);\r
409                                 sb.append(value);\r
410                                 sb.append(quote);\r
411                         }\r
412                         return sb.toString();\r
413                 }\r
414         }\r
415 \r
416 }\r