ServletUtil.java 10.6 KB
Newer Older
Kim Gyeongeun committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 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 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 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 298 299 300 301 302 303 304 305 306 307 308
package jp.agentec.sinaburocast.common.util;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashMap;
import java.util.Map;

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

import jp.agentec.sinaburocast.common.SinaburoConstant.AttrKey;
import jp.agentec.sinaburocast.common.SinaburoConstant.MesResKey.Errors;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.seasar.framework.exception.IORuntimeException;
import org.seasar.struts.util.ActionMessagesUtil;

/**
 * HttpServletRequest, HttpServletResponse, HttpSessionを
 * 扱うメソッドはここに集約する。
 * ただし、DBアクセスは行わない。
 * staticメソッドのため、request, session等はパラメータで渡す。
 *
 * @author tsukada
 *
 */
public class ServletUtil {
	private static final Logger LOGGER = Logger.getLogger(ServletUtil.class);

	/**
	 * セッションがタイムアウトしたか?
	 *
	 * @param request
	 * @return セッションを持っていて、タイムアウトした場合のみtrue; セッションが生きている場合及びそもそもセッションがない場合はfalse
	 */
	public static boolean isSessionTimeout(HttpServletRequest request) {
		if (request == null)	return	false;

		HttpSession session = request.getSession(false);
		if (session != null)	return	false;	// セッションが存在して生きている

		return	request.getRequestedSessionId() != null;
	}

	/**
	 * ログイン中か?
	 *
	 * @param request
	 * @return
	 */
	public static boolean isLogined(HttpServletRequest request) {
		HttpSession session = request.getSession(false);
		if (session == null)	return	false;

		return	session.getAttribute(AttrKey.AUTHENTICATED_TOKEN) != null;
	}

	/**
     * @param sessionBak
     * @param atrNames
     */
    private static void backupAttribute(HttpSession session, Map<String, Object> sessionBak, String... atrNames) {
	    for (String anAtrName : atrNames) {
	    	Object anAtr = session.getAttribute(anAtrName);
	    	if (anAtr != null) {
	    		sessionBak.put(anAtrName, anAtr);
	    	}
	    }
    }

    /**
     * セッションを再作成
     * 指定された属性を引き継ぐ
     * @param request	このリクエストに紐づいたセッションを貼り替える
     * @param atrNames	新セッションへ移行したい属性名
     * @return	新しく作成されたセッション
     */
    public static HttpSession renewSession(HttpServletRequest request, String... atrNames) {
    	HttpSession session = request.getSession(false);
    	Map<String, Object>	sessionBak = new HashMap<String, Object>();
    	if (session != null) {
    		backupAttribute(session, sessionBak, atrNames);
    		backupAttribute(session, sessionBak, Globals.ERROR_KEY, Globals.MESSAGE_KEY);	// エラーとメッセージは強制的に引き継ぐ
    		try {
                session.invalidate();
            } catch (IllegalStateException e) {
            	LOGGER.info("session isn't null, but is already invalidated!");
            }
    	}
    	HttpSession newSession = request.getSession(true);
    	for (Map.Entry<String, Object> anEntry : sessionBak.entrySet()) {
    		newSession.setAttribute(anEntry.getKey(), anEntry.getValue());
    	}

    	return	newSession;
    }

	/**
	 * エラーメッセージがあるかどうかを返します.
	 *
	 * {@link ActionMessagesUtil#hasErrors(HttpServletRequest)}
	 * はエラーがセッションに入っている時falseを返すので使用しないこと!
	 *
	 * @param request リクエスト
	 * @return エラーメッセージがあるかどうか
	 */
    public static boolean hasErrors(HttpServletRequest request) {
    	if (ActionMessagesUtil.hasErrors(request))	return	true;

    	HttpSession session = request.getSession(false);
    	if (session == null)	return	false;

        ActionMessages errors = (ActionMessages)session.getAttribute(Globals.ERROR_KEY);
        return	(errors != null && !errors.isEmpty());
    }

	private static void addActionMessage(HttpServletRequest request, String key, String property, String... args) {
		ActionMessages messages = (ActionMessages)request.getAttribute(key);
		if (messages == null) {
			messages = new ActionMessages();
		}
		messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(property, args));
		request.setAttribute(key, messages);
	}

	private static void addActionMessage(HttpSession session, String key, String property, String... args) {
		ActionMessages messages = (ActionMessages)session.getAttribute(key);
		if (messages == null) {
			messages = new ActionMessages();
		}
		messages.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(property, args));
		session.setAttribute(key, messages);
	}

	/**
	 * メッセージ設定<br>
	 * application_ja.propertiesにpropertyとlabelが設定されていない場合に使用。
	 * @param message メッセージ
	 */
	protected static void addMessage(HttpServletRequest request, String message){
		addMessage(request, Errors.GeneralError, message);
	}

	/**
	 * エラーメッセージ<br>
	 * application_ja.propertiesにpropertyとlabelが設定されていない場合に使用。
	 * @param message エラーメッセージ
	 */
	protected static void addError(HttpServletRequest request, String message){
		addError(request, Errors.GeneralError, message);
	}

    /**
	 * エラーメッセージをリクエストに追加.
	 *
	 * application_ja.propertiesにpropertyとlabelが設定されている場合に使用。
	 * 複数メッセージを一度に追加する場合は
	 * {@link org.seasar.struts.util.ActionMessagesUtil#addErrors(HttpServletRequest, ActionMessages)} を使用のこと。
	 *
	 * @param request
	 * @param property プロパティ名. errors.YYY等
	 * @param args 置換パラメータ. プロパティ名でないことに注意。
	 */
    public static void addError(HttpServletRequest request, String property, String... args) {
    	addActionMessage(request, Globals.ERROR_KEY, property, args);
    }


    /**
	 * エラーメッセージをセッションに追加.
	 *
	 * application_ja.propertiesにpropertyとlabelが設定されている場合に使用。
	 * 複数メッセージを一度に追加する場合は
	 * {@link org.seasar.struts.util.ActionMessagesUtil#addErrors(HttpSession, ActionMessages)} を使用のこと。
	 *
	 * @param session
	 * @param property プロパティ名. errors.YYY等
	 * @param args 置換パラメータ. プロパティ名でないことに注意。
	 */
    public static void addError(HttpSession session, String property, String... args) {
    	addActionMessage(session, Globals.ERROR_KEY, property, args);
    }

    /**
	 * メッセージをリクエストに追加.
	 *
	 * application_ja.propertiesにpropertyとlabelが設定されている場合に使用。
	 * 複数メッセージを一度に追加する場合は
	 * {@link org.seasar.struts.util.ActionMessagesUtil#addMessages(HttpServletRequest, ActionMessages)} を使用のこと。
	 *
	 * @param request
	 * @param property プロパティ名. errors.YYY等
	 * @param args 置換パラメータ. プロパティ名でないことに注意。
	 */
    public static void addMessage(HttpServletRequest request, String property, String... args) {
    	addActionMessage(request, Globals.MESSAGE_KEY, property, args);
    }

    /**
	 * メッセージをセッションに追加.
	 *
	 * application_ja.propertiesにpropertyとlabelが設定されている場合に使用。
	 * 複数メッセージを一度に追加する場合は
	 * {@link org.seasar.struts.util.ActionMessagesUtil#addMessages(HttpSession, ActionMessages)} を使用のこと。
	 *
	 * @param session
	 * @param property プロパティ名. errors.YYY等
	 * @param args 置換パラメータ. プロパティ名でないことに注意。
	 */
    public static void addMessage(HttpSession session, String property, String... args) {
    	addActionMessage(session, Globals.MESSAGE_KEY, property, args);
    }


	/**
	 * コンテキスト名を返す
	 *
	 * @param request
	 * @return
	 */
	public static String getContext(HttpServletRequest request) {
		String contextPath = request.getContextPath();
		return (contextPath.length() == 0 || contextPath.equals("/"))? "": contextPath.substring(1);
	}

	public static Cookie setCookie(String key, String value, String path, int age) {
		Cookie cookie = new Cookie(key, value);
		cookie.setPath(path);
		cookie.setMaxAge(age);
		return cookie;
	}

	public static Cookie getCookie(HttpServletRequest request , String key) {
		if (request.getCookies() != null) {
			for (Cookie cookie : request.getCookies()){
				if (cookie.getName().equals(key)) {
					return cookie;
				}
			}
		}
		return null;
	}

    /**
     * BOM付きの文書をレスポンスにテキストを書き込みます。
     *
     * @param response レスポンス
     * @param text テキスト
     * @param contentType コンテントタイプ。 デフォルトはtext/plain。
     * @param encoding エンコーディング。 指定しなかった場合は、UTF-8。
     */
    public static void responseWrite(HttpServletResponse response, String text, String contentType, String encoding) {
        if (contentType == null) {
            contentType = "text/plain";
        }
        if (encoding == null) {
            encoding = "UTF-8";
        }
        try {
        	BufferedWriter out = null;
            try {
                out = new BufferedWriter(new OutputStreamWriter(response.getOutputStream(), encoding));
                out.write(65279);
                out.write(text);
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch (IOException e) {
            throw new IORuntimeException(e);
        }
    }

    /**
     * クライアントのアドレスを返す。
     *
     * @return
     */
    public static String getRemoteAddr(HttpServletRequest request) {
    	if (PropertyUtil.getBoolean("USE_X_FORWARDED_FOR")) {
    		String addr = request.getHeader("X-Forwarded-For");
    		if (StringUtils.isNotEmpty(addr)) {
    			return addr;
    		}
    	}
   		return request.getRemoteAddr();
    }

    /**
     * UserAgentにSafariが含まれるか返す。
     *
     * @param session
     * @return
     */
    public static boolean isSafari(HttpServletRequest request) {
    	String userAgent = request.getHeader("user-agent");
    	return StringUtils.contains(userAgent, "Safari");
    }

}