com.aistor.modules.sys.utils.DictUtils.java Source code

Java tutorial

Introduction

Here is the source code for com.aistor.modules.sys.utils.DictUtils.java

Source

/**
 * Copyright &copy; 2012-2013 <a href="https://github.com/Dopas/dopas">Dopas</a> All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package com.aistor.modules.sys.utils;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.aistor.common.utils.CacheUtils;
import com.aistor.modules.sys.dao.DictDao;
import com.aistor.modules.sys.entity.Dict;

/**
 * 
 * @author Zaric
 * @version 2013-03-15
 */
@Service
public class DictUtils implements ApplicationContextAware {

    private static DictDao dictDao;

    public static String getDictLabel(String value, String type, String defaultValue) {
        if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(value)) {
            for (Dict dict : getDictList(type)) {
                if (type.equals(dict.getType()) && value.equals(dict.getValue())) {
                    return dict.getLabel();
                }
            }
        }
        return defaultValue;
    }

    public static String getDictValue(String label, String type, String defaultLabel) {
        if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(label)) {
            for (Dict dict : getDictList(type)) {
                if (type.equals(dict.getType()) && label.equals(dict.getLabel())) {
                    return dict.getValue();
                }
            }
        }
        return defaultLabel;
    }

    public static List<Dict> getDictList(String type) {
        @SuppressWarnings("unchecked")
        Map<String, List<Dict>> dictMap = (Map<String, List<Dict>>) CacheUtils.get("dictMap");
        if (dictMap == null) {
            dictMap = Maps.newHashMap();
            for (Dict dict : dictDao.findAllList()) {
                List<Dict> dictList = dictMap.get(dict.getType());
                if (dictList != null) {
                    dictList.add(dict);
                } else {
                    dictMap.put(dict.getType(), Lists.newArrayList(dict));
                }
            }
            CacheUtils.put("dictMap", dictMap);
        }
        List<Dict> dictList = Lists.newArrayList();
        if (dictList != null) {
            dictList = dictMap.get(type);
        }
        return dictList;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        dictDao = (DictDao) applicationContext.getBean("dictDao");
    }
}