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-2001 Sun
 * Microsystems, Inc. All Rights Reserved.
 */
package org.netbeans.lib.jmi.xmi;

import java.io.*;
import java.util.*;
import java.net.URL;
import org.xml.sax.*;
import org.xml.sax.helpers.DefaultHandler;

import org.netbeans.lib.jmi.util.DebugException;

public class DefaultWriter extends DefaultHandler {

    private static final char QUOTE = '\'';
    private static final char EOL = '\n';
    private static final String INDENT = "  ";
    private static final int INDENT_LENGTH = INDENT.length ();
    /** An upper bound on the number of characters that can be printed to the output writer 
     * per one line. A new line is started every time when the number of characters in a line
     * (excluding indent spaces) after @link #startElement or @link #addAttribute exceeds MAX.
     */
    private static final int MAX = 70;
    
    private static final String XMI_VERSION = "1.2";
    private static final String EXPORTER_NAME = "Netbeans XMI Writer";
    private static final String EXPORTER_VERSION = "1.0";
    private static final String DEFAULT_ENCODING = "ISO-8859-1";
    
    // variables ................................................................
            
    //
    private OutputStreamWriter writer;    
    // document locator
    private Locator locator;
    //
    private String encoding = null;
    
    // true if the currently written XML element has at least one sub-element
    private boolean hasContent = true; // inited by true due to condition in @link #startElement
    // true if the currently written XML element has some characters in its content
    private boolean hasCharacters = false;
    // indentation spaces to be currently used
    private String indentSpaces = "";
    // number of charecters written on current line so far (excluding indent spaces)
    private int charsCount = 0;
    
    // init .....................................................................
    
    public DefaultWriter() {
    }
    
    public DefaultWriter(OutputStreamWriter writer, String encoding) {
        this.writer = writer;
        this.encoding = encoding;
    }
    
    public void init () throws SAXException {        
        hasContent = true;
        hasCharacters = true;
        indentSpaces = "";
        charsCount = 0;
        
        if (writer == null) {
            try {
                OutputStream ostr = new URL (locator.getSystemId()).openConnection().getOutputStream();
                writer = new OutputStreamWriter (ostr);
            } catch (IOException e) {
                throw new SAXException (e);
            }
        }
        String enc = (encoding != null) ? encoding : DEFAULT_ENCODING;
        write ("");
        writeln ();
    }
    
    // methods ..................................................................
     
    public Writer getWriter () {
        return writer;
    }
    
    /**
     * Writes a string to the output writer.
     *
     * @param text a string to be written in the output writer
     */
    private void write (String text) throws SAXException {
        try {
            writer.write (text);
        } catch (IOException e) {
            throw new SAXException (e);
        }
    }
    
    /**
     * Writes end of line to the output writer.
     */
    private void writeln () throws SAXException {
        try {
            writer.write ("\r\n");
        } catch (IOException e) {
            throw new SAXException (e);
        }
        charsCount = 0;
    }
    
    /**
     * Locates occurences of special XML charecters (like '<', '&', etc.) in a string
     * and replaces them by sequences of the form &X...X;
     *
     * In addition, if replaceWhitechars parameter is true, '\n', '\r' and '\t' are replaced
     * by &#NN; sequences. 
     */
    private String replaceSpecialChars (String s, boolean replaceWhitechars) {
        int length = s.length ();
        char [] chars = new char [6 * length];
        int n = 0;
        for (int x = 0; x < length; x++) {
            char c = s.charAt (x);
            switch (c) {
                case '&':
                    chars [n] = '&'; n++;   chars [n] = 'a'; n++;
                    chars [n] = 'm'; n++;   chars [n] = 'p'; n++;
                    chars [n] = ';'; n++; 
                break;
                case '\'':
                    chars [n] = '&'; n++;   chars [n] = 'a'; n++;
                    chars [n] = 'p'; n++;   chars [n] = 'o'; n++;
                    chars [n] = 's'; n++;   chars [n] = ';'; n++;
                break;
                case '\"':
                    chars [n] = '&'; n++;   chars [n] = 'q'; n++;
                    chars [n] = 'u'; n++;   chars [n] = 'o'; n++;
                    chars [n] = 't'; n++;   chars [n] = ';'; n++;
                break;
                case '<':
                    chars [n] = '&'; n++;   chars [n] = 'l'; n++;
                    chars [n] = 't'; n++;   chars [n] = ';'; n++;
                break;
                case '>':
                    chars [n] = '&'; n++;   chars [n] = 'g'; n++;
                    chars [n] = 't'; n++;   chars [n] = ';'; n++;
                break;
                default:
                    if (replaceWhitechars) {
                        switch (c) {
                            case '\n':
                                chars [n] = '&'; n++; chars [n] = '#'; n++;
                                chars [n] = '1'; n++; chars [n] = '0'; n++;
                                chars [n] = ';'; n++;
                            break;
                            case '\r':
                                chars [n] = '&'; n++; chars [n] = '#'; n++;
                                chars [n] = '1'; n++; chars [n] = '3'; n++;
                                chars [n] = ';'; n++;
                            break;
                            case '\t':
                                chars [n] = '&'; n++; chars [n] = '#'; n++;
                                chars [n] = '9'; n++; chars [n] = ';'; n++;
                            break;
                            default:
                                chars [n] = c; n++;
                        }
                    } else {
                        chars [n] = c; n++;
                    }
            } // switch
        } // for
        return new String (chars, 0, n);
    }
    
    /**
     * Writes start of a XML element to the output writer.
     *
     * @param name name of the XML element to be written
     */
    private void startElement (String name, Attributes attrs) throws SAXException {
        if (!hasContent && !hasCharacters) {
            write (">");
            writeln ();
        }
        hasContent = false;
        hasCharacters = false;
        write (indentSpaces);
        write ("<" + name);
        charsCount += name.length () + 1;
        indentSpaces = indentSpaces + INDENT;
        for (int x = 0; x < attrs.getLength(); x++) {
            addAttribute (attrs.getQName(x), attrs.getValue(x));
        }
    }
    
    /**
     * Writes end of an XML element to the output writer.
     *
     * @param name name of the XML element to be written
     */
    private void endElement (String name) throws SAXException {
        indentSpaces = indentSpaces.substring (0, indentSpaces.length () - INDENT_LENGTH);
        if (hasContent) {
            write (indentSpaces);
            write ("");
        } else if (hasCharacters) {
            write ("");
        } else
            write ("/>");
        writeln ();
        hasContent = true;
    }
    
    /**
     * Writes an attribute of the currenly written XML elemnt to the output writer.
     *
     * @param name attribute name
     * @param value value of the attribute
     */
    private void addAttribute (String name, String value) throws SAXException {
        value = replaceSpecialChars (value, true);
        // [PENDING] ??? can be special characters in name too ???
        if (charsCount > MAX) {
            writeln ();
            write (indentSpaces);
        } else {
            write (" ");
            charsCount++;
        }
        write (name + " = " + QUOTE + value + QUOTE);
        charsCount += name.length () + value.length () + 5;
    }
    
    /**
     * Writes characters into body of the currenly written XML elemnt.
     * Before the string is written, @link #replaceSpecialChars is called
     * on it to replace special XML characters.
     *
     * @param text string to be written
     */
    private void characters (String text) throws SAXException {
        text = replaceSpecialChars (text, false);
        if (!hasContent)
            write (">");
        write (text);        
        hasCharacters = true;
    }        
    
    // org.xml.sax.ContentHandler interface implementation ......................
    
    public void startDocument() throws org.xml.sax.SAXException {
        init ();
    }
    
    public void endDocument() throws org.xml.sax.SAXException {
        try {
            writer.flush();
            writer.close();
        } catch (IOException e) {
            throw new SAXException (e);
        }
    }
    
    public void startElement(String uri, String sName, String qName, Attributes attributes) throws org.xml.sax.SAXException {
        startElement (qName, attributes);
    }
    
    public void endElement(String uri, String sName, String qName) throws org.xml.sax.SAXException {
        endElement (qName);
    }
    
    public void characters(char[] buf, int offset, int len) throws org.xml.sax.SAXException {
        characters (new String (buf, offset, len));
    }

    public void setDocumentLocator(Locator locator) {
        this.locator = locator;
    }
    
    /*
    public void skippedEntity(String str) throws org.xml.sax.SAXException {
    }
    
    public void processingInstruction(String str, String str1) throws org.xml.sax.SAXException {
    }        
    
    public void endPrefixMapping(String str) throws org.xml.sax.SAXException {
    }
    
    public void startPrefixMapping(String str, String str1) throws org.xml.sax.SAXException {
    }        
        
    public void ignorableWhitespace(char[] values, int param, int param2) throws org.xml.sax.SAXException {
    }
     */
    
}
... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2024 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.