com.wiiyaya.provider.main.service.impl.ResourceServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.wiiyaya.provider.main.service.impl.ResourceServiceImpl.java

Source

/*
 * Copyright 2016-2017 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wiiyaya.provider.main.service.impl;

import com.mysema.query.jpa.JPQLQuery;
import com.wiiyaya.framework.common.exception.BusinessException;
import com.wiiyaya.framework.common.model.CurrUserDto;
import com.wiiyaya.framework.common.model.easyui.EasyUiComboBox;
import com.wiiyaya.framework.common.model.easyui.EasyUiDataGrid;
import com.wiiyaya.framework.common.model.easyui.EasyUiTree;
import com.wiiyaya.framework.common.utils.CollectionUtils;
import com.wiiyaya.framework.common.utils.StringUtils;
import com.wiiyaya.framework.provider.tools.JF;
import com.wiiyaya.framework.provider.utils.ConsumerUtils;
import com.wiiyaya.provider.main.constant.MainConstant;
import com.wiiyaya.provider.main.entity.Privilege;
import com.wiiyaya.provider.main.entity.Resource;
import com.wiiyaya.provider.main.enums.ResourceType;
import com.wiiyaya.provider.main.model.ResourceDto;
import com.wiiyaya.provider.main.repository.PrivilegeDao;
import com.wiiyaya.provider.main.repository.ResourceDao;
import com.wiiyaya.provider.main.repository.querydsl.ResourceQry;
import com.wiiyaya.provider.main.service.ResourceService;
import org.apache.commons.collections4.IterableUtils;
import org.apache.commons.collections4.Predicate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service("resourceService")
public class ResourceServiceImpl implements ResourceService, InitializingBean {

    private static final Logger LOG = LoggerFactory.getLogger(ResourceServiceImpl.class);

    @Autowired
    private ResourceDao resourceDao;

    @Autowired
    private PrivilegeDao privilegeDao;

    private Map<Long, ResourceDto> mainMenu = new LinkedHashMap<>();
    private Map<Long, ResourceDto> childMenu = new LinkedHashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        List<Resource> resources = resourceDao.findAllMenu();
        List<EasyUiTree> allNodes = new ArrayList<>();
        List<EasyUiTree> middleNodes = new ArrayList<>();

        for (Resource resource : resources) {
            if (resource.getParentId() == null) {
                mainMenu.put(resource.getId(), prepareNode(resource));
            } else if (resource.getLeaf()) {
                childMenu.put(resource.getId(), prepareNode(resource));
            }
        }
    }

    @Override
    public List<ResourceDto> getUserAuthoritiesMainMenu() throws BusinessException {
        List<Long> menuIds = resourceDao
                .findMainByPrivileges_IdIn(ConsumerUtils.<CurrUserDto>getCurrUser().getAuthoritieIds());
        List<ResourceDto> mainNodes = new ArrayList<>();
        for (Map.Entry<Long, ResourceDto> menu : mainMenu.entrySet()) {
            if (menuIds.contains(menu.getKey())) {
                mainNodes.add(menu.getValue());
            }
        }
        return mainNodes;
    }

    @Override
    public List<ResourceDto> getUserAuthoritiesChildMenu(Long menuId) {
        List<Long> menuIds = resourceDao
                .findChildByPrivileges_IdIn(ConsumerUtils.<CurrUserDto>getCurrUser().getAuthoritieIds(), menuId);
        List<ResourceDto> childNodes = new ArrayList<>();
        for (Map.Entry<Long, ResourceDto> menu : childMenu.entrySet()) {
            if (menuIds.contains(menu.getKey())) {
                childNodes.add(menu.getValue());
            }
        }
        return childNodes;
    }

    private ResourceDto prepareNode(Resource resource) {
        ResourceDto dto = new ResourceDto();
        dto.setId(resource.getId());
        dto.setName(resource.getName());
        dto.setUrl(resource.getUrl());
        return dto;
    }

    @Override
    public String[] getNoNeedAuthResources() {
        List<String> resources = resourceDao.findNoNeedAuthResources();
        return resources.toArray(new String[resources.size()]);
    }

    @Override
    @Transactional(readOnly = true)
    public Map<String, String[]> getNeedAuthResources() {
        List<Resource> resources = resourceDao.findNeedAuthResources();

        Map<String, String[]> resourcePrivilegeMap = new HashMap<>();
        Set<Privilege> privileges;

        for (Resource resource : resources) {
            privileges = resource.getPrivileges();
            if (CollectionUtils.isEmpty(privileges)) {
                LOG.warn("Resource [" + resource.getId() + "] no privilege has been found!");
                continue;
            }

            String[] privilegeNames = new String[privileges.size()];
            int i = 0;
            for (Privilege privilege : privileges) {
                privilegeNames[i] = privilege.getCode();
                i = i + 1;
            }
            resourcePrivilegeMap.put(resource.getUrl(), privilegeNames);
        }
        return resourcePrivilegeMap;
    }

    @Override
    public EasyUiDataGrid<ResourceDto> getAllResources(final ResourceDto resourceDto, Pageable pageRequest) {
        List<ResourceDto> resourceDtoList = new ArrayList<>();
        Page<Resource> resourceDbs = resourceDao.findAllJF(new JF() {
            @Override
            public void prepareQry(JPQLQuery qry, boolean notCountQry) {
                ResourceQry.searchResource(qry, notCountQry, resourceDto);
            }
        }, pageRequest);
        for (Resource resourceDb : resourceDbs) {
            ResourceDto dto = new ResourceDto();

            dto.setId(resourceDb.getId());
            dto.setName(resourceDb.getName());
            dto.setUrl(resourceDb.getUrl());
            dto.setType(resourceDb.getType());
            dto.setAuthType(resourceDb.getAuthType());
            dto.setLeaf(resourceDb.getLeaf());
            dto.setOrders(resourceDb.getOrders());
            dto.setParentId(resourceDb.getParentId());
            dto.setParentName(resourceDb.getParentName());
            resourceDtoList.add(dto);
        }
        return new EasyUiDataGrid<>(resourceDtoList, resourceDbs.getTotalElements());
    }

    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public void saveResource(ResourceDto resourceDto) throws BusinessException {
        if (resourceDao.isUrlExists(resourceDto.getUrl()) > 0) {
            throw new BusinessException(MainConstant.ERROR_RESOURCE_URL_EXISTS);
        }
        Resource resource = new Resource();
        resource.setName(resourceDto.getName());
        resource.setUrl(resourceDto.getUrl());
        resource.setType(resourceDto.getType());
        resource.setAuthType(resourceDto.getAuthType());
        if (resourceDto.getType() == ResourceType.M) {
            checkAndSetMenuInfo(resource, resourceDto);
        }

        resourceDao.save(resource);
    }

    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public void updateResource(ResourceDto resourceDto) throws BusinessException {
        Resource resourceDb = resourceDao.findOne(resourceDto.getId());
        if (resourceDb == null) {
            throw new BusinessException(MainConstant.ERROR_RESOURCE_NOT_FOUND);
        }
        resourceDb.setVersion(resourceDto.getVersion());// ??????

        resourceDb.setName(resourceDto.getName());
        resourceDb.setUrl(resourceDto.getUrl());
        resourceDb.setType(resourceDto.getType());
        resourceDb.setAuthType(resourceDto.getAuthType());

        if (resourceDto.getType() == ResourceType.M) {//??
            checkAndSetMenuInfo(resourceDb, resourceDto);
        } else {
            resourceDb.setLeaf(null);
            resourceDb.setOrders(null);
            resourceDb.setParentId(null);
            resourceDb.setParentName(null);
        }
        resourceDao.save(resourceDb);
    }

    private void checkAndSetMenuInfo(Resource resource, ResourceDto resourceDto) throws BusinessException {
        if (resourceDto.getParentId() != null) {
            Resource parent = resourceDao.findOne(resourceDto.getParentId());
            if (parent == null) {
                throw new BusinessException(MainConstant.ERROR_RESOURCE_PARENT_NOT_FOUND);
            }
            resource.setParentId(parent.getId());
            resource.setParentName(parent.getName());
        } else {
            resource.setParentId(null);
            resource.setParentName(null);
        }
        resource.setLeaf(resourceDto.getLeaf());
        resource.setOrders(resourceDto.getOrders());
    }

    @Override
    public ResourceDto getResourceById(Long resourceId) throws BusinessException {
        Resource resourceDb = resourceDao.findOne(resourceId);
        if (resourceDb == null) {
            throw new BusinessException(MainConstant.ERROR_RESOURCE_NOT_FOUND);
        }

        ResourceDto resourceDto = new ResourceDto();

        resourceDto.setId(resourceDb.getId());
        resourceDto.setVersion(resourceDb.getVersion());

        resourceDto.setName(resourceDb.getName());
        resourceDto.setUrl(resourceDb.getUrl());
        resourceDto.setLeaf(resourceDb.getLeaf());
        resourceDto.setParentId(resourceDb.getParentId());
        resourceDto.setParentName(resourceDb.getParentName());
        resourceDto.setType(resourceDb.getType());
        resourceDto.setAuthType(resourceDb.getAuthType());
        resourceDto.setOrders(resourceDb.getOrders());

        return resourceDto;
    }

    @Override
    @Transactional(readOnly = true)
    public List<EasyUiTree> getMainResourceTree() {
        List<EasyUiTree> mainMenuTree = new ArrayList<>();
        List<Resource> resources = resourceDao.findMainResource();

        for (Resource resource : resources) {
            mainMenuTree.add(prepareTreeNode(resource));
        }
        return mainMenuTree;
    }

    @Override
    @Transactional(readOnly = true)
    public List<EasyUiTree> getChildResourceTree(Long parentId) {
        Resource parentDb = resourceDao.findOne(parentId);
        List<EasyUiTree> childMenuTree = new ArrayList<>();
        List<Resource> resources = null;
        switch (parentDb.getType()) {
        case M:
            if (!parentDb.getLeaf()) {
                resources = resourceDao.findChildResource(parentId);
            } else {
                resources = resourceDao.findByResource_Id(parentId);
            }
            break;
        case H:
            resources = resourceDao.findByResource_Id(parentId);
            break;
        default:
            break;
        }
        if (resources != null) {
            for (Resource resource : resources) {
                childMenuTree.add(prepareTreeNode(resource));
            }
        }
        return childMenuTree;
    }

    private EasyUiTree prepareTreeNode(Resource resource) {

        EasyUiTree treeNode = new EasyUiTree();
        treeNode.setId(resource.getId().toString());
        treeNode.setParent(StringUtils.defaultString(resource.getParentId(), "0"));
        treeNode.setText(resource.getName());
        switch (resource.getType()) {
        case M:
            if (!resource.getLeaf()) {
                treeNode.setState(EasyUiTree.State.closed);//????
            } else {
                if (resource.getContents().size() > 0) {
                    treeNode.setState(EasyUiTree.State.closed);//??
                } else {
                    treeNode.setState(EasyUiTree.State.open);
                }
            }
            break;
        case H:
            if (resource.getContents().size() > 0) {
                treeNode.setState(EasyUiTree.State.closed);//
            } else {
                treeNode.setState(EasyUiTree.State.open);
            }
            break;
        default:
            treeNode.setState(EasyUiTree.State.open);//
            break;
        }

        treeNode.setChecked(false);

        return treeNode;
    }

    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public void updateResourceAuth(ResourceDto resourceDto) throws BusinessException {
        Resource resourceDb = resourceDao.findOne(resourceDto.getId());
        if (resourceDb == null) {
            throw new BusinessException(MainConstant.ERROR_RESOURCE_NOT_FOUND);
        }
        resourceDb.setVersion(resourceDto.getVersion());

        if (CollectionUtils.isNotEmpty(resourceDto.getPrivilegeIds())) {
            for (Iterator<Privilege> itDb = resourceDb.getPrivileges().iterator(); itDb.hasNext();) {
                final Privilege privilegeDb = itDb.next();
                boolean existInPage = IterableUtils.matchesAny(resourceDto.getPrivilegeIds(),
                        new Predicate<Long>() {
                            @Override
                            public boolean evaluate(Long object) {
                                return privilegeDb.getId().equals(object);
                            }
                        });
                if (!existInPage) {
                    itDb.remove();
                }
            }
            resourceDb.getPrivileges().addAll(privilegeDao.findAll(resourceDto.getPrivilegeIds()));
        } else {
            resourceDb.getPrivileges().clear();
        }
        resourceDao.save(resourceDb);
    }

    @Override
    public List<EasyUiComboBox> getResourceContent(Long resourceId) {
        List<Resource> contentList = resourceDao.findByResource_Id(resourceId);
        List<EasyUiComboBox> auths = new ArrayList<>();
        for (Resource content : contentList) {
            EasyUiComboBox combo = new EasyUiComboBox();
            combo.setValue(content.getId().toString());
            combo.setText(content.getName());
            combo.setGroup(content.getType().getDesc());
            auths.add(combo);
        }
        return auths;
    }

    @Override
    public List<EasyUiComboBox> getOtherResource(Long resourceId) {
        List<Resource> contentList = resourceDao.findWithoutByResources_Id(resourceId);
        List<EasyUiComboBox> auths = new ArrayList<>();
        for (Resource content : contentList) {
            EasyUiComboBox combo = new EasyUiComboBox();
            combo.setValue(content.getId().toString());
            combo.setText(content.getName());
            combo.setGroup(content.getType().getDesc());
            auths.add(combo);
        }
        return auths;
    }

    @Override
    @Transactional(rollbackFor = BusinessException.class)
    public void updateResourceContent(ResourceDto resourceDto) throws BusinessException {
        Resource resourceDb = resourceDao.findOne(resourceDto.getId());
        if (resourceDb == null) {
            throw new BusinessException(MainConstant.ERROR_RESOURCE_NOT_FOUND);
        }
        resourceDb.setVersion(resourceDto.getVersion());

        if (CollectionUtils.isNotEmpty(resourceDto.getContentIds())) {
            for (Iterator<Resource> itDb = resourceDb.getContents().iterator(); itDb.hasNext();) {
                final Resource contentDb = itDb.next();
                boolean existInPage = IterableUtils.matchesAny(resourceDto.getContentIds(), new Predicate<Long>() {
                    @Override
                    public boolean evaluate(Long object) {
                        return contentDb.getId().equals(object);
                    }
                });
                if (!existInPage) {
                    itDb.remove();
                }
            }
            resourceDb.getContents().addAll(resourceDao.findAll(resourceDto.getContentIds()));
        } else {
            resourceDb.getContents().clear();
        }
        resourceDao.save(resourceDb);
    }
}