KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > netbeans > core > registry > DocumentUtils


1 /*
2  * The contents of this file are subject to the terms of the Common Development
3  * and Distribution License (the License). You may not use this file except in
4  * compliance with the License.
5  *
6  * You can obtain a copy of the License at http://www.netbeans.org/cddl.html
7  * or http://www.netbeans.org/cddl.txt.
8  *
9  * When distributing Covered Code, include this CDDL Header Notice in each file
10  * and include the License file at http://www.netbeans.org/cddl.txt.
11  * If applicable, add the following below the CDDL Header, with the fields
12  * enclosed by brackets [] replaced by your own identifying information:
13  * "Portions Copyrighted [year] [name of copyright owner]"
14  *
15  * The Original Software is NetBeans. The Initial Developer of the Original
16  * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
17  * Microsystems, Inc. All Rights Reserved.
18  */

19
20 package org.netbeans.core.registry;
21
22 import org.openide.ErrorManager;
23 import org.openide.filesystems.FileLock;
24 import org.openide.filesystems.FileObject;
25 import org.openide.xml.EntityCatalog;
26 import org.openide.xml.XMLUtil;
27 import org.w3c.dom.*;
28 import org.xml.sax.InputSource JavaDoc;
29 import org.xml.sax.EntityResolver JavaDoc;
30 import org.xml.sax.SAXException JavaDoc;
31
32 import javax.xml.parsers.DocumentBuilderFactory JavaDoc;
33 import javax.xml.parsers.FactoryConfigurationError JavaDoc;
34 import javax.xml.parsers.ParserConfigurationException JavaDoc;
35 import java.io.IOException JavaDoc;
36 import java.io.InputStream JavaDoc;
37 import java.io.OutputStream JavaDoc;
38 import java.io.ByteArrayInputStream JavaDoc;
39 import java.lang.ref.Reference JavaDoc;
40 import java.lang.ref.WeakReference JavaDoc;
41 import java.util.Properties JavaDoc;
42 import javax.xml.parsers.DocumentBuilder JavaDoc;
43
44 /**
45  *
46  * @author copy&pasted from core/settings
47  */

48 public class DocumentUtils {
49     
50     private static DocumentBuilderFactory JavaDoc factory;
51     private static DocumentBuilder JavaDoc builder;
52     
53     private DocumentUtils() {
54     }
55
56     private static DocumentBuilderFactory JavaDoc getDocumentBuilderFactory() {
57         if (factory == null) {
58             //TODO: suspicious impl. - evaluate
59
// XXX Crimson documents do not seem to work too well; e.g. create a document element
60
// with a namespace and attributes, and Xerces will not write out the attributes
61
try {
62                 String JavaDoc prop = "javax.xml.parsers.DocumentBuilderFactory"; // NOI18N
63
Properties JavaDoc p = System.getProperties();
64                 String JavaDoc old = p.getProperty(prop);
65                 try {
66                     p.setProperty(prop, "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); // NOI18N
67
factory = DocumentBuilderFactory.newInstance();
68                 } finally {
69                     if (old != null) {
70                         p.setProperty(prop, old);
71                     } else {
72                         p.remove(prop);
73                     }
74                 }
75             } catch (FactoryConfigurationError JavaDoc e) {
76                 // OK, Xerces didn't work, try the default configuration and hope.
77
factory = DocumentBuilderFactory.newInstance();
78             }
79             factory = DocumentBuilderFactory.newInstance();
80             factory.setNamespaceAware(true);
81             factory.setValidating(false);
82             // Please read follwing about why are these here:
83
// http://www-106.ibm.com/developerworks/xml/library/x-perfap2.html
84
factory.setAttribute("http://apache.org/xml/properties/dom/document-class-name", "org.apache.xerces.dom.CoreDocumentImpl");
85             factory.setAttribute("http://apache.org/xml/features/dom/defer-node-expansion", Boolean.FALSE);
86         }
87         return factory;
88     }
89
90     
91     private static DocumentBuilder JavaDoc getDocumentBuilder() throws ParserConfigurationException JavaDoc {
92         if (builder == null) {
93             builder = getDocumentBuilderFactory().newDocumentBuilder();
94             builder.setEntityResolver(EntityCatalog.getDefault());
95         }
96         return builder;
97     }
98     
99     static Document createDocument() {
100         Document doc = null;
101         try {
102             doc = getDocumentBuilder().newDocument();
103         } catch (ParserConfigurationException JavaDoc ex) {
104             ErrorManager.getDefault().log(ErrorManager.WARNING, "Could not create instance of new dom.Document.\n" + ex.toString());
105             return null;
106         }
107         return doc;
108     }
109
110     static void writeDocument(FileObject fo, Document doc) throws IOException JavaDoc {
111         FileLock lock = fo.lock();
112         OutputStream JavaDoc os = fo.getOutputStream(lock);
113         boolean ok = false;
114         try {
115             XMLUtil.write(doc, os, "UTF-8"); // NOI18N
116
ok = true;
117         } finally {
118             os.close();
119             lock.releaseLock();
120             if (!ok) {
121                 // writing failed. kill the file
122
fo.delete();
123             }
124         }
125     }
126
127     public static String JavaDoc getTextValue(Element element) {
128         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
129         NodeList nodes = element.getChildNodes();
130         for (int i = 0; i < nodes.getLength(); i++) {
131             Node node = nodes.item(i);
132             if (node.getNodeType() == Node.TEXT_NODE) {
133                 sb.append(((Text)node).getData());
134             }
135             if (node.getNodeType() == Node.CDATA_SECTION_NODE) {
136                 sb.append(((CDATASection)node).getData());
137             }
138         }
139         return sb.toString();
140     }
141     
142     final static class DocumentRef {
143         private Reference JavaDoc docRef;
144         private static final Object JavaDoc[] document = new Object JavaDoc[2];
145
146         Document getDocument(FileObject fo) {
147             assert fo != null;
148
149             Document d = null;
150             synchronized (this) {
151                 if (docRef == null || (d = (Document) docRef.get()) == null) {
152                     d = getDOM(fo);
153                     docRef = new WeakReference JavaDoc(d);
154                 }
155             }
156
157             // Check whether the resulting document is Ok:
158
if (d.getDocumentElement() == null) {
159                 docRef = null;
160                 document[0] = null;
161                 document[1] = null;
162                 // Try to parse it again:
163
synchronized (this) {
164                     if (docRef == null || (d = (Document) docRef.get()) == null) {
165                         d = getDOM(fo);
166                         docRef = new WeakReference JavaDoc(d);
167                     }
168                 }
169                 if (d.getDocumentElement() == null) {
170                     printFile(fo);
171                     throw new IllegalStateException JavaDoc("Cannot parse file " + fo);
172                 }
173                 
174             }
175             
176             return d;
177         }
178
179
180         static synchronized Document getDOM(FileObject fo) {
181             Document retVal = (Document) ((document[0] == null) ? null : ((Reference JavaDoc) (document[0])).get());
182             if (retVal != null) {
183                 FileObject foRef = (FileObject) ((document[1] == null) ? null : ((Reference JavaDoc) (document[1])).get());
184                 if (foRef != null && foRef == fo) {
185                     return retVal;
186                 }
187             }
188             try {
189                 if (fo.getSize() == 0) {
190                     return null;
191                 }
192                 InputStream JavaDoc is = fo.getInputStream();
193                 try {
194                     InputSource JavaDoc iss = new InputSource JavaDoc(is);
195                     retVal = XMLUtil.parse(iss, false, true, null, new EntityResolver JavaDoc() {
196                         public InputSource JavaDoc resolveEntity(String JavaDoc publicId,String JavaDoc systemId)
197                                 throws SAXException JavaDoc, IOException JavaDoc {
198                             InputSource JavaDoc retVal = EntityCatalog.getDefault().resolveEntity(publicId,systemId);
199                             return (retVal != null) ? retVal : new InputSource JavaDoc(new ByteArrayInputStream JavaDoc(new byte[0]));
200                         }
201                     });
202                     if (retVal != null) {
203                         document[0] = new WeakReference JavaDoc(retVal);
204                         document[1] = new WeakReference JavaDoc(fo);
205                     }
206                     return retVal;
207                 } catch (Exception JavaDoc e) {
208                     if (ErrorManager.getDefault().isLoggable(ErrorManager.INFORMATIONAL)) {
209                         ErrorManager.getDefault().log(ErrorManager.WARNING, "Could not parse file [" + fo + "].\n" + e.toString());
210                         ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
211                     }
212                 } finally {
213                     is.close();
214                 }
215             } catch (IOException JavaDoc e) {
216                 if (ErrorManager.getDefault().isLoggable(ErrorManager.INFORMATIONAL)) {
217                     ErrorManager.getDefault().log(ErrorManager.WARNING, "Could not parse file [" + fo + "].\n" + e.toString());
218                     ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e);
219                 }
220             }
221             return null;
222         }
223     }
224     
225     /** Debugging printout of the file */
226     private static void printFile(FileObject f) {
227         try {
228             System.err.println("Printing problem file: " + f); // NOI18N
229
java.io.InputStream JavaDoc in = f.getInputStream();
230             int ch = 0;
231             while ( (ch = in.read()) != -1) {
232                 System.err.write(ch);
233             }
234             in.close();
235         } catch (java.io.IOException JavaDoc ioe) {
236             ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ioe);
237         }
238     }
239 }
240
Popular Tags