EntityGroupSaveAction.java

/*
 *        @ Copyright 2001 FA Software;
 *        All right reserved. No part of this program may be reproduced or
 *        transmitted in any form or by any means, electronic or
 *        mechanical, including photocopying, recording, or by any
 *        information storage or retrieval system without written
 *        permission from FA Software, except for inclusion of brief
 *        quotations in a review.
 */
package com.mycim.webapp.actions.entitygroup;

import com.fa.sesa.exception.Assert;
import com.fa.sesa.exception.Errors;
import com.fa.sesa.threadlocal.LocalContext;
import com.mycim.framework.utils.beans.PropertyUtils;
import com.mycim.framework.utils.lang.BooleanUtils;
import com.mycim.framework.utils.lang.StringUtils;
import com.mycim.framework.utils.lang.collections.MapUtils;
import com.mycim.valueobject.MessageIdList;
import com.mycim.valueobject.ObjectList;
import com.mycim.valueobject.bas.Relation;
import com.mycim.valueobject.consts.LinkTypeList;
import com.mycim.valueobject.consts.SessionNames;
import com.mycim.valueobject.ems.EntityGroup;
import com.mycim.valueobject.prp.Operation;
import com.mycim.webapp.Constants;
import com.mycim.webapp.WebUtils;
import com.mycim.webapp.actions.EmsSetupAction;
import com.mycim.webapp.forms.EntityGroupInfoForm;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * @author songp
 */
public class EntityGroupSaveAction extends EmsSetupAction {

    @Override
    public ActionForward init(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        EntityGroupInfoForm theform = (EntityGroupInfoForm) form;

        if (WebUtils.getParameterBoolean(Constants.NAV_KEY, request)) {
            request.removeAttribute(SessionNames.ENTITYGROUP_KEY);
            theform.setTransId(Constants.INIT_KEY);
            theform.setInstanceId(StringUtils.EMPTY);
            theform.setInstanceDesc(StringUtils.EMPTY);
            return mapping.getInputForward();
        }

        // Populate the new valid format id
        String id = "";

        // When from another mapping page,construct new id through valueObject in session
        id = theform.getInstanceId().trim().toUpperCase();

        EntityGroup entityGroup = new EntityGroup(id, getNamedSpace(ObjectList.ENTITYGROUP_KEY,
                                                                    LocalContext.getFacilityRrn()),
                                                  ObjectList.ENTITYGROUP_KEY);

        entityGroup = (EntityGroup) getInstance(entityGroup);

        if (entityGroup == null || entityGroup.getInstanceRrn() == 0) {
            entityGroup = new EntityGroup(id, getNamedSpace(ObjectList.ENTITYGROUP_KEY, LocalContext.getFacilityRrn()),
                                          ObjectList.ENTITYGROUP_KEY);

            PropertyUtils.copyProperties(theform, entityGroup);

            theform.setTransId(Constants.CREATE_KEY);
            request.setAttribute(SessionNames.ENTITYGROUP_KEY, entityGroup);
            return mapping.getInputForward();
        }

        PropertyUtils.copyProperties(theform, entityGroup);
        // the following step will occur when in a one2many relation
        entityGroup.setEntities(emsService.getAllEntities(entityGroup.getInstanceRrn()));
        theform.setTransId(Constants.MODIFY_KEY);
        request.setAttribute(SessionNames.ENTITYGROUP_KEY, entityGroup);
        return mapping.getInputForward();
    }

    @Override
    public ActionForward cancel(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        if (mapping.getAttribute() != null) {
            request.removeAttribute(mapping.getAttribute());
        }
        EntityGroupInfoForm theform = (EntityGroupInfoForm) form;
        request.removeAttribute(SessionNames.ENTITYGROUP_KEY);
        theform.setInstanceId("");
        return mapping.getInputForward();
    }

    public ActionForward modify(ActionMapping mapping, EntityGroupInfoForm theform, HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        String user = LocalContext.getUserId();
        long facilityRrn = LocalContext.getFacilityRrn();
        EntityGroup entityGroup = new EntityGroup(theform.getInstanceId(), getNamedSpace(ObjectList.ENTITYGROUP_KEY,
                                                                                         LocalContext.getFacilityRrn()),
                                                  ObjectList.ENTITYGROUP_KEY);

        PropertyUtils.copyProperties(entityGroup, theform);

        entityGroup.setInstanceRrn(getInstanceRrn(theform.getInstanceId(), getNamedSpace(ObjectList.ENTITYGROUP_KEY,
                                                                                         LocalContext.getFacilityRrn()),
                                                  ObjectList.ENTITYGROUP_KEY));

        entityGroup.setTransPerformedby(user);
        if (theform.getRoleId().trim().length() > 0) {
            long roleRrn = getInstanceRrn(theform.getRoleId().trim(), getNamedSpace(ObjectList.ROLE_KEY, facilityRrn),
                                          ObjectList.ROLE_KEY);
            Assert.isFalse(roleRrn <= 0,
                           Errors.create().key(MessageIdList.SYSTEM_INSTANCE_NOT_FOUND).content("{} 没有找到对象!")
                                 .args("Role").build());
            entityGroup.setRoleRrn(roleRrn);
        } else {
            entityGroup.setRoleRrn(null);
        }
        entityGroup.setTransId(Constants.MODIFY_KEY);

        // no matter add or modify, they all execute the same function
        process(entityGroup);

        // just for logic equals tag
        theform.setTransId(Constants.MODIFY_KEY);
        theform.setOperationSuccess("true");

        entityGroup.setEntities(emsService.getAllEntities(entityGroup.getInstanceRrn()));
        request.setAttribute(SessionNames.ENTITYGROUP_KEY, entityGroup);
        WebUtils.setSuccessMsg(request);
        return mapping.getInputForward();
    }

    public ActionForward create(ActionMapping mapping, EntityGroupInfoForm theform, HttpServletRequest request) {
        String user = LocalContext.getUserId();
        long facilityRrn = LocalContext.getFacilityRrn();
        EntityGroup entityGroup = new EntityGroup(theform.getInstanceId(), getNamedSpace(ObjectList.ENTITYGROUP_KEY,
                                                                                         LocalContext.getFacilityRrn()),
                                                  ObjectList.ENTITYGROUP_KEY);

        PropertyUtils.copyProperties(entityGroup, theform);

        entityGroup.setInstanceRrn(getInstanceRrn(theform.getInstanceId(), getNamedSpace(ObjectList.ENTITYGROUP_KEY,
                                                                                         LocalContext.getFacilityRrn()),
                                                  ObjectList.ENTITYGROUP_KEY));

        entityGroup.setTransPerformedby(user);
        if (theform.getRoleId().trim().length() > 0) {
            long roleRrn = getInstanceRrn(theform.getRoleId().trim(), getNamedSpace(ObjectList.ROLE_KEY, facilityRrn),
                                          ObjectList.ROLE_KEY);
            Assert.isFalse(roleRrn <= 0,
                           Errors.create().key(MessageIdList.SYSTEM_INSTANCE_NOT_FOUND).content("{} 没有找到对象!")
                                 .args("Role").build());
            entityGroup.setRoleRrn(roleRrn);
        } else {
            entityGroup.setRoleRrn(null);
        }
        entityGroup.setTransId(Constants.CREATE_KEY);

        // no matter add or modify, they all execute the same function
        process(entityGroup);

        // just for logic equals tag
        theform.setTransId(Constants.MODIFY_KEY);
        theform.setOperationSuccess("true");

        entityGroup.setEntities(emsService.getAllEntities(entityGroup.getInstanceRrn()));
        request.setAttribute(SessionNames.ENTITYGROUP_KEY, entityGroup);
        WebUtils.setSuccessMsg(request);
        return mapping.getInputForward();
    }

    public ActionForward delete(ActionMapping mapping, EntityGroupInfoForm theform, HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        String user = LocalContext.getUserId();
        long facilityRrn = LocalContext.getFacilityRrn();
        EntityGroup entityGroup = new EntityGroup(theform.getInstanceId(), getNamedSpace(ObjectList.ENTITYGROUP_KEY,
                                                                                         LocalContext.getFacilityRrn()),
                                                  ObjectList.ENTITYGROUP_KEY);

        PropertyUtils.copyProperties(entityGroup, theform);

        entityGroup.setInstanceRrn(getInstanceRrn(theform.getInstanceId(), getNamedSpace(ObjectList.ENTITYGROUP_KEY,
                                                                                         LocalContext.getFacilityRrn()),
                                                  ObjectList.ENTITYGROUP_KEY));

        entityGroup.setTransPerformedby(user);
        if (theform.getRoleId().trim().length() > 0) {
            long roleRrn = getInstanceRrn(theform.getRoleId().trim(), getNamedSpace(ObjectList.ROLE_KEY, facilityRrn),
                                          ObjectList.ROLE_KEY);
            Assert.isFalse(roleRrn <= 0,
                           Errors.create().key(MessageIdList.SYSTEM_INSTANCE_NOT_FOUND).content("{} 没有找到对象!")
                                 .args("Role").build());
            entityGroup.setRoleRrn(roleRrn);
        } else {
            entityGroup.setRoleRrn(null);
        }

        // add by Bright for chint 添加设备组删除的判断,如果设备组正被使用,不允许删除
        String entityGroupId = theform.getInstanceId();
        long entityGroupRrn = 0;

        if (StringUtils.isNotEmpty(entityGroupId)) {
            entityGroupId = entityGroupId.trim().toUpperCase();
            entityGroupRrn = this.getInstanceRrn(entityGroupId, facilityRrn, "ENTITYGROUP");
        }
        Assert.isFalse(entityGroupRrn < 1,
                       Errors.create().key(MessageIdList.ENTITYGROUP_INVALID_ID).content("Invalid EQP group id!")
                             .build());

        List<Operation> operations = emsService.getOperationsByEntityGroup(entityGroupRrn);
        Assert.isFalse(operations != null && !operations.isEmpty(),
                       Errors.create().key(MessageIdList.ENTITYGROUP_HAS_STEPS).content("此设备组正被步骤使用中").build());


        Assert.isFalse(emsService.getEntitiesFromEntityToEntityGroup(entityGroupRrn).size() > 0,
                       Errors.create().key(MessageIdList.ENTITYGROUP_HAS_EQUIPMENT).content("此设备组中存在设备,无法删除!").build());

        entityGroup.setTransId(Constants.DELETE_KEY);
        request.setAttribute("deletedFlag", "1");

        // no matter add or modify, they all execute the same function
        process(entityGroup);

        // just for logic equals tag
        theform.setTransId(Constants.CREATE_KEY);
        theform.setInstanceId("");
        WebUtils.setSuccessMsg(request);
        entityGroup.setEntities(emsService.getAllEntities(entityGroup.getInstanceRrn()));
        request.setAttribute(SessionNames.ENTITYGROUP_KEY, entityGroup);
        return init(mapping, theform, request, response);
    }

    /**
     * 分页
     **/
    public ActionForward pagination(ActionMapping mapping, EntityGroupInfoForm theform, HttpServletRequest request) {
        String user = LocalContext.getUserId();
        long facilityRrn = LocalContext.getFacilityRrn();
        EntityGroup entityGroup = new EntityGroup(theform.getInstanceId(), getNamedSpace(ObjectList.ENTITYGROUP_KEY,
                                                                                         LocalContext.getFacilityRrn()),
                                                  ObjectList.ENTITYGROUP_KEY);

        PropertyUtils.copyProperties(entityGroup, theform);

        entityGroup.setInstanceRrn(getInstanceRrn(theform.getInstanceId(), getNamedSpace(ObjectList.ENTITYGROUP_KEY,
                                                                                         LocalContext.getFacilityRrn()),
                                                  ObjectList.ENTITYGROUP_KEY));

        entityGroup.setTransPerformedby(user);
        if (theform.getRoleId().trim().length() > 0) {
            long roleRrn = getInstanceRrn(theform.getRoleId().trim(), getNamedSpace(ObjectList.ROLE_KEY, facilityRrn),
                                          ObjectList.ROLE_KEY);
            Assert.isFalse(roleRrn <= 0,
                           Errors.create().key(MessageIdList.SYSTEM_INSTANCE_NOT_FOUND).content("{} 没有找到对象!")
                                 .args("Role").build());
            entityGroup.setRoleRrn(roleRrn);
        } else {
            entityGroup.setRoleRrn(null);
        }
        this.processItemAction(request, theform);

        theform.setTransId(Constants.MODIFY_KEY);
        return mapping.getInputForward();
    }

    public ActionForward members(ActionMapping mapping, EntityGroupInfoForm theform, HttpServletRequest request) {
        theform.setTransId(Constants.MODIFY_KEY);

        EntityGroup entityGroup = new EntityGroup(theform.getInstanceId(), getNamedSpace(ObjectList.ENTITYGROUP_KEY,
                                                                                         LocalContext.getFacilityRrn()),
                                                  ObjectList.ENTITYGROUP_KEY);

        entityGroup = (EntityGroup) getInstance(entityGroup);

        long entityRrn = 0;
        Relation relation = new Relation();
        Relation parentRelation = null;

        // if (Constants.UPDATE_KEY.equals(request.getParameter(Constants.MEMBERS_KEY))) {
        //     // 修改
        //     entityRrn = new Long(request.getParameter(Constants.ITEM_KEY));
        //     relation.setTransId(Constants.UPDATE_KEY);
        //     if (request.getParameter(Constants.LIKETYPE_KEY).equals(LinkTypeList.ENTITY_ENTITYROUP_KEY)) {
        //         relation.setLinkType(LinkTypeList.ENTITY_GROUP_INACTIVE_KEY);
        //     } else {
        //         relation.setLinkType(LinkTypeList.ENTITY_ENTITYROUP_KEY);
        //     }
        //     emsService.updateRel4EntityGroupToEntityLT(relation.getLinkType(), entityRrn, entityGroup.getInstanceRrn(),
        //                                                request.getParameter(Constants.LIKETYPE_KEY));
        // } else
        if (Constants.DELETE_KEY.equals(request.getParameter(Constants.MEMBERS_KEY))) {
            // 删除
            if (request.getParameter(Constants.ITEM_KEY) != null) {
                entityRrn = new Long(request.getParameter(Constants.ITEM_KEY));
                relation.setTransId(Constants.DELETE_KEY);
            }
        } else {
            // 新增
            String entityId = theform.getEntityId().trim().toUpperCase();

            Assert.isFalse(StringUtils.isBlank(entityId),
                           Errors.create().key(MessageIdList.ENTITYGROUP_MISSING_ENTITY_ID).content("设备号不能为空").build());

            entityRrn = getInstanceRrn(entityId, getNamedSpace(ObjectList.ENTITY_KEY, LocalContext.getFacilityRrn()),
                                       ObjectList.ENTITY_KEY);

            // if no such user exist, do nothing
            Assert.isFalse(entityRrn <= 0,
                           Errors.create().key(MessageIdList.ENTITYGROUP_INVALID_ENTITY).content("设备号无效").build());

            List<Relation> entities = emsService.getAllEntities(entityGroup.getInstanceRrn());
            if (entities != null & entities.size() > 0) {
                boolean grpIsChamgberGrp = false;
                for (Relation entity : entities) {
                    Map entityExtMap = emsService.getEquipmentExtMap(entity.getInstanceRrn());
                    if (StringUtils.equalsIgnoreCase(StringUtils.STRING_ON,
                                                     MapUtils.getString(entityExtMap, "isChamberEquip"))) {
                        grpIsChamgberGrp = true;
                        break;
                    }
                }

                boolean isChamberEquip = false;
                Map entityExtMap = emsService.getEquipmentExtMap(entityRrn);
                if (StringUtils
                        .equalsIgnoreCase(StringUtils.STRING_ON, MapUtils.getString(entityExtMap, "isChamberEquip"))) {
                    isChamberEquip = true;
                }

                if (MapUtils.getLongValue(entityExtMap, "parentEqptRrn") > 0) {
                    Map parentEquipMap = emsService
                            .getEquipmentExtMap(MapUtils.getLongValue(entityExtMap, "parentEqptRrn"));
                    if (StringUtils.equalsIgnoreCase(StringUtils.STRING_ON,
                                                     MapUtils.getString(parentEquipMap, "isChamberEquip"))) {
                        isChamberEquip = true;
                        parentRelation = new Relation();
                        parentRelation.setFromRrn(MapUtils.getLong(entityExtMap, "parentEqptRrn"));
                        parentRelation.setToRrn(new Long(entityGroup.getInstanceRrn()));
                        parentRelation.setLinkType(LinkTypeList.ENTITY_ENTITYROUP_KEY);
                    }
                }

                Assert.isFalse(isChamberEquip && !grpIsChamgberGrp,
                               Errors.create().key(MessageIdList.CHAMBER_FORBID_PUT_GRP).content("chamber不能放进此设备组")
                                     .build());

                Assert.isFalse(!isChamberEquip && grpIsChamgberGrp,
                               Errors.create().key(MessageIdList.ENTITYGROUP_PUT_CHAMBER_EQP)
                                     .content("此设备组应该放进chamber中").build());
            } else {
                Map entityExtMap = emsService.getEquipmentExtMap(entityRrn);
                if (MapUtils.getLongValue(entityExtMap, "parentEqptRrn") > 0) {
                    Map parentEquipMap = emsService
                            .getEquipmentExtMap(MapUtils.getLongValue(entityExtMap, "parentEqptRrn"));
                    if (StringUtils.equalsIgnoreCase(StringUtils.STRING_ON,
                                                     MapUtils.getString(parentEquipMap, "isChamberEquip"))) {
                        parentRelation = new Relation();
                        parentRelation.setFromRrn(MapUtils.getLong(entityExtMap, "parentEqptRrn"));
                        parentRelation.setToRrn(entityGroup.getInstanceRrn());
                        parentRelation.setLinkType(LinkTypeList.ENTITY_ENTITYROUP_KEY);
                    }
                }
            }
            relation.setLinkType(LinkTypeList.ENTITY_ENTITYROUP_KEY);
            relation.setTransId(Constants.CREATE_KEY);
        }

        // constructs the relation object
        relation.setFromRrn(entityRrn);
        relation.setToRrn(entityGroup.getInstanceRrn());

        if ((theform.getDefaultFlag() != null) && theform.getDefaultFlag().equalsIgnoreCase(StringUtils.STRING_ON)) {
            relation.setAttributedata1(BooleanUtils.toIntegerObject(true).toString());
        } else {
            relation.setAttributedata1(BooleanUtils.toIntegerObject(false).toString());
        }

        processDetails(relation);

        if (parentRelation != null) {
            Relation tmp = baseService.getRelation(parentRelation);
            if (tmp == null || tmp.getFromRrn() <= 0) {
                emsService.addEntityToEntityGroup(parentRelation.getToRrn(), parentRelation.getFromRrn());
            }
        }

        entityGroup.setEntities(emsService.getAllEntities(entityGroup.getInstanceRrn()));
        theform.setEntityId("");
        theform.setDefaultFlag("");

        // clear add object
        theform.setEntityId(null);
        request.setAttribute(SessionNames.ENTITYGROUP_KEY, entityGroup);
        WebUtils.setSuccessMsg(request);
        return mapping.getInputForward();
    }

    public ActionForward copy(ActionMapping mapping, EntityGroupInfoForm theform,
                              HttpServletRequest request) throws Exception {
        Assert.isFalse(theform.getInstanceId() == null || "".equals(theform.getInstanceId()),
                       Errors.create().key(MessageIdList.RETICLE_ENTER_ID).content("请输入ID或者按下回车键确认ID号!").build());
        EntityGroup entityGroup = new EntityGroup(theform.getInstanceId(), getNamedSpace(ObjectList.ENTITYGROUP_KEY,
                                                                                         LocalContext.getFacilityRrn()),
                                                  ObjectList.ENTITYGROUP_KEY);

        PropertyUtils.copyProperties(entityGroup, theform);

        String id = request.getParameter(Constants.COPY_KEY);

        entityGroup.setInstanceId(id);

        doCopy(theform, entityGroup);
        // for logic equal tag, copy is the same action as create
        theform.setTransId(Constants.CREATE_KEY);

        return mapping.getInputForward();
    }

    private void processDetails(Relation relation) {
        String action = relation.getTransId();

        if (action.equals(Constants.CREATE_KEY)) {
            emsService.addEntityToEntityGroup(relation.getToRrn(), relation.getFromRrn());
        } else if (action.equals(Constants.DELETE_KEY)) {
            emsService.removeEntityFromGroup(relation.getToRrn(), relation.getFromRrn());
        }
    }

}