All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.sf.xolite.sax.SaxXMLSerializer Maven / Gradle / Ivy

Go to download

This project provides a lightweight framework to serialize/deserialize (or marshall/unmarshall) java objects into XML. The implementation is based on standard SAX (Simple Api for Xml) but it follows a original approach based on the strong data encapsulation paradigm of Object Oriented (OO) programming.

The newest version!
/*-------------------------------------------------------------------------
 Copyright 2012 Olivier Berlanger

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 -------------------------------------------------------------------------*/
package net.sf.xolite.sax;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.xolite.XMLSerializable;
import net.sf.xolite.XMLSerializeException;
import net.sf.xolite.XMLSerializer;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.Locator;


/**
 * XMLSerializer passing all the serialization events to a SAX ContentHandler.
 * 
 * @author Olivier Berlanger
 */
public class SaxXMLSerializer implements XMLSerializer {


    private int elementIndex;
    private ContentHandler handler;
    private Map customObjects;
    private Map prefixMappings;
    private String elementUri;
    private String elementTag;
    private AttributesImpl attributes = new AttributesImpl();


    public SaxXMLSerializer() {
    }


    public SaxXMLSerializer(ContentHandler theHandler) {
        setContentHandler(theHandler);
    }


    public void setContentHandler(ContentHandler theHandler) {
        if (handler != theHandler) {
            if (handler != null) handler.setDocumentLocator(null);
            handler = theHandler;
            handler.setDocumentLocator(new LocatorProxy());
        }
    }


    public ContentHandler getContentHandler() {
        return handler;
    }


    public void serialize(XMLSerializable root) throws XMLSerializeException {
        startDocument();
        root.serialize(this);
        endDocument();
    }


    public void startDocument() throws XMLSerializeException {
        if (handler == null) throw new XMLSerializeException("Handler not set");
        try {
            handler.startDocument();
        } catch (Exception e) {
            throw new XMLSerializeException("Handler exception", e);
        }
    }


    public void startElement(String namespaceUri, String localName) throws XMLSerializeException {
        flushStartedElement();
        elementUri = namespaceUri;
        elementTag = localName;
        attributes.clear();
    }


    public void attribute(String localName, String value) throws XMLSerializeException {
        attributes.addAttribute(null, localName, value);
    }


    public void attribute(String namespaceUri, String localName, String value) throws XMLSerializeException {
        attributes.addAttribute(namespaceUri, localName, value);
    }


    private void flushStartedElement() throws XMLSerializeException {
        if (elementTag != null) {
            try {
                handler.startElement(elementUri, elementTag, getQualifiedName(elementUri, elementTag), attributes);
            } catch (Exception e) {
                throw new XMLSerializeException("Handler exception", e);
            }
            elementUri = null;
            elementTag = null;
        }
    }


    public void characters(String text) throws XMLSerializeException {
        flushStartedElement();
        try {
            handler.characters(text.toCharArray(), 0, text.length());
        } catch (Exception e) {
            throw new XMLSerializeException("Handler exception", e);
        }
    }


    public void charactersMultiLine(String text) throws XMLSerializeException {
        flushStartedElement();
        try {
            handler.characters(text.toCharArray(), 0, text.length());
        } catch (Exception e) {
            throw new XMLSerializeException("Handler exception", e);
        }
    }


    public void endElement(String namespaceUri, String localName) throws XMLSerializeException {
        flushStartedElement();
        try {
            handler.endElement(namespaceUri, localName, getQualifiedName(namespaceUri, localName));
        } catch (Exception e) {
            throw new XMLSerializeException("Handler exception", e);
        }
    }


    public void endDocument() throws XMLSerializeException {
        try {
            handler.endDocument();
        } catch (Exception e) {
            throw new XMLSerializeException("Handler exception", e);
        }
    }


    String getQualifiedName(String namespaceUri, String localName) {
        String prefix = null;
        if (prefixMappings != null) {
            prefix = prefixMappings.get(namespaceUri);
        }
        if ((prefix == null) || prefix.equals("")) return localName;
        return prefix + ":" + localName;
    }


    public Object getCustomObject(Object key) {
        if (customObjects == null) return null;
        return customObjects.get(key);
    }


    public void putCustomObject(Object key, Object value) {
        if (customObjects == null) customObjects = new HashMap();
        customObjects.put(key, value);
    }


    public void simpleElement(String namespaceUri, String localName, String text) throws XMLSerializeException {
        startElement(namespaceUri, localName);
        if (text != null) characters(text);
        endElement(namespaceUri, localName);
    }


    public void startPrefixMapping(String prefix, String namespaceUri) throws XMLSerializeException {
        if (prefixMappings == null) prefixMappings = new HashMap();
        if (!prefixMappings.containsKey(namespaceUri)) {
            prefixMappings.put(namespaceUri, prefix);
        }
        try {
            handler.startPrefixMapping(prefix, namespaceUri);
        } catch (Exception e) {
            throw new XMLSerializeException("Handler exception", e);
        }
    }


    int getElementIndex() {
        return elementIndex;
    }


    public static boolean stringEquals(Object obj1, Object obj2) {
        if (obj1 == obj2) return true;
        String str1 = (obj1 == null) ? "" : obj1.toString().trim();
        String str2 = (obj2 == null) ? "" : obj2.toString().trim();
        return str1.equals(str2);
    }


    /**
     * Implementation of the SAX Locator.
     */
    class LocatorProxy implements Locator {


        public int getColumnNumber() {
            return 0;
        }


        public int getLineNumber() {
            return getElementIndex();
        }


        public String getPublicId() {
            return "generated-sax-xml";
        }


        public String getSystemId() {
            return "generated-sax-xml";
        }

    }


    /**
     * Implementation of the SAX Attributes interface.
     */
    class AttributesImpl implements Attributes {


        private List attrs = new ArrayList();


        void clear() {
            attrs.clear();
        }


        void addAttribute(String uri, String name, String value) {
            attrs.add(new SimpleAttribute(uri, name, value));
        }


        public int getIndex(String qName) {
            for (int i = 0; i < attrs.size(); i++) {
                if (attrs.get(i).hasQualifiedName(qName)) return i;
            }
            return -1;
        }


        public int getIndex(String uri, String localName) {
            for (int i = 0; i < attrs.size(); i++) {
                if (attrs.get(i).hasName(uri, localName)) return i;
            }
            return -1;
        }


        public int getLength() {
            return attrs.size();
        }


        public String getLocalName(int index) {
            return attrs.get(index).getLocalName();
        }


        public String getQName(int index) {
            return attrs.get(index).getQName();
        }


        public String getType(int index) {
            return "CDATA";
        }


        public String getType(String name) {
            return "CDATA";
        }


        public String getType(String uri, String localName) {
            return "CDATA";
        }


        public String getURI(int index) {
            return attrs.get(index).getURI();
        }


        public String getValue(int index) {
            return attrs.get(index).getValue();
        }


        public String getValue(String qName) {
            int index = getIndex(qName);
            if (index < 0) return null;
            return attrs.get(index).getValue();
        }


        public String getValue(String uri, String localName) {
            int index = getIndex(uri, localName);
            if (index < 0) return null;
            return attrs.get(index).getValue();
        }

    }


    /**
     * Class to hold values of a XML attribute.
     */
    class SimpleAttribute {


        private String uri;
        private String name;
        private String value;
        private String qName;


        public SimpleAttribute(String u, String n, String v) {
            uri = u;
            name = n;
            value = v;
        }


        public String getValue() {
            return value;
        }


        public String getURI() {
            return uri;
        }


        public String getQName() {
            if (qName == null) qName = getQualifiedName(uri, name);
            return qName;
        }


        public String getLocalName() {
            return name;
        }


        public boolean hasName(String namespaceUri, String localName) {
            if (!stringEquals(uri, namespaceUri)) return false;
            return stringEquals(name, localName);
        }


        public boolean hasQualifiedName(String comparedQName) {
            return comparedQName.equalsIgnoreCase(getQName());
        }

    }


}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy