alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

What this is

This file is included in the DevDaily.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Other links

The source code

/*
 *                 Sun Public License Notice
 * 
 * The contents of this file are subject to the Sun Public License
 * Version 1.0 (the "License"). You may not use this file except in
 * compliance with the License. A copy of the License is available at
 * http://www.sun.com/
 * 
 * The Original Code is NetBeans. The Initial Developer of the Original
 * Code is Sun Microsystems, Inc. Portions Copyright 1997-2003 Sun
 * Microsystems, Inc. All Rights Reserved.
 */

package org.netbeans.core.registry;

import org.openide.ErrorManager;
import org.openide.filesystems.FileLock;
import org.openide.filesystems.FileObject;
import org.openide.xml.EntityCatalog;
import org.openide.xml.XMLUtil;
import org.w3c.dom.*;
import org.xml.sax.InputSource;
import org.xml.sax.EntityResolver;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.ByteArrayInputStream;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.util.Properties;

/** 
 *
 * @author copy&pasted from core/settings
 */
public class DocumentUtils {
    private DocumentUtils() {
    }

    static Document createDocument() {
        //TODO: suspicious impl. - evaluate        
        // XXX Crimson documents do not seem to work too well; e.g. create a document element
        // with a namespace and attributes, and Xerces will not write out the attributes
        DocumentBuilderFactory factory;
        try {
            String prop = "javax.xml.parsers.DocumentBuilderFactory"; // NOI18N
            Properties p = System.getProperties();
            String old = p.getProperty(prop);
            try {
                p.setProperty(prop, "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl"); // NOI18N
                factory = DocumentBuilderFactory.newInstance();
            } finally {
                if (old != null) {
                    p.setProperty(prop, old);
                } else {
                    p.remove(prop);
                }
            }
        } catch (FactoryConfigurationError e) {
            // OK, Xerces didn't work, try the default configuration and hope.
            factory = DocumentBuilderFactory.newInstance();
        }
        factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        factory.setValidating(false);
        Document doc = null;
        try {
            doc = factory.newDocumentBuilder().newDocument();
        } catch (ParserConfigurationException ex) {
            ErrorManager.getDefault().log(ErrorManager.WARNING, "Could not create instance of new dom.Document.\n" + ex.toString());
            return null;
        }
        return doc;
    }

    static void writeDocument(FileObject fo, Document doc) throws IOException {
        FileLock lock = fo.lock();
        OutputStream os = fo.getOutputStream(lock);
        boolean ok = false;
        try {
            XMLUtil.write(doc, os, "UTF-8"); // NOI18N
            ok = true;
        } finally {
            os.close();
            lock.releaseLock();
            if (!ok) {
                // writing failed. kill the file
                fo.delete();
            }
        }
    }

    public static String getTextValue(Element element) {
        StringBuffer sb = new StringBuffer();
        NodeList nodes = element.getChildNodes();
        for (int i = 0; i < nodes.getLength(); i++) {
            Node node = nodes.item(i);
            if (node.getNodeType() == Node.TEXT_NODE) {
                sb.append(((Text)node).getData());
            }
            if (node.getNodeType() == Node.CDATA_SECTION_NODE) {
                sb.append(((CDATASection)node).getData());
            }
        }
        return sb.toString();
    }
    
    final static class DocumentRef {
        private Reference docRef;
        private static final Object[] document = new Object[2];

        Document getDocument(FileObject fo) {
            assert fo != null;

            Document d = null;
            synchronized (this) {
                if (docRef == null || (d = (Document) docRef.get()) == null) {
                    d = getDOM(fo);
                    docRef = new WeakReference(d);
                }
            }
            return d;
        }

        static synchronized Document getDOM(FileObject fo) {
            Document retVal = (Document) ((document[0] == null) ? null : ((Reference) (document[0])).get());
            if (retVal != null) {
                FileObject foRef = (FileObject) ((document[1] == null) ? null : ((Reference) (document[1])).get());
                if (foRef != null && foRef == fo) {
                    return retVal;
                }
            }
            try {
                InputStream is = fo.getInputStream();
                try {
                    InputSource iss = new InputSource(is);
                    retVal = XMLUtil.parse(iss, false, true, null, new EntityResolver() {
                        public InputSource resolveEntity(String publicId,String systemId)
                                throws SAXException, IOException {
                            InputSource retVal = EntityCatalog.getDefault().resolveEntity(publicId,systemId);
                            return (retVal != null) ? retVal : new InputSource(new ByteArrayInputStream(new byte[0]));
                        }
                    });
                    if (retVal != null) {
                        document[0] = new WeakReference(retVal);
                        document[1] = new WeakReference(fo);
                    }
                    return retVal;
                } catch (Exception e) {
                    ErrorManager.getDefault().log(ErrorManager.WARNING, "Could not parse file [" + fo + "].\n" + e.toString());
                } finally {
                    is.close();
                }
            } catch (IOException e) {
                ErrorManager.getDefault().log(ErrorManager.WARNING, "Could not parse file [" + fo + "].\n" + e.toString());
            }
            return null;
        }
    }

}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.