com.mmj.app.common.pipeline.value.BaseWebUserBuilderValve.java Source code

Java tutorial

Introduction

Here is the source code for com.mmj.app.common.pipeline.value.BaseWebUserBuilderValve.java

Source

/*
 * Copyright 2011-2016 MSUN.com All right reserved. This software is the confidential and proprietary information of
 * MSUN.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into with MSUN.com.
 */
package com.mmj.app.common.pipeline.value;

import java.io.IOException;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.util.UrlPathHelper;

import com.mmj.app.common.cookie.manager.CookieManager;
import com.mmj.app.common.cookie.manager.CookieManagerLocator;
import com.mmj.app.common.pipeline.PipelineMap;
import com.mmj.app.common.pipeline.PipelineResult;
import com.mmj.app.common.result.Result;
import com.mmj.app.common.util.HttpUtil;

/**
 * WebUser
 * 
 * @author zxc Jul 8, 2014 10:03:10 AM
 */
public abstract class BaseWebUserBuilderValve<T extends BaseWebUser> extends AbstractPipelineValves {

    public static Logger logger = LoggerFactory.getLogger(BaseWebUserBuilderValve.class);

    private UrlPathHelper urlPathHelper = new UrlPathHelper();

    /**
     * ANT URL??SpringAntPathMatcher??
     * 
     * <pre>
     * ?
     *  ? ??
     *  * ?0??
     *  ** ?0
     *   ?(has more characters)
     * </pre>
     */
    protected PathMatcher pathMatcher = new AntPathMatcher();

    @SuppressWarnings("unused")
    private String noPermissionUrl = "/nopermission.htm";
    protected String loginUrl = "/";
    protected String homeUrl = "/home.htm";
    private List<String> noCheckUrlLikeList;
    private List<String> noCheckUrlList;
    // ??
    protected static final long MAX_LAST_ACCESS_TIME = 1000 * 60 * 60 * 24;

    protected boolean checkUrl;

    public PipelineResult invoke(HttpServletRequest request, HttpServletResponse response, PipelineMap map)
            throws Exception {
        // ???
        RequestDigger.saveRequestInfo(request);
        String uri = urlPathHelper.getLookupPathForRequest(request);
        // String uri = request.getRequestURI();
        // logger.info("<value>" + uri + "</value>");

        // 1. WebUser
        CookieManager cookieManager = CookieManagerLocator.get(request, response);
        T webUser = createWebUser(request, cookieManager);

        // 2. ???
        boolean canAccessAnonymous = canAccessAnonymous(uri);
        if (!webUser.hasLogin()) {
            if (!canAccessAnonymous) {
                return getToLogin(request, response, uri);
            } else {
                judgeAccessTime(cookieManager);
                return null;
            }
        }

        // //////////////////////??/////////////////////////////

        // 3. (??,login?????judgeAccessTime??????
        if (!judgeAccessTime(cookieManager) && !canAccessAnonymous) {
            return getToLogin(request, response, uri);
        }

        // 4. URL??(??
        if (!canAccessAnonymous) {
            Result result = judgePermission(request, response, uri, webUser);
            if (result.isFailed()) {
                return PipelineResult.gotoAfterCompletion("gotoLogin",
                        (result.getData() == null ? null : (String) result.getData()));
            }
        }
        return null;
    }

    protected PipelineResult getToLogin(HttpServletRequest request, HttpServletResponse response, String uri)
            throws Exception {
        String url = loginUrl;
        // ????returnurl
        if (request.getParameterMap().isEmpty() && !StringUtils.contains("/login", uri)) {
            url = loginUrl + "?returnurl=" + uri;
        }
        return PipelineResult.gotoAfterCompletion("gotoLogin", url);
    }

    /**
     * URL????
     * 
     * @param uri
     * @return ???<code>true</code>?<code>false</code>
     */
    private boolean canAccessAnonymous(String uri) {
        if (!checkUrl) {
            return true;
        }
        boolean needcheck = needcheck(uri);
        if (!needcheck) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * ???URL?????????
     * 
     * @return true ????false
     * @throws IOException
     * @throws Exception
     */
    protected Result judgePermission(HttpServletRequest request, HttpServletResponse response, String uri,
            T webUser) throws Exception {
        return Result.success();
    }

    /**
     * ??true??(??
     * 
     * @return true ????false
     */
    protected boolean judgeAccessTime(CookieManager cookieManager) {
        return true;
    }

    /**
     * Cookie?????WebUser?(??
     * 
     * @param request
     */
    protected abstract T createWebUser(HttpServletRequest request, CookieManager cookieManager);

    protected boolean needcheck(String uri) {
        if (noCheckUrlList != null && noCheckUrlList.contains(uri)) {
            return false;
        }
        if (noCheckUrlLikeList != null) {
            for (String s : noCheckUrlLikeList) {
                if (this.pathMatcher.match(s, uri)) {
                    return false;
                }
            }
        }
        return true;
    }

    protected static long parserLong(String number) {
        try {
            return Long.parseLong(number);
        } catch (NumberFormatException e) {
            return -1;
        }
    }

    public void setNoPermissionUrl(String noPermissionUrl) {
        this.noPermissionUrl = noPermissionUrl;
    }

    public void setLoginUrl(String loginUrl) {
        this.loginUrl = loginUrl;
    }

    public void setNoCheckUrlLikeList(List<String> noCheckUrlLikeList) {
        this.noCheckUrlLikeList = noCheckUrlLikeList;
    }

    public boolean isCheckUrl() {
        return checkUrl;
    }

    public void setCheckUrl(boolean checkUrl) {
        this.checkUrl = checkUrl;
    }

    public List<String> getNoCheckUrlList() {
        return noCheckUrlList;
    }

    public void setNoCheckUrlList(List<String> noCheckUrlList) {
        this.noCheckUrlList = noCheckUrlList;
    }

    /**
     * ???
     * 
     * @author zxc Jul 8, 2014 10:03:40 AM
     */
    public static class RequestDigger {

        @SuppressWarnings("rawtypes")
        public static StringBuilder saveRequestInfo(HttpServletRequest request) {
            // ?header
            Enumeration headerNames = request.getHeaderNames();
            StringBuilder sb = new StringBuilder();
            while (headerNames.hasMoreElements()) {
                Object object = (Object) headerNames.nextElement();
                sb.append((String) object).append(":").append(request.getHeader((String) object)).append("\r\n");
            }
            // ?IP???header
            sb.append("remoteAddr:").append(HttpUtil.getIpAddr(request)).append("\r\n");
            // ????
            sb.append("requestURI:").append(request.getRequestURI()).append("\r\n");
            Map parameterMap = request.getParameterMap();
            for (Object key : parameterMap.keySet()) {
                sb.append(key.toString()).append(":").append(request.getParameter(key.toString())).append("\r\n");
            }
            // ??
            RequestInfo.set(sb.toString());
            return sb;
        }

        public static String getSavedRequestInfo() {
            return RequestInfo.get();
        }
    }

    /**
     * ??
     * 
     * @author zxc Jul 8, 2014 10:03:30 AM
     */
    public static class RequestInfo {

        private static ThreadLocal<String> cache = new ThreadLocal<String>() {

            protected String initialValue() {
                return "unKnow";
            }
        };

        public static String get() {
            return cache.get();
        }

        public static void set(String info) {
            cache.set(info);
        }
    }
}