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

📄 marshaller.java

📁 OR Mapping工具
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
package org.ephman.abra.tools;import java.util.*;import java.text.SimpleDateFormat;import java.lang.reflect.*;import java.io.*;import java.sql.Timestamp;import javax.xml.parsers.*;import org.xml.sax.*;import org.w3c.dom.*;import org.ephman.xml.*;import org.ephman.utils.*;import org.ephman.abra.utils.*;    /** A class to marshall from Java classes to XML docs.     * instantiate with a mapping file conforming to http://charzard/codegen.dtdpackage org.ephman use the same package MapToJava to generate code from that map file     * with approptiate get/set methods and for a Vector foo, addToFoo     *     *  @author Paul M. Bethe     *  @version 0.0.1 (11/3/00)    */public class Marshaller extends XmlProcessor {  /** *   constants to handle circular links * */    protected static String _ID = "ID";    protected static String _IDREF = "IDREF";	protected static String RUN_TIME = "dk-java-type";    protected ClassLoader classLoader;	private MapToJava mtj;    Class string;    public Marshaller () throws Exception {		super (false); // don't use abraXmlParser        classLoader = ClassLoader.getSystemClassLoader();        string = classLoader.loadClass ("java.lang.String");        classList = new HashMap ();        xmlNodeList = new HashMap ();		// for doing descriptors..		mtj = new MapToJava ("", false, false, false, false, false);		TypeMapper.setObjectMap (new JavaClassGenerator ("",' ',"").getTypeMap ());    }    public Marshaller (String mapFileName) throws Exception {        this ();        addMapFile (mapFileName);    }	public void useAbraXmlParser () { 		mtj.useAbraParser = true; 		useAbraParser = true;	}	    private HashMap classList;	// list of formats for unmarshalling	private String [] dateFormatStrings;	// when marshalling use this format..	private String outFormat;    private HashMap xmlNodeList;	private boolean idTags;	/** method to remove "ID" tags (will throw exception if circular ref..)	 */	public void setIdTagsOff () {		idTags = false;	}	private boolean writeTypes = false;	public void setWriteRunTimeTypes (boolean b) { this.writeTypes = b; }	/** method to allow setting of unmarshal formats..	 * should be done while initializing mapFiles.. 	 */	public void setUnmarshalDateFormats (String [] formats) {		this.dateFormatStrings = formats;	}	/* allows the setting of the string format to use for dates	 * default is Unix seconds (since Unix 0)	 */	public void setMarshalDateFormat (String format) {		this.outFormat = format;    }    /**     * @param mapFileName the path and file name of an xml file conforming to     *        codegen.dtd     *  add a mapfile using a String fileName..     */    public void addMapFile (String mapFileName, boolean validating) throws Exception {        addMapFile (new FileReader(mapFileName), validating, mapFileName);    }	/**	 */	public void addMapFile (String mapFileName) throws Exception {		addMapFile (mapFileName, true); // assume validating..	}    /** to add a mapfile to a given marshaller     *  thus extending the set of classes that the marshaller knows how to marshal and unmarshal     *  @param reader -	 *  @param validating whether or not to use any dtds to validate..     *  @throws IOException if file un-openable     */    public void addMapFile (Reader reader, boolean validating, String inputName) throws Exception {        try {            mtj.applyRules(mtj.mapXMLFile(reader, validating), inputName);            HashMap classTree = mtj.getClassTree();            Iterator it = classTree.values().iterator();			// clear lists..			classList = new HashMap ();			xmlNodeList = new HashMap ();            while (it.hasNext()) {                JClass jc = (JClass)it.next();				String cname = jc.hasDescendant () ? jc.getDescendantName() 					: jc.getPackageName() + "." + jc.getClassName ();                XmlDescriptor new_desc = new XmlDescriptor (cname, jc.getXmlNodeName());				//				Debugger.trace ("Added " + cname,				//			Debugger.SHORT);                Vector fields = new Vector(jc.getAllFields().values ());                addDescriptorFields (new_desc, fields);                classList.put(cname, new_desc);                xmlNodeList.put(jc.getXmlNodeName(), new_desc);				Iterator viewList = jc.getViewList ();				while (viewList.hasNext()) {					JView jv = (JView)viewList.next ();					XmlDescriptor view_desc = new XmlDescriptor (jv.getViewName (), jv.getClassName ());					Vector viewFields = jv.getAllFields ();					addDescriptorViewFields (view_desc, viewFields);					classList.put(jv.getViewName (), view_desc);					xmlNodeList.put(jv.getClassName(), view_desc);				}            }        }        catch (XmlException e) {            System.out.println ("Error parsing, " +e.getMessage());			//            e.printStackTrace();			throw e;        }    }	/** add a vector of JFields to an XmlDescriptor */	private void addDescriptorFields (XmlDescriptor new_desc, Vector fields) {		for (int i = 0; i < fields.size(); i++) {			JField jf = (JField)fields.elementAt(i);			if (!jf._noMarshal) {								if (jf.isXmlAttribute())					new_desc.addAttribute (jf);				else					new_desc.addElement (jf);			} else {				//System.out.println ("not adding unmarshal field.." + jf.getJavaName ());			}		}	}	private void addDescriptorViewFields (XmlDescriptor new_desc, Vector fields) {		for (int i = 0; i < fields.size(); i++) {			JFieldView jfv = (JFieldView)fields.elementAt(i);			JField jf = jfv.getField ();			if (jf instanceof JCompositeField && ((JCompositeField)jf).getJClass () != null) {				JCompositeField jcf = (JCompositeField)jfv.getField ();				if (jfv.getAsView ()) { // is complete foreign-view					JCompositeField new_jcf = new JCompositeField ();					JView for_view = jcf.getJClass ().getView (jfv.getViewFormat ());					if (for_view != null) {						new_jcf.setDkType (TypeMapper.getType (for_view.getViewName ()));						new_jcf.setJavaName (jcf.getJavaName ());						new_desc.addElement (new_jcf);					}				} else { // just foreign field (make a JField node)					JField for_field = (jcf).getJClass ().getFieldByName (jfv.getViewFormat());					if (for_field != null) {						JField new_jf = new JField ();						new_jf.setJavaName (jcf.getJavaName ());						new_jf.setDkType (TypeMapper.getType (for_field.getObjectType ()));						new_desc.addElement (new_jf);					}				}			} else {				if (jf.isXmlAttribute())					new_desc.addAttribute (jf);				else					new_desc.addElement (jf);			}		}	}    /** a routine to marshal objects to xml strings     *     * uses descriptor class - if not found uses reflection from mapping..     *     *     */    public String marshal (Object obj) throws Exception {        Class thisClass = obj.getClass();        XmlDescriptor desc = (XmlDescriptor)classList.get(thisClass.getName());        if (desc == null) {			//Debugger.trace ("Class " + thisClass.getName () + " not found.."			//				, Debugger.SHORT);            return reflectMarshal (obj); // if no descriptor class - try to use relection to marshal.		}        return this.marshal(obj, new MarshalContext (outFormat), desc.xmlName);    }    protected String marshal (Object obj, MarshalContext context, String nodeName) throws Exception {		return marshal (obj, context, nodeName, null);	}    protected String marshal (Object obj, MarshalContext context, String nodeName, String compileTimeType) throws Exception {        Class thisClass = obj.getClass();        XmlDescriptor desc = (XmlDescriptor)classList.get(thisClass.getName());        if (desc == null) {			// Debugger.trace ("Class " + thisClass.getName () + " not found.."			//				, Debugger.SHORT);            return reflectMarshal (obj, context, nodeName); // if no descriptor class - try to use relection to marshal.		}        String indent = context.getIndent();        Integer prev_exist = context.get(obj);        if (prev_exist != null) {            return indent + "<" + nodeName + " " +_IDREF+"=\"" + prev_exist.toString() + "\" />\n"; // is a recursive that we have already seen        }        int recursiveId = context.put(obj);        String result = indent + "<" + nodeName + " " + _ID+"=\"" + recursiveId +"\"";		if (writeTypes && compileTimeType != null &&			!compileTimeType.equals (thisClass.getName ()))			// write out run-time type for unmarshalling..			result += " " + RUN_TIME + "=\""+ thisClass.getName() + "\"";		if (obj instanceof Versioned)			result += " " + VERSION_NUMBER + "=\"" 				+ ((Versioned)obj).getVersion () + "\"";        Iterator att = desc.attributeList.iterator ();        while (att.hasNext()) {            JField jf = (JField)att.next();            Object value = getValue (jf, obj);            if (value != null)                result += " " + jf.getJavaName() + "=\"" + objectOut (jf, value, context)                    + "\"";        }        result += ">\n";        Iterator els = desc.elementList.values().iterator();        while (els.hasNext()) {            JField jf = (JField)els.next();            Object value = getValue (jf, obj);            if (value != null) {                if (jf.isVector()) {                    // TODO: what about other collections?                    Vector v = (Vector)value;                    for (int i = 0; i < v.size(); i++) {                        Object o = v.elementAt(i);						            result += makeElementString (o, jf, context);                    }                } else if (jf.isArray ()) {					int length = Array.getLength (value);					for (int i=0; i < length; i++) {						Object o = Array.get (value, i);						if (o!= null)							result += makeElementString (o, jf, context);					}											} else {					result += makeElementString (value, jf, context);                }            }        }        return result + indent + "</" + nodeName + ">\n";    }    /** aroutine to find the text output for an object. */    String objectOut (JField jf, Object value, MarshalContext context) {		String result = value.toString ();		if (jf.isDate ()) {			SimpleDateFormat sdf = context.getDateFormat ();

⌨️ 快捷键说明

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