⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 skinutils.java

📁 Jive论坛2.5版本的源程序
💻 JAVA
📖 第 1 页 / 共 3 页
字号:
/**
 * $RCSfile: SkinUtils.java,v $
 * $Revision: 1.1.1.1 $
 * $Date: 2002/09/09 13:51:08 $
 *
 * New Jive  from Jdon.com.
 *
 * This software is the proprietary information of CoolServlets, Inc.
 * Use is subject to license terms.
 */

package com.jivesoftware.forum.util;

import java.io.*;
import java.text.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

import com.jivesoftware.forum.*;
import com.jivesoftware.util.*;

/**
 * A collection of utility methods for use in Jive Skins. Because these
 * methods make skin development much easier, skin authors should study them
 * carefully.<p>
 *
 * Three major areas of funtionality are provided:<p><ol>
 *  <li> Methods that simplify Authorization tasks:
 *    <ul>
 *      <li>{@link #login(HttpServletRequest, HttpServletResponse, String, String, boolean)}
 *      <li>{@link #getUserAuthorization(HttpServletRequest, HttpServletResponse)}
 *      <li>{@link #removeUserAuthorization(HttpServletRequest, HttpServletResponse)}
 *    </ul>
 *    <p>
 *  <li> Methods that get and set Session and cookie values.
 *    <ul>
 *      <li>{@link #getCookie(HttpServletRequest, String)}
 *      <li>{@link #remove(HttpServletRequest, HttpServletResponse, String)}
 *      <li>{@link #retrieve(HttpServletRequest, HttpServletResponse, String)}
 *      <li>{@link #store(HttpServletRequest, HttpServletResponse, String, String)}
 *      <li>{@link #store(HttpServletRequest, HttpServletResponse, String, String, int)}
 *      <li>{@link #store(HttpServletRequest, HttpServletResponse, String, String, int boolean)}
 *    </ul>
 *    <p>
 *  <li> Date methods.
 *    <ul>
 *      <li>{@link #dateToText(HttpServletRequest, HttpServletResponse, User, Date)}
 *      <li>{@link #formatDate(HttpServletRequest, HttpServletResponse, User, Date)}
 *      <li>{@link #getLastVisited(HttpServletRequest, HttpServletResponse)}
 *    </ul>
 *  <li> Other methods.
 *    <ul>
 *      <li>{@link #quoteOriginal(String, String, int)}
 *      <li>{@link #getResourceBundle(String, Locale)}
 *    </ul>
 * </ol>
 *
 */
public class SkinUtils {

    /** Name of the authentication token (stored in the user's session) */
    private static final String JIVE_AUTH_TOKEN = "jive.authorization.token";

    /** Name of the cookie used to store user info for auto-login purposes */
    private static final String JIVE_AUTOLOGIN_COOKIE = "jive.authorization.autologin";

    /** Name of the last visited token (stored in the user's session) */
    private static final String JIVE_LASTVISITED_TOKEN = "jive.user.lastvisited";

    // Default cookie time to live (in seconds).
    private static final int MAX_COOKIE_AGE = (int)(JiveGlobals.WEEK / 1000) * 8;

    // Days of the week
    private static final String[] DAYS_OF_WEEK =
            {"Sun","Mon","Tues","Wed","Thurs","Fri","Sat"};
    // Months of the year
    private static final String[] MONTHS_OF_YEAR =
            {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug",
             "Sep","Oct","Nov","Dec"};

    // "Tweakable" parameters for the cookie password encoding. NOTE: changing
    // these and recompiling this class will essentially invalidate old cookies.
    private final static int  ENCODE_XORMASK = 0x5A;
    private final static char ENCODE_DELIMETER = '\002';
    private final static char ENCODE_CHAR_OFFSET1 = 'A';
    private final static char ENCODE_CHAR_OFFSET2 = 'h';

    // A cache of DateFormat objects:
    private static HashMap dateFormatCache = new HashMap();

    // A reuseable global calendar object
    private static Calendar globalCal = Calendar.getInstance();


    /**
     * Returns an Authorization token for the user. The session is first checked
     * and if the token is not found, the Jive cookie is checked. If the cookie
     * is found,
     *
     * @param request the HttpServletRequest object, known as "request" in a
     *      JSP page.
     * @param response The HttpServletResponse object, known as "response" in
     *      a JSP page.
     * @return A users's authorization token if they're already authenticated,
     *      otherwise <code>null</code>.
     */
    public static Authorization getUserAuthorization
            (HttpServletRequest request, HttpServletResponse response)
    {
        HttpSession session = request.getSession();

        // Check 1: check for the Jive authentication token in the user's session.
        Authorization authToken = (Authorization)session.getAttribute(JIVE_AUTH_TOKEN);
        if (authToken != null) {
            return authToken;
        }

        // Check 2: check the jive cookie for username and password
        Cookie cookie = getCookie(request, JIVE_AUTOLOGIN_COOKIE);
        if (cookie != null) {
            try {
                // at this point, we found a cookie so grab the username and
                // password from it, create an authorization token and store
                // that in the session
                String[] values = decodePasswordCookie(cookie.getValue());
                String username = values[0];
                String password = values[1];
                // Try to validate the user based on the info from the cookie.
                // Catch any exceptions
                authToken = AuthorizationFactory.getAuthorization(username,password);
            }
            catch (Exception e) {}

            // put that token in the user's session:
            if (authToken != null) {
                session.setAttribute(JIVE_AUTH_TOKEN, authToken);
            }

            // return the authorization token
            return authToken;
        }
        return null;
    }

    /**
     * Validates the user and optionally enables auto-login by creating an
     * auto-login cookie.
     *
     * @param request the HttpServletRequest object, known as "request" in a JSP page.
     * @param response the HttpServletResponse object, known as "response" in a JSP page.
     * @param username the username.
     * @param password the password.
     * @param autoLogin if <code>true</code> create a cookie that enables auto-login.
     * @throws UserNotFoundException
     * @throws UnauthorizedException
     */
    public static Authorization login(HttpServletRequest request,
            HttpServletResponse response, String username, String password,
            boolean autoLogin) throws UserNotFoundException, UnauthorizedException
    {
        HttpSession session = request.getSession();
        Authorization authToken = AuthorizationFactory.getAuthorization(username, password);
        session.setAttribute(JIVE_AUTH_TOKEN, authToken);

        // If auto-login is enabled, create the auto-login cookie
        if (autoLogin) {
            saveCookie(response,JIVE_AUTOLOGIN_COOKIE,
                    encodePasswordCookie(username,password));
        }
        return authToken;
    }
    public static Authorization setUserAuthorization(HttpServletRequest request,
            HttpServletResponse response, String username, String password,
            boolean autoLogin) throws UserNotFoundException, UnauthorizedException
    {
        return login(request, response, username, password, autoLogin);
    }


    /**
     *  Removes a user's token from the session and invalidates the auto-login
     *  cookie (if one exists).
     *
     *  @param request the HttpServletRequest object; "request" in JSP pages.
     *  @param response the HttpServletResponse object; "response" in JSP pages.
     */
    public static void logout(HttpServletRequest request,
            HttpServletResponse response)
    {
        HttpSession session = request.getSession();
        session.removeAttribute(JIVE_AUTH_TOKEN);
        deleteCookie(request, response, JIVE_AUTOLOGIN_COOKIE);
    }
    public static void removeUserAuthorization(HttpServletRequest request,
            HttpServletResponse response)
    {
        logout(request,response);
    }


    /**
     * Invalidates the specified cookie.
     */
    public static void deleteCookie(HttpServletRequest request,
            HttpServletResponse response, String cookieName)
    {
        // invalidate the cookie
        Cookie cookie = new Cookie(cookieName, "");
        // delete the cookie when the user closes their webbrowser
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    /**
     *  Persists a value for the length of the user's session.
     *
     *  @see SkinUtils#store(HttpServletRequest,HttpServletResponse,String,String,int) store
     */
    public static void store(HttpServletRequest request, HttpServletResponse response,
            String id, String value)
    {
        // By default, we'll just store the value in the session (saveTime
        // is zero)
        store(request, response, id, value, 0);
    }

    /**
     *  This method should be used in a skin to store an arbritary value.
     *  For example, we could persist the name of a user so that on a form page
     *  where they enter their name, that field could be auto-filled in with
     *  the stored value.
     *  <p>
     *  To indicate that the data should only be persisted for a session, pass
     *  in 0 as the <code>timeToLive</code>. Otherwise, the value will be
     *  saved for one month.
     *
     *  @param request The HttpServletRequest object, known as "request" on a
     *      JSP page.
     *  @param response The HttpServletRequest object, known as "response" on a
     *      JSP page.
     *  @param id The name or identifier of the data you want to persist.
     *  @param value The value you wish to store.
     *  @param saveTime The length (in seconds) this value will persist. Any
     *      value of 0 or less indicates this data should only persist for
     *      a session.
     */
    public static void store(HttpServletRequest request,
            HttpServletResponse response, String id, String value, int saveTime)
    {
        // If the id is null, return
        if (id == null) {
            return;
        }

        // Get the session object
        HttpSession session = request.getSession();

        // Store the value in the session
        session.setAttribute(id, value);

        // if the timeToLive param is > 0, store to a cookie
        if (saveTime > 0) {
            saveCookie(response, id, value, saveTime);
        }
    }

    /**
     *  Retrieves a user stored value. Values are set using the
     *  <code>store(...)</code> methods. If <code>remove</code> is true, the
     *  value is also removed from persistence.
     *
     *  @param request The HttpServletRequest object, known as "request" on
     *      a JSP page.
     *  @param response The HttpServletRequest object, known as "response" on
     *      a JSP page.
     *  @param id The id or name of the stored value.
     */
    public static String retrieve(HttpServletRequest request,
            HttpServletResponse response, String id)
    {
        // First, check the session.
        HttpSession session = request.getSession();
        String value = (String)session.getAttribute(id);

        // if it's not found, check the cookies
        if (value == null) {
            Cookie cookie = getCookie(request, id);
            if (cookie != null) {
                value = cookie.getValue();
            }
            if (id != null && value != null) {
                session.setAttribute(id, value);
            }
        }
        return value;
    }

    /**

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -