📄 schemagenerator.java
字号:
/*Copyright (c) 2004-2005, Dennis M. SosnoskiAll 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" ANDANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIEDWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE AREDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FORANY 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 ONANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THISSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.*/package org.jibx.binding;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.net.MalformedURLException;import java.net.URL;import java.util.ArrayList;import java.util.HashMap;import java.util.Iterator;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.FactoryConfigurationError;import javax.xml.parsers.ParserConfigurationException;import javax.xml.transform.Result;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerConfigurationException;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerFactory;import javax.xml.transform.TransformerFactoryConfigurationError;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.jibx.binding.classes.ClassCache;import org.jibx.binding.classes.ClassFile;import org.jibx.binding.model.BindingElement;import org.jibx.binding.model.ClassWrapper;import org.jibx.binding.model.CollectionElement;import org.jibx.binding.model.ContainerElementBase;import org.jibx.binding.model.DefinitionContext;import org.jibx.binding.model.ElementBase;import org.jibx.binding.model.IClass;import org.jibx.binding.model.IClassLocator;import org.jibx.binding.model.MappingElement;import org.jibx.binding.model.NestingAttributes;import org.jibx.binding.model.NestingElementBase;import org.jibx.binding.model.StructureElement;import org.jibx.binding.model.StructureElementBase;import org.jibx.binding.model.TemplateElementBase;import org.jibx.binding.model.ValidationContext;import org.jibx.binding.model.ValidationProblem;import org.jibx.binding.model.ValueElement;import org.jibx.binding.util.ObjectStack;import org.jibx.runtime.JiBXException;import org.jibx.runtime.ValidationException;import org.w3c.dom.Document;import org.w3c.dom.Element;/** * Binding generator. This loads the specified input classes and processes them * to generate a default binding definition. * * @author Dennis M. Sosnoski * @version 1.0 */ public class SchemaGenerator{ /** Generator version. */ private static String CURRENT_VERSION = "0.2"; /** Schema namespace URI. */ private static final String XSD_URI = "http://www.w3.org/2001/XMLSchema"; /** Fixed XML namespace. */ public static final String XML_URI = "http://www.w3.org/XML/1998/namespace"; /** Fixed XML namespace namespace. */ public static final String XMLNS_URI = "http://www.w3.org/2000/xmlns/"; /** Set of object types mapped to schema types. */ private static HashMap s_objectTypeMap = new HashMap(); static { s_objectTypeMap.put("java.lang.Boolean", "xsd:boolean"); s_objectTypeMap.put("java.lang.Byte", "xsd:byte"); s_objectTypeMap.put("java.lang.Char", "xsd:unsignedInt"); s_objectTypeMap.put("java.lang.Double", "xsd:double"); s_objectTypeMap.put("java.lang.Float", "xsd:float"); s_objectTypeMap.put("java.lang.Integer", "xsd:int"); s_objectTypeMap.put("java.lang.Long", "xsd:long"); s_objectTypeMap.put("java.lang.Short", "xsd:short"); s_objectTypeMap.put("java.math.BigDecimal", "xsd:decimal"); s_objectTypeMap.put("java.math.BigInteger", "xsd:integer");//#!j2me{ s_objectTypeMap.put("java.sql.Date", "xsd:date"); s_objectTypeMap.put("java.sql.Time", "xsd:time"); s_objectTypeMap.put("java.sql.Timestamp", "xsd:dateTime");//#j2me} s_objectTypeMap.put("java.util.Date", "xsd:dateTime"); s_objectTypeMap.put("byte[]", "xsd:base64"); } /** Set of primitive types mapped to schema types. */ private static HashMap s_primitiveTypeMap = new HashMap(); static { s_primitiveTypeMap.put("boolean", "xsd:boolean"); s_primitiveTypeMap.put("byte", "xsd:byte"); s_primitiveTypeMap.put("char", "xsd:unsignedInt"); s_primitiveTypeMap.put("double", "xsd:double"); s_primitiveTypeMap.put("float", "xsd:float"); s_primitiveTypeMap.put("int", "xsd:int"); s_primitiveTypeMap.put("long", "xsd:long"); s_primitiveTypeMap.put("short", "xsd:short"); } /** Show verbose output flag. */ private boolean m_verbose; /** Use qualified elements default in schema flag. */ private boolean m_isElementQualified; /** Use qualified attributes default in schema flag. */ private boolean m_isAttributeQualified; /** Indentation sequence per level of nesting. */ private String m_indentSequence; /** Map from namespaces to schemas. */ private HashMap m_schemaMap; /** Locator for finding classes referenced by binding. */ private IClassLocator m_classLocator; /** Document used for all schema definitions. */ private Document m_document; /** Stack of structure definitions in progress (used to detect cycles). */ private ObjectStack m_structureStack; /** * Constructor with only paths supplied. This just initializes all other * options disabled. * * @param paths class paths to be checked for classes referenced by bindings */ public SchemaGenerator(ArrayList paths) { m_structureStack = new ObjectStack(); m_schemaMap = new HashMap(); // set paths to be used for loading referenced classes String[] parray = (String[])paths.toArray(new String[paths.size()]); ClassCache.setPaths(parray); ClassFile.setPaths(parray); // set class locator m_classLocator = new IClassLocator() { public IClass getClassInfo(String name) { try { return new ClassWrapper(ClassCache.getClassFile(name)); } catch (JiBXException e) { throw new IllegalStateException("Class not found " + name); } } }; try { // create the document used for all schemas DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); m_document = dbf.newDocumentBuilder().newDocument(); } catch (ParserConfigurationException e) { throw new IllegalStateException("Parser configuration error " + e.getMessage()); } catch (FactoryConfigurationError e) { throw new IllegalStateException("Factory configuration error " + e.getMessage()); } } /** * Constructor with settings specified. * * @param verbose report binding details and results * @param equal use element form default qualified flag * @param aqual use attribute form default qualified flag * @param paths class paths to be checked for classes referenced by bindings */ public SchemaGenerator(boolean verbose, boolean equal, boolean aqual, ArrayList paths) { this(paths); m_verbose = verbose; m_isElementQualified = equal; m_isAttributeQualified = aqual; m_indentSequence = " "; } /** * Set control flag for verbose processing reports. * * @param verbose report verbose information in processing bindings flag */ public void setVerbose(boolean verbose) { m_verbose = verbose; } /** * Set control flag for element qualified default schema. * * @param qual element qualified default schemas flag */ public void setElementQualified(boolean qual) { m_isElementQualified = qual; } /** * Set control flag for attribute qualified default schema. * * @param qual attribute qualified default schemas flag */ public void setAttributeQualified(boolean qual) { m_isAttributeQualified = qual; } /** * Get array of generated schemas. * * @return array of schema elements */ public Element[] getSchemas() { Element[] schemas = new Element[m_schemaMap.size()]; int fill = 0; for (Iterator iter = m_schemaMap.values().iterator(); iter.hasNext();) { schemas[fill++] = (Element)iter.next(); } return schemas; } /** * Generate indentation to proper depth for current item. This creates the * indentation text and appends it to the supplied parent. The generated * indentation is appropriate for the close tag of the parent element; if * a child element is to be added following this indentation it needs to * use an additional leading indent. * * @param parent element to contain indented child item */ private void indentForClose(Element parent) { StringBuffer buff = new StringBuffer(20); buff.append('\n'); Element ancestor = parent; boolean count = false; while (ancestor != null) { if (count) { buff.append(m_indentSequence); } ancestor = (Element)ancestor.getParentNode(); count = true; } parent.appendChild(m_document.createTextNode(buff.toString())); } /** * Add comment with appropriate indentation. * * @param parent element to contain indented child item * @param text comment text */ private void addComment(Element parent, String text) { if (parent.getChildNodes().getLength() == 0) { indentForClose(parent); } parent.appendChild(m_document.createTextNode(m_indentSequence)); parent.appendChild(m_document.createComment(text)); indentForClose(parent); } /** * Add child element with appropriate indentation. This generates and * returns the child element after adding it to the supplied parent, * allowing further modification of the new child element. * * @param parent element to contain indented child item * @param name child element name */ private Element addChildElement(Element parent, String name) { if (parent.getChildNodes().getLength() == 0) { indentForClose(parent); } parent.appendChild(m_document.createTextNode(m_indentSequence)); Element element = m_document.createElementNS(XSD_URI, name); parent.appendChild(element); indentForClose(parent); return element; } /** * Get innermost containing definition context. * * @return innermost definition context containing this element */ public DefinitionContext getDefinitions() { int index = 0;
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -