VelocityTool.java 14.8 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 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 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 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
package jp.agentec.sinaburocast.common.util.velocity;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Locale;

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

import jp.agentec.sinaburocast.common.SinaburoConstant;
import jp.agentec.sinaburocast.common.SinaburoConstant.AttrKey;
import jp.agentec.sinaburocast.common.util.PropertyUtil;
import jp.agentec.sinaburocast.common.util.SinaburoUtil;
import jp.agentec.sinaburocast.common.util.SinaburoViewUtil;
import jp.agentec.sinaburocast.dto.TestDto;
import jp.agentec.sinaburocast.entity.AdminUser;
import jp.agentec.sinaburocast.entity.Member;
import jp.agentec.sinaburocast.vo.AuthenticatedTokenVO;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.util.MessageResources;
import org.apache.struts.util.TokenProcessor;
import org.apache.velocity.tools.generic.ListTool;
import org.apache.velocity.tools.struts.StrutsUtils;
import org.apache.velocity.tools.view.context.ViewContext;
import org.seasar.framework.util.StringUtil;

/**
 * SinaburoCastプロジェクト用VelocityTools
 *
 * @author tsukada
 *
 */
public class VelocityTool {
	private static Logger LOGGER = Logger.getLogger(VelocityTool.class);

	protected ServletContext application;
	protected HttpServletRequest request;
	protected HttpSession session;
	protected HttpServletResponse response;

//	public static final boolean devmode = PropertyUtil.getBoolean(PropertyKey.DEVMODE);
	public static final int sslMode = PropertyUtil.getInt("sslMode");

	/**
	 * Initializes this tool.
	 *
	 * @param obj the current ViewContext
	 * @throws IllegalArgumentException if the param is not a ViewContext
	 */
	public void init(Object obj) {
		if (! (obj instanceof ViewContext)) {
			throw new IllegalArgumentException("Tool can only be initialized with a ViewContext");
		}

		ViewContext context = (ViewContext) obj;
		this.request = context.getRequest();
		this.response = context.getResponse();
		this.session = request.getSession();
		this.application = context.getServletContext();
	}

	/**
	 * コンテキストパスを返す。
	 * ROOTの場合から文字を返す。
	 *
	 * @return
	 * @deprecated request.getContextPath()自体'/'を含まないしROOT時は空文字列を返すはず。もし症状再発したら復活させる。
	 */
	@Deprecated
	public String getContextPath() {
		String contextPath = request.getContextPath();
		return contextPath.equals("/")? "": contextPath;
	}

	public String getContext() {
		String contextPath = request.getContextPath();
		return (contextPath.length() == 0 || contextPath.equals("/"))? "": contextPath.substring(1);
	}

	/**
	 * リクエストURLを返す。
	 *
	 * @return
	 */
	public String getRequestUrl() {
		String base = SinaburoUtil.extractRegexString(request.getRequestURL().toString(), "(http?://.+?)/", 1);
		String error_uri = (String)request.getAttribute("javax.servlet.error.request_uri");
		if (StringUtils.isNotEmpty(error_uri)) {
			/* HTTPエラーコードが発生した場合 */
			return	base + error_uri;
		}

		String orig_uri = (String)request.getAttribute("javax.servlet.forward.request_uri");
		if (StringUtils.isNotEmpty(orig_uri)) {
			/* 一度以上フォワードされている場合 */
			return	base + orig_uri;
		}

		// falldown
		return	request.getRequestURL().toString();
	}

	/**
	 * セキュアなURL(フルパス)をエンコードして返す。
	 *
	 * @param path
	 * @return
	 */
	public String getEncodeUrl(String path) {

		String urlpath = getUrl(path);

		urlpath = response.encodeURL(urlpath);

		return ( sslMode > 0	? new StringBuilder("https://").append(request.getServerName()).append(urlpath).toString() : urlpath);

//		String url = getSecureUrl(path);
//
//		String aaa = response.encodeURL(url);

//		return response.encodeURL(url);
	}

	/**
	 * セキュアなURL(フルパス)を生成して返す。
	 *
	 * @param path
	 * @return
	 */
	public String getSecureUrl(String path) {
		String urlpath = getUrl(path);

		return ( sslMode > 0	? new StringBuilder("https://").append(request.getServerName()).append(urlpath).toString() : urlpath);
	}

	/**
	 * TopページURLを生成して返す。
	 * エンドユーザ、契約事業者、サービスプロバイダそれぞれのトップページへのURLを返す。
	 * どの種別か判別できない場合は、エンドユーザのログインページに返す。
	 *
	 * @param path
	 * @return
	 */
	public String getTopUrl() {


		return request.getContextPath();
	}

	/**
	 * TopページURLを生成して返す。
	 * エンドユーザ、契約事業者、サービスプロバイダそれぞれのトップページへのURLを返す。
	 * どの種別か判別できない場合は、エンドユーザのログインページに返す。
	 *
	 * @param path
	 * @return
	 */
	public String getTopUrlAdmin() {
		return request.getContextPath()+"/admin/member/";
	}

	/**
	 * MyページURLを生成して返す。
	 * エンドユーザ、契約事業者、サービスプロバイダそれぞれのトップページへのURLを返す。
	 * どの種別か判別できない場合は、エンドユーザのログインページに返す。
	 *
	 * @param path
	 * @return
	 */
	public String getMyPageUrl() {

		return request.getContextPath()+"/user/myPage/";
	}

	/**
	 * URLを生成して返す。
	 *
	 * @param path
	 * @return
	 */
	public String getUrl(Object path) {
		return request.getContextPath() + SinaburoUtil.nvl(path, "");
	}


	public String getPadId(Object contractId){
		if (contractId == null)	return	null;
		return SinaburoUtil.leftPad(Long.parseLong(contractId.toString()), 4, "0");
	}

	public String getCid(Object contractId){
		if (contractId == null)	return	null;
		return "C"+ getPadId(contractId.toString());
	}

	/**
	 * devmodeに応じてプロトコルを返す
	 *
	 * @return
	 */
	public String getProtocol() {
		return sslMode > 0? "https" : "http";
	}

	public boolean isWindows() {
		final String userAgent = request.getHeader("user-agent");
		if (StringUtils.isEmpty(userAgent)) {
			LOGGER.warn("user-agent is not found.");
			return	false;
		}

		return	userAgent.toLowerCase(Locale.ENGLISH).contains("win");
	}

	public String getOsDependCSS() {
		return	isWindows() ? "win.css" : "mac.css";
	}

	/**
	 * 文字列長が指定したmaxlengthを越えないように適宜省略する
	 * @param str 表示される文字列
	 * @param maxlength 許容される最大長
	 * @return
	 */
	public String getBrief(final String str, final int maxlength) {
		return	SinaburoUtil.getBrief(str, maxlength);
	}

	/**
	 * 2つの文字列を一行に並べて表示する。その際、合計の文字列長が指定したmaxlengthを越えないように適宜省略する
	 * @param str1 左側に表示される文字列
	 * @param str2 右側に表示される文字列
	 * @param maxlength 許容される最大長
	 * @return
	 */
	public static String getBrief2(final String str1, final String str2, final int maxlength) {
		return	SinaburoUtil.getBrief2(str1, str2, maxlength);
	}

	/**
	 * エラーメッセージを取得する
	 * @param property nameのID
	 * @return エラーメッセージ
	 */
	public String getMsg(String property) {
		return errorMarkup(property, null, request, request.getSession(false), application);
	}

	/**
	 * エラーメッセージを取得する
	 * @return エラーメッセージ
	 */
	public String getMsgs() {
		return errorMarkup(null, null, request, request.getSession(false), application);
	}

	@SuppressWarnings("unchecked")
	private static String errorMarkup(String property, String bundle, HttpServletRequest request, HttpSession session, ServletContext application) {

		ActionMessages errors = StrutsUtils.getErrors(request);
		if (errors == null) {
			return "";
		}

		Iterator reports = null;
		if (property == null) {
			reports = errors.get();
		}
		else {
			reports = errors.get(property);
		}

		if (!reports.hasNext()) {
			return "";
		}

		/* Render the error messages appropriately if errors have been queued */
		StringBuffer results = new StringBuffer();
		String header = null;
		String footer = null;
		String prefix = null;
		String suffix = null;
		Locale locale = SinaburoViewUtil.getLocale();

		MessageResources resources =
			StrutsUtils.getMessageResources(request, application, bundle);
		if (resources != null) {
			header = resources.getMessage(locale, "errors.header");
			footer = resources.getMessage(locale, "errors.footer");
			prefix = resources.getMessage(locale, "errors.prefix");
			suffix = resources.getMessage(locale, "errors.suffix");
		}
		if (header == null) {
			header = "errors.header";
		}
		if (footer == null) {
			footer = "errors.footer";
		}
		/* prefix or suffix are optional, be quiet if they're missing */
		if (prefix == null) {
			prefix = "";
		}
		if (suffix == null) {
			suffix = "";
		}

		results.append(header);
		results.append("\r\n");

		String message;
		SinaburoEscapeTool escapeTool = new SinaburoEscapeTool();

		while (reports.hasNext()) {
			message = null;
			ActionMessage report = (ActionMessage)reports.next();
			if (resources != null && report.isResource()) {
				message = resources.getMessage(locale, report.getKey(), report.getValues());
			}
			results.append(prefix);
			if (message != null) {
				results.append(message);
			} else {
				results.append(escapeTool.html(report.getKey()));
			}
			results.append(suffix);
			results.append("\r\n");
		}
		results.append(footer);
		results.append("\r\n");

		return results.toString();
	}

	public String getProperty(String key) {
		return PropertyUtil.getProperty(key);
	}

	/**
	 * ログインユーザー情報取得 Memberテーブルの情報
	 * @return ログインユーザー情報取得
	 */
	public Member getUserInfo(){
		AuthenticatedTokenVO token = (AuthenticatedTokenVO)session.getAttribute(AttrKey.AUTHENTICATED_TOKEN);
		if(token == null){
			return new Member();
		}

		return token.member;
	}

	/**
	 * ログインユーザー情報取得 Memberテーブルの情報
	 * @return ログインユーザー情報取得
	 */
	public AdminUser getAdminUserInfo(){
		AuthenticatedTokenVO token = (AuthenticatedTokenVO)session.getAttribute(AttrKey.AUTHENTICATED_TOKEN);
		if(token == null){
			return new AdminUser();
		}

		return token.adminUser;
	}



	/**
	 * 数字変換可能valueにコンマを追加する。
	 * @param value 数字変換可能value
	 * @return valueにコンマ追加
	 */
    public static String getNumberFormatStr(Object value){
    	if(!StringUtil.isNumber((value+""))){
    		return "0";
    	}
    	return String.format("%1$,3d", Long.parseLong(value.toString()));
    }

    /**
     * application_ja.propertiesから値を取得する。
     * @return
     */
    public String getMessage(String key){
    	return SinaburoViewUtil.getMessage(key);

    }

    public void saveToken(){
    	TokenProcessor.getInstance().saveToken(request);
    }

//    public String makeToken(){
//    		session.getAttribute("Globals.TRANSACTION_TOKEN_KEY");
//    	return "";
//
//    }


    public TestDto sessionkey(){
    	request.getAttribute("testDto");
    	return (TestDto)session.getAttribute("testDto");
    }

    /**
     * 改行コードをBRに変換する。
     * @param arg
     * @return
     */
    public String newLineToBr(String arg){
    	return StringUtil.isBlank(arg) ? arg : arg.replace(SinaburoConstant.newLine.SYSTEM, "</BR>");
    }

    public String addSlashDate(String arg){
    	if(arg == null){
    		return arg;
    	}
    	String val = arg;

    	if (arg.length() == 8) {
    		val =  SinaburoUtil.convertStringDateToFormat(arg, "/");
    	}
    	if (arg.length() == 6) {
    		val =  SinaburoUtil.convertStringDateToFormat2(arg, "/");
    	}
    	return val;
    }

    public String addSlashTime(String arg){
    	if(arg == null){
    		return arg;
    	}
    	String val = arg;

    	val =  SinaburoUtil.convertStringTimeToFormat(arg, "/");

    	return val;
    }

    /**
     * 今日の日付をyyyy/MM/ddで返す。
     * @return
     */
    public String getToDay(){
    	return  addSlashDate(SinaburoUtil.getToDayString());

    }

    /**
     * クリップボードを取得する。
     * @return
     */
    public static String getClipboardString() {
		Toolkit kit = Toolkit.getDefaultToolkit();
		Clipboard clip = kit.getSystemClipboard();

		try {
			return (String) clip.getData(DataFlavor.stringFlavor);
		} catch (UnsupportedFlavorException e) {
			return null;
		} catch (IOException e) {
			return null;
		}
	}

    /**
     * クリップボードを設定する。
     * @return
     */
    public static void setClipboardString(String str) {
		Toolkit kit = Toolkit.getDefaultToolkit();
		Clipboard clip = kit.getSystemClipboard();

		StringSelection ss = new StringSelection(str);
		clip.setContents(ss, ss);
	}

    /**
     * フルパスから、ファイル名だけ取得する。
     * @return
     */
    public static String getFileName(String fullPath/*,String split*/){
    	String split= "/";//split==null ? "/" : split;
    	if(fullPath.lastIndexOf(split) == -1){
    		return fullPath;
    	}
    	return fullPath.substring(fullPath.lastIndexOf(split)+1);
    }

    public Boolean isNotEmpty(Object list){

    	Boolean isEmplty = new ListTool().isEmpty(list);
    	if(isEmplty == null){
    		return false;
    	}
    	return  !isEmplty;
    }

    public Boolean isEmpty(String arg){
    	return StringUtil.isBlank(arg);
    }

    public String addNewLine(String arg){
    	return addNewLine(arg,30);
    }

    public String addNewLine(String arg,Integer count){
    	StringBuffer result = new StringBuffer();
    	String [] lines = arg.split("\r\n");
    	for (int i = 0; i < lines.length; i++) {
    		StringBuffer sb= new StringBuffer(lines[i]);
    		for(int j=count; j < sb.length();j+=count+2){
    			sb.insert(j,"\r\n");
    		}
    		result.append(sb);
		}
    	return result.toString();

    }

    public  String getSubStringByte(String arg){
    	return getSubStringByte(arg,12);
    }

    public  String getSubStringByte(String src,int len){
    	  int dstlen = 0;
    	  for(int i = 0;i < src.length() ;i++){
    	    dstlen += (src.charAt(i) <= 0xff ? 1 : 2);
    	    if(dstlen > len)
    	    return src.substring(0,i)+"..";
    	  }
    	  return src;
    }
    
    
    public String toShiftKARA() throws UnsupportedEncodingException{
    	return new String("~".getBytes(), "Shift_JIS");
    	
    }
//    public static void main(String[] args) {
//		System.out.println(getSubStringByte("指名指"));
//	}

}