com.jeans.iservlet.controller.impl.AssetsController.java Source code

Java tutorial

Introduction

Here is the source code for com.jeans.iservlet.controller.impl.AssetsController.java

Source

package com.jeans.iservlet.controller.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.annotation.JsonView;
import com.jeans.iservlet.controller.BaseController;
import com.jeans.iservlet.enums.hr.HRTreeType;
import com.jeans.iservlet.model.AssetConstants;
import com.jeans.iservlet.model.asset.Asset;
import com.jeans.iservlet.model.asset.Hardware;
import com.jeans.iservlet.model.asset.Software;
import com.jeans.iservlet.model.hr.Employee;
import com.jeans.iservlet.model.hr.HRUnit;
import com.jeans.iservlet.service.asset.AssetService;
import com.jeans.iservlet.service.hr.HRService;
import com.jeans.iservlet.utils.TreeUtils;
import com.jeans.iservlet.view.ViewFactory;
import com.jeans.iservlet.view.ViewFactory.DataGrid;
import com.jeans.iservlet.view.ViewFilters;
import com.jeans.iservlet.view.ViewSorter;
import com.jeans.iservlet.view.asset.AssetValidateResult;
import com.jeans.iservlet.view.asset.AssetView;
import com.jeans.iservlet.view.asset.HardwareView;
import com.jeans.iservlet.view.asset.SoftwareView;
import com.jeans.iservlet.view.hr.HRUnitView;

@Controller
@RequestMapping("/asset")
public class AssetsController extends BaseController {
    @Autowired
    private AssetService assetService;

    @Autowired
    private HRService hrService;

    /**
     * ?idtype?
     * 
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/load-asset")
    @ResponseBody
    public ModelMap loadAsset(@RequestParam long id, @RequestParam byte type) {
        return type == AssetConstants.HARDWARE_ASSET
                ? new ModelMap("data",
                        ViewFactory.createView(Hardware.class, HardwareView.class, assetService.loadHardware(id)))
                : new ModelMap("data",
                        ViewFactory.createView(Software.class, SoftwareView.class, assetService.loadSoftware(id)));
    }

    /**
     * ?
     * 
     * @param type
     *            ??
     * @param page
     *            ?
     * @param rows
     *            ?
     * @param sort
     *            ?null??
     * @param order
     *            ??ascdesc
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/list-assets")
    @ResponseBody
    public DataGrid<? extends AssetView> listAssets(@RequestParam byte type, @RequestParam String filters,
            @RequestParam int page, @RequestParam int rows, @RequestParam(required = false) String sort,
            @RequestParam(required = false) String order) {
        long[] total = new long[1];
        if (AssetConstants.HARDWARE_ASSET == AssetConstants.getAssetType(type)) {
            List<Hardware> assets = assetService.listAssets(Hardware.class, getCurrentCompany(), type,
                    parseFilters(filters), page, rows, total);
            List<HardwareView> views = ViewFactory.createViewList(Hardware.class, HardwareView.class, assets);
            if (null != sort) {
                ViewSorter.sort(views, ViewSorter.createSortField(HardwareView.class, sort, order));
            }
            return ViewFactory.createDataGrid(HardwareView.class, views, total[0]);
        } else {
            List<Software> assets = assetService.listAssets(Software.class, getCurrentCompany(), type,
                    parseFilters(filters), page, rows, total);
            List<SoftwareView> views = ViewFactory.createViewList(Software.class, SoftwareView.class, assets);
            if (null != sort) {
                ViewSorter.sort(views, ViewSorter.createSortField(SoftwareView.class, sort, order));
            }
            return ViewFactory.createDataGrid(SoftwareView.class, views, total[0]);
        }
    }

    private Map<String, Object> parseFilters(String filters) {
        Map<String, Object> ret = new HashMap<String, Object>();
        String[] fs = filters.split("&");
        Set<String> vendors = new HashSet<String>();
        String[] vs = fs[0].split(",");
        for (String v : vs) {
            if (!StringUtils.isBlank(v)) {
                vendors.add(v);
            }
        }
        ret.put("vendor", vendors);
        Calendar start = Calendar.getInstance();
        try {
            start.set(Calendar.YEAR, Integer.parseInt(fs[1]));
            start.set(Calendar.MONTH, Calendar.JANUARY);
            start.set(Calendar.DATE, 1);
            start.set(Calendar.HOUR_OF_DAY, 0);
            start.set(Calendar.MINUTE, 0);
            start.set(Calendar.SECOND, 0);
            start.set(Calendar.MILLISECOND, 0);
            ret.put("purchaseTimeStart", start.getTime());
        } catch (Exception e) {
            ret.put("purchaseTimeStart", null);
        }
        Calendar end = Calendar.getInstance();
        try {
            end.set(Calendar.YEAR, Integer.parseInt(fs[2]));
            end.set(Calendar.MONTH, Calendar.DECEMBER);
            end.set(Calendar.DATE, 31);
            end.set(Calendar.HOUR_OF_DAY, 23);
            end.set(Calendar.MINUTE, 59);
            end.set(Calendar.SECOND, 59);
            end.set(Calendar.MILLISECOND, 999);
            ret.put("purchaseTimeEnd", end.getTime());
        } catch (Exception e) {
            ret.put("purchaseTimeEnd", null);
        }
        try {
            ret.put("state", Byte.parseByte(fs[3]));
        } catch (Exception e) {
            ret.put("state", (byte) 9);
        }
        if (fs.length == 6) { // : warranty, importance
            try {
                ret.put("warranty", Byte.parseByte(fs[5]));
            } catch (Exception e) {
                ret.put("warranty", (byte) 9);
            }
            try {
                ret.put("importance", Byte.parseByte(fs[6]));
            } catch (Exception e) {
                ret.put("importance", (byte) 9);
            }
        } else if (fs.length == 5) { // : softwareType
            try {
                ret.put("softwareType", Byte.parseByte(fs[4]));
            } catch (Exception e) {
                ret.put("softwareType", (byte) 9);
            }
        }
        return ret;
    }

    /**
     * ??
     * 
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/departments")
    @ResponseBody
    @JsonView(ViewFilters.HRSummary.class)
    public List<HRUnitView> listDepartments() {
        return TreeUtils.expand(
                hrService.loadHRTree(getCurrentCompany().getId(), HRTreeType.DepartmentsTree, false, false), 1);
    }

    /**
     * ?
     * 
     * @param deptId
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/employees")
    @ResponseBody
    @JsonView(ViewFilters.HRSummary.class)
    public List<HRUnitView> listEmployees(@RequestParam("id") long deptId) {
        return hrService.listEmployees(deptId, false);
    }

    /**
     * 
     * ???<br>
     * <ul>
     * 
     * <li> -> /
     * <li> -> /
     * <li> -> null <br>
     * </ul>
     * <ul>
     * (???)
     * <li> -> //
     * <li> -> //
     * <li> -> //?
     * <li> -> ?
     * <li>? -> null <br>
     * </ul>
     * ???
     * 
     * @param ids
     *            ids
     * @param type
     *            , AssetConstants.HARDWARE_ASSETAssetConstants.SOFTWARE_ASSET
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/check-states")
    @ResponseBody
    public Set<Byte> checkStates(@RequestParam String ids, @RequestParam byte type) {
        return assetService.checkNextStates(splitIds(ids), type);
    }

    /**
     * ?
     * 
     * @param ids
     *            ids
     * @param type
     *            , AssetConstants.HARDWARE_ASSETAssetConstants.SOFTWARE_ASSET
     * @param newState
     *            ?
     * @param ownerId
     *            id
     * @param keepOldOwner
     *            ??
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/change-state")
    @ResponseBody
    public int changeState(@RequestParam String ids, @RequestParam byte type, @RequestParam("state") byte newState,
            @RequestParam("owner") long ownerId, @RequestParam("keep") boolean keepOldOwner) {
        return assetService.changeState(splitIds(ids), type, newState,
                (Employee) hrService.loadUnitByType(ownerId, HRUnit.EMPLOYEE), keepOldOwner, getCurrentEmployee());
    }

    @RequestMapping(method = RequestMethod.POST, value = "/load-props")
    @ResponseBody
    public Map<String, Object> loadProperties(@RequestParam String ids, @RequestParam byte type) {
        return mergeProps(assetService.listAssets(splitIds(ids), type));
    }

    /**
     * ??<br>
     * ?propskey?<br>
     * ?propskeyvalue==nullvalue?????null<br>
     * 
     * @param asset
     */
    private Map<String, Object> mergeProps(List<Asset> assets) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> props = new HashMap<String, Object>();
        for (Asset asset : assets) {
            merge("name", asset.getName(), props);
            merge("vendor", asset.getVendor(), props);
            merge("modelOrVersion", asset.getModelOrVersion(), props);
            merge("assetUsage", asset.getAssetUsage(), props);
            merge("purchaseTime", null == asset.getPurchaseTime() ? null : sdf.format(asset.getPurchaseTime()),
                    props);
            merge("quantity", asset.getQuantity(), props);
            merge("cost", asset.getCost(), props);
            merge("comment", asset.getComment(), props);
            if (asset instanceof Hardware) {
                merge("code", ((Hardware) asset).getCode(), props);
                merge("financialCode", ((Hardware) asset).getFinancialCode(), props);
                merge("sn", ((Hardware) asset).getSn(), props);
                merge("configuration", ((Hardware) asset).getConfiguration(), props);
                merge("warranty", ((Hardware) asset).getWarranty(), props);
                merge("location", ((Hardware) asset).getLocation(), props);
                merge("ip", ((Hardware) asset).getIp(), props);
                merge("importance", ((Hardware) asset).getImportance(), props);
            } else if (asset instanceof Software) {
                merge("softwareType", ((Software) asset).getSoftwareType(), props);
                merge("license", ((Software) asset).getLicense(), props);
                merge("expiredTime", null == ((Software) asset).getExpiredTime() ? null
                        : sdf.format(((Software) asset).getExpiredTime()), props);
            }
        }
        return props;
    }

    private void merge(String key, Object value, Map<String, Object> props) {
        if (null == value) {
            // null??purchaseTimeexpiredTime?null??
            props.put(key, value);
        } else {
            if (props.containsKey(key)) {
                // ?propskey
                Object oldValue = props.get(key);
                if (null != oldValue && !value.equals(oldValue)) {
                    // ?null?merge?
                    // value??null?
                    props.put(key, null);
                }
                // ??null????value???props??
            } else {
                // propskey??
                props.put(key, value);
            }
        }
    }

    /**
     * ???Map??String???????null
     * 
     * @return
     * @throws Exception
     */
    private Map<String, Object> transProps(Map<String, String> props) throws Exception {
        Map<String, Object> p = new HashMap<String, Object>();
        Set<String> keys = props.keySet();
        for (String key : keys) {
            String value = props.get(key);
            if ("expiredTime".equals(key) || "purchaseTime".equals(key)) {
                p.put(key, "".equals(value) ? null : (new SimpleDateFormat("yyyy-MM-dd")).parse(value));
            } else if ("quantity".equals(key) || "number".equals(key)) {
                p.put(key, Integer.parseInt(value));
            } else if ("cost".equals(key)) {
                p.put(key, BigDecimal.valueOf(Double.parseDouble(value)));
            } else if ("warranty".equals(key) || "importance".equals(key) || "softwareType".equals(key)
                    || "type".equals(key) || "catalog".equals(key) || "state".equals(key)) {
                p.put(key, Byte.parseByte(value));
            } else if ("ownerId".equals(key)) {
                p.put("owner", (Employee) hrService.loadUnitByType(Long.parseLong(value), HRUnit.EMPLOYEE));
            } else {
                p.put(key, value);
            }
        }
        if (!p.containsKey("company")) {
            p.put("company", getCurrentCompany());
        }
        return p;
    }

    /**
     * ?
     * 
     * @param ids
     *            ids
     * @param type
     *            
     * @param props
     *            Map?String
     * @return
     * @throws Exception
     */
    @RequestMapping(method = RequestMethod.POST, value = "/save-props")
    @ResponseBody
    public int updateProperties(@RequestParam String ids, @RequestParam byte type,
            @RequestParam Map<String, String> props) throws Exception {
        return assetService.saveProps(splitIds(ids), type, transProps(props));
    }

    /**
     * ??
     * 
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/validate")
    @ResponseBody
    public Map<String, String> validate() {
        Map<String, String> validation = new LinkedHashMap<String, String>();
        List<AssetValidateResult> v = assetService.validate(getCurrentCompany());
        for (AssetValidateResult r : v) {
            StringBuilder builder = new StringBuilder("<li>");
            switch (r.getResult()) {
            case AssetConstants.INVALID_OWNER:
                builder.append("").append(r.getAssetCatalogName()).append("<span>[")
                        .append(r.getAssetFullName()).append("]</span>??");
                break;
            case AssetConstants.IN_USE_ASSET_OWNED_BY_FORMER_EMPLOYEE:
                builder.append("").append(r.getAssetCatalogName()).append("<span>[")
                        .append(r.getAssetFullName())
                        .append("]</span>?<span>[")
                        .append(r.getOwnerName()).append("]</span>???");
                break;
            case AssetConstants.INVALID_OWNER_COMPANY:
                builder.append("").append(r.getAssetCatalogName()).append("<span>[")
                        .append(r.getAssetFullName()).append("]</span><span>[")
                        .append(r.getOwnerName()).append("]</span><span>[").append(r.getOwnerCompanyName())
                        .append("]</span>???&emsp;<a href=\"javascript:void(0);\" class=\"_Chcmp\">?</a>");
                break;
            case AssetConstants.IN_USE_ASSET_WITHOUT_OWNER:
                builder.append("").append(r.getAssetCatalogName()).append("<span>[")
                        .append(r.getAssetFullName())
                        .append("]</span>??");
            }
            builder.append(
                    "&emsp;<a href=\"javascript:void(0);\" class=\"_ShowAst\"></a>&emsp;<a href=\"javascript:void(0);\" class=\"_Chown\"></a>&emsp;<a href=\"javascript:void(0);\" class=\"_SetIdle\"></a></li>");
            validation.put(Long.toString(r.getId()), builder.toString());
        }
        return validation;
    }

    /**
     * ???? adjustType: 0=(???owner); 1=; 2=??
     * 
     * @param id
     *            id
     * @param adjustType
     *            ?0=(???ownerId?), 1=, 2=??
     * @param ownerId
     *            idadjustType==0????
     * @return
     */
    @RequestMapping(method = RequestMethod.POST, value = "/adjust")
    @ResponseBody
    public int adjust(@RequestParam long id, @RequestParam byte adjustType,
            @RequestParam(value = "owner", defaultValue = "0") long ownerId) {
        return assetService.adjust(id, adjustType, (Employee) hrService.loadUnitByType(ownerId, HRUnit.EMPLOYEE));
    }

    /**
     * ??number
     * 
     * @param props
     *            ??
     * @return
     * @throws Exception
     */
    @RequestMapping(method = RequestMethod.POST, value = "/create")
    @ResponseBody
    public int updateProperties(@RequestParam Map<String, String> props) throws Exception {
        return assetService.createNewAssets(transProps(props)).size();
    }
}