WebContext.java 14.6 KB
Newer Older
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
1 2
package org.maxkey.web;

MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
3 4 5
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
6
import java.util.Locale;
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
7
import java.util.Map;
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
8
import java.util.Properties;
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
9
import javax.servlet.http.Cookie;
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
10
import javax.servlet.http.HttpServletRequest;
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
11
import javax.servlet.http.HttpServletResponse;
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
12 13
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.LogFactory;
14
import org.maxkey.authn.BasicAuthentication;
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
15
import org.maxkey.authn.realm.AbstractAuthenticationRealm;
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
16
import org.maxkey.configuration.ApplicationConfig;
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
import org.maxkey.domain.UserInfo;
import org.maxkey.util.DateUtils;
import org.maxkey.util.StringGenerator;
import org.maxkey.web.message.Message;
import org.springframework.context.ApplicationContext;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.i18n.CookieLocaleResolver;
import org.springframework.web.servlet.support.RequestContextUtils;

/**
MaxKey单点登录官方's avatar
v1.3 RC  
MaxKey单点登录官方 已提交
32
 * Application is common class for Web Application Context.
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
33 34 35 36 37 38
 * 
 * @author Crystal.Sea
 * @since 1.5
 */
public final class WebContext {

MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
39 40
    public static Properties properties;
     
MaxKey单点登录官方's avatar
v1.3 RC  
MaxKey单点登录官方 已提交
41 42 43 44 45 46 47
    /**
     * set Current login user to session.
     * 
     * @see WebConstants.CURRENT_USER
     */
    public static void setUserInfo(UserInfo userInfo) {
        setAttribute(WebConstants.CURRENT_USER, userInfo);
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
48
    }
MaxKey单点登录官方's avatar
v1.3 RC  
MaxKey单点登录官方 已提交
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235

    /**
     * get Current login user from session.
     * 
     * @see WebConstants.CURRENT_USER
     * @return UserInfo
     */
    public static UserInfo getUserInfo() {
        return ((UserInfo) getAttribute(WebConstants.CURRENT_USER));
    }

    /**
     * set Message to session,session id is Constants.MESSAGE
     * 
     * @see WebConstants.MESSAGE
     * @param message Message
     */
    public static void setMessage(Message message) {
        setAttribute(WebConstants.CURRENT_MESSAGE, message);
    }

    /**
     * get message from session,session id is Constants.MESSAGE
     * 
     * @see WebConstants.MESSAGE
     * @return Message
     */
    public static Message getMessage() {
        return ((Message) getAttribute(WebConstants.CURRENT_MESSAGE));
    }

    /**
     * clear session Message ,session id is Constants.MESSAGE
     * 
     * @see WebConstants.MESSAGE
     */
    public static void clearMessage() {
        removeAttribute(WebConstants.CURRENT_MESSAGE);
    }

    /**
     * setAuthentication.
     * @param username String
     * @param type String
     * @param provider String
     * @param code String
     * @param message String
     * @return boolean
     */
    public static boolean setAuthentication(String username, 
                                            String type, 
                                            String provider, 
                                            String code,
                                            String message) {
        AbstractAuthenticationRealm authenticationRealm = 
                (AbstractAuthenticationRealm) getBean("authenticationRealm");
        UserInfo loadeduserInfo = authenticationRealm.loadUserInfo(username, "");
        if (loadeduserInfo != null) {
            setUserInfo(loadeduserInfo);
            BasicAuthentication authentication = new BasicAuthentication();
            authentication.setUsername(loadeduserInfo.getUsername());
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken =
                    new UsernamePasswordAuthenticationToken(
                            authentication, 
                            "PASSWORD", 
                            authenticationRealm.grantAuthority(loadeduserInfo)
                    );

            authentication.setAuthenticated(true);
            WebContext.setAuthentication(usernamePasswordAuthenticationToken);
            WebContext.setUserInfo(loadeduserInfo);

            authenticationRealm.insertLoginHistory(loadeduserInfo, type, provider, code, message);
        }
        return true;
    }

    public static void setAuthentication(Authentication authentication) {
        setAttribute(WebConstants.AUTHENTICATION, authentication);
    }

    public static Authentication getAuthentication() {
        Authentication authentication = (Authentication) getAttribute(WebConstants.AUTHENTICATION);
        return authentication;
    }

    /**
     * isAuthenticated.
     * @return isAuthenticated
     */
    public static boolean isAuthenticated() {
        if (getUserInfo() != null) {
            return true;
        }
        return false;
    }

    /**
     * get ApplicationContext from web ServletContext configuration.
     * 
     * @return ApplicationContext
     */
    public static ApplicationContext getApplicationContext() {
        return WebApplicationContextUtils.getWebApplicationContext(
                    getSession().getServletContext());
    }

    /**
     * get bean from spring configuration by bean id.
     * 
     * @param id String
     * @return Object
     */
    public static Object getBean(String id) {
        return getApplicationContext().getBean(id);
    }

    // below method is common HttpServlet method
    /**
     * get Spring HttpServletRequest.
     * 
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) 
                    RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * get Http Context full Path,if port equals 80 is omitted.
     * 
     * @return String eg:http://192.168.1.20:9080/webcontext or
     *         http://www.website.com/webcontext
     */
    public static String getHttpContextPath() {
        HttpServletRequest httpServletRequest = WebContext.getRequest();
        ApplicationConfig applicationConfig = (
                ApplicationConfig) WebContext.getBean("applicationConfig");

        if (applicationConfig.getServerPrefix() != null 
                && !applicationConfig.getServerPrefix().equals("")) {
            return applicationConfig.getServerPrefix();
        } else {
            String httpContextPath = 
                    httpServletRequest.getScheme() + "://" + applicationConfig.getDomainName();
            int port = httpServletRequest.getServerPort();
            if (port == 443 && httpServletRequest.getScheme().equalsIgnoreCase("https")) {
                //
            } else if (port == 80 && httpServletRequest.getScheme().equalsIgnoreCase("http")) {
                //
            } else {
                httpContextPath += ":" + port;
            }
            httpContextPath += httpServletRequest.getContextPath() + "";
            return httpContextPath;
        }

    }

    /**
     * get current Session.
     * 
     * @return HttpSession
     */
    public static HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     * get current Session,if no session ,new Session created.
     * 
     * @return HttpSession
     */
    public static HttpSession getSession(boolean create) {
        return getRequest().getSession(create);
    }

    /**
     * set Attribute to session ,Attribute name is name,value is value.
     * 
     * @param name String
     * @param value String
     */
    public static void setAttribute(String name, Object value) {
        getSession().setAttribute(name, value);
    }

MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
236
    /**
MaxKey单点登录官方's avatar
v1.3 RC  
MaxKey单点登录官方 已提交
237 238 239
     * get Attribute from session by name.
     * 
     * @param name String
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
240 241
     * @return
     */
MaxKey单点登录官方's avatar
v1.3 RC  
MaxKey单点登录官方 已提交
242 243
    public static Object getAttribute(String name) {
        return getSession().getAttribute(name);
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
244
    }
MaxKey单点登录官方's avatar
v1.3 RC  
MaxKey单点登录官方 已提交
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262

    /**
     * remove Attribute from session by name.
     * 
     * @param name String
     */
    public static void removeAttribute(String name) {
        getSession().removeAttribute(name);
    }

    /**
     * get Request Parameter by name.
     * 
     * @param name String
     * @return String
     */
    public static String getParameter(String name) {
        return getRequest().getParameter(name);
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
263
    }
MaxKey单点登录官方's avatar
v1.3 RC  
MaxKey单点登录官方 已提交
264

MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
265
    /**
MaxKey单点登录官方's avatar
v1.3 RC  
MaxKey单点登录官方 已提交
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
     * encoding encodingString by ApplicationConfig.
     * 
     * @param encodingString String
     * @return encoded String
     */
    public static String encoding(String encodingString) {
        ApplicationConfig applicationConfig = (ApplicationConfig) getBean("applicationConfig");
        return applicationConfig.getCharacterEncodingConfig().encoding(encodingString);
    }

    /**
     * get locale from Spring Resolver,if locale is null,get locale from Spring.
     * SessionLocaleResolver this is from internationalization
     * 
     * @return Locale
     */
    public static Locale getLocale() {
        Locale locale = null;
        try {
            CookieLocaleResolver cookieLocaleResolver = 
                    (CookieLocaleResolver) getBean("localeResolver");
            locale = cookieLocaleResolver.resolveLocale(getRequest());

        } catch (Exception e) {
            LogFactory.getLog(WebContext.class).debug("getLocale() error . ");
            e.printStackTrace();
            locale = RequestContextUtils.getLocale(getRequest());
        }

        return locale;
    }

MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
    /**
     * 根据名字获取cookie.
     *
     * @param request HttpServletRequest
     * @param name  cookie名字
     * @return Cookie
     */
    public static Cookie readCookieByName(HttpServletRequest request, String name) {
        Map<String, Cookie> cookieMap = readCookieAll(request);
        if (cookieMap.containsKey(name)) {
            Cookie cookie = (Cookie) cookieMap.get(name);
            return cookie;
        } else {
            return null;
        }
    }
 
    /**
     * 将cookie封装到Map里面.
     *
     * @param request HttpServletRequest
     * @return Map 
     */
    private static Map<String, Cookie> readCookieAll(HttpServletRequest request) {
        Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }
 
    /**
     * 保存Cookies.
     *
     * @param response response响应
     * @param name cookie的名字
     * @param value cookie的值
     * @param time cookie的存在时间
     */
    public static HttpServletResponse setCookie(
            HttpServletResponse response, String name, String value, int time) {
        // new一个Cookie对象,键值对为参数
        Cookie cookie = new Cookie(name, value);
        // tomcat下多应用共享
        cookie.setPath("/");
        // 如果cookie的值中含有中文时,需要对cookie进行编码,不然会产生乱码
        try {
            URLEncoder.encode(value, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        // 单位:秒
        cookie.setMaxAge(time);
        // 将Cookie添加到Response中,使之生效
        response.addCookie(cookie); // addCookie后,如果已经存在相同名字的cookie,则最新的覆盖旧的cookie
        return response;
    }

MaxKey单点登录官方's avatar
v1.3 RC  
MaxKey单点登录官方 已提交
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428
    /**
     * get Current Date,eg 2012-07-10.
     * 
     * @return String
     */
    public static String getCurrentDate() {
        return DateUtils.getCurrentDateAsString(DateUtils.FORMAT_DATE_YYYY_MM_DD);
    }

    /**
     * get System Menu RootId,root id is constant.
     * 
     * @return String
     */
    public static String getSystemNavRootId() {
        return "100000000000";
    }

    /**
     * get Request IpAddress,for current Request.
     * 
     * @return String,100.167.216.100
     */
    public static final String getRequestIpAddress() {
        return getRequestIpAddress(getRequest());
    }

    /**
     * get Request IpAddress by request.
     * 
     * @param request HttpServletRequest
     * @return String
     */
    public static final String getRequestIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        LogFactory.getLog(WebContext.class).debug(
                "getRequestIpAddress() RequestIpAddress:" + ipAddress);
        return ipAddress;
    }

    /**
     * captchaValid.
     * @param captcha String
     * @return
     */
    public static boolean captchaValid(String captcha) {
        if (captcha == null || !captcha
                .equals(WebContext.getSession().getAttribute(
                        WebConstants.KAPTCHA_SESSION_KEY).toString())) {
            return false;
        }
        return true;
    }

    //TODO:
    /**
     * getI18nValue.
     *  @param code String
     * @return
     */
    public static String getI18nValue(String code) {
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
429 430 431 432 433 434 435 436 437 438 439
        String message = code;
        try {
            message = getApplicationContext().getMessage(
                code.toString(), 
                null,
                getLocale());
        } catch (Exception e) {
            //
            e.printStackTrace();
        }
        return message;
MaxKey单点登录官方's avatar
v1.3 RC  
MaxKey单点登录官方 已提交
440 441
    }

MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
442 443 444 445 446 447
    /**
     * getI18nValue.
     * @param code String
     * @param filedValues Object
     * @return
     */
MaxKey单点登录官方's avatar
v1.3 RC  
MaxKey单点登录官方 已提交
448
    public static String getI18nValue(String code, Object[] filedValues) {
MaxKey单点登录官方's avatar
MaxKey单点登录官方 已提交
449 450 451 452 453 454 455 456 457 458 459
        String message = code;
        try { 
            message = getApplicationContext().getMessage(
                code.toString(), 
                filedValues,
                getLocale());
        } catch (Exception e) {
            //
            e.printStackTrace();
        }
        return message;
MaxKey单点登录官方's avatar
v1.3 RC  
MaxKey单点登录官方 已提交
460 461 462 463 464
    }
    
    //TODO:
    /**
     * getRequestLocale.
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
465 466
     * @return
     */
MaxKey单点登录官方's avatar
v1.3 RC  
MaxKey单点登录官方 已提交
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486
    public static String getRequestLocale() {
        return "";
    }

    /**
     * generate random Universally Unique Identifier,delete -.
     * 
     * @return String
     */
    public static String genId() {
        return (new StringGenerator()).uuidGenerate();
    }

    public static ModelAndView redirect(String redirectUrl) {
        return new ModelAndView("redirect:" + redirectUrl);
    }

    public static ModelAndView forward(String forwardUrl) {
        return new ModelAndView("forward:" + forwardUrl);
    }
MaxKey单点登录官方's avatar
init  
MaxKey单点登录官方 已提交
487
}