/** * */ package jp.gr.java_conf.blancpanda.basic; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.ResourceBundle; import org.apache.commons.lang.StringUtils; /** * SystemDateはシステム日時を制御するためのクラスです。 * システム中で使用するシステム日時を1つにまとめて制御することで、 * 特定の日付でのテストが可能になります。 * */ public class SystemDate { private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd"); private static final SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm:ss.SSS"); private static boolean isFixed() { String fixed = getProperty("SystemDate.fixed"); if (fixed != null && fixed.toLowerCase().equals("true")) { return true; } return false; } private static Date fixDate() { Calendar cal = Calendar.getInstance(); try { String dateStr = getProperty("SystemDate.fixedDate"); String timeStr = getProperty("SystemDate.fixedTime"); if (!StringUtils.isEmpty(dateStr)) { Calendar tmpCal = Calendar.getInstance(); tmpCal.setTime(dateFormat.parse(dateStr)); if (!StringUtils.isEmpty(timeStr)) { Calendar tmpCal2 = Calendar.getInstance(); tmpCal2.setTime(timeFormat.parse(timeStr)); cal.set(tmpCal.get(Calendar.YEAR), tmpCal.get(Calendar.MONTH), tmpCal.get(Calendar.DATE), tmpCal2.get(Calendar.HOUR_OF_DAY), tmpCal2.get(Calendar.SECOND), tmpCal2.get(Calendar.MILLISECOND)); } else { cal.set(tmpCal.get(Calendar.YEAR), tmpCal.get(Calendar.MONTH), tmpCal.get(Calendar.DATE)); } } } catch (ParseException e) { // 固定値が正しく取得できなかった場合は本来のシステム日時を返す cal = Calendar.getInstance(); } return cal.getTime(); } public static Date getDate() { if (isFixed()) { return fixDate(); } else { return Calendar.getInstance().getTime(); } } public static Calendar getCalendar() { Calendar cal = Calendar.getInstance(); if (isFixed()) { cal.setTime(fixDate()); } return cal; } private static String getProperty(String key) { ResourceBundle rb = ResourceBundle.getBundle("basic", ResourceBundle.Control .getControl(ResourceBundle.Control.FORMAT_PROPERTIES)); return rb.getString(key); } }