ResultMap

/*
 * Copyright (c) 2015. Bond(China), java freestyle app
 */

package com.jfa.app.common;

import com.jfa.commons.util.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author bond
 */
public class ResultMap {

    private static final Logger LOGGER = LoggerFactory.getLogger(ResultMap.class);

    /**
     * 缓存返回结果,控制线程安全
     */
    private static ThreadLocal<Map<String, Object>> threadLocal = new ThreadLocal<Map<String, Object>>();

    /**
     * 加入其它需要返回的结果
     *
     * @param key    String
     * @param object Object
     */
    public static void put(String key, Object object) {
        if (threadLocal.get() == null) {
            threadLocal.set(new HashMap<String, Object>());
        }
        LOGGER.info("[Add a result to ResultMap][Key]:" + key + ",[Value]:" + object.toString());
        threadLocal.get().put(key, object);
    }

    /**
     * 返回成功处理结果
     *
     * @param message String
     * @return
     */

    public static Map<String, Object> success(String message) {
        put(Constants.REST_MESSAGE, message);
        return success();
    }

    /**
     * 返回失败处理结果
     *
     * @param message String
     * @param e       Exception
     * @return
     */
    public static Map<String, Object> failure(String message, Exception e) {
        put(Constants.REST_MESSAGE, message);
        return failure(e);
    }

    /**
     * 返回成功处理结果
     *
     * @param
     * @return
     */

    public static Map<String, Object> success() {
        put(Constants.REST_STATUS, Constants.REST_ACK_OK);
        put(Constants.REST_MESSAGE, Constants.REST_OK_MESSAGE);
        return returnResult();
    }

    /**
     * 返回失败处理结果
     *
     * @param
     * @return
     */
    public static Map<String, Object> failure(Exception e) {
        if (e != null) {
            LOGGER.error(e.getMessage(), e);
        }
        put(Constants.REST_STATUS, Constants.REST_ACK_ERROR);
        put(Constants.REST_MESSAGE, Constants.REST_ERROR_MESSAGE);
        return returnResult();
    }

    private static Map<String, Object> returnResult() {
        Map<String, Object> rs = threadLocal.get();
        threadLocal.set(null);
        return rs;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值