All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.qcloud.cos.internal.cihandler.XStreamXmlResponsesSaxParser Maven / Gradle / Ivy

There is a newer version: 5.6.238.2
Show newest version
package com.qcloud.cos.internal.cihandler;

import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.internal.CosServiceRequest;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.security.AnyTypePermission;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.concurrent.ConcurrentHashMap;

public abstract class XStreamXmlResponsesSaxParser {
    private static final ConcurrentHashMap xStreamMap = new ConcurrentHashMap();

    abstract T getResponse(InputStream in);

    static XStream initXStream(Object obj) {
        return initXStream(obj.getClass());
    }

    static  XStream initXStream(Class cls) {
        if (!xStreamMap.containsKey(cls.getName())) {
            XStream xstream = new XStream();
            //忽略不需要的节点
            xstream.ignoreUnknownElements();
            //对指定的类使用Annotations 进行序列化
            xstream.processAnnotations(cls);
            xstream.addPermission(AnyTypePermission.ANY);
            Field[] fields = CosServiceRequest.class.getDeclaredFields();
            for (Field field : fields) {
                xstream.omitField(CosServiceRequest.class, field.getName());
            }
            xStreamMap.put(cls.getName(), xstream);
            return xstream;
        }
        return xStreamMap.get(cls.getName());
    }

    public static String toXML(Object obj) {
        XStream xstream = initXStream(obj);
        return xstream.toXML(obj);
    }

    public static  T toBean(InputStream inputStream, Class cls) {
        try (InputStream in = inputStream) {
            XStream xstream = initXStream(cls);
            return (T) xstream.fromXML(in);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CosServiceException("Response parse error");
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy