beanutil.java

来自「开源的axis2框架的源码。用于开发WEBSERVER」· Java 代码 · 共 811 行 · 第 1/3 页

JAVA
811
字号
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package org.apache.axis2.databinding.utils;


import org.apache.axiom.om.*;
import org.apache.axiom.om.impl.builder.StAXOMBuilder;
import org.apache.axiom.om.impl.llom.factory.OMXMLBuilderFactory;
import org.apache.axiom.om.util.Base64;
import org.apache.axis2.AxisFault;
import org.apache.axis2.description.java2wsdl.TypeTable;
import org.apache.axis2.databinding.typemapping.SimpleTypeMapper;
import org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl;
import org.apache.axis2.engine.ObjectSupplier;
import org.apache.axis2.util.StreamWrapper;
import org.apache.axis2.util.Loader;
import org.codehaus.jam.JClass;
import org.codehaus.jam.JProperty;
import org.codehaus.jam.JamClassIterator;
import org.codehaus.jam.JamService;
import org.codehaus.jam.JamServiceFactory;
import org.codehaus.jam.JamServiceParams;

import javax.xml.namespace.QName;
import javax.xml.stream.XMLStreamReader;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;


public class BeanUtil {

    private static int nsCount = 1;


    /**
     * To Serilize Bean object this method is used, this will create an object array using given
     * bean object
     *
     */
    public static XMLStreamReader getPullParser(Object beanObject,
                                                QName beanName,
                                                TypeTable typeTable,
                                                boolean qualified,
                                                boolean processingDocLitBare) {
        try {
            JamServiceFactory factory = JamServiceFactory.getInstance();
            JamServiceParams jam_service_parms = factory.createServiceParams();
            ClassLoader cl = beanObject.getClass().getClassLoader();
            if (cl == null)
                cl = ClassLoader.getSystemClassLoader();
            jam_service_parms.addClassLoader(cl);

            jam_service_parms.includeClass(beanObject.getClass().getName());
            JamService service = factory.createService(jam_service_parms);
            JamClassIterator jClassIter = service.getClasses();
            JClass jClass;
            if (jClassIter.hasNext()) {
                jClass = (JClass)jClassIter.next();
            } else {
                throw new AxisFault("No service class found , exception from JAM");
            }
            QName elemntNameSpace = null;
            if (typeTable != null && qualified) {
                QName qNamefortheType =
                        typeTable.getQNamefortheType(beanObject.getClass().getName());
                if (qNamefortheType == null) {
                    qNamefortheType = typeTable.getQNamefortheType(
                            beanObject.getClass().getPackage().getName());
                }
                if (qNamefortheType == null) {
                    throw new AxisFault("Mapping qname not fond for the package: " +
                            beanObject.getClass().getPackage().getName());
                }

                elemntNameSpace = new QName(qNamefortheType.getNamespaceURI(),
                                            "elementName");
            }

            // properties from JAM
            ArrayList propertyList = new ArrayList();
            JProperty properties [] = jClass.getDeclaredProperties();
            for (int i = 0; i < properties.length; i++) {
                JProperty property = properties[i];
                propertyList.add(property);
            }
            JClass supClass = jClass.getSuperclass();
            while (!"java.lang.Object".equals(supClass.getQualifiedName())) {
                properties = supClass.getDeclaredProperties();
                for (int i = 0; i < properties.length; i++) {
                    JProperty property = properties[i];
                    propertyList.add(property);
                }
                supClass = supClass.getSuperclass();
            }
            properties = new JProperty[propertyList.size()];
            for (int i = 0; i < propertyList.size(); i++) {
                JProperty jProperty = (JProperty)propertyList.get(i);
                properties[i] = jProperty;
            }
            Arrays.sort(properties);
            BeanInfo beanInfo = Introspector.getBeanInfo(beanObject.getClass());
            PropertyDescriptor [] propDescs = beanInfo.getPropertyDescriptors();
            HashMap propertMap = new HashMap();
            for (int i = 0; i < propDescs.length; i++) {
                PropertyDescriptor propDesc = propDescs[i];
                propertMap.put(propDesc.getName(), propDesc);
            }
            ArrayList object = new ArrayList();
            for (int i = 0; i < properties.length; i++) {
                JProperty property = properties[i];
                PropertyDescriptor propDesc = (PropertyDescriptor)propertMap.get(
                        getCorrectName(property.getSimpleName()));
                if (propDesc == null) {
                    // JAM does bad thing so I need to add this
                    continue;
                }
                Class ptype = propDesc.getPropertyType();
                if (propDesc.getName().equals("class")) {
                    continue;
                }
                if (SimpleTypeMapper.isSimpleType(ptype)) {
                    Method readMethod = propDesc.getReadMethod();
                    Object value;
                    if(readMethod!=null){
                      value = readMethod.invoke(beanObject, null);
                    } else {
                        throw new AxisFault("can not find read method for : "  + propDesc.getName());
                    }

                    addTypeQname(elemntNameSpace, object, propDesc, beanName,processingDocLitBare);
                    object.add(value == null ? null : SimpleTypeMapper.getStringValue(value));
                } else if (ptype.isArray()) {
                    if (SimpleTypeMapper.isSimpleType(ptype.getComponentType())) {
                        Method readMethod = propDesc.getReadMethod();
                        Object value;
                        if(readMethod!=null){
                            value = readMethod.invoke(beanObject,
                                    null);
                        } else {
                            throw new AxisFault("can not find read method for : "  + propDesc.getName());
                        }
                        if (value != null) {
                            if("byte".equals(ptype.getComponentType().getName())) {
                                addTypeQname(elemntNameSpace, object, propDesc, beanName,processingDocLitBare);
                                object.add(Base64.encode((byte[]) value));
                            } else {
                                int i1 = Array.getLength(value);
                                for (int j = 0; j < i1; j++) {
                                    Object o = Array.get(value, j);
                                    addTypeQname(elemntNameSpace, object, propDesc, beanName,processingDocLitBare);
                                    object.add(o == null ? null : SimpleTypeMapper.getStringValue(o));
                                }
                            }
                        } else {
                            addTypeQname(elemntNameSpace, object, propDesc, beanName,processingDocLitBare);
                            object.add(value);
                        }
                    } else {
                        Object value [] = (Object[])propDesc.getReadMethod().invoke(beanObject,
                                                                                    null);
                        if (value != null) {
                            for (int j = 0; j < value.length; j++) {
                                Object o = value[j];
                                addTypeQname(elemntNameSpace, object, propDesc, beanName,processingDocLitBare);
                                object.add(o);
                            }
                        } else {
                            addTypeQname(elemntNameSpace, object, propDesc, beanName,processingDocLitBare);
                            object.add(value);
                        }
                    }
                } else if (SimpleTypeMapper.isCollection(ptype)) {
                    Object value = propDesc.getReadMethod().invoke(beanObject,
                                                                   null);
                    Collection objList = (Collection)value;
                    if (objList != null && objList.size() > 0) {
                        //this was given error , when the array.size = 0
                        // and if the array contain simple type , then the ADBPullParser asked
                        // PullParser from That simpel type
                        for (Iterator j = objList.iterator(); j.hasNext();) {
                            Object o = j.next();
                            if (SimpleTypeMapper.isSimpleType(o)) {
                                addTypeQname(elemntNameSpace, object, propDesc, beanName,processingDocLitBare);
                                object.add(o);
                            } else {
                                addTypeQname(elemntNameSpace, object, propDesc, beanName ,processingDocLitBare);
                                object.add(o);
                            }
                        }

                    } else {
                        addTypeQname(elemntNameSpace, object, propDesc, beanName,processingDocLitBare);
                        object.add(value);
                    }
                } else {
                    addTypeQname(elemntNameSpace, object, propDesc, beanName,processingDocLitBare);
                    Object value = propDesc.getReadMethod().invoke(beanObject,
                                                                   null);
                    object.add(value);
                }
            }
             // Added objectAttributes as a fix for issues AXIS2-2055 and AXIS2-1899 to 
            // support polymorphism in POJO approach.
            // For some reason, using QName(Constants.XSI_NAMESPACE, "type", "xsi") does not generate
            // an xsi:type attribtue properly for inner objects. So just using a simple QName("type").
            ArrayList objectAttributes = new ArrayList();
            objectAttributes.add(new QName("type"));
            objectAttributes.add(beanObject.getClass().getName());
            return new ADBXMLStreamReaderImpl(beanName, object.toArray(), objectAttributes.toArray(),
                                              typeTable, qualified);

        } catch (java.io.IOException e) {
            throw new RuntimeException(e);
        } catch (java.beans.IntrospectionException e) {
            throw new RuntimeException(e);
        } catch (java.lang.reflect.InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (java.lang.IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    private static void addTypeQname(QName elemntNameSpace,
                                     ArrayList object,
                                     PropertyDescriptor propDesc,
                                     QName beanName,
                                     boolean processingDocLitBare) {
        if (elemntNameSpace != null) {
            object.add(new QName(elemntNameSpace.getNamespaceURI(),
                    propDesc.getName(), elemntNameSpace.getPrefix()));
        } else {
            if(processingDocLitBare){
                object.add(new QName(propDesc.getName()));
            } else {
                object.add(new QName(beanName.getNamespaceURI(),
                        propDesc.getName(), beanName.getPrefix()));
            }

        }
    }

    /**
     * to get the pull parser for a given bean object , generate the wrpper element using class
     * name

⌨️ 快捷键说明

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