View Javadoc

1   /*
2    * $Id: ParserPage.java,v 1.31 2008/01/14 21:23:24 edankert Exp $
3    *
4    * The contents of this file are subject to the Mozilla Public License 
5    * Version 1.1 (the "License"); you may not use this file except in 
6    * compliance with the License. You may obtain a copy of the License at 
7    * http://www.mozilla.org/MPL/ 
8    *
9    * Software distributed under the License is distributed on an "AS IS" basis, 
10   * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License 
11   * for the specific language governing rights and limitations under the License.
12   *
13   * The Original Code is XML Hammer code. (org.xmlhammer.*)
14   *
15   * The Initial Developer of the Original Code is Edwin Dankert. Portions created 
16   * by the Initial Developer are Copyright (C) 2005 - 2006 the Initial Developer. 
17   * All Rights Reserved.
18   *
19   * Contributor(s): Edwin Dankert <edankert@gmail.com>
20   */
21  
22  package org.xmlhammer.gui.parser;
23  
24  import java.awt.Dimension;
25  import java.awt.event.ItemEvent;
26  import java.awt.event.ItemListener;
27  import java.io.File;
28  import java.net.URI;
29  import java.net.URISyntaxException;
30  import java.util.ArrayList;
31  import java.util.List;
32  
33  import javax.swing.Box;
34  import javax.swing.JCheckBox;
35  import javax.swing.JComboBox;
36  import javax.swing.JLabel;
37  import javax.swing.JPanel;
38  import javax.swing.border.EmptyBorder;
39  import javax.swing.event.ChangeEvent;
40  import javax.swing.event.ChangeListener;
41  
42  import org.bounce.FormLayout;
43  import org.bounce.util.URIUtils;
44  import org.xmlhammer.PreferencesHandler;
45  import org.xmlhammer.gui.Page;
46  import org.xmlhammer.gui.ProjectView;
47  import org.xmlhammer.gui.actions.PagePropertiesAction;
48  import org.xmlhammer.gui.output.SourceBuilder;
49  import org.xmlhammer.gui.overview.CheckBoxNode;
50  import org.xmlhammer.gui.overview.ComboBoxNode;
51  import org.xmlhammer.gui.overview.OverviewNode;
52  import org.xmlhammer.gui.preferences.PropertiesDialog;
53  import org.xmlhammer.gui.util.JAXPSettings;
54  import org.xmlhammer.gui.util.TitleBar;
55  import org.xmlhammer.gui.util.UndoableCheckBoxItemListener;
56  import org.xmlhammer.gui.util.UndoableComboBoxItemListener;
57  import org.xmlhammer.model.jaxp.Attribute;
58  import org.xmlhammer.model.jaxp.Feature;
59  import org.xmlhammer.model.jaxp.JAXPDocumentBuilderFactory;
60  import org.xmlhammer.model.jaxp.JAXPSAXParserFactory;
61  import org.xmlhammer.model.jaxp.Property;
62  import org.xmlhammer.model.jaxp.SchemaFactoryProperty;
63  import org.xmlhammer.model.jaxp.Settings;
64  import org.xmlhammer.model.project.Document;
65  import org.xmlhammer.model.project.Parser;
66  import org.xmlhammer.model.project.Source;
67  
68  /***
69   * Input Panel.
70   * 
71   * Allows to select either one URI, multiple URIs or 
72   * a range of files.
73   * 
74   * @version $Revision: 1.31 $, $Date: 2008/01/14 21:23:24 $
75   * @author Edwin Dankert <edankert@gmail.com>
76   */
77  
78  public class ParserPage extends Page implements OverviewNode, ItemListener {
79  	private static final long serialVersionUID = 3257852090755134776L;
80      
81      private static final String DOM_PARSER_ITEM = "DOM (Document Object Model)";
82      private static final String SAX_PARSER_ITEM = "SAX (Simple API for XML)";
83  
84      private static final String WELLFORMEDNESS                 = "Checking wellformed-ness";
85      private static final String VALIDATE_DTD                   = "Validate using DTD (internal and external subsets)";
86      private static final String VALIDATE_SCHEMA_LOCATION_HINTS = "Validate using xsi:schemaLocation attribute hints";
87      private static final String VALIDATE_SPECIFIED_SCHEMAS     = "Validate using specified Schema(s) (ignoring hints)";
88      private static final String VALIDATE_DTD_SPECIFIED_SCHEMAS = "Validate using DTD and specified Schema(s)";
89      
90      protected JComboBox selector 			= null;
91  	private PropertiesDialog propertiesDialog = null;
92  
93      protected JComboBox validationSelector  = null;
94  
95      private ArrayList<OverviewNode> nodes	= null;
96      private SchemaURIsPanel urisPanel       = null;
97  	private JCheckBox validating			= null;
98  	private JCheckBox namespaceAware		= null;
99  	private JCheckBox xincludeAware			= null;
100     
101     private boolean updatingValidationSelector = false;
102 
103 	/***
104 	 * Constructs a new Input Panel.
105 	 */
106 	public ParserPage( ProjectView view, boolean sax) {
107 		super( view);
108 		
109         urisPanel = new SchemaURIsPanel( this);
110 
111         selector = new JComboBox();
112         selector.addItem( DOM_PARSER_ITEM);
113         if ( sax) {
114             selector.addItem( SAX_PARSER_ITEM);
115         }
116         selector.addItemListener(new UndoableComboBoxItemListener(this, selector));
117         
118         view.getFieldManager().addField( selector);
119 		
120 		nodes = new ArrayList<OverviewNode>();
121 		
122 		JPanel center = new JPanel( new FormLayout( 11, 5));
123 		center.setBorder( new EmptyBorder( 10, 10, 20, 10));
124 
125 		namespaceAware = new JCheckBox( "Namespace Aware");
126         namespaceAware.addItemListener(new UndoableCheckBoxItemListener(this, namespaceAware));
127 		xincludeAware = new JCheckBox( "XInclude Aware");
128         xincludeAware.addItemListener(new UndoableCheckBoxItemListener(this, xincludeAware));
129 		validating = new JCheckBox( "Validating");
130         validating.addItemListener(new UndoableCheckBoxItemListener(this, validating));
131 
132         view.getFieldManager().addField( namespaceAware);
133         view.getFieldManager().addField( xincludeAware);
134         view.getFieldManager().addField( validating);
135         
136         view.getFieldManager().addChangeListener(new ChangeListener() {
137             public void stateChanged(ChangeEvent arg0) {
138                 if (isVisible()) {
139                     updateValidationSelector();
140                 }
141             }
142         });
143 		
144         JLabel label = new JLabel("Parser:");
145         label.setPreferredSize(new Dimension(urisPanel.getLabelWidth(), label.getPreferredSize().height));
146         label.setHorizontalAlignment(JLabel.RIGHT);
147 
148         center.add(label, FormLayout.LEFT);
149         center.add(selector, FormLayout.RIGHT);
150 
151         center.add(Box.createVerticalStrut(8), FormLayout.FULL);
152 
153         label = new JLabel("Settings:");
154         label.setPreferredSize(new Dimension(urisPanel.getLabelWidth(), label.getPreferredSize().height));
155         label.setHorizontalAlignment(JLabel.RIGHT);
156         center.add( label, FormLayout.LEFT);
157 		center.add( namespaceAware, FormLayout.RIGHT);
158         center.add( new JLabel(), FormLayout.LEFT);
159 		center.add( xincludeAware, FormLayout.RIGHT);
160         center.add( new JLabel(), FormLayout.LEFT);
161 		center.add( validating, FormLayout.RIGHT);
162 		
163         nodes.add( new ComboBoxNode( this, selector, "parser"));
164 		nodes.add( new CheckBoxNode( this, namespaceAware));
165 		nodes.add( new CheckBoxNode( this, xincludeAware));
166 		nodes.add( new CheckBoxNode( this, validating));
167 		
168 		center.add( urisPanel, FormLayout.FULL_FILL);
169 
170         validationSelector = new JComboBox();
171         validationSelector.addItem(WELLFORMEDNESS);
172         validationSelector.addItem(VALIDATE_DTD);
173         validationSelector.addItem(VALIDATE_SCHEMA_LOCATION_HINTS);
174         validationSelector.addItem(VALIDATE_SPECIFIED_SCHEMAS);
175         validationSelector.addItem(VALIDATE_DTD_SPECIFIED_SCHEMAS);
176         validationSelector.addItemListener( this);
177         validationSelector.addItemListener(new ItemListener() {
178             public void itemStateChanged(ItemEvent event) {
179                 if (event.getStateChange() == ItemEvent.SELECTED && !updatingValidationSelector) {
180                     try {
181                         updatingValidationSelector = true;
182                         getProjectView().getUndoManager().startCompound();
183 
184                         switch (validationSelector.getSelectedIndex()) {
185                             case 0:
186                                 validating.setSelected(false);
187                                 urisPanel.setSchemaLanguage(null);
188                                 break;
189                             case 1:
190                                 validating.setSelected(true);
191                                 urisPanel.setSchemaLanguage(null);
192                                 break;
193                             case 2:
194                                 validating.setSelected(true);
195                                 urisPanel.setSchemaLanguage("http://www.w3.org/2001/XMLSchema");
196     
197                                 if (urisPanel.getURIs(null).size() > 0) {
198                                     urisPanel.removeAllURIs();
199                                 }
200                                 break;
201                             case 3:
202                                 validating.setSelected(false);
203                                 
204                                 if (urisPanel.getSchemaLanguage() == null) {
205                                     urisPanel.setSchemaLanguage("http://www.w3.org/2001/XMLSchema");
206                                 }
207                                 
208                                 if (urisPanel.getURIs(null).size() == 0) {
209                                     List<Document> list = new ArrayList<Document>();
210                                     Document doc = new Document();
211                                     doc.setSrc(URIUtils.getRelativePath(null, new File(System.getProperty("user.home"))));
212                                     list.add(doc);
213     
214                                     urisPanel.setURIs(null, list);
215                                 }
216                                 break;
217                             case 4:
218                                 validating.setSelected(true);
219     
220                                 if (urisPanel.getSchemaLanguage() == null) {
221                                     urisPanel.setSchemaLanguage("http://www.w3.org/2001/XMLSchema");
222                                 }
223                                 
224                                 if (urisPanel.getURIs(null).size() == 0) {
225                                     List<Document> list = new ArrayList<Document>();
226                                     Document doc = new Document();
227                                     doc.setSrc(URIUtils.getRelativePath(null, new File(System.getProperty("user.home"))));
228                                     list.add(doc);
229                                     urisPanel.setURIs(null, list);
230                                 }
231                                 break;
232                             default:
233                                 validating.setSelected(false);
234                                 urisPanel.setSchemaLanguage(null);
235                                 break;
236                         }
237 
238                     } finally {
239                         getProjectView().getUndoManager().endCompound();
240                         updatingValidationSelector = false;
241                     }
242                 }
243             }
244         });
245         
246         TitleBar titleBar = new TitleBar( "XML Parser:", validationSelector);
247 		titleBar.add(new PagePropertiesAction( this));
248 		
249 		setTitleBar( titleBar);
250 		setCenterPanel( center);
251 	}
252     
253     private void updateValidationSelector() {
254         if (!updatingValidationSelector) {
255             try {
256                 updatingValidationSelector = true;
257                 
258                 if (validating.isSelected()) {
259                     // validate dtd or internal xsd, or dtd and external xsd ...
260                     String language = urisPanel.getSchemaLanguage();
261                     if (language != null) {
262                         List<Document> list = urisPanel.getURIs(null);
263                         
264                         if (list.size() == 0 && language.equals("http://www.w3.org/2001/XMLSchema")){
265                             validationSelector.setSelectedItem(VALIDATE_SCHEMA_LOCATION_HINTS);
266                         } else {
267                             validationSelector.setSelectedItem(VALIDATE_DTD_SPECIFIED_SCHEMAS);
268                         }
269                     } else {
270                         validationSelector.setSelectedItem(VALIDATE_DTD);
271                     }
272                 } else {
273                     // checking well formedness or validate external schema ...
274                     String language = urisPanel.getSchemaLanguage();
275                     if (language != null) {
276                         validationSelector.setSelectedItem(VALIDATE_SPECIFIED_SCHEMAS);
277                     } else {
278                         validationSelector.setSelectedItem(WELLFORMEDNESS);
279                     }
280                 }
281             } finally {
282                 updatingValidationSelector = false;
283             }
284         }
285     }
286 	
287 	/***
288 	 * Sets the input model.
289 	 * Null resets current values.
290 	 * 
291 	 * @param parser the parser settings.
292 	 * @throws URISyntaxException
293 	 */
294 	public void setParser(URI base, Parser parser) {
295         if ( parser == null) {
296             parser = new Parser();
297         }
298 
299         validating.setSelected( parser.isValidating());
300         namespaceAware.setSelected( parser.isNamespaceAware());
301         xincludeAware.setSelected( parser.isXincludeAware());
302         
303         if ( "dom".equals( parser.getType())) {
304             selector.setSelectedItem(DOM_PARSER_ITEM);
305         } else {
306             selector.setSelectedItem(SAX_PARSER_ITEM);
307         }
308         
309         if ( parser.getLanguage() != null) {
310             urisPanel.setSchemaLanguage( parser.getLanguage());
311         }
312         
313 		urisPanel.setURIs( base, parser.getSource());
314         
315         updateValidationSelector();
316 	}
317     
318     public void setSchemaLanguages( List<String> languages) {
319         urisPanel.setSchemaLanguages( languages);
320     }
321 	
322 	/***
323 	 * Shows the properties dialog.
324 	 */
325 	public void showPropertiesDialog() {
326 		Settings settings = getProjectView().getProject(null).getJAXPSettings();
327 
328 		if ( propertiesDialog == null) {
329 			propertiesDialog = new PropertiesDialog(getProjectView().getProjectsView().getRoot(), true, true, false, false, true);
330 		}
331 		
332 		propertiesDialog.setSAXParserFactory(settings.getJAXPSAXParserFactory());
333 		propertiesDialog.setDocumentBuilderFactory(settings.getJAXPDocumentBuilderFactory());
334 		propertiesDialog.setSchemaFactory(settings.getJAXPSchemaFactory());
335 
336 		if (propertiesDialog.open() == PropertiesDialog.OK_OPTION) {
337  			settings.setJAXPSAXParserFactory(propertiesDialog.getSAXParserFactory());
338  			settings.setJAXPDocumentBuilderFactory(propertiesDialog.getDocumentBuilderFactory());
339  			settings.setJAXPSchemaFactory(propertiesDialog.getSchemaFactory());
340  			getProjectView().getFieldManager().setPropertiesChanged(true);
341  		}
342 	}
343 
344     public void itemStateChanged( ItemEvent e) {
345     	getProjectView().getOverviewPanel().getModel().nodeChanged( this);
346     }
347 	
348 	public Parser getParser(URI base) {
349         Parser parser = new Parser();
350 
351         parser.setValidating(validating.isSelected());
352         parser.setNamespaceAware(namespaceAware.isSelected());
353         parser.setXincludeAware(xincludeAware.isSelected());
354         
355         if (isDOMSelected()) {
356             parser.setType( "dom");
357         } else {
358             parser.setType( "sax");
359         }
360         
361         parser.setLanguage( urisPanel.getSchemaLanguage());
362         
363         List<Source> documents = parser.getSource();
364         documents.clear();
365         
366         for (Document document : urisPanel.getURIs(base)) {
367             if (document instanceof Source) {
368                 documents.add((Source)document);
369             }
370         }
371 		
372 		return parser;
373 	}
374     
375     public boolean isDOMSelected() {
376         return DOM_PARSER_ITEM.equals(selector.getSelectedItem());
377     }
378     
379     public String getShortName() {
380         return "Parser";
381     }
382 
383 	/* (non-Javadoc)
384 	 * @see org.xmlhammer.gui.overview.OverviewNode#getNodeName()
385 	 */
386 	public String getNodeName() {
387         switch (validationSelector.getSelectedIndex()) {
388             case 1:
389                 return "XML Parser (DTD)";
390             case 2:
391                 return "XML Parser (xsi:schemaLocation)";
392             case 3:
393                 return "XML Parser (specified schemas(s))";
394             case 4:
395                 return "XML Parser (DTD + specified schema(s))";
396             default:
397                 return "XML Parser (wellformed)";
398         }
399 	}
400     
401     /* (non-Javadoc)
402      * @see org.xmlhammer.gui.overview.OverviewNode#getChildNodes()
403      */
404     public ArrayList<OverviewNode> getChildNodes() {
405         ArrayList<OverviewNode> children = new ArrayList<OverviewNode>(nodes);
406         children.add( urisPanel);
407         
408         return children;
409     }
410     
411     public String getError() {
412         return null;
413     }
414 
415     public void dispose() {
416         urisPanel.dispose();
417     }
418 
419     public void appendSource(StringBuilder builder) {
420         this.appendSource(builder, false);
421     }
422 
423     public void appendSource(StringBuilder builder, boolean builderOnly) {
424         if (isDOMSelected()) {
425             appendDocumentBuilder(builder, builderOnly);
426         } else {
427             appendSAXParserFactory(builder, builderOnly);
428         }
429     }
430     
431     public void appendJavaImports(StringBuilder builder) {
432         SourceBuilder.appendImport(builder, "java.io.IOException");
433         SourceBuilder.appendImport(builder, "java.net.URI");
434     }
435 
436     public void appendDOMImports(StringBuilder builder) {
437         if (isDOMSelected()) {
438             SourceBuilder.appendImport(builder, "org.w3c.dom.Document");
439         }
440         builder.append("\n");
441     }
442 
443     public void appendSAXImports(StringBuilder builder) {
444         if (!isDOMSelected()) {
445             SourceBuilder.appendImport(builder, "org.xml.sax.XMLReader");
446             SourceBuilder.appendImport(builder, "org.xml.sax.SAXNotRecognizedException");
447             SourceBuilder.appendImport(builder, "org.xml.sax.SAXNotSupportedException");
448         }
449 
450         SourceBuilder.appendImport(builder, "org.xml.sax.ErrorHandler");
451         SourceBuilder.appendImport(builder, "org.xml.sax.InputSource");
452         SourceBuilder.appendImport(builder, "org.xml.sax.SAXException");
453         SourceBuilder.appendImport(builder, "org.xml.sax.SAXParseException");
454     }
455 
456     public void appendJavaxImports(StringBuilder builder) {
457         if (isDOMSelected()) {
458             SourceBuilder.appendImport(builder, "javax.xml.parsers.DocumentBuilder");
459             SourceBuilder.appendImport(builder, "javax.xml.parsers.DocumentBuilderFactory");
460         } else {
461             SourceBuilder.appendImport(builder, "javax.xml.parsers.SAXParserFactory");
462             SourceBuilder.appendImport(builder, "javax.xml.parsers.SAXParser");
463         }
464         
465         SourceBuilder.appendImport(builder, "javax.xml.parsers.ParserConfigurationException");
466 
467         if ( urisPanel.getURIs(null).size() > 0 && urisPanel.getSchemaLanguage() != null) {
468             builder.append("\n");
469             SourceBuilder.appendImport(builder, "javax.xml.transform.Source");
470             SourceBuilder.appendImport(builder, "javax.xml.transform.stream.StreamSource");
471             builder.append("\n");
472             SourceBuilder.appendImport(builder, "javax.xml.validation.Schema");
473             SourceBuilder.appendImport(builder, "javax.xml.validation.SchemaFactory");
474         }
475     }
476 
477     private void appendSAXParserFactory(StringBuilder builder, boolean readerOnly) {
478         if ( getProjectView().getProject().getJAXPSettings() != null) {
479             JAXPSettings jaxp = new JAXPSettings(PreferencesHandler.getInstance().getPreferences().getJAXPSettings(), getProjectView().getProject().getJAXPSettings());
480     
481             JAXPSAXParserFactory.Settings settings = jaxp.getSAXParserSettings();
482             
483             if ( settings.getValue() != null) {
484                 builder.append("        System.setProperty(");
485                 SourceBuilder.appendConstant(builder, "\"javax.xml.parsers.SAXParserFactory\"");
486                 builder.append(", ");
487                 builder.append( settings.getValue());
488                 builder.append(");\n\n");
489             }
490                     
491             builder.append("        SAXParserFactory factory = SAXParserFactory.newInstance();\n\n");
492     
493             builder.append("        factory.setValidating(");
494             SourceBuilder.appendConstant(builder, validating.isSelected());
495             builder.append(");\n");
496     
497             builder.append("        factory.setNamespaceAware(");
498             SourceBuilder.appendConstant(builder, namespaceAware.isSelected());
499             builder.append(");\n");
500     
501             builder.append("        factory.setXIncludeAware(");
502             SourceBuilder.appendConstant(builder, xincludeAware.isSelected());
503             builder.append(");\n\n");
504 
505             List<Feature> features = jaxp.getSAXParserFactoryFeatures();
506 
507             if (features.size() > 0) {
508                 SourceBuilder.appendReserved(builder, "        try ");
509                 builder.append("{\n");
510         
511                 for ( Feature feature : features) {
512                     builder.append("            factory.setFeature(");
513                     SourceBuilder.appendConstant(builder, "\""+feature.getName()+"\"");
514                     builder.append(", ");
515                     SourceBuilder.appendConstant(builder, feature.isEnabled());
516                     builder.append(");\n");
517                 }
518             
519                 SourceBuilder.appendCatch(builder, "        ", "ParserConfigurationException");
520                 SourceBuilder.appendCatch(builder, "        ", "SAXNotSupportedException");
521                 SourceBuilder.appendCatch(builder, "        ", "SAXNotRecognizedException");
522                 builder.append("        }\n");
523 
524                 builder.append("\n");
525             }
526             
527             builder.append("        XMLReader reader = ");
528             SourceBuilder.appendReserved(builder, "null");
529             builder.append(";\n\n");
530 
531             if ( urisPanel.getSchemaLanguage() != null) {
532                 if ( urisPanel.getURIs(null).size() > 0) {
533                     appendSchema(jaxp, builder);
534                     builder.append("        factory.setSchema(schema);\n\n");
535                     SourceBuilder.appendReserved(builder, "        try ");
536                     builder.append("{\n");
537                     builder.append("            SAXParser parser = factory.newSAXParser();\n");
538                 } else {
539                     SourceBuilder.appendReserved(builder, "        try ");
540                     builder.append("{\n");
541                     builder.append("            SAXParser parser = factory.newSAXParser();\n");
542                     builder.append("            parser.setProperty(");
543                     SourceBuilder.appendConstant(builder, "\"http://java.sun.com/xml/jaxp/properties/schemaLanguage\"");
544                     builder.append(", ");
545                     SourceBuilder.appendConstant(builder, "\""+urisPanel.getSchemaLanguage()+"\"");
546                     builder.append(");\n\n");
547                 }
548             } else {
549                 SourceBuilder.appendReserved(builder, "        try ");
550                 builder.append("{\n");
551                 builder.append("            SAXParser parser = factory.newSAXParser();\n\n");
552             }
553     
554             List<Property> properties = jaxp.getSAXParserFactoryProperties();
555             
556             for ( Property property : properties) {
557                 builder.append("            parser.setProperty(");
558                 SourceBuilder.appendConstant(builder, "\""+property.getName()+"\"");
559                 builder.append(", ");
560                 SourceBuilder.appendConstant(builder, "\""+property.getValue()+"\"");
561                 builder.append(");\n");
562             }
563     
564             if ( properties.size() > 0) {
565                 builder.append("\n");
566             }
567     
568 
569             builder.append("            reader = parser.getXMLReader();\n");
570 
571             builder.append("            reader.setErrorHandler(");
572             SourceBuilder.appendReserved(builder, "new ");
573             builder.append("SimpleErrorHandler());\n");
574             
575             if (!readerOnly) {
576                 builder.append("            reader.parse(");
577                 SourceBuilder.appendReserved(builder, "new");
578                 builder.append(" InputSource(uri.toString()));\n");
579             }
580 
581             SourceBuilder.appendCatch(builder, "        ", "ParserConfigurationException");
582             SourceBuilder.appendCatch(builder, "        ", "SAXException");
583             
584             if (!readerOnly) {
585                 SourceBuilder.appendCatch(builder, "        ", "IOException");
586             }
587             
588             builder.append("        }\n");
589         }
590     }
591 
592     private void appendDocumentBuilder(StringBuilder builder, boolean builderOnly) {
593         if ( getProjectView().getProject().getJAXPSettings() != null) {
594             JAXPSettings jaxp = new JAXPSettings(PreferencesHandler.getInstance().getPreferences().getJAXPSettings(), getProjectView().getProject().getJAXPSettings());
595     
596             JAXPDocumentBuilderFactory.Settings settings = jaxp.getDocumentBuilderFactorySettings();
597             
598             if ( settings.getValue() != null) {
599                 builder.append("        System.setProperty(");
600                 SourceBuilder.appendConstant(builder, "\"javax.xml.parsers.DocumentBuilderFactory\"");
601                 builder.append(", ");
602                 builder.append( settings.getValue());
603                 builder.append(");\n\n");
604             }
605                     
606             builder.append("        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\n\n");
607     
608             builder.append("        factory.setCoalescing(");
609             SourceBuilder.appendConstant(builder, settings.isCoalescing());
610             builder.append(");\n");
611     
612             builder.append("        factory.setExpandEntityReferences(");
613             SourceBuilder.appendConstant(builder, settings.isExpandEntityReference());
614             builder.append(");\n");
615     
616             builder.append("        factory.setIgnoringComments(");
617             SourceBuilder.appendConstant(builder, settings.isIgnoringComments());
618             builder.append(");\n");
619     
620             builder.append("        factory.setIgnoringElementContentWhitespace(");
621             SourceBuilder.appendConstant(builder, settings.isIgnoringElementContentWhitespace());
622             builder.append(");\n\n");
623     
624             builder.append("        factory.setValidating(");
625             SourceBuilder.appendConstant(builder, validating.isSelected());
626             builder.append(");\n");
627     
628             builder.append("        factory.setNamespaceAware(");
629             SourceBuilder.appendConstant(builder, namespaceAware.isSelected());
630             builder.append(");\n");
631     
632             builder.append("        factory.setXIncludeAware(");
633             SourceBuilder.appendConstant(builder, xincludeAware.isSelected());
634             builder.append(");\n\n");
635     
636             List<Feature> features = jaxp.getDocumentBuilderFactoryFeatures();
637     
638             for ( Feature feature : features) {
639                 builder.append("        factory.setFeature(");
640                 SourceBuilder.appendConstant(builder, "\""+feature.getName()+"\"");
641                 builder.append(", ");
642                 SourceBuilder.appendConstant(builder, feature.isEnabled());
643                 builder.append(");\n");
644             }
645             
646             if ( features.size() > 0) {
647                 builder.append("\n");
648             }
649             
650             List<Attribute> attributes = jaxp.getDocumentBuilderFactoryAttributes();
651     
652             for ( Attribute attribute : attributes) {
653                 builder.append("        factory.setFeature(");
654                 SourceBuilder.appendConstant(builder, "\""+attribute.getName()+"\"");
655                 builder.append(", ");
656                 SourceBuilder.appendConstant(builder, "\""+attribute.getValue()+"\"");
657                 builder.append(");\n");
658             }
659     
660             if ( attributes.size() > 0) {
661                 builder.append("\n");
662             }
663     
664             if ( urisPanel.getSchemaLanguage() != null) {
665                 if ( urisPanel.getURIs(null).size() > 0) {
666                     appendSchema(jaxp, builder);
667                     builder.append("        factory.setSchema(schema);\n\n");
668                 } else {
669                     builder.append("        factory.setAttribute(");
670                     SourceBuilder.appendConstant(builder, "\"http://java.sun.com/xml/jaxp/properties/schemaLanguage\"");
671                     builder.append(", ");
672                     SourceBuilder.appendConstant(builder, "\""+urisPanel.getSchemaLanguage()+"\"");
673                     builder.append(");\n\n");
674                 }
675             }
676     
677             if (!builderOnly) {
678                 builder.append("        Document document = ");
679                 SourceBuilder.appendReserved(builder, "null");
680                 builder.append(";\n");
681             }
682             builder.append("        DocumentBuilder builder = ");
683             SourceBuilder.appendReserved(builder, "null");
684             builder.append(";\n\n");
685             SourceBuilder.appendReserved(builder, "        try ");
686             builder.append("{\n");
687             builder.append("            builder = factory.newDocumentBuilder();\n\n");
688 
689             builder.append("            builder.setErrorHandler(");
690             SourceBuilder.appendReserved(builder, "new ");
691             builder.append("SimpleErrorHandler());\n");
692 
693             if (!builderOnly) {
694                 builder.append("            document = builder.parse(");
695                 SourceBuilder.appendReserved(builder, "new");
696                 builder.append(" InputSource(uri.toString()));\n");
697             }
698 
699             SourceBuilder.appendCatch(builder, "        ", "ParserConfigurationException");
700 
701             if (!builderOnly) {
702                 SourceBuilder.appendCatch(builder, "        ", "SAXException");
703                 SourceBuilder.appendCatch(builder, "        ", "IOException");
704             }
705             
706             builder.append("        }\n");
707         }
708     }
709     
710     private void appendSchema(JAXPSettings settings, StringBuilder builder) {
711         String schemaLanguage = urisPanel.getSchemaLanguage();
712 
713         List<SchemaFactoryProperty> languages = settings.getSchemaFactoryLanguageProperties();
714         
715         for ( SchemaFactoryProperty language : languages) {
716             String factory = language.getFactory();
717             String lang = language.getLanguage();
718             
719             if ( lang != null && lang.equals(schemaLanguage) && factory != null && factory.trim().length() > 0) {
720                 builder.append("        System.setProperty(");
721                 SourceBuilder.appendConstant(builder, "\"javax.xml.validation.SchemaFactory:"+lang+"\"");
722                 builder.append(", ");
723                 SourceBuilder.appendConstant(builder, "\""+factory+"\"");
724                 builder.append(");\n\n");
725             }
726         }
727         
728         JAXPSAXParserFactory.Settings saxParserSettings = settings.getSAXParserSettings();
729         
730         if (saxParserSettings.getValue() != null) {
731             builder.append("        System.setProperty(");
732             SourceBuilder.appendConstant(builder, "\"javax.xml.parsers.SAXParserFactory\"");
733             builder.append(", ");
734             SourceBuilder.appendConstant(builder, "\""+saxParserSettings.getValue()+"\"");
735             builder.append(");\n\n");
736         }
737 
738         builder.append("        SchemaFactory schemaFactory = SchemaFactory.newInstance(");
739         SourceBuilder.appendConstant(builder, "\""+schemaLanguage+"\"");
740         builder.append(");\n\n");
741 
742         List<Feature> features = settings.getSchemaFactoryFeatures();
743 
744         for ( Feature feature : features) {
745             builder.append("        schemaFactory.setFeature(");
746             SourceBuilder.appendConstant(builder, "\""+feature.getName()+"\"");
747             builder.append(", ");
748             SourceBuilder.appendConstant(builder, feature.isEnabled());
749             builder.append(");\n");
750         }
751         
752         if (features.size() > 0) {
753             builder.append("\n");
754         }
755         
756         List<Property> properties = settings.getSchemaFactoryProperties();
757 
758         for ( Property property : properties) {
759             builder.append("        schemaFactory.setProperty(");
760             SourceBuilder.appendConstant(builder, "\""+property.getName()+"\"");
761             builder.append(", ");
762             SourceBuilder.appendConstant(builder, "\""+property.getValue()+"\"");
763             builder.append(");\n");
764         }
765 
766         if (properties.size() > 0) {
767             builder.append("\n");
768         }
769 
770         List<Document> uris = urisPanel.getURIs(null);
771         if ( uris.size() > 0) {
772             builder.append("        Source[] sources = ");
773             SourceBuilder.appendReserved(builder, "new");
774             builder.append(" Source["+uris.size()+"];\n\n");
775 
776             for ( int i = 0; i < uris.size(); i++) {
777                 builder.append("        sources["+i+"] = ");
778                 SourceBuilder.appendReserved(builder, "new");
779                 builder.append(" StreamSource(");
780                 SourceBuilder.appendConstant(builder, "\""+uris.get(i).getSrc()+"\"");
781                 builder.append(");\n");
782             }
783             
784             builder.append("\n        Schema schema = ");
785             SourceBuilder.appendReserved(builder, "null;\n\n");
786             SourceBuilder.appendReserved(builder, "        try ");
787             builder.append("{\n");
788             builder.append("            schema = schemaFactory.newSchema(sources);\n");
789             SourceBuilder.appendCatch(builder, "        ", "SAXException");
790             builder.append("        }\n\n");
791         }
792     }
793 
794     public static void appendErrorHandler(StringBuilder builder) {
795         SourceBuilder.appendReserved(builder, "    public ");
796         SourceBuilder.appendReserved(builder, "class ");
797         builder.append("SimpleErrorHandler ");
798         SourceBuilder.appendReserved(builder, "implements");
799         builder.append(" ErrorHandler {\n");
800 
801         appendErrorHandlerMethod(builder, "warning");
802         builder.append("\n");
803         appendErrorHandlerMethod(builder, "error");
804         builder.append("\n");
805         appendErrorHandlerMethod(builder, "fatalError");
806         builder.append("    }\n");
807     }
808     
809     private static void appendErrorHandlerMethod(StringBuilder builder, String method) {
810         SourceBuilder.appendReserved(builder, "        public void ");
811         builder.append(method);
812         builder.append("(SAXParseException e) ");
813         SourceBuilder.appendReserved(builder, "throws");
814         builder.append(" SAXException {\n");
815         builder.append("            System.");
816         SourceBuilder.appendConstant(builder, "out");
817         builder.append(".println(e.getMessage());\n");
818         builder.append("        }\n");
819     }
820 
821     @Override
822     public String getHelpID() {
823         return getProjectView().getHelpID()+".parser.configuration";
824     }
825 }