Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: org/media/mn8/mn8XMLReader.java


1   /* 
2    * $COPYRIGHT$
3    * $Id: mn8XMLReader.java,v 1.8 2002/07/24 23:25:47 neuro Exp $
4    *
5    * Date        Author            Changes 
6    * May 18 2001 Remus Pereni      Created
7    */
8   package org.media.mn8;
9   
10  
11  
12  import org.media.mn8.concepts.*;
13  import org.media.mn8.event.*;
14  
15  import javax.xml.parsers.SAXParserFactory;
16  import javax.xml.parsers.SAXParser;
17  import javax.xml.parsers.ParserConfigurationException;
18  import org.xml.sax.*;
19  import org.xml.sax.helpers.*;
20  
21  import java.net.URL;
22  import java.net.MalformedURLException;
23  import java.io.StringReader;
24  import java.io.IOException;
25  import java.io.File;
26  import java.util.Stack;
27  import java.util.EmptyStackException;
28  
29  /**
30   * Class that reads an String containing a well formated XML
31   * document and creates an Concept from it's content.
32   * @author <a href="mailto:remus@nolimits.ro">Remus Pereni</a>
33   * @version $Revision: 1.8 $ $Date: 2002/07/24 23:25:47 $
34   */
35  public class mn8XMLReader extends DefaultHandler implements EntityResolver {
36  
37      private XMLReader _xmlReader = null;
38      private ElementConcept _flexConcept = new ElementConcept();
39      private Stack _elStack = new Stack();
40      private static String _startUrl = null;
41      private String _locationURI = null;
42  
43  
44      protected mn8XMLReader() {
45          try {
46              _startUrl  = (new File("")).toURL().toString();
47          } catch ( MalformedURLException mex) {}
48  
49          try {
50              SAXParserFactory sxParserFactory = SAXParserFactory.newInstance();
51              SAXParser sxParser = sxParserFactory.newSAXParser();
52              _xmlReader = sxParser.getXMLReader();
53              _xmlReader.setEntityResolver(this);
54              _xmlReader.setContentHandler(this);
55          } catch ( ParserConfigurationException pce ) {
56              new ErrorConcept( "warning", "XMLParseException", pce.getMessage() );
57              if( mn8RuntimeFlags.isVerbose () ) {
58                  System.err.println(pce.getMessage());
59              }
60              if( mn8RuntimeFlags.isDebug () ) {
61                  pce.printStackTrace();
62              }
63  
64          } catch ( SAXException saxe ) {
65              new ErrorConcept( "warning", "XMLParseException", saxe.getMessage() );
66              if( mn8RuntimeFlags.isVerbose () ) {
67                  System.err.println(saxe.getMessage());
68              }
69              if( mn8RuntimeFlags.isDebug () ) {
70                  saxe.printStackTrace();
71              }
72          }
73      }
74  
75      public void parse(String value) throws SAXException, IOException {
76          URL url = null;
77          try {
78              url = new URL(value);
79          } catch (MalformedURLException mex) {
80              ;
81          }
82          if( url != null ) {
83              _xmlReader.parse((new InputSource( url.toString())));
84          } else {
85              _xmlReader.parse((new InputSource( new StringReader(value))));
86          }
87      }
88  
89  
90      public ElementConcept getFlexFromXML(StringConcept xmlDocument) {
91          try {            
92              _locationURI = xmlDocument.getResourceURI().getValue().equals("") ? null : xmlDocument.getResourceURI().getValue();
93              parse( xmlDocument.toString() );
94              return _flexConcept;
95          } catch ( SAXParseException saxe ) {
96              new ErrorConcept( "warning"
97                                , "XMLParseException"
98                                , saxe.getMessage() + " Line: " + saxe.getLineNumber() 
99                                + " Column: " + saxe.getColumnNumber()   
100                               , xmlDocument );
101             if( mn8RuntimeFlags.isVerbose () ) {
102                 System.err.println(saxe.getMessage());
103             }
104             if( mn8RuntimeFlags.isDebug () ) {
105                 saxe.printStackTrace();
106             }            
107         } catch ( SAXException saxe ) {
108             new ErrorConcept( "warning"
109                               , "XMLParseException"
110                               , saxe.getMessage() 
111                               , xmlDocument );
112             if( mn8RuntimeFlags.isVerbose () ) {
113                 System.err.println(saxe.getMessage());
114             }
115             if( mn8RuntimeFlags.isDebug () ) {
116                 saxe.printStackTrace();
117             }            
118         } catch ( IOException iox ) {
119             if( mn8RuntimeFlags.isVerbose () ) {
120                 System.err.println(iox.getMessage());
121             }
122             if( mn8RuntimeFlags.isDebug () ) {
123                 iox.printStackTrace();
124             }
125         }
126         return null;
127     }
128 
129 
130     public void startDocument() throws SAXException {
131     }
132 
133 
134     public void endDocument() throws SAXException {
135     }
136 
137 
138     public void startElement(String uri, String localname, String qname, Attributes attributes) throws SAXException {        
139         AttributeConcept attr = null;
140         ElementConcept element = null;
141         SeriesConcept attribs = new SeriesConcept();
142 
143         for( int i = 0 ; i < attributes.getLength(); i++) {
144             attr = new AttributeConcept();
145             attr.setAttributeName( attributes.getQName(i));
146             attr.setAttributeLabel( attributes.getQName(i));
147             attr.setAttributeValue(new StringConcept(attributes.getValue(i)));
148             attribs.add( attr );
149         }
150         
151         try {
152             if( _elStack.peek() instanceof ElementConcept ) {
153                 element = new ElementConcept( qname, qname, null, attribs);
154                 if( _locationURI != null ) element.setResourceURI( new StringConcept(_locationURI));
155                 ((ElementConcept)_elStack.peek()).addValue(element);
156             } 
157 
158             _elStack.push( element );                
159         } catch ( EmptyStackException see ) {
160             _flexConcept.setLabel( new StringConcept( qname ));
161             for( int i = 0 ; i < attributes.getLength(); i++) {
162                 _flexConcept.addAttribute( new StringConcept(attributes.getQName(i)),
163                                            new StringConcept(attributes.getQName(i)),
164                                            new StringConcept(attributes.getValue(i)));
165             }
166             _elStack.push( _flexConcept );
167         }
168             
169     }
170 
171 
172     public void endElement(String uri, String localname, String qname) throws SAXException {
173         _elStack.pop();
174     }
175 
176 
177     public void characters(char[] ch, int start, int length ) throws SAXException {
178         StringBuffer value = new StringBuffer(new String( ch, start, length));
179         if( value.toString().trim().length() == 0) return;
180 
181         if( !mn8Interpreter.EOL.equals("\n") ) {
182             int idx = value.toString().indexOf('\n');
183             while( idx != -1 && idx < value.length()) {
184                 value.replace(idx, idx+1, mn8Interpreter.EOL);
185                 idx = value.toString().indexOf('\n', idx+ mn8Interpreter.EOL.length());
186             }
187         }
188 
189         if( _elStack.peek() instanceof ElementConcept ) {
190             ElementConcept currElem = (ElementConcept)_elStack.peek();
191             if( currElem.isMulti().getValue() ) {
192                 Concept lastElem = (Concept) ((SeriesConcept)currElem.getValue()).getVector().lastElement();
193                 
194                 if( lastElem instanceof StringConcept) { 
195                     ((SeriesConcept)currElem.getValue()).getVector().set( ((SeriesConcept)currElem.getValue()).getVector().size() -1,
196                                                                           new StringConcept( ((StringConcept)lastElem).toString() +
197                                                                                              value.toString()));
198                 } else {
199                     appendString(currElem, value.toString());
200                 }                
201             } else {
202                 appendString( currElem, value.toString());
203             }
204         }            
205     }
206 
207 
208     public void ignorableWhitespace (char[] ch, int start, int length ) throws SAXException {
209     }
210 
211 
212     public void processChar(String val) {
213         for( int i = 0 ; i < val.length(); i++ ) {
214             if( val.charAt(i) == '\r' ) {
215                 System.err.print("\\r");
216             }else if( val.charAt(i) == '\n' ) {
217                     System.err.print("\\n");
218             } else {
219                     System.err.print("" + val.charAt(i));
220             }
221         }
222     }
223 
224 
225 
226     public InputSource resolveEntity (String publicId, String systemId){
227         if (systemId.toLowerCase().startsWith("file") && _locationURI != null ) {
228             File fl = new File( systemId);
229             if( !fl.exists() ) {                    
230                 if( systemId.startsWith("file:///") && !_startUrl.startsWith("file:///") ) {
231                     // corections to the url
232                     _startUrl = _startUrl.substring(0, _startUrl.indexOf("/")) + "//" + _startUrl.substring(_startUrl.indexOf("/"));
233                 }
234                 if( systemId.toLowerCase().startsWith(_startUrl.toLowerCase())) {
235                     if( !_locationURI.trim().endsWith("/") && !_locationURI.trim().endsWith("\\") ) {
236                         if( _locationURI.indexOf("/") != -1 ) {
237                             _locationURI = _locationURI.substring(0, _locationURI.lastIndexOf("/"));
238                         }
239                     }
240                     if( mn8RuntimeFlags.isDebug()) {
241                         mn8Interpreter.GLOBAL_ERR_STREAM.println("fromXML: Resolving system id from: " +  _locationURI + systemId.substring( _startUrl.length()));
242                     }
243                     return new InputSource( _locationURI + systemId.substring( _startUrl.length()));
244                 } else {
245                     return null;
246                 }
247             } else {
248                 // use the default behaviour
249                 return null;
250             }
251         } else {
252             // use the default behaviour
253             return null;
254         }
255     }
256 
257 
258     void appendString(ElementConcept toElem, String value) {
259         if( toElem.getValueType().toString().equalsIgnoreCase("string") ) {
260             toElem.setValue( new StringConcept( ((StringConcept)toElem.getValue()).toString() + value));
261         } else {
262             toElem.addValue(new StringConcept(value));
263         }
264     }
265 }