模块间接口报文校验2

来源:互联网 发布:单机围棋软件 编辑:程序博客网 时间:2024/05/20 00:11


    /**
     * 校验项目类型
     * @param type
     * @param value
     * @return
     */
    private static boolean checkType(Object value, String type, boolean isCheckPass)
    {
        logger.enterFuncDebugLog();
        if ("Integer".equalsIgnoreCase(type))
        {
            try
            {
                Integer.parseInt(String.valueOf(value));
            }
            catch (Exception e)
            {
                isCheckPass = false;
            }
        }
        /* 2010/03/15 文件大小长度类型改为long */
        else if ("Long".equalsIgnoreCase(type))
        {
            try
            {
                Long.parseLong(String.valueOf(value));
            }
            catch (Exception e)
            {
                isCheckPass = false;
            }
        }
        /* 2010/03/15 文件大小长度类型改为long */
        else if ("Double".equalsIgnoreCase(type))
        {
            try
            {
                Double.parseDouble(String.valueOf(value));
            }
            catch (Exception e)
            {
                isCheckPass = false;
            }
        }
        // 所有变量都是字符型
        if ("String".equalsIgnoreCase(type) && !(value instanceof String))
        {
            isCheckPass = false;
        }

        if ("Date".equalsIgnoreCase(type))
        {
            try
            {
                DateFormat df = new SimpleDateFormat(CMSConstants.IF_DATE_FORMAT);

                df.parse((String) value);
            }
            catch (Exception e)
            {
                isCheckPass = false;
            }
        }
        logger.exitFuncDebugLog();
        return isCheckPass;
    }

    /**
     * 获取存储到Oracle的长度
     * 对于utf8的oracle来说,一个双字节字符等于3个单字节字符的长度
     * @param value 需要转化的字符串
     * @return 存储到Oracle的字符串长度
     *
     * @return int [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    private static int getJava2OracleLength(String value)
    {
        if (value == null)
        {
            return 0;
        }

        // if (value.length() == value.getBytes().length)
        // {
        // // 无双字节字符
        // return value.length();
        // }
        //        
        // int len = 0;
        // // 转换为字节数组
        // char[] charArr = value.toCharArray();
        // for (int i = 0; i < charArr.length; i++)
        // {
        // if (String.valueOf(charArr[i]).matches("[^x00-xff]"))
        // {
        // len += 3;
        // }
        // else
        // {
        // len++;
        // }
        // }
        // return len;
        // 按照接口定义的长度进行校验
        return value.length();
    }

    /**
     * 获取检查XML的值
     * 获取检查XML的值,保存入checkMap
     * @return [参数说明]
     *
     * @return Map<String,CheckObj> [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    private synchronized static void initMap()
    {
        logger.enterFuncDebugLog();
        if (checkMap != null)
        {
            logger.exitFuncDebugLog();
            return;
        }
        checkMap = new HashMap<String, CheckObj>();
        try
        {
            SAXReader reader = new SAXReader();
            String filePath = SyncDataCheck.class.getResource("").getFile() + CHECK_XML_NAME;
            filePath = URLDecoder.decode(filePath, "utf-8");
            Document document = reader.read(new File(filePath));
            Element ele = document.getRootElement();
            List<?> fieldList = ele.selectNodes("/validators/table/field");
            for (Iterator<?> iterator = fieldList.iterator(); iterator.hasNext();)
            {
                Element fieldEle = (Element) iterator.next();
                String tblName = fieldEle.getParent().attributeValue("name");
                String fieldName = fieldEle.attributeValue("name");

                Node maxLenEle = fieldEle.selectSingleNode("max-length");
                Node fieldTypeEle = fieldEle.selectSingleNode("field-type");
                Node isNullEle = fieldEle.selectSingleNode("is-null");
                Node expressionEle = fieldEle.selectSingleNode("expression");
                CheckObj obj = new CheckObj();
                if (maxLenEle != null)
                {
                    String maxLen = maxLenEle.getStringValue();
                    int maxLenInt = -1;
                    maxLenInt = Integer.parseInt(maxLen);
                    obj.setMaxLength(maxLenInt);
                }
                if (fieldTypeEle != null)
                {
                    obj.setFieldType(fieldTypeEle.getStringValue());
                }
                if (isNullEle != null)
                {
                    obj.setIsNull(isNullEle.getStringValue());
                }
                if (expressionEle != null)
                {
                    obj.setExpression(expressionEle.getStringValue());
                }
                checkMap.put(tblName + "." + fieldName, obj);
            }
        }

        catch (UnsupportedEncodingException e)
        {
            logger.excepFuncDebugLog("Obtaining configuration file ,exception 。", e);
        }
        catch (DocumentException e)
        {
            logger.excepFuncDebugLog("Obtaining configuration file ,document exception 。", e);
        }

    }

}

/**
 * 检查信息VO
 * 定义检查项目
 *
 * @author  
 * @version  [V200R001, 2009-12-7]
 * @see  [相关类/方法]
 * @since  [DHM.Core.portalMS-V200R001]
 */
class CheckObj
{
    /**
     * 字段类型int String Date
     */
    private String fieldType;

    /**
     * 是否为空
     */
    private String isNull;

    /**
     * 最大长度
     */
    private int maxLength = -1;

    /**
     * 正则表达式
     */
    private String expression;

    /**
     * @return 返回 maxLength
     */
    public int getMaxLength()
    {
        return maxLength;
    }

    /**
     * @param 对maxLength进行赋值
     */
    public void setMaxLength(int maxLength)
    {
        this.maxLength = maxLength;
    }

    /**
     * @return 返回 fieldType
     */
    public String getFieldType()
    {
        return fieldType;
    }

    /**
     * @param 对fieldType进行赋值
     */
    public void setFieldType(String fieldType)
    {
        this.fieldType = fieldType;
    }

    /**
     * @return 返回 isNull
     */
    public String getIsNull()
    {
        return isNull;
    }

    /**
     * @param 对isNull进行赋值
     */
    public void setIsNull(String isNull)
    {
        this.isNull = isNull;
    }

    /**
     * @return 返回 expression
     */
    public String getExpression()
    {
        return expression;
    }

    /**
     * @param 对expression进行赋值
     */
    public void setExpression(String expression)
    {
        this.expression = expression;
    }
}
 
  // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) radix(10) lradix(10)
// Source File Name:   PropertiesFactory.java

package com.comname.dhm.common.config.impl;

import com.comname.dhm.common.config.base.CompositeConfig;
import com.comname.dhm.common.util.StringUtil;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.log4j.Logger;

public class PropertiesFactory
{

    private PropertiesFactory()
    {
    }

    public static synchronized void addConfiguration(String path)
    {
        initFlag = true;
        try
        {
            PropertiesConfiguration configuration = new PropertiesConfiguration(path);
            configuration.setEncoding("UTF-8");
            config.addConfiguration(configuration);
        }
        catch(ConfigurationException e)
        {
            log.error((new StringBuilder("\u52A0\u8F7D\u914D\u7F6E\u6587\u4EF6 ")).append(path).append(" \u53D1\u751F\u9519\u8BEF\uFF0C\u8BF7\u67E5\u770B\u6587\u4EF6\u662F\u5426\u5B58\u5728\uFF0C\u6216\u683C\u5F0F\u662F\u5426\u9519\u8BEF").toString());
        }
    }

    public static long getValueLong(String key)
    {
        if(!initFlag)
            log.error("\u8D44\u6E90\u914D\u7F6E\u5C1A\u672A\u521D\u59CB\u5316\uFF0C\u6216\u8005\u8D44\u6E90\u6587\u4EF6\u4E0D\u5B58\u5728");
        return config.getLong(key);
    }

    public static long getNmsValueLong(String key)
    {
        if(!initFlag)
            log.error("\u8D44\u6E90\u914D\u7F6E\u5C1A\u672A\u521D\u59CB\u5316\uFF0C\u6216\u8005\u8D44\u6E90\u6587\u4EF6\u4E0D\u5B58\u5728");
        return config.getLong(key) != 0L ? config.getLong(key) : 2147483647L;
    }

    public static int getValueInt(String key)
    {
        if(!initFlag)
            log.error("\u8D44\u6E90\u914D\u7F6E\u5C1A\u672A\u521D\u59CB\u5316\uFF0C\u6216\u8005\u8D44\u6E90\u6587\u4EF6\u4E0D\u5B58\u5728");
        return config.getInt(key);
    }

    public static String getValueString(String key)
    {
        if(!initFlag)
            log.error("\u8D44\u6E90\u914D\u7F6E\u5C1A\u672A\u521D\u59CB\u5316\uFF0C\u6216\u8005\u8D44\u6E90\u6587\u4EF6\u4E0D\u5B58\u5728");
        return config.getString(key);
    }

    public static String getValueString(String key, String params[])
    {
        if(!initFlag)
            log.error("\u8D44\u6E90\u914D\u7F6E\u5C1A\u672A\u521D\u59CB\u5316\uFF0C\u6216\u8005\u8D44\u6E90\u6587\u4EF6\u4E0D\u5B58\u5728");
        return StringUtil.substituteParams(config.getString(key), params);
    }

    public static double getValueDouble(String key)
    {
        if(!initFlag)
            log.error("\u8D44\u6E90\u914D\u7F6E\u5C1A\u672A\u521D\u59CB\u5316\uFF0C\u6216\u8005\u8D44\u6E90\u6587\u4EF6\u4E0D\u5B58\u5728");
        return config.getDouble(key);
    }

    public static Iterator getKeys()
    {
        if(!initFlag)
            log.error("\u8D44\u6E90\u914D\u7F6E\u5C1A\u672A\u521D\u59CB\u5316\uFF0C\u6216\u8005\u8D44\u6E90\u6587\u4EF6\u4E0D\u5B58\u5728");
        return config.getKeys();
    }

    public static String[] getValueArray(String key)
    {
        if(!initFlag)
            log.error("\u8D44\u6E90\u914D\u7F6E\u5C1A\u672A\u521D\u59CB\u5316\uFF0C\u6216\u8005\u8D44\u6E90\u6587\u4EF6\u4E0D\u5B58\u5728");
        return config.getStringArray(key);
    }

    public static BigDecimal getValueBigDecimal(String key)
    {
        if(!initFlag)
            log.error("\u8D44\u6E90\u914D\u7F6E\u5C1A\u672A\u521D\u59CB\u5316\uFF0C\u6216\u8005\u8D44\u6E90\u6587\u4EF6\u4E0D\u5B58\u5728");
        return config.getBigDecimal(key);
    }

    public static float getValueFloat(String key)
    {
        if(!initFlag)
            log.error("\u8D44\u6E90\u914D\u7F6E\u5C1A\u672A\u521D\u59CB\u5316\uFF0C\u6216\u8005\u8D44\u6E90\u6587\u4EF6\u4E0D\u5B58\u5728");
        return config.getFloat(key);
    }

    public static boolean getValueBoolean(String key)
    {
        if(!initFlag)
            log.error("\u8D44\u6E90\u914D\u7F6E\u5C1A\u672A\u521D\u59CB\u5316\uFF0C\u6216\u8005\u8D44\u6E90\u6587\u4EF6\u4E0D\u5B58\u5728");
        return config.getBoolean(key);
    }

    public static BigInteger getValueBigInteger(String key)
    {
        if(!initFlag)
            log.error("\u8D44\u6E90\u914D\u7F6E\u5C1A\u672A\u521D\u59CB\u5316\uFF0C\u6216\u8005\u8D44\u6E90\u6587\u4EF6\u4E0D\u5B58\u5728");
        return config.getBigInteger(key);
    }

    public static List getValueList(String key)
    {
        if(!initFlag)
            log.error("\u8D44\u6E90\u914D\u7F6E\u5C1A\u672A\u521D\u59CB\u5316\uFF0C\u6216\u8005\u8D44\u6E90\u6587\u4EF6\u4E0D\u5B58\u5728");
        return config.getList(key);
    }

    public static void clear()
    {
        if(config != null)
        {
            config.clear();
            initFlag = false;
        }
    }

    public static void setProperty(String key, String value)
    {
        if(!initFlag)
            log.error("\u8D44\u6E90\u914D\u7F6E\u5C1A\u672A\u521D\u59CB\u5316\uFF0C\u6216\u8005\u8D44\u6E90\u6587\u4EF6\u4E0D\u5B58\u5728");
        config.setPropertyProperties(key, value);
    }

    private static Logger log = Logger.getLogger(com/comname/dhm/common/config/impl/PropertiesFactory);
    private static final CompositeConfig config = new CompositeConfig();
    private static boolean initFlag = false;

}



// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) radix(10) lradix(10)
// Source File Name:   CompositeConfig.java

package com.comname.dhm.common.config.base;

import java.util.*;
import org.apache.commons.configuration.*;
import org.apache.log4j.Logger;

public class CompositeConfig extends AbstractConfiguration
    implements Cloneable
{

    public CompositeConfig()
    {
        configList = new LinkedList();
        clear();
    }

    public void addConfiguration(Configuration config)
    {
        if(!configList.contains(config))
        {
            configList.add(configList.indexOf(inMemoryConfiguration), config);
            if(config instanceof AbstractConfiguration)
                ((AbstractConfiguration)config).setThrowExceptionOnMissing(isThrowExceptionOnMissing());
        }
    }

    public void removeConfiguration(Configuration config)
    {
        if(!config.equals(inMemoryConfiguration))
            configList.remove(config);
    }

    public int getNumberOfConfigurations()
    {
        return configList.size();
    }

    public void clear()
    {
        configList.clear();
        inMemoryConfiguration = new BaseConfiguration();
        ((BaseConfiguration)inMemoryConfiguration).setThrowExceptionOnMissing(isThrowExceptionOnMissing());
        ((BaseConfiguration)inMemoryConfiguration).setListDelimiter(getListDelimiter());
        ((BaseConfiguration)inMemoryConfiguration).setDelimiterParsingDisabled(isDelimiterParsingDisabled());
        configList.add(inMemoryConfiguration);
    }

    protected void addPropertyDirect(String key, Object token)
    {
        inMemoryConfiguration.addProperty(key, token);
    }

    public void setPropertyXML(String key, Object obj)
    {
        for(Iterator i = configList.iterator(); i.hasNext();)
        {
            Configuration config = (Configuration)i.next();
            if(config.containsKey(key))
            {
                ((XMLConfiguration)config).setProperty(key, obj);
                try
                {
                    ((XMLConfiguration)config).save();
                }
                catch(ConfigurationException e)
                {
                    logger.error((new StringBuilder("\u66F4\u65B0\u914D\u7F6E\u9879 key:")).append(key).append(";value:").append(obj).append(" \u5931\u8D25").toString());
                }
            }
        }

    }

    public void setPropertyProperties(String key, Object obj)
    {
        for(Iterator i = configList.iterator(); i.hasNext();)
        {
            Configuration config = (Configuration)i.next();
            if(config.containsKey(key))
            {
                ((PropertiesConfiguration)config).setProperty(key, obj);
                try
                {
                    ((PropertiesConfiguration)config).save();
                }
                catch(ConfigurationException e)
                {
                    logger.error((new StringBuilder("\u66F4\u65B0\u914D\u7F6E\u9879 key:")).append(key).append(";value:").append(obj).append(" \u5931\u8D25").toString());
                }
            }
        }

    }

    public Object getProperty(String key)
    {
        Configuration firstMatchingConfiguration = null;
        for(Iterator i = configList.iterator(); i.hasNext();)
        {
            Configuration config = (Configuration)i.next();
            if(config.containsKey(key))
            {
                firstMatchingConfiguration = config;
                break;
            }
        }

        if(firstMatchingConfiguration != null)
            return firstMatchingConfiguration.getProperty(key);
        else
            return null;
    }

    public Iterator getKeys()
    {
        List keys = new ArrayList();
        for(Iterator i = configList.iterator(); i.hasNext();)
        {
            Configuration config = (Configuration)i.next();
            for(Iterator j = config.getKeys(); j.hasNext();)
            {
                String key = (String)j.next();
                if(!keys.contains(key))
                    keys.add(key);
            }

        }

        return keys.iterator();
    }

    public Iterator getKeys(String key)
    {
        List keys = new ArrayList();
        for(Iterator i = configList.iterator(); i.hasNext();)
        {
            Configuration config = (Configuration)i.next();
            for(Iterator j = config.getKeys(key); j.hasNext();)
            {
                String newKey = (String)j.next();
                if(!keys.contains(newKey))
                    keys.add(newKey);
            }

        }

        return keys.iterator();
    }

    public boolean isEmpty()
    {
        boolean isEmpty = true;
        for(Iterator i = configList.iterator(); i.hasNext();)
        {
            Configuration config = (Configuration)i.next();
            if(!config.isEmpty())
                return false;
        }

        return isEmpty;
    }

    protected void clearPropertyDirect(String key)
    {
        Configuration config;
        for(Iterator i = configList.iterator(); i.hasNext(); config.clearProperty(key))
            config = (Configuration)i.next();

    }

    public boolean containsKey(String key)
    {
        for(Iterator i = configList.iterator(); i.hasNext();)
        {
            Configuration config = (Configuration)i.next();
            if(config.containsKey(key))
                return true;
        }

        return false;
    }

    public List getList(String key, List defaultValue)
    {
        List list = new ArrayList();
        for(Iterator it = configList.iterator(); it.hasNext() && list.isEmpty();)
        {
            Configuration config = (Configuration)it.next();
            if(config != inMemoryConfiguration && config.containsKey(key))
                appendListProperty(list, config, key);
        }

        appendListProperty(list, inMemoryConfiguration, key);
        if(list.isEmpty())
            return defaultValue;
        for(ListIterator lit = list.listIterator(); lit.hasNext(); lit.set(interpolate(lit.next())));
        return list;
    }

    public String[] getStringArray(String key)
    {
        List list = getList(key);
        String tokens[] = new String[list.size()];
        for(int i = 0; i < tokens.length; i++)
            tokens[i] = String.valueOf(list.get(i));

        return tokens;
    }

    public Configuration getConfiguration(int index)
    {
        return (Configuration)configList.get(index);
    }

    public Configuration getInMemoryConfiguration()
    {
        return inMemoryConfiguration;
    }

    public Object clone()
    {
        try
        {
            CompositeConfig copy = (CompositeConfig)super.clone();
            copy.clearConfigurationListeners();
            copy.configList = new LinkedList();
            copy.inMemoryConfiguration = ConfigurationUtils.cloneConfiguration(getInMemoryConfiguration());
            copy.configList.add(copy.inMemoryConfiguration);
            for(int i = 0; i < getNumberOfConfigurations(); i++)
            {
                Configuration config = getConfiguration(i);
                if(config != getInMemoryConfiguration())
                    copy.addConfiguration(ConfigurationUtils.cloneConfiguration(config));
            }

            return copy;
        }
        catch(CloneNotSupportedException cnex)
        {
            throw new ConfigurationRuntimeException(cnex);
        }
    }

    public void setDelimiterParsingDisabled(boolean delimiterParsingDisabled)
    {
        ((BaseConfiguration)getInMemoryConfiguration()).setDelimiterParsingDisabled(delimiterParsingDisabled);
        super.setDelimiterParsingDisabled(delimiterParsingDisabled);
    }

    public void setListDelimiter(char listDelimiter)
    {
        ((BaseConfiguration)getInMemoryConfiguration()).setListDelimiter(listDelimiter);
        super.setListDelimiter(listDelimiter);
    }

    public Configuration getSource(String key)
    {
        if(key == null)
            throw new IllegalArgumentException("Key must not be null!");
        Configuration source = null;
        for(Iterator it = configList.iterator(); it.hasNext();)
        {
            Configuration conf = (Configuration)it.next();
            if(conf.containsKey(key))
            {
                if(source != null)
                    throw new IllegalArgumentException((new StringBuilder("The key ")).append(key).append(" is defined by multiple sources!").toString());
                source = conf;
            }
        }

        return source;
    }

    private static void appendListProperty(List dest, Configuration config, String key)
    {
        Object value = config.getProperty(key);
        if(value != null)
            if(value instanceof Collection)
                dest.addAll((Collection)value);
            else
                dest.add(value);
    }

    private static Logger logger = Logger.getLogger(com/comname/dhm/common/config/base/CompositeConfig);
    private List configList;
    private Configuration inMemoryConfiguration;

}


// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) radix(10) lradix(10)
// Source File Name:   StringUtil.java

package com.comname.dhm.common.util;

import java.text.MessageFormat;

public class StringUtil
{

    public StringUtil()
    {
    }

    public static String substituteParams(String msgtext, Object params[])
    {
        if(params == null || msgtext == null)
        {
            return msgtext;
        } else
        {
            MessageFormat mf = new MessageFormat(msgtext);
            return mf.format(((Object) (params)));
        }
    }
}



/* 文 件 名:  DebugLogHelper.java
 * 版    权:
 * 描    述:  debug日志包装类。
 * 修 改 人:  
 * 修改时间:  [2014-01-28]
 * 修改内容:  新增
 */
package com.comname.dhm.portalMS.common;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PersistenceDelegate;
import java.beans.PropertyDescriptor;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.Serializer;
import com.sun.org.apache.xml.internal.serialize.SerializerFactory;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;

/**
 * debug日志包装类。
 * @author
 * @version [2014-01-28]
 */
public class DebugLogHelper
{
    
    /** 写日志的类 */
    private Class<?> cls;
    
    /** 系统配置的日志对象 */
    private Logger debugLogger;
    
    /** 不同版本jdk对应类信息在堆栈中的索引 */
    private Integer jdkIndex;
    
    /** 系统换行分隔符 */
    private static final String LINESEPARATOR = System.getProperty("line.separator");
    
    /**
     * 构造方法。
     * @param cls 写日志的类。
     * @author
     * @version [2014-01-28]
     */
    public DebugLogHelper(Class<?> cls)
    {
        try
        {
            this.cls = cls;
            debugLogger = Logger.getLogger(cls);
            
        }
        catch (Exception e)
        {
            System.out.println("Open DebugLog is Error!");
        }
    }
    
    /**
     * 进行方法的日志入口。
     * @param objects 要打印的参数(N)。
     * @author
     * @version [2014-01-28]
     */
    public void enterFuncDebugLog(Object... objects)
    {
        
        if (!isDebugEnable())
        {
            return;
        }
        
        try
        {
            StackTraceElement[] eles = Thread.currentThread().getStackTrace();
            int index = getMethodIndex(eles);
            String methodName = eles[index].getMethodName();
            Integer num = eles[index].getLineNumber();
            StringBuffer str = new StringBuffer();
            str.append("[");
            str.append(Thread.currentThread().hashCode());
            str.append("]");
            str.append("[----Enter----]" + methodName + "." + num + "[Params");
            if (objects == null || objects.length == 0)
            {
                str.append("(null)");
            }
            
            else
            {
                str.append(LINESEPARATOR + "(");
                str.append(LINESEPARATOR + "<Param>");
                for (int i = 0; i < objects.length; i++)
                {
                    str.append(LINESEPARATOR);
                    str.append("<Param" + (i + 1) + ">").append(LINESEPARATOR);
                    
                    String foramtParam = appendParam(null, objects[i]);
                    if (null != foramtParam)
                    {
                        str.append(foramtParam);
                        str.deleteCharAt(str.length() - 1);
                    }
                    else
                    {
                        str.append(convertObjectToXml(objects[i]));
                    }
                    
                    str.append(LINESEPARATOR).append("</Param" + (i + 1) + ">");
                }
                str.append(LINESEPARATOR).append("<Param>");
                str.append(LINESEPARATOR + ")");
                
            }
            
            debugLogger.debug(str.toString());
        }
        catch (Throwable e)
        {
            
            debugLogger.debug(e.toString());
        }
    }
    
    /**
     * 在方法的内打日志入口。
     * @param objects 要打印的参数(N)。
     * @author
     * @version [2014-01-28]
     */
    public void atFuncDebugLog(Object... objects)
    {
        if (!isDebugEnable())
        {
            return;
        }
        try
        {
            StackTraceElement[] eles = Thread.currentThread().getStackTrace();
            int index = getMethodIndex(eles);
            String methodName = eles[index].getMethodName();
            Integer num = eles[index].getLineNumber();
            StringBuffer str = new StringBuffer();
            str.append("[");
            str.append(Thread.currentThread().hashCode());
            str.append("]");
            str.append("[----At-------]" + methodName + "." + num + "[Params]");
            
            if (objects == null || objects.length == 0)
            {
                str.append("(null)");
            }
            else
            {
                str.append("( ");
                for (int i = 0; i < objects.length; i++)
                {
                    if (objects[i] != null)
                    {
                        str.append(appendParam(null, objects[i]));
                        
                    }
                }
                str.deleteCharAt(str.length() - 1);
                str.append(" )");
                
            }
            
            debugLogger.debug(str.toString());
        }
        catch (Throwable e)
        {
            debugLogger.debug("[Exception][Function]atFuncDebugLog[Description]"
                    + e.toString());
        }
    }
    
    /**
     * 在方法的内打日志入口。
     * @param desc 描述
     * @param object 要打印的参数。
     * @author
     * @version [2014-01-28]
     */
    public void atFuncDebugLog(String desc, Object object)
    {
        if (!isDebugEnable())
        {
            return;
        }
        try
        {
            StackTraceElement[] eles = Thread.currentThread().getStackTrace();
            
            int index = getMethodIndex(eles);
            String methodName = eles[index].getMethodName();
            Integer num = eles[index].getLineNumber();
            StringBuffer str = new StringBuffer();
            str.append("[");
            str.append(Thread.currentThread().hashCode());
            str.append("]");
            str.append("[----At-------]" + methodName + "." + num + "[Params]");
            
            str.append("( ");
            str.append(appendParam(desc, object));
            
            str.deleteCharAt(str.length() - 1);
            str.append(" )");
            
            debugLogger.debug(str.toString());
        }
        catch (Throwable e)
        {
            debugLogger.debug("[Exception][Function]atFuncDebugLog[Description]"
                    + e.toString());
        }
        
    }
    
    /**
     * 退出方法异常的日志入口。
     * @param object 要打印的参数。
     * @author
     * @version [2014-01-28]
     */
    public void exitFuncDebugLog(Object obj)
    {
        if (!isDebugEnable())
        {
            return;
        }
        try
        {
            StackTraceElement[] eles = Thread.currentThread().getStackTrace();
            int index = getMethodIndex(eles);
            String methodName = eles[index].getMethodName();
            
            StringBuffer str = new StringBuffer();
            str.append("[");
            str.append(Thread.currentThread().hashCode());
            str.append("]");
            str.append("[----Exit-----]" + methodName + "[Results]");
            
            if (obj == null)
            {
                str.append("null");
            }
            else
            {
                str.append("( ");
                str.append(appendParam(null, obj));
                str.deleteCharAt(str.length() - 1);
                str.append(" )");
                
            }
            
            debugLogger.debug(str.toString());
        }
        catch (Throwable e)
        {
            debugLogger.debug("[Exception][Function]exitFuncDebugLog[Description]"
                    + e.toString());
        }
    }
    
    /**
     * 退出方法的日志入口。
     * @author
     * @version [2014-01-28]
     */
    public void exitFuncDebugLog()
    {
        if (!isDebugEnable())
        {
            return;
        }
        try
        {
            StackTraceElement[] eles = Thread.currentThread().getStackTrace();
            int index = getMethodIndex(eles);
            String methodName = eles[index].getMethodName();
            Integer num = eles[index].getLineNumber();
            StringBuffer str = new StringBuffer();
            str.append("[");
            str.append(Thread.currentThread().hashCode());
            str.append("]");
            str.append("[----Exit-----]" + methodName + "." + num
                    + "[Resultss]");
            str.append("void");
            debugLogger.debug(str.toString());
        }
        catch (Throwable e)
        {
            debugLogger.debug("[Exception][Function]exitFuncDebugLog[Description]"
                    + e.toString());
        }
    }
    
    /**
     * 方法异常的日志入口。
     * @param desc 描述
     * @param object 要打印的参数。
     * @author
     * @version [2014-01-28]
     */
    public void excepFuncDebugLog(Object obj)
    {
        
        excepFuncDebugLog("", obj);
    }
    
    /**
     * 方法异常的日志入口。
     * @param desc 描述
     * @param object 要打印的参数。
     * @author
     * @version [2014-01-28]
     */
    public void excepFuncDebugLog(String message, Object obj)
    {
        
        try
        {
            StackTraceElement[] eles = Thread.currentThread().getStackTrace();
            int index = getMethodIndex(eles);
            String methodName = eles[index].getMethodName();
            Integer num = eles[index].getLineNumber();
            StringBuffer str = new StringBuffer();
            str.append("[");
            str.append(Thread.currentThread().hashCode());
            str.append("]");
            str.append("[----Exception----]" + methodName + "." + num);
            str.append(":");
            str.append(message);
            
            str.append(LINESEPARATOR);
            
            if (obj == null)
            {
                str.append("null");
            }
            else if (obj instanceof String)
            {
                str.append(obj);
            }
            else if (obj instanceof Exception)
            {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                PrintStream ps = new PrintStream(baos);
                ((Exception)obj).printStackTrace(ps);
                String result = baos.toString();
                
                try
                {
                    ps.close();
                    baos.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
                str.append("( ");
                str.append(result);
                str.append(" )");
            }
            else
            {
                str.append("( ");
                str.append(appendParam(null, obj));
                str.deleteCharAt(str.length() - 1);
                str.append(" )");
            }
            
            debugLogger.error(str.toString());
            if (isDebugEnable())
            {
                debugLogger.debug(str.toString());
            }
            
        }
        catch (Throwable e)
        {
            debugLogger.error("[Exception][Function]excepFuncDebugLog[Description]"
                    + e.toString());
            if (isDebugEnable())
            {
                debugLogger.debug("[Exception][Function]excepFuncDebugLog[Description]"
                        + e.toString());
            }
        }
    }
    
    /**
     * 获取当前类线程信息的方法。
     * @param eles 栈信息
     * @author
     * @version [2014-01-28]
     */
    private int getMethodIndex(StackTraceElement[] eles)
    {
        // 如果已经正确取得一次索引,将直接返回。
        if (null != jdkIndex)
        {
            return jdkIndex.intValue();
        }
        int index = 0;
        for (StackTraceElement ele : eles)
        {
            
            // 默认错误时返回jdk1.6的索引.
            if (index > 5)
            {
                index = 3;
                break;
            }
            if (ele.getClassName().equals(cls.getName()))
            {
                jdkIndex = index;
                break;
            }
            ++index;
        }
        
        return index;
    }
    
    /**
     * 获取当前类线程信息的方法。
     * @param name 名称
     * @param obj 要打印的参数。
     * @author
     * @version [2014-01-28]
     */
    private String appendParam(String name, Object obj)
    {
        StringBuffer strBuf = null;
        try
        {
            strBuf = new StringBuffer();
            
            if (obj == null)
            {
                strBuf.append(name);
                strBuf.append("=");
                strBuf.append("null,");
                return String.valueOf(strBuf);
            }
            
            boolean isClassType = Integer.class.isAssignableFrom(obj.getClass())
                    || Long.class.isAssignableFrom(obj.getClass())
                    || Character.class.isAssignableFrom(obj.getClass())
                    || Byte.class.isAssignableFrom(obj.getClass())
                    || Boolean.class.isAssignableFrom(obj.getClass());
            if (isClassType || String.class.isAssignableFrom(obj.getClass())
                    || StringBuffer.class.isAssignableFrom(obj.getClass())
                    || Double.class.isAssignableFrom(obj.getClass())
                    || Float.class.isAssignableFrom(obj.getClass())
                    || Date.class.isAssignableFrom(obj.getClass())
                    || Number.class.isAssignableFrom(obj.getClass()))
            {
                
                strBuf.append(obj.getClass().getSimpleName());
                strBuf.append(name == null ? "" : (":" + name));
                strBuf.append(" = " + obj.toString() + ",");
            }
            
            else if (Map.class.isAssignableFrom(obj.getClass()))
            {
                Map<?, ?> map = (Map<?, ?>)obj;
                
                if (map.isEmpty())
                {
                    strBuf.append(map.getClass().getSimpleName() + "[],");
                    return String.valueOf(strBuf);
                }
                
                strBuf.append("\r" + map.getClass().getSimpleName());
                strBuf.append(name == null ? "" : (":" + name));
                strBuf.append("( size = " + map.size() + " ) = { ");
                Set<?> keySet = map.entrySet();
                
                for (Iterator<?> iter = keySet.iterator(); iter.hasNext();)
                {
                    Map.Entry<?, ?> entry = (Map.Entry<?, ?>)iter.next();
                    Object listObj = entry.getKey();
                    
                    if (listObj != null)
                    {
                        strBuf.append("\r\t[ " + appendParam(null, listObj));
                        strBuf.append(appendParam(null, entry.getValue()));
                        strBuf.deleteCharAt(strBuf.length() - 1);
                        strBuf.append(" ]");
                    }
                    
                }
                strBuf.append("\r},");
            }
            else if (Collection.class.isAssignableFrom(obj.getClass()))
            {
                Collection<?> coll = (Collection<?>)obj;
                
                if (coll.isEmpty())
                {
                    strBuf.append(coll.getClass().getSimpleName() + "[],");
                    return String.valueOf(strBuf);
                }
                
                strBuf.append("\r" + coll.getClass().getSimpleName());
                strBuf.append(name == null ? "" : (":" + name));
                strBuf.append("( size = " + coll.size() + ") = { ");
                
                for (Iterator<?> iter = coll.iterator(); iter.hasNext();)
                {
                    Object listObj = iter.next();
                    
                    if (listObj != null)
                    {
                        strBuf.append("\r\t[ " + appendParam(null, listObj));
                        strBuf.deleteCharAt(strBuf.length() - 1);
                        strBuf.append(" ]");
                    }
                    
                }
                strBuf.append("\r},");
            }
            else if (org.dom4j.Node.class.isAssignableFrom(obj.getClass()))
            {
                if (org.dom4j.Document.class.isAssignableFrom(obj.getClass()))
                {
                    org.dom4j.Document doc = (org.dom4j.Document)obj;
                    strBuf.append(doc.asXML());
                }
                else
                {
                    org.dom4j.Node node = (org.dom4j.Node)obj;
                    strBuf.append(node.asXML());
                }
                strBuf.append(",");
            }
            else if (Node.class.isAssignableFrom(obj.getClass()))
            {
                if (Document.class.isAssignableFrom(obj.getClass()))
                {
                    Document document = (Document)obj;
                    strBuf.append(DOM2String(document));
                }
                else
                {
                    Node node = (Node)obj;
                    strBuf.append(node2String(node, true));
                }
                strBuf.append(",");
            }
            else
            {
                BeanInfo info = Introspector.getBeanInfo(obj.getClass());
                PropertyDescriptor[] props = info.getPropertyDescriptors();
                System.out.println(obj.getClass().getName());
                System.out.println(obj.getClass().getSimpleName());
                strBuf.append(obj.getClass().getName());
                strBuf.append(name == null ? "" : (":" + name));
                strBuf.append(" = ( ");
                
                for (PropertyDescriptor prop : props)
                {
                    String propName = prop.getName();
                    if (prop.getWriteMethod() == null
                            || prop.getReadMethod() == null)
                    {
                        continue;
                    }
                    
                    Method readMethod = prop.getReadMethod();
                    Object paramObj = invokeMethod(readMethod, obj);
                    if (obj == paramObj)
                    {
                        continue;
                    }
                    if (paramObj != null)
                    {
                        strBuf.append(appendParam(propName, paramObj));
                    }
                }
                strBuf.deleteCharAt(strBuf.length() - 1);
                strBuf.append(" ),");
            }
            
        }
        catch (Throwable e)
        {
            debugLogger.debug("[Exception][Function]appendParam[Description]"
                    + e.toString());
        }
        
        return String.valueOf(strBuf);
        
    }
    
    /**
     * 将对象过XMLEncode转换为String
     *
     * @param requestObject 请求对象
     * @return String 对象转换后的String
     * @author
     * @version [2014-01-28]
     */
    public String convertObjectToXml(Object requestObject)
    {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        
        BufferedOutputStream bos = new BufferedOutputStream(bo);
        
        XMLEncoder xmlEncoder = new XMLEncoder(bos);
        
        PersistenceDelegate pd = xmlEncoder.getPersistenceDelegate(Date.class);
        
        xmlEncoder.setPersistenceDelegate(Timestamp.class, pd);
        
        String content = null;
        
        try
        {
            // 使用XML编码器写对象
            xmlEncoder.writeObject(requestObject);
            
            xmlEncoder.close();
            
            content = bo.toString();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                bos.close();
                bo.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        
        return content;
    }
    
    /**
     * 将DOM对象转换为String
     * @param doc DOM对象
     * @return String 对象转换后的String
     * @author
     * @version [2014-01-28]
     */
    public String DOM2String(Document doc)
    {
        String docStr;
        ByteArrayOutputStream outPut;
        if (doc == null)
            return null;
        docStr = null;
        outPut = null;
        try
        {
            outPut = new ByteArrayOutputStream();
            OutputFormat format = new OutputFormat(doc);
            format.setIndenting(true);
            format.setEncoding("UTF-8");
            Serializer serializer = SerializerFactory.getSerializerFactory("xml")
                    .makeSerializer(outPut, format);
            serializer.asDOMSerializer().serialize(doc);
            docStr = new String(outPut.toByteArray(), "UTF-8");
        }
        catch (Exception ex)
        {
            
        }
        finally
        {
            
            IOUtils.closeQuietly(outPut);
        }
        
        return docStr;
    }
    
    /**
     * 将Node对象转换为String
     * @param doc DOM对象
     * @return String 对象转换后的String
     * @author
     * @version [2014-01-28]
     */
    public final String node2String(Node node, boolean isPreserveSpace)
    {
        if (node == null)
            return null;
        if (node.getNodeType() == 9)
            node = ((Document)node).getDocumentElement();
        OutputFormat format = new OutputFormat(node.getOwnerDocument());
        format.setEncoding("UTF-8");
        format.setIndenting(false);
        format.setPreserveSpace(isPreserveSpace);
        StringWriter stringOut = new StringWriter();
        XMLSerializer serial = new XMLSerializer(stringOut, format);
        try
        {
            serial.asDOMSerializer();
            serial.serialize((Element)node);
        }
        catch (IOException ex)
        {
            
        }
        return stringOut.toString();
    }
    
    /**
     * 通过反射获取内部属性对象。
     * @param method 方法
     * @param target 类
     * @return Object 参数值
     * @author
     * @version [2014-01-28]
     */
    public Object invokeMethod(Method method, Object target)
    {
        return invokeMethod(method, target, null);
    }
    
    /**
     * 通过反射获取内部属性对象。
     * @param method方法
     * @param target 类
     * @return Object 参数值
     * @author
     * @version [2014-01-28]
     */
    public Object invokeMethod(Method method, Object target, Object args[])
    {
        try
        {
            return method.invoke(target, args);
        }
        catch (IllegalAccessException ex)
        {
            handleReflectionException(ex);
            throw new IllegalStateException((new StringBuilder(
                    "Unexpected reflection exception - ")).append(ex.getClass()
                    .getName()).append(": ").append(ex.getMessage()).toString());
        }
        catch (InvocationTargetException ex)
        {
            handleReflectionException(ex);
            throw new IllegalStateException((new StringBuilder(
                    "Unexpected reflection exception - ")).append(ex.getClass()
                    .getName()).append(": ").append(ex.getMessage()).toString());
        }
    }
    
    /**
     * 处理异常
     *
     * @param ex 异常
     * @author
     * @version [2014-01-28]
     */
    public void handleReflectionException(Exception ex)
    {
        if (ex instanceof NoSuchMethodException)
            throw new IllegalStateException((new StringBuilder(
                    "Method not found: ")).append(ex.getMessage()).toString());
        if (ex instanceof IllegalAccessException)
            throw new IllegalStateException((new StringBuilder(
                    "Could not access method: ")).append(ex.getMessage())
                    .toString());
        if (ex instanceof InvocationTargetException)
            handleInvocationTargetException((InvocationTargetException)ex);
        throw new IllegalStateException((new StringBuilder(
                "Unexpected reflection exception - ")).append(ex.getClass()
                .getName()).append(": ").append(ex.getMessage()).toString());
    }
    
    /**
     * 处理异常
     * @param ex 异常
     * @author
     * @version [2014-01-28]
     */
    public void handleInvocationTargetException(InvocationTargetException ex)
    {
        if (ex.getTargetException() instanceof RuntimeException)
            throw (RuntimeException)ex.getTargetException();
        if (ex.getTargetException() instanceof Error)
            throw (Error)ex.getTargetException();
        else
            throw new IllegalStateException(
                    (new StringBuilder(
                            "Unexpected exception thrown by method - ")).append(ex.getTargetException()
                            .getClass()
                            .getName())
                            .append(": ")
                            .append(ex.getTargetException().getMessage())
                            .toString());
    }
    
    public boolean isDebugEnable()
    {
        return debugLogger.isDebugEnabled();
    }
    
    public void atCollectionSize(String desc, Collection<?> collection)
    {
        if (!isDebugEnable())
        {
            return;
        }
        try
        {
            StackTraceElement[] eles = Thread.currentThread().getStackTrace();
            
            int index = getMethodIndex(eles);
            String methodName = eles[index].getMethodName();
            Integer num = eles[index].getLineNumber();
            StringBuffer str = new StringBuffer();
            str.append("[");
            str.append(Thread.currentThread().hashCode());
            str.append("]");
            str.append("[----At-------]" + methodName + "." + num + "[Params]");
            
            str.append("( ");
            str.append(desc);
            str.append("[size]");
            str.append("=");
            if (null == collection)
            {
                str.append("null");
                
            }
            else
            {
                str.append(collection.size());
            }
            
            str.append(" )");
            
            debugLogger.debug(str.toString());
        }
        catch (Throwable e)
        {
            debugLogger.debug("[Exception][Function]atFuncDebugLog[Description]"
                    + e.toString());
        }
    }
}


/*
 * 工 程 名:  portalMS
 * 包       名:  com.comname.dhm.portalMS.exception
 * 文 件 名:  portalMSException.java
 * 版       权:  Copyright (c) 2009 comname All Rights Reserved.
 * 描       述:  IEPG管理系统的自定义异常
 * 修 改 人:  
 * 修改时间:  2009-11-23
 * 跟踪单号:  <跟踪单号>
 * 修改单号:  <修改单号>
 * 修改内容:  <修改内容>
 */
package com.comname.dhm.portalMS.exception;

import com.comname.dhm.portalMS.common.DebugLogHelper;


/**
 *
 * 管理系统自定义异常
 * 当系统发生异常时统一包装抛出
 *
 * @author
 * @version  []
 * @see  Exception
 * @since  []
 */
public class PortalMSException extends Exception
{
    
    /**
     * 序列化ID
     */
    private static final long serialVersionUID = 1772426579115321126L;
    
    /**
     * 错误编号
     */
    private long errorCode = 0;
    
    /**
     * 日志对象
     */
    private static final DebugLogHelper logger = new DebugLogHelper(PortalMSException.class);
    
    /**
     * <默认构造函数>
     */
    public PortalMSException()
    {
        super();
    }
    
    /**
     * 传入错误信息构造异常
     * @param message 异常提示信息
     */
    public PortalMSException(String message)
    {
        super(message);
    }
    
    /**
     * 传入异常构造异常
     * @param cause 异常
     */
    public PortalMSException(Throwable cause)
    {
        super(cause);
        // 向NMS告警
        sendDbExceptionTrap(errorCode,cause);
    }
    
    /**
     * 传入提示信息和异常内容
     * @param message 异常提示信息
     * @param cause 异常
     */
    public PortalMSException(String message, Throwable cause)
    {
        super(message, cause);
        // 向NMS告警
        sendDbExceptionTrap(errorCode,cause);
    }
    
    /**
     * 获得错误编号
     * @return long [错误码]
     */
    public long getErrorCode()
    {
        return errorCode;
    }
    
    /**
     * 传入错误编号构造异常
     * @param errorCode 异常错误代码
     */
    public PortalMSException(long errorCode)
    {
        super();
        this.errorCode = errorCode;
    }
    
    /**
     * 传入错误编号和消息信息构造异常
     * @param errorCode 异常代码
     * @param message 异常提示信息
     */
    public PortalMSException(long errorCode, String message)
    {
        super(message);
        this.errorCode = errorCode;
    }
    
    /**
     * 传入错误编号和异常内容构造异常
     * @param errorCode 错误代码
     * @param cause 异常
     */
    public PortalMSException(long errorCode, Throwable cause)
    {
        super(cause);
        this.errorCode = errorCode;
        // 向NMS告警
        sendDbExceptionTrap(errorCode,cause);
    }
    
    /**
     * 传入错误编号,消息信息和异常内容构造异常
     * @param errorCode 异常错误代码
     * @param message 异常提示信息
     * @param cause 异常本身
     */
    public PortalMSException(long errorCode, String message, Throwable cause)
    {
        super(message, cause);
        this.errorCode = errorCode;
        // 向NMS告警
        sendDbExceptionTrap(errorCode,cause);
    }
    
    /**
     * 发生数据库异常时,向NMS发送告警信息
     * @param cause 异常信息
     *
     * @return void [返回类型说明]
     * @exception throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    private void sendDbExceptionTrap(long errorCode,Throwable cause)
    {
        if (cause == null)
        {
            return;
        }
        String errMsg = cause.getMessage();
        if (errMsg != null && errMsg.contains("ORA-"))
        {
            logger.excepFuncDebugLog("Abnormal DB ,To NMS warning。");
        }
    }
}

0 0
原创粉丝点击