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

📄 marshaller.java

📁 OR Mapping工具
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
			if (sdf == null) // the usuals seconds ..				result = ((java.sql.Timestamp)value).getTime() + "";			else				result = sdf.format ((java.sql.Timestamp)value);		}		else if (jf.getObjectType ().equals ("char") && result.charAt (0) == (char)0)			result = "";		else if (jf.getObjectType ().equals ("double") && result.equals ("NaN"))			result = "";		return result;    }    /* a routine which makes the string for a single element (either by recursing)     * or writing out     *     */    private String makeElementString (Object value, JField jf, MarshalContext context) throws Exception {		String result;        if (jf instanceof JCompositeField) {			context.addDepth ();			result = marshal (value, context, jf.getJavaName(),							  jf.getObjectType ());			context.removeDepth ();		} else			result = context.getIndent () + "\t<" + jf.getJavaName() + ">" + objectOut (jf, value, context)				+ "</" + jf.getJavaName() + ">\n";		return result;    }	/** get a value for the field represented in the JField using get<name>	 * using reflection	 *   @param obj the current object to marshal	 *   @param jf the JField that describes the variable to be accessed	 *	 *   @return the object representing the value which was stored in the object	 */    private Object getValue (JField jf, Object obj) throws Exception {        Class thisClass = obj.getClass();        Object value = null;        Class c = thisClass;        boolean done = false;        while (!done) {            try {                value = c.getDeclaredMethod ("get" + jf.getGetSet(), null).invoke(obj, null);                done = true;            } catch (NoSuchMethodException e) {                c = c.getSuperclass();                if (c == null) {					System.out.println ("Unable to find: " + "get" + jf.getGetSet() + " in class: " + thisClass.getName());                    throw e;				}            }        }        return value;    }    /** try to use reflection to marshal a Java Class to an XML representation    *   @param obj any object    *    *   @return the String which represents this class in XML    */	protected String reflectMarshal (Object obj) throws Exception {		return reflectMarshal (obj, new MarshalContext ());	}    protected Object [] dummyArray = new Object [] {};    protected boolean isNativeType (String typeName) {        return typeName.equals ("java.lang.String") || typeName.equals ("String") ||            typeName.equals("java.lang.Integer") ||            typeName.equals("java.lang.Long") ||            typeName.equals("java.lang.Boolean") ||            typeName.equals("java.lang.Double") ||            typeName.equals("java.lang.Float") ||            typeName.equals("java.sql.Timestamp");    }    protected String getClassName (Object obj) {        Class thisClass = obj.getClass();		String className = thisClass.getName ();		className = className.substring (className.lastIndexOf (".") + 1);        return className;    }    protected String reflectMarshal (Object obj, MarshalContext context) throws Exception {        if (obj == null) return "";		Class thisClass = obj.getClass ();        if (isNativeType (thisClass.getName ()))            return obj.toString();        String className = getClassName (obj);        return reflectMarshal (obj, context, className);    }    protected String reflectMarshal  (Object obj, MarshalContext context, String nodeName) throws Exception {        if (obj == null) return "";        Class thisClass = obj.getClass ();        Integer last = context.get(obj);        if (last != null)            return context.getIndent() + "<" + nodeName + " "                + this._IDREF + "=\"" + last.intValue() + "\"/>\n";        int id = context.put(obj);		Method [] methods = thisClass.getDeclaredMethods ();		String result = "";        if (obj instanceof List) {            List v = (List)obj;            for (int i=0; i <v.size(); i++)                result += marshal (v.get(i), context, nodeName);            return result;        }        result += context.getIndent() + "<" + nodeName + " " + _ID + "=\"" + id +"\">\n";        context.addDepth();        boolean foundAGet = false;		for (int i=0; i< methods.length; i++) {			Method aMethod = methods[i];			if (aMethod.getName ().startsWith ("get") && aMethod.isAccessible ()) { 				  // is a get method so do..				if (aMethod.getParameterTypes().length == 0) { // takes no params..                    foundAGet = true;                    Object val = aMethod.invoke(obj, dummyArray);                    if (aMethod.getReturnType().isPrimitive()) { // prim..                        String valName = getNameFromMethod (aMethod);                        result += context.getIndent() + "<" + valName + ">";                        result += val.toString() + "</" + valName + ">\n";                    }                    else if (val instanceof Vector)                        result += marshal (val, context, getNameFromMethod (aMethod));                    else if (val != null) { // not primitive call toString () or reflect..                        result += marshal (val, context, getNameFromMethod (aMethod));                    }                } // else takes > 0 params.. I don't know what to pass..			}			// else ignore..		}        context.removeDepth();        if (!foundAGet)  // try toString..            return context.getIndent() + obj.toString() + " " + getClassName (obj) + "\n";        return result + context.getIndent () + "</" + nodeName + ">\n"; // nothing for now    }    protected String getNameFromMethod (Method m) throws Exception {        String result = m.getName().substring(3);        result = result.substring(0,1).toLowerCase() + result.substring(1);        return result;    }    /** a routine to unmarshal xml text to a Java object -     * assumes that the class is loadable and that the object is described in the map file     * @param xmlText an xml text string - whose root node was described in the map file     * @return Object a new instance with all data in place     * @throws Exception - when the xml-Java descriptor is not found or the Java object is not found     * by the class loader - or when the xml is not well formed    */    public Object unmarshal (String xmlText) throws Exception {		return unmarshal (xmlText, true); // default is true..	}    public Object unmarshal (String xmlText, boolean ignoreMissingFields) throws Exception {        return unmarshal (new StringReader (xmlText), ignoreMissingFields);    }    public Object unmarshal (Reader r) throws Exception {		return unmarshal (r, true); // default is true	}    public Object unmarshal (Reader r, boolean ignoreMissingFields) throws Exception {        XmlNode root = super.mapXMLFile(r, false);        String name = root.getName(); //getTagName        XmlDescriptor desc = (XmlDescriptor)xmlNodeList.get(name);        if (desc == null)            throw new AbraException ("ephman.abra.tools.nodescriptor");        return this.unmarshal(root, new UnmarshalContext (ignoreMissingFields), desc);    }	/** a routine to be called on a composite node - with the current context and the Xml descriptor	 * for this object	 * @param thisNode the org.w3c Element	 * @param context a wrapper containing the ID and IDREF tags	 * @param  desc for the object to be built containing attributes	 * and elements..	 * @return Object a new object as described in descriptor with all fields set	 */    protected Object unmarshal (XmlNode thisNode, UnmarshalContext context, XmlDescriptor desc) throws Exception {        String recurseId = thisNode.getAttribute(_IDREF);        Object prevInstance = null;        try {            Integer key = new Integer (recurseId);            prevInstance = context.get(key);        } catch (Exception e) {}    // if caught no id..        if (prevInstance != null)            return prevInstance;        else { // put in list			String runTimeType = thisNode.getAttribute (RUN_TIME);			if (Checks.exists (runTimeType)) {				//				System.out.println ("getting new descriptor for " + runTimeType);				if (classList.get (runTimeType) != null)					desc = (XmlDescriptor)classList.get (runTimeType);			}            Class thisClass = Class.forName (desc.className);            Object new_object = thisClass.newInstance();            try {                Integer recId = new Integer(thisNode.getAttribute(_ID));                context.put (recId, new_object);            } catch (NumberFormatException e) {}			if (new_object instanceof Versioned) {				String vNum = thisNode.getAttribute (VERSION_NUMBER);				try {					((Versioned)new_object).setVersion (Integer.parseInt (vNum));				} catch (NumberFormatException e) {}			}            setAllAttributes (thisNode, new_object, desc, context);            recurseOnChildList (thisNode.getChildNodes(), new_object, desc, context);			// also handle arrays..			Vector fieldArrays = desc.arrayElList;			for (int f = 0; f<fieldArrays.size (); f++) {				JField jf = (JField)fieldArrays.elementAt (f);				//W3CXmlNode node = new W3CXmlNode (thisNode);				Vector elNodes = thisNode.getChildNodes (jf.getJavaName ());				setArray (jf, elNodes, new_object, desc, context);			}            return new_object;        }        //return null;    }	/** a method to set an array described by jf into obj (whose descriptor is desc 	 */	protected void setArray (JField jf, Vector nodes, Object obj, XmlDescriptor desc,							 UnmarshalContext context) throws Exception {		if (nodes.size () == 0) return;		Class thisClass = obj.getClass();		Object theArray = Array.newInstance (getAClass (jf.getObjectType ()), nodes.size ());		Object value = null;        Method m = null;		m = getASetMethod (thisClass, "set" + jf.getGetSet(), theArray.getClass ());		for (int i=0; i< nodes.size (); i++) {			// W3CXmlNode ..			XmlNode thisNode = ((XmlNode)nodes.elementAt (i));			if (jf instanceof JCompositeField) {				XmlDescriptor fieldDesc = (XmlDescriptor)this.classList.get (jf.getObjectType());				value = unmarshal (thisNode, context, fieldDesc);			}			else {				value = getPrimitive (thisNode, jf, context);							}			Array.set (theArray, i, value);		}		m.invoke(obj, new Object[]{theArray});	}    protected void setAllAttributes (XmlNode thisNode, Object obj, XmlDescriptor desc, UnmarshalContext context) throws Exception {        Iterator it = desc.attributeList.iterator();        while (it.hasNext()) {            JField jf = (JField)it.next();            String attValue = thisNode.getAttribute(jf.getJavaName());            if (attValue != null && !attValue.equals("")) {	            //for now string only    	        Class c = obj.getClass();	            boolean isPrimitive = true;    	        String paramClassType = jf.getObjectType();	            if (paramClassType.equals("String")) {    	            isPrimitive = false;        	        paramClassType = "java.lang.String";	            }	            //classType = getFieldType (classType);    	        Method m = getASetMethod (c, "set"+jf.getGetSet(), paramClassType);	            if (!isPrimitive)        	        m.invoke (obj, new Object[] {attValue});				else if (jf.isDate () && dateFormatStrings != null) {

⌨️ 快捷键说明

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