⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 marshallingcontext.java

📁 对xml很好的java处理引擎,编译中绑定xml
💻 JAVA
📖 第 1 页 / 共 4 页
字号:
/*
Copyright (c) 2002-2005, Dennis M. Sosnoski.
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.
 * Neither the name of JiBX nor the names of its contributors may be used
   to endorse or promote products derived from this software without specific
   prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package org.jibx.runtime.impl;

import java.io.*;
import java.util.*;

import org.jibx.runtime.*;
import org.jibx.runtime.ICharacterEscaper;
import org.jibx.runtime.IMarshallable;
import org.jibx.runtime.IMarshaller;
import org.jibx.runtime.IMarshallingContext;
import org.jibx.runtime.JiBXException;

/**
 * JiBX serializer supplying convenience methods for marshalling. Most of these
 * methods are designed for use in code generated by the binding generator.
 *
 * @author Dennis M. Sosnoski
 * @version 1.0
 */

public class MarshallingContext implements IMarshallingContext
{
    /** Fixed XML namespace. */
    public static final String XML_NAMESPACE = 
        "http://www.w3.org/XML/1998/namespace";
        
    /** Starting size for object stack. */
    private static final int INITIAL_STACK_SIZE = 20;
    
    /** Binding factory used to create this unmarshaller. */
    private IBindingFactory m_factory;
        
    /** Names of classes included in mapping definition. */
    private String[] m_classes;
    
    /** Number of classes with global marshallers. */
    private int m_globalCount;
    
    /** Marshaller classes for mapping definition (<code>null</code> for
     mappings out of context). */
    private String[] m_marshallerClasses;
    
    /** Marshallers for classes in mapping definition (lazy create of actual
     marshaller instances) */
    private IMarshaller[] m_marshallers;
    
    /** URIs for namespaces used in binding. */
    private String[] m_uris;
    
    /** Current marshalling stack depth. */
    private int m_stackDepth;
    
    /** Stack of objects being marshalled. */
    private Object[] m_objectStack;
    
    /** Indent character count per level. */
    private int m_indentCount;
    
    /** Character sequence for end of line. */
    private String m_newLine;
    
    /** Character used for indenting. */
    private char m_indentChar;
    
    /** Shared map from IDs to objects. This is not used directly by the
      marshalling code, but is available for user extensions (lazy create). */
    private HashMap m_idMap;
    
    /** Output document handler. */
    private IXMLWriter m_writer;
    
    /** User context object (not used by JiBX, only for user convenience). */
    protected Object m_userContext;
    
    /**
     * Constructor.
     *
     * @param classes ordered array of class names included in mapping
     * definition (reference kept, must be constant)
     * @param mcs names of marshaller classes for indexes with fixed marshallers
     * (as opposed to mapping slots, which may be overridden; reference kept,
     * must be constant)
     * @param uris ordered array of URIs for namespaces used in binding (must
     * be constant; the value in position 0 must always be the empty string "",
     * and the value in position 1 must always be the XML namespace
     * "http://www.w3.org/XML/1998/namespace")
     * @param ifact binding factory creating this unmarshaller
     */
    public MarshallingContext(String[] classes, String[] mcs, String[] uris,
        IBindingFactory ifact) {
        m_classes = classes;
        m_globalCount = mcs.length;
        m_marshallers = new IMarshaller[classes.length];
        m_marshallerClasses = new String[classes.length];
        System.arraycopy(mcs, 0, m_marshallerClasses, 0, mcs.length);
        m_uris = uris;
        m_objectStack = new Object[INITIAL_STACK_SIZE];
        m_indentCount = -1;
        m_indentChar = ' ';
        m_newLine = "\n";
        m_factory = ifact;
    }
    
    /**
     * Create character escaper for encoding.
     *
     * @param enc document output encoding, or <code>null</code> for default
     * @return character escaper for encoding
     * @throws JiBXException if error creating setting output
     */
    private ICharacterEscaper createEscaper(String enc) throws JiBXException {
        if (enc.equalsIgnoreCase("UTF-8") || enc.equalsIgnoreCase("UTF-16") ||
            enc.equalsIgnoreCase("UTF-16BE") ||
            enc.equalsIgnoreCase("UTF-16LE")) {
            return UTF8Escaper.getInstance();
        } else if (enc.equalsIgnoreCase("ISO-8859-1")) {
            return ISO88591Escaper.getInstance();
        } else if (enc.equalsIgnoreCase("US-ASCII")) {
            return USASCIIEscaper.getInstance();
        } else {
            throw new JiBXException
                ("No character escaper defined for encoding " + enc);
        }
    }
    
    /**
     * Set output stream with encoding and escaper. This forces handling of the
     * output stream to use the Java character encoding support with the
     * supplied escaper.
     *
     * @param outs stream for document data output
     * @param enc document output encoding, or <code>null</code> uses UTF-8
     * default
     * @param esc escaper for writing characters to stream
     * @throws JiBXException if error setting output
     */
    public void setOutput(OutputStream outs, String enc, ICharacterEscaper esc)
        throws JiBXException {
        try {
            if (enc == null) {
                enc = "UTF-8";
            }
                
            // handle any other encodings using library support
            if (!(m_writer instanceof GenericXMLWriter)) {
                m_writer = new GenericXMLWriter(m_uris);
                m_writer.setIndentSpaces(m_indentCount, m_newLine,
                     m_indentChar);
            }
            Writer writer = new BufferedWriter
                (new OutputStreamWriter(outs, enc));
            ((GenericXMLWriter)m_writer).setOutput(writer, esc);
            reset();
            
        } catch (IOException ex) {
            throw new JiBXException("Error setting output", ex);
        }
    }
    
    /**
     * Set output stream and encoding.
     *
     * @param outs stream for document data output
     * @param enc document output encoding, or <code>null</code> for default
     * @throws JiBXException if error creating setting output
     */
    public void setOutput(OutputStream outs, String enc) throws JiBXException {
        if (enc == null) {
            enc = "UTF-8";
        }
        if ("UTF-8".equalsIgnoreCase(enc)) {
                
            // handle UTF-8 output to stream directly
            if (!(m_writer instanceof UTF8StreamWriter)) {
                m_writer = new UTF8StreamWriter(m_uris);
                m_writer.setIndentSpaces(m_indentCount, m_newLine,
                     m_indentChar);
            }
            ((UTF8StreamWriter)m_writer).setOutput(outs);
            reset();
                
        } else if ("ISO-8859-1".equalsIgnoreCase(enc)) {
                
            // handle ISO-8859-1 output to stream directly
            if (!(m_writer instanceof ISO88591StreamWriter)) {
                m_writer = new ISO88591StreamWriter(m_uris);
                m_writer.setIndentSpaces(m_indentCount, m_newLine,
                     m_indentChar);
            }
            ((ISO88591StreamWriter)m_writer).setOutput(outs);
            reset();
                
        } else {
            setOutput(outs, enc, createEscaper(enc));
        }
    }
    
    /**
     * Set output writer and escaper.
     *
     * @param outw writer for document data output
     * @param esc escaper for writing characters
     */
    public void setOutput(Writer outw, ICharacterEscaper esc) {
        if (!(m_writer instanceof GenericXMLWriter)) {
            m_writer = new GenericXMLWriter(m_uris);
            m_writer.setIndentSpaces(m_indentCount, m_newLine,
                 m_indentChar);
        }
        ((GenericXMLWriter)m_writer).setOutput(outw, esc);
        reset();
    }
    
    /**
     * Set output writer.
     *
     * @param outw writer for document data output
     */
    public void setOutput(Writer outw) {
        setOutput(outw, UTF8Escaper.getInstance());
    }

    /**
     * Get the writer being used for output.
     *
     * @return XML writer used for output
     */
    public IXMLWriter getXmlWriter() {
        return m_writer;
    }

    /**
     * Set the writer being used for output.
     *
     * @param xwrite XML writer used for output
     */
    public void setXmlWriter(IXMLWriter xwrite) {
        m_writer = xwrite;
    }
    
    /**
     * Get current nesting indent spaces. This returns the number of spaces used
     * to show indenting, if used.
     *
     * @return number of spaces indented per level, or negative if indentation
     * disabled
     */
    public int getIndent() {
        return m_indentCount;
    }
    
    /**
     * Set nesting indent spaces. This is advisory only, and implementations of
     * this interface are free to ignore it. The intent is to indicate that the
     * generated output should use indenting to illustrate element nesting.
     *
     * @param count number of spaces to indent per level, or disable
     * indentation if negative
     */
    public void setIndent(int count) {
        if (m_writer != null) {
            m_writer.setIndentSpaces(count, m_newLine, m_indentChar);
        }
        m_indentCount = count;
    }
    
    /**
     * Set nesting indentation. This is advisory only, and implementations of
     * this interface are free to ignore it. The intent is to indicate that the
     * generated output should use indenting to illustrate element nesting.
     *
     * @param count number of character to indent per level, or disable
     * indentation if negative (zero means new line only)
     * @param newline sequence of characters used for a line ending
     * (<code>null</code> means use the single character '\n')
     * @param indent whitespace character used for indentation
     */
    public void setIndent(int count, String newline, char indent) {
        if (m_writer != null) {
            m_writer.setIndentSpaces(count, newline, indent);
        }
        m_indentCount = count;
        m_newLine = newline;
        m_indentChar = indent;
    }

    /**

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -