FTPC通用对象转换JSON工具类

支持ORDER EQUIPMENT USER …几乎所有的FTPC内置对象

package com.rockwell.webapp.service.system.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.datasweep.compatibility.client.*;
import com.datasweep.compatibility.ui.Time;
import com.datasweep.plantops.common.dataobjects.*;
import com.datasweep.plantops.common.utility.DataObjectCopier;
import com.rockwell.mes.commons.base.ifc.objects.MESATObject;
import com.rockwell.mes.commons.base.ifc.utility.CollectionUtility;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import java.util.stream.Collectors;

/**
 * FTPC对象转Map
 *
 * @author xuweijun
 * @date 2022/5/9
 */
public class ConvertObject {
    /**
     * 私有构造
     * @author xuweijun
     * @date 2022/5/16 14:28
     * @param
     * @return
     */
    private ConvertObject() {
    }
   /**
    * 工单转换成Map
    * @author xuweijun
    * @date 2022/5/16 09:08
    * @param order
    * @return java.util.Map<java.lang.String,java.lang.Object>
    */
   @Deprecated
    public static Map<String, Object> convertOrder(final Order order) throws Exception {
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        if (null == order) {
            return map;
        }
        final String dworkOrder = "dworkOrder";
        Object objByField = ReflectUtilsEx.getObjByField(order, order.getClass(), dworkOrder);
        DWorkOrder dWorkOrder = (DWorkOrder) objByField;
        DWorkOrder copy = (DWorkOrder) DataObjectCopier.deepCopy(dWorkOrder);
        copy.setOrderItems(null);
        copy.setUserDefinedAttributes(null);
        map.putAll(JSON.parseObject(JSON.toJSONString(copy,getFTPCJsonFileter(null)), new TypeReference<LinkedHashMap<String, Object>>() {
        }));

        DUDAInstance userDefinedAttributes = dWorkOrder.getUserDefinedAttributes();
        UDAInstance udaSupport = getUdaSupport(order);
        map.putAll(getUdaMap(userDefinedAttributes,udaSupport));
        ArrayList<Object> objects = new ArrayList<>();
        map.put("orderItems",objects);
        Vector<OrderItem> orderItems = order.getOrderItems();
        for (OrderItem orderItem : orderItems) {
            objects.add(convertOrderItem(orderItem));
        }
        return map;
    }

    public static UDAInstance getUdaSupport(IBoundObject boundObject){
        final String udaSupport = "udaSupport";
        Object objByField = ReflectUtilsEx.getObjByField(boundObject, boundObject.getClass(), udaSupport);
        return (UDAInstance)objByField;
    }

    public static Map<String,Object> getUdaMap(DUDAInstance userDefinedAttributes,UDAInstance udaSupport) throws DatasweepException {
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        for (DUDAInstanceItem dataItem : userDefinedAttributes.getDataItems()) {
            String name = dataItem.getName();
            Object uda = udaSupport.getUDA(name);
            if(uda instanceof Time){
                Time time = (Time)uda;
                Calendar calendar = time.getCalendar();
                String format = DateFormatUtils.format(calendar, "yyyy-MM-dd HH:mm:ss");
                uda = format;
            }
            if(uda instanceof Keyed){
                Keyed keyed = (Keyed) uda;
                uda = keyed.getKey();
            }
            map.put(name,uda);
        }
        return map;
    }

    /**
     * 子工单转换成Map
     * @author xuweijun
     * @date 2022/5/16 09:08
     * @param orderItem
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @Deprecated
    public static Map<String, Object> convertOrderItem(final OrderItem orderItem) throws Exception {
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        if (null == orderItem) {
            return map;
        }
        final String dworkOrderItem = "dworkOrderItem";
        Object objByField = ReflectUtilsEx.getObjByField(orderItem, orderItem.getClass(), dworkOrderItem);
        DWorkOrderItem dWorkOrderItem = (DWorkOrderItem) objByField;
        DWorkOrderItem copy = (DWorkOrderItem) DataObjectCopier.deepCopy(dWorkOrderItem);
        copy.setUserDefinedAttributes(null);
        map.putAll(JSON.parseObject(JSON.toJSONString(copy,getFTPCJsonFileter(null)), new TypeReference<LinkedHashMap<String, Object>>() {
        }));

        DUDAInstance userDefinedAttributes = dWorkOrderItem.getUserDefinedAttributes();
        UDAInstance udaSupport = getUdaSupport(orderItem);
        map.putAll(getUdaMap(userDefinedAttributes,udaSupport));
        return map;
    }
    /**
     * 物料转换成Map
     * @author xuweijun
     * @date 2022/5/16 09:08
     * @param part
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @Deprecated
    public static Map<String, Object> convertPart(final Part part) throws Exception {
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        if (null == part) {
            return map;
        }
        final String fieldDpart = "dPart";
        Object objByField = ReflectUtilsEx.getObjByField(part, part.getClass(), fieldDpart);
        DPart dPart = (DPart) objByField;
        DPart copy = (DPart) DataObjectCopier.deepCopy(dPart);
        copy.setUserDefinedAttributes(null);
        map.putAll(JSON.parseObject(JSON.toJSONString(copy,getFTPCJsonFileter(null)), new TypeReference<LinkedHashMap<String, Object>>() {
        }));
        DUDAInstance userDefinedAttributes = dPart.getUserDefinedAttributes();
        UDAInstance udaSupport = getUdaSupport(part);
        map.putAll(getUdaMap(userDefinedAttributes,udaSupport));
        return map;
    }

    /**
     * 设备转换成Map
     * @author xuweijun
     * @date 2022/5/16 09:08
     * @param param
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @Deprecated
    public static Map<String, Object> convertEquipment(final Equipment param) throws Exception {
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        if (null == param) {
            return map;
        }
        final String dfieldD = "dEquipment";
        Object objByField = ReflectUtilsEx.getObjByField(param, param.getClass(), dfieldD);
        DEquipment dEquipment = (DEquipment) objByField;
        DEquipment copy = (DEquipment) DataObjectCopier.deepCopy(dEquipment);
        copy.setUserDefinedAttributes(null);
        map.putAll(JSON.parseObject(JSON.toJSONString(copy,getFTPCJsonFileter(null)), new TypeReference<LinkedHashMap<String, Object>>() {
        }));
        DUDAInstance userDefinedAttributes = dEquipment.getUserDefinedAttributes();
        UDAInstance udaSupport = getUdaSupport(param);
        map.putAll(getUdaMap(userDefinedAttributes,udaSupport));
        return map;
    }

    /**
     * 用户转换成Map
     * @author xuweijun
     * @date 2022/5/16 09:08
     * @param param
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    @Deprecated
    public static Map<String, Object> convertUser(final User param) throws Exception {
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        if (null == param) {
            return map;
        }
        Class<DUser> clazz = DUser.class;
        final String dfieldD = StringUtilsExs.toLowerCaseFirstOne(clazz.getSimpleName());
        Object objByField = ReflectUtilsEx.getObjByField(param, param.getClass(), dfieldD);
        DUser dUser = ReflectUtilsEx.convertValue(objByField, clazz);
        Object o = DataObjectCopier.deepCopy(dUser);
        DUser copy = ReflectUtilsEx.convertValue(o, clazz);
        copy.setUserDefinedAttributes(null);
        map.putAll(JSON.parseObject(JSON.toJSONString(copy,getFTPCJsonFileter(null)), new TypeReference<LinkedHashMap<String, Object>>() {
        }));
        DUDAInstance userDefinedAttributes = dUser.getUserDefinedAttributes();
        UDAInstance udaSupport = getUdaSupport(param);
        map.putAll(getUdaMap(userDefinedAttributes,udaSupport));
        return map;
    }

    public static  Map<String, Object> convertFtpcObjectWithFilter(final Keyed param,SimplePropertyPreFilter filter) throws Exception {
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        if (null == param) {
            return map;
        }
        Class<IBoundObject> objClass = IBoundObject.class;
        Class<IExtendable> dObjClass = IExtendable.class;
        Class<DKeyed> dKeyedClass = DKeyed.class;
        //获取innerdata  dkeyed getInnerData
//        final String methodName = "getInnerData";
//        Object o1 = invokMethod(param, param.getClass(), methodName, null, null);
        Object o2 = ReflectUtilsEx.getObjByField(param, param.getClass(),  dKeyedClass.getSimpleName().toLowerCase());
//        System.out.println(o1.equals(o2));
        IExtendable iExtendable = ReflectUtilsEx.convertValue(o2, dObjClass);
        Object o = DataObjectCopier.deepCopy(iExtendable);
        IExtendable copy = ReflectUtilsEx.convertValue(o, dObjClass);
        copy.setUserDefinedAttributes(null);
        map.putAll(JSON.parseObject(JSON.toJSONString(copy, filter), new TypeReference<LinkedHashMap<String, Object>>() {
        }));
        DUDAInstance userDefinedAttributes = iExtendable.getUserDefinedAttributes();
        IBoundObject iBoundObject = ReflectUtilsEx.convertValue(param, objClass);
        UDAInstance udaSupport = getUdaSupport(iBoundObject);
        map.putAll(getUdaMap(userDefinedAttributes,udaSupport));
        return map;
    }
    /**
     * 转换FTPC对象
     * @author xuweijun
     * @date 2022/7/7 11:52
     * @param param
     * @return java.util.Map<java.lang.String,java.lang.Object>
     */
    public static  Map<String, Object> convertFtpcObject(final Keyed param) throws Exception {
      return convertFtpcObjectWithFilter(param,null);
    }
    /**
     * 批量转换FTPC对象
     * @author xuweijun
     * @date 2022/7/7 11:52
     * @param params
     * @param filter
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     */
    public static List<Map<String, Object>> convertFtpcObjects(final List<? extends Keyed> params, final SimplePropertyPreFilter filter) throws Exception {
        List<Map<String, Object>> collect = params.stream().map(item -> {
            try {
                return convertFtpcObjectWithFilter(item, filter);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new LinkedHashMap<String, Object>();
        }).filter(item -> !item.isEmpty()).collect(Collectors.toList());
        return collect;
    }
    /**
     * 批量转换FTPC对象
     * @author xuweijun
     * @date 2022/7/7 11:52
     * @param params
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     */
    public static List<Map<String, Object>> convertFtpcObjects(final List<? extends Keyed> params) throws Exception {
        return convertFtpcObjects(params,null);
    }
    /**
     * 对象转Map
     *
     * @param object
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> beanToMap(Object object) throws IllegalAccessException {
        Map<String, Object> map = new LinkedHashMap<>();
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Object o = field.get(object);
            if (null != o) {
                map.put(field.getName(), field.get(object));
            }
        }
        return map;
    }





    public static Map<String, Object> convertATObjectWithFilter(final MESATObject mesatObject,final SimplePropertyPreFilter filter) throws Exception {
        ATRow atRow = mesatObject.getATRow();
        return convertATROW(null, null, atRow, filter);
    }
    /**
     * 批量转换
     * @author xuweijun
     * @date 2022/7/7 11:02
     * @param mesatObject
     * @param filter
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     */
    public static List<Map<String, Object>> convertATObjects(final List<? extends MESATObject> mesatObject,final SimplePropertyPreFilter filter) throws Exception {
        List<Map<String, Object>> collect = mesatObject.stream().map(item -> {
            try {
                return convertATObjectWithFilter(item, filter);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new LinkedHashMap<String, Object>();
        }).filter(item -> !item.isEmpty()).collect(Collectors.toList());
        return collect;
    }
    /**
     * 批量转换
     * @author xuweijun
     * @date 2022/7/7 11:02
     * @param mesatObject
     * @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     */
    public static List<Map<String, Object>> convertATObjects(final List<? extends MESATObject> mesatObject) throws Exception {
        return convertATObjects(mesatObject,null);
    }

    public static Map<String, Object> convertATObject(final MESATObject mesatObject) throws Exception {
        return convertATObjectWithFilter(mesatObject,null);
    }

    public static LinkedHashMap<String, Object> convertATROW(LinkedHashMap<String, Object> linkedHashMap, DATRow datRow, ATRow atRow, SimplePropertyPreFilter filter) throws Exception {
        if (null == linkedHashMap) {
            final String fieldName = "datRow";
            Object objByField = ReflectUtilsEx.getObjByField(atRow, atRow.getClass(), fieldName);
            DATRow copy = (DATRow) DataObjectCopier.deepCopy(objByField);
            copy.setDataCells(null);
            copy.setDependentATRows(null);
            datRow = (DATRow) objByField;
            linkedHashMap = JSON.parseObject(JSON.toJSONString(copy,filter), new TypeReference<LinkedHashMap<String, Object>>() {
            });
        }
        if (linkedHashMap.isEmpty()) {
            DATRow copy = (DATRow) DataObjectCopier.deepCopy(datRow);
            copy.setDataCells(null);
            copy.setDependentATRows(null);
            linkedHashMap.putAll(JSON.parseObject(JSON.toJSONString(copy,filter), new TypeReference<LinkedHashMap<String, Object>>() {
            }));
        }
        DATCell[] dataCells = datRow.getDataCells();
        for (int i = 0; i < dataCells.length; i++) {
            DATCell dataCell = dataCells[i];
            String name = dataCell.getName();
            final String methodName = "getObjectValue";
            Class<DATCell>[] clazzType = new Class[1];
            clazzType[0] = DATCell.class;
            Object[] args = new Object[1];
            args[0] = dataCell;
            Object value = ReflectUtilsEx.invokMethod(atRow, atRow.getClass(), methodName, clazzType, args);
            if(value instanceof Time){
                Time time = (Time)value;
                Calendar calendar = time.getCalendar();
                String format = DateFormatUtils.format(calendar, "yyyy-MM-dd HH:mm:ss");
                value = format;
            }
            if(value instanceof MeasuredValue){
                MeasuredValue measuredValue = (MeasuredValue) value;
                value = measuredValue.toString();
            }
            if(value instanceof UoMConversion){
                UoMConversion uoMConversion = (UoMConversion) value;
                value = uoMConversion.toString();
            }
            linkedHashMap.put(name, value);
        }
        if (hashDependent(datRow)) {
            DATRow[] dependentATRows = datRow.getDependentATRows();
            ArrayList<LinkedHashMap<String, Object>> linkedHashMapList = new ArrayList<>();
            linkedHashMap.put("dependentDatas", linkedHashMapList);
            for (int i = 0; i < dependentATRows.length; i++) {
                LinkedHashMap<String, Object> dependentMap = new LinkedHashMap<>();
                DATRow datRow1 = dependentATRows[i];
                linkedHashMapList.add(convertATROW(dependentMap, datRow1, atRow,filter));
            }
        }
        return linkedHashMap;
    }

    private static boolean hashDependent(DATRow datRow) {
        return datRow.getDependentATRows() != null && datRow.getDependentATRows().length > 0;
    }
    /**
     * 获取需要过滤的Ftpc属性
     * @author xuweijun
     * @date 2022/5/16 14:10
     * @param excludeFields
     * @return com.alibaba.fastjson.serializer.SimplePropertyPreFilter
     */
    public static SimplePropertyPreFilter getFTPCJsonFileter(final String ...excludeFields){
        SimplePropertyPreFilter filter = getDefaultsonFileter();
        Set<String> excludes = filter.getExcludes();
        excludes.add("creationTime");
        excludes.add("creatorKey");
        excludes.add("lastModifiedTime");
        excludes.add("lastModifierKey");
        excludes.add("modificationFlag");
        excludes.add("objectSource");
        if (null != excludeFields && excludeFields.length > 0)
            Arrays.stream(excludeFields).forEach(item -> excludes.add(item));
        return filter;
    }
    /**
     * 获取属性过滤器
     * @author xuweijun
     * @date 2022/5/16 14:12
     * @param
     * @return com.alibaba.fastjson.serializer.SimplePropertyPreFilter
     */
    public static SimplePropertyPreFilter getDefaultsonFileter(){
        return  new SimplePropertyPreFilter();
    }


   /**
    * 复制指定字段值
    * @author xuweijun
    * @date 2022/5/12 15:04
    * @param sourceKey
    * @param targetKey
    * @param maps
    * @return void
    */
    public static void  copyKeyValue(final String sourceKey,final String targetKey,final List<LinkedHashMap<String,Object>> maps){
        for (LinkedHashMap<String, Object> item : maps) {
            Object value = item.get(sourceKey);
            item.put(targetKey,value);
        }
    }

}

内置对象使用方法

package com.rockwell.webapp.controller.mah.querydata;

import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import com.annotation.CommonLog;
import com.annotation.RouteLog;
import com.datasweep.compatibility.client.Equipment;
import com.datasweep.compatibility.client.Order;
import com.datasweep.compatibility.client.User;
import com.rockwell.mes.commons.base.ifc.services.PCContext;
import com.rockwell.webapp.service.system.common.ConvertObject;
import com.rockwell.webapp.service.system.common.R;
import com.rockwell.webapp.service.system.common.RErroMsg;
import com.rockwell.webapp.service.system.common.TestLog;
import lombok.extern.log4j.Log4j2;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * 类说明
 *
 * @author xuweijun
 * @date 2022/5/16
 */
@RestController
@RequestMapping("/webapp/service/mah/querydata")
@Log4j2
public class QueryData {
    /**
     * 查询数据信息
     * @author xuweijun
     * @date 2022/5/9 15:33
     * @return com.rockwell.webapp.service.system.common.R
     */

    @GetMapping("/query")
    @RouteLog
    @CommonLog("通用对象转JSON")
    public R query(){
        TestLog.main();
        R r = new R();
        try {
            log.info("进行查询,转换成通用的JSON");
            //filter过滤圆棒信息
            Equipment 注塑机 = PCContext.getFunctions().getEquipmentByName("注塑机");
            User xwj = PCContext.getFunctions().getUser("xwj");
            Order workOrder = PCContext.getFunctions().getWorkOrder("1111");
            SimplePropertyPreFilter ftpcJsonFileter = ConvertObject.getFTPCJsonFileter("orderItems");
            r.ok(ConvertObject.convertFtpcObjectWithFilter(workOrder,ftpcJsonFileter));
        } catch (Exception e) {
            //todo 错误日志记录
            e.printStackTrace();
            RErroMsg rErroMsg = new RErroMsg("-1", e.getLocalizedMessage());
            r.error(rErroMsg);
        }
        return r;
    }
}

AT表对象使用方法

MESMAHReCutBad mesmahReCutBad = new MESMAHReCutBad();
Map<String, Object> stringObjectMap = ConvertObject.convertATObject(mesmahReCutBad);

可以使用过滤器

参数表示需要过滤的字段,是一个可变长String数组

SimplePropertyPreFilter ftpcJsonFileter = ConvertObject.getFTPCJsonFileter("orderItems");

相对好用的反射工具类,上面的工具类依赖了这个相对好用反射工具类

package com.rockwell.webapp.service.system.common;


import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 反射增强
 *
 * @author xuweijun
 * @date 2022/5/16
 */
public class ReflectUtilsEx {
    /**
     * 执行方法
     * @author xuweijun
     * @date 2022/5/16 14:00
     * @param object
     * @param clazz
     * @param methodName
     * @param parameterTypes
     * @param args
     * @return java.lang.Object
     */
    public static Object invokMethod(final Object object,final Class<?> clazz, final String methodName, final Class<?>[] parameterTypes, final Object[] args) {
        try {
            Method declaredMethod = clazz.getDeclaredMethod(methodName, parameterTypes);
            declaredMethod.setAccessible(true);
            return declaredMethod.invoke(object, args);
        } catch (Exception e) {
            if (e instanceof NoSuchMethodException) {
                Class<?> superclass = clazz.getSuperclass();
                if (null == superclass) {
                    return null;
                }
                return invokMethod(object,superclass,methodName,parameterTypes,args);
            } else {
                e.printStackTrace();
            }
        }
        return null;
    }
    /**
     * 获取属性
     * @author xuweijun
     * @date 2022/5/16 14:00
     * @param object
     * @param clazz
     * @param fname
     * @return java.lang.Object
     */
    public static Object getObjByField(Object object, Class<?> clazz, final String fname) {
        try {
            final Field field = clazz.getDeclaredField(fname);
            field.setAccessible(true);
            return field.get(object);
        } catch (Exception e) {
            if (e instanceof NoSuchFieldException) {
                Class<?> superclass = clazz.getSuperclass();
                if (null == superclass) {
                    return null;
                }
                return getObjByField(object,superclass,fname);
            } else {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static <T> T convertValue(Object fromValue, Class<T> toValueType) throws IllegalArgumentException {
        return (T) fromValue;
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JerryLXu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值