View Javadoc

1   /*   Copyright 2004 BEA Systems, Inc.
2    *
3    *   Licensed under the Apache License, Version 2.0 (the "License");
4    *   you may not use this file except in compliance with the License.
5    *   You may obtain a copy of the License at
6    *
7    *       http://www.apache.org/licenses/LICENSE-2.0
8    *
9    *   Unless required by applicable law or agreed to in writing, software
10   *   distributed under the License is distributed on an "AS IS" BASIS,
11   *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   *   See the License for the specific language governing permissions and
13   *   limitations under the License.
14   */
15  package com.bea.xml.stream;
16  
17  import java.io.Reader;
18  import java.io.InputStream;
19  import java.io.InputStreamReader;
20  import javax.xml.namespace.NamespaceContext;
21  import javax.xml.namespace.QName;
22  import javax.xml.stream.XMLOutputFactory;
23  import javax.xml.stream.XMLStreamReader;
24  import javax.xml.stream.XMLStreamWriter;
25  import javax.xml.stream.Location;
26  import javax.xml.stream.events.XMLEvent;
27  import javax.xml.stream.XMLStreamConstants;
28  import javax.xml.stream.XMLStreamException;
29  import javax.xml.stream.events.Attribute;
30  import javax.xml.stream.events.Namespace;
31  import com.bea.xml.stream.util.NamespaceContextImpl;
32  
33  /***
34   * <p> Creates an XMLStreamReader over a non-xml ascii format </p>
35   */
36  
37  public class XMLStreamPlayer implements XMLStreamReader {
38    EventState state;
39    EventScanner scanner;
40    NamespaceContextImpl context = 
41      new NamespaceContextImpl();
42    
43    public XMLStreamPlayer(){}
44  
45    public XMLStreamPlayer(InputStream stream) {
46      try {
47        scanner = new EventScanner(new InputStreamReader(stream));
48        next();
49        if (getEventType()==XMLEvent.START_DOCUMENT) {
50          String encoding = getCharacterEncodingScheme();
51          scanner = new EventScanner(new InputStreamReader(stream,
52                                                           encoding));
53        }
54      } catch (Exception e) {
55        throw new IllegalArgumentException("Unable to instantiate the XMLStreamPlayer"+e.getMessage());
56      }
57    }
58    public XMLStreamPlayer(Reader reader) {
59      try {
60        scanner = new EventScanner(reader);
61        next();
62      } catch (Exception e) {
63        System.out.println(e);
64      }
65    }
66  
67    public Object getProperty(java.lang.String name) 
68      throws java.lang.IllegalArgumentException
69    {
70      return null;
71    }  
72  
73    public int next() throws XMLStreamException {
74  
75      try {
76        if (scanner.hasNext() == false) {
77          state = null;
78          return -1;
79        }
80        state = scanner.readElement();
81        if (isStartElement()) {
82          context.openScope();
83          for (int i =0; i < getNamespaceCount(); i++) {
84            context.bindNamespace(getNamespacePrefix(i),
85                                  getNamespaceURI(i));
86          }
87        } else if (isEndElement()) {
88          if (context.getDepth() > 0)
89            context.closeScope();
90        }
91        return state.getType();
92      } catch (Exception e) {
93        System.out.println(e);
94        e.printStackTrace();
95        throw new XMLStreamException(e.getMessage(),e);
96      }
97    }
98    public void require(int type, 
99                        String namespaceURI, 
100                       String localName)  
101     throws XMLStreamException 
102   {}
103 
104   public String getElementText() 
105     throws XMLStreamException 
106   {
107     StringBuffer buf = new StringBuffer();
108     if(getEventType() != START_ELEMENT)
109       throw new XMLStreamException(
110                                    "Precondition for readText is getEventType() == START_ELEMENT");
111     do {
112       if(next() == END_DOCUMENT)
113         throw new XMLStreamException("Unexpected end of Document");
114       if(isStartElement())
115         throw new XMLStreamException("Unexpected Element start");
116       if(isCharacters())
117         buf.append(getText());
118    } while(!isEndElement());
119    return buf.toString();
120   }
121 
122   public int nextTag() throws XMLStreamException {
123     do {
124       if(next() == END_DOCUMENT)
125         throw new XMLStreamException("Unexpected end of Document");
126       if(isCharacters() && !isWhiteSpace())
127         throw new XMLStreamException("Unexpected text");
128     } while(!isStartElement() && !isEndElement());
129     return getEventType();
130   }
131 
132   public boolean hasNext() 
133     throws XMLStreamException
134   {
135     try {
136       return state != null && state.getType() != XMLStreamConstants.END_DOCUMENT;
137     } catch (Exception e) {
138       throw new XMLStreamException(e);
139     }
140   }
141 
142   public void close() throws XMLStreamException {}
143 
144   public String getNamespaceURI(String prefix) {
145     return context.getNamespaceURI(prefix);
146   }
147 
148   private Attribute getAttributeInternal(int index) {
149     return (Attribute) state.getAttributes().get(index);
150   }
151 
152   private Attribute getNamespaceInternal(int index) {
153     return (Attribute) state.getNamespaces().get(index);
154   }
155 
156   public boolean isStartElement() {
157     return ((getEventType() & XMLStreamConstants.START_ELEMENT) != 0);
158   }
159 
160   public boolean isEndElement() {
161     return ((getEventType() & XMLStreamConstants.END_ELEMENT) != 0);
162   }
163 
164   public boolean isCharacters() {
165     return ((getEventType() & XMLStreamConstants.CHARACTERS) != 0);
166   }
167 
168   public boolean isWhiteSpace() {
169     return false;
170   }
171 
172   public String getAttributeValue(String namespaceUri,
173                                   String localName) 
174   {
175     for (int i=0; i < getAttributeCount(); i++) {
176       Attribute a = getAttributeInternal(i);
177       if (localName.equals(a.getName().getLocalPart()))
178         if (namespaceUri == null)
179           return a.getValue();
180         else
181           if (namespaceUri.equals(a.getName().getNamespaceURI()))
182             return a.getValue();
183  
184     }
185     return null;
186   }
187 
188   public int getAttributeCount() {
189     if (isStartElement())
190       return state.getAttributes().size();
191     else 
192       return 0;
193   }
194 
195   public QName getAttributeName(int index) {
196     return new QName(getAttributeNamespace(index),
197                      getAttributeLocalName(index),
198                      getAttributePrefix(index));
199 
200   }
201 
202   public String getAttributeNamespace(int index) {
203     Attribute a = getAttributeInternal(index);
204     if (a == null) return null;
205     return a.getName().getNamespaceURI();
206   }
207 
208   public String getAttributeLocalName(int index) {
209     Attribute a = getAttributeInternal(index);
210     if (a == null) return null;
211     return a.getName().getLocalPart();
212   }
213 
214   public String getAttributePrefix(int index) {
215     Attribute a = getAttributeInternal(index);
216     if (a == null) return null;
217     return a.getName().getPrefix();
218   }
219 
220   public String getAttributeType(int index) {
221     return "CDATA";
222   }
223   public String getAttributeValue(int index){
224     Attribute a = getAttributeInternal(index);
225     if (a == null) return null;
226     return a.getValue();
227   }
228   public boolean isAttributeSpecified(int index) {
229     return false;
230   }
231 
232   // Namespaces
233 
234   public int getNamespaceCount() {
235     if (isStartElement())
236       return state.getNamespaces().size();
237     else
238       return 0;
239   }
240 
241   public String getNamespacePrefix(int index) {
242 
243     Attribute a = getNamespaceInternal(index);
244     if (a == null) return null;
245     return a.getName().getLocalPart();
246   }
247 
248   public String getNamespaceURI(int index) {
249     Attribute a = getNamespaceInternal(index);
250     if (a == null) return null;
251     return a.getValue();
252   }
253 
254   public NamespaceContext getNamespaceContext() {
255     return context;
256   }
257 
258   public XMLStreamReader subReader() 
259     throws XMLStreamException
260   {
261     return null; 
262   }
263 
264   public int getEventType() {
265     if (state == null) return XMLStreamConstants.END_DOCUMENT;
266     return state.getType();
267   }
268 
269   public String getText() {
270     return state.getData();
271   }
272 
273   public Reader getTextStream() {
274     throw new UnsupportedOperationException();
275   }
276 
277   public char[] getTextCharacters() {
278     return state.getData().toCharArray();
279   }
280 
281   public int getTextCharacters(int src, char[] target, int targetStart, int length)
282     throws XMLStreamException {
283     throw new UnsupportedOperationException();
284   }
285 
286 
287   public int getTextStart() {
288     return 0;
289   }
290   public int getTextLength(){
291     return state.getData().length();
292   }
293   public String getEncoding() {
294     return state.getData();
295   }
296 
297   public boolean hasText() {
298    return (0 != (getEventType() & (XMLStreamConstants.CHARACTERS |
299                                XMLStreamConstants.DTD |
300                                XMLStreamConstants.COMMENT |
301                                XMLStreamConstants.ENTITY_REFERENCE)));
302 
303   }
304 
305   public Location getLocation() {
306     return null;
307   }
308   public QName getName() {
309     return new QName(getNamespaceURI(),
310                      getLocalName(),
311                      getPrefix());
312   }
313   public String getLocalName() {
314     return state.getLocalName();
315   }
316   public boolean hasName() {
317     return (0 != (getEventType()  & (XMLEvent.START_ELEMENT 
318                             | XMLEvent.END_ELEMENT
319                             | XMLEvent.ENTITY_REFERENCE)));
320   }
321   public String getNamespaceURI() {
322     return state.getNamespaceURI();
323   }
324   public String getPrefix() {
325     return state.getPrefix();
326   }
327   public String getVersion() {
328     return "1.0";
329   }
330   public boolean isStandalone() {
331     return true;
332   }
333   public boolean standaloneSet() {
334     return false;
335   }
336   public String getCharacterEncodingScheme() {
337     return null; 
338   }
339   public String getPITarget() {
340     return state.getData();
341   }
342   public String getPIData() {
343     return state.getExtraData();
344   }
345   public boolean endDocumentIsPresent() {
346     return scanner.endDocumentIsPresent();
347   }
348 
349   public static void main(String args[]) throws Exception {
350     XMLStreamReader reader = new XMLStreamPlayer(
351                   new java.io.FileReader(args[0]));
352     XMLOutputFactory xmlof = XMLOutputFactory.newInstance();
353     XMLStreamWriter xmlw = xmlof.createXMLStreamWriter(System.out);
354     ReaderToWriter rtow = new ReaderToWriter(xmlw);
355     while (reader.hasNext()) {
356       rtow.write(reader);
357       reader.next();
358     }
359     xmlw.flush();
360   }
361 }
362 
363 
364