var FormTool = { submit: function(obj, theForm){ var f = theForm && theForm.tagName == "FORM" ? theForm : document.createElement("form"); if(obj){ var e = false; for(var i in obj){ if(i.toString().charAt(0) == "$"){ // form attribute f.setAttribute(i.toString().substring(1),obj[i]); }else{ e = document.createElement("input"); e.type = "hidden"; e.name = i; e.value = obj[i]; f.appendChild(e); } } } if(!f.parentElement) document.body.appendChild(f); f.submit(); } }; // ex: // FormTool.submit({$action:'/myPage.php',pageIndex:2,pageSize:10});
2009/09/20
Form tool
2009/09/16
FileFactory
package bruce.lib.io; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; /** * @author Bruce Tsai * */ public final class FileFactory { /** * 建立目錄, 若父層目錄不存在一併建立 * * @param file * 目錄路徑 */ public static void createDirectory(String file) { createDirectory(new File(file)); } /** * 建立目錄, 若父層目錄不存在一併建立 * * @param file * 目錄 */ public static void createDirectory(File file) { if (file.getParentFile() != null && !file.getParentFile().exists()) { createDirectory(file.getParentFile()); } if (!file.exists()) file.mkdir(); } /** * 刪除檔案或目錄, 若刪除的為目錄, 一併刪除目錄下的所有檔案 * * @param file * 檔案或目錄 */ public static void delete(String file) { delete(new File(file)); } /** * 刪除檔案或目錄, 若刪除的為目錄, 一併刪除目錄下的所有檔案 * * @param file * 檔案或目錄 */ public static void delete(File file) { if (file.exists()) { if (file.isDirectory()) { File[] files = file.listFiles(); for (File f : files) { FileFactory.delete(f); } } int limit = 10 * 1000; // 10秒 long tick = System.currentTimeMillis(); while (file.exists()) { // 指定時間內無法刪除時擲出例外 if (file.delete() && System.currentTimeMillis() - tick > limit) throw new RuntimeException(); } } } /** * 複製檔案或目錄 * * @param sourceFile * 來源檔案或目錄 * @param destFile * 目的目錄 * @throws IOException */ public static void copy(String sourceFile, String destFile) throws IOException { copy(new File(sourceFile), new File(destFile)); } /** * 複製檔案或目錄 * * @param sourceFile * 來源檔案或目錄 * @param destFile * 目的目錄 * @throws IOException */ public static void copy(File sourceFile, File destFile) throws IOException { if (sourceFile.isFile()) { sourceFile.setReadable(true); FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(destFile); BufferedInputStream bis = new BufferedInputStream(fis); BufferedOutputStream bos = new BufferedOutputStream(fos); byte[] buffer = new byte[128]; int readed = -1; while ((readed = bis.read(buffer)) > -1) { bos.write(buffer, 0, readed); } bos.close(); fos.close(); fis.close(); fos.close(); } else { destFile.mkdir(); File[] files = sourceFile.listFiles(); for (File f : files) { copy(f, new File(String.format("%s\\%s", destFile.getAbsolutePath(), f.getName()))); } } } /** * 讀取檔案內的全部文字資料 * * @param file * 要讀取的檔案 * @return * @throws IOException */ public static String readAllText(File file) throws IOException { return new String(readAllBytes(file)); } /** * 讀取檔案內的全部文字資料 * * @param file * 要讀取的檔案 * @param encoding * 文字編碼 * @return * @throws IOException */ public static String readAllText(File file, String encoding) throws IOException { return new String(readAllBytes(file), encoding); } /** * 讀取檔案內的全部位元資料 * * @param file * 要讀取的檔案 * @return * @throws IOException */ public static byte[] readAllBytes(File file) throws IOException { FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int b = -1; while ((b = fis.read()) > -1) { baos.write(b); } baos.close(); fis.close(); return baos.toByteArray(); } /** * 將內容寫入檔案. 寫入時呼叫 toString() 並將回傳值寫入檔案 * * @param file * 要寫入的檔案 * @param content * 要寫入的內容 * @throws IOException */ public static void writeAllText(File file, Object content) throws IOException { FileWriter writer = new FileWriter(file); writer.write(content.toString()); writer.close(); } /** * 將內容寫入檔案. 寫入時呼叫 toString() 並將回傳值寫入檔案 * * @param file * 要寫入的檔案 * @param content * 要寫入的內容 * @param encoding * 文字編碼 * @throws IOException */ public static void writeAllText(File file, Object content, String encoding) throws IOException { FileOutputStream fos = new FileOutputStream(file); OutputStreamWriter writer = new OutputStreamWriter(fos, encoding); writer.write(content.toString()); writer.close(); fos.close(); } /** * 將內容寫入檔案. 寫入時呼叫 toString() 並將回傳值寫入檔案, 若檔案存在, 將內容加入至檔案結尾, 檔案不存在時, 直接寫入 * * @param file * 要寫入的檔案 * @param content * 要寫入的內容 * @throws IOException */ public static void appendAllText(File file, Object content) throws IOException { FileWriter writer = new FileWriter(file, true); writer.write(content.toString()); writer.close(); } /** * 將內容寫入檔案. 寫入時呼叫 toString() 並將回傳值寫入檔案, 若檔案存在, 將內容加入至檔案結尾, 檔案不存在時, 直接寫入 * * @param file * 要寫入的檔案 * @param content * 要寫入的內容 * @param encoding * 文字編碼 * @throws IOException */ public static void appendAllText(File file, Object content, String encoding) throws IOException { if (file.exists()) { appendAllText(file, content); } else { writeAllText(file, content, encoding); } } /** * 將內容寫入檔案 * * @param file * 要寫入的檔案 * @param bytes * 要寫入的內容 * @throws IOException */ public static void writeAllBytes(File file, byte[] bytes) throws IOException { FileOutputStream fos = new FileOutputStream(file); fos.write(bytes); fos.close(); } /** * 將內容寫入檔案. 若檔案存在, 將內容加入至檔案結尾, 檔案不存在時, 直接寫入 * * @param f * 要寫入的檔案 * @param bytes * 要寫入的內容 * @throws IOException */ public static void appendAllBytes(File f, byte[] bytes) throws IOException { FileOutputStream fos = new FileOutputStream(f, true); fos.write(bytes); fos.close(); } }
DateHelper
package bruce.lib; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** * @author NaNashi * */ public class DateHelper { private final static SimpleDateFormat LOG_DATE = new SimpleDateFormat("yyyyMMdd", Locale.US); private final static SimpleDateFormat DATE_ONLY = new SimpleDateFormat("yyyy/MM/dd", Locale.US); private final static SimpleDateFormat FULL_DATE = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss", Locale.US); public final static String logDate() { return LOG_DATE.format(new Date()); } public final static String formatDate(Date date) { return date == null ? null : DATE_ONLY.format(date); } public final static String formatFullDate(Date date) { return date == null ? null : FULL_DATE.format(date); } public final static Date parseDate(String source) { return parseDate(source, false); } public final static Date parseDate(String source, boolean returnNowOnfailed) { try { return DATE_ONLY.parse(source); } catch (Exception e) { return returnNowOnfailed ? new Date() : null; } } public final static Date parseFullDate(String source) { return parseDate(source, false); } public final static Date parseFullDate(String source, boolean returnNowOnfailed) { try { return FULL_DATE.parse(source); } catch (Exception e) { return returnNowOnfailed ? new Date() : null; } } public final static String diffTime(Date before, Date after) { long sticks = Math.abs(before.getTime() - after.getTime()); int seconds = (int) (sticks / 1000); int minutes = seconds / 60; int hours = minutes / 60; int days = hours / 24; StringBuilder sb = new StringBuilder(); if (days > 0) { sb.append(days).append("天"); hours -= days * 24; minutes -= days * 24 * 60; seconds -= days * 24 * 60 * 60; } if (hours > 0) { sb.append(hours).append("小時"); minutes -= hours * 60; seconds -= hours * 60 * 60; } if (hours > 0 || minutes > 0) { sb.append(minutes).append("分"); seconds -= minutes * 60; } sb.append(seconds).append("秒").append(before.after(after) ? "後" : "前"); return sb.toString(); } public static String replaceMonthWord(String s) { s = s.toLowerCase(); String[] month = new String[] { "January", "Februaary", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; for (int i = 0; i < month.length; i++) { String m = month[i].toLowerCase(); if (s.contains(m.toLowerCase())) return s.replace(m, String.valueOf(i + 1)); } return s; } }
DateTime
package bruce.lib; import java.io.Serializable; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.Locale; import java.util.TimeZone; import java.util.TreeSet; public class DateTime implements Serializable, Cloneable, Comparable<DateTime> { public static DateTime now() { return new DateTime(); } public static DateTime fromDate(Date date) { DateTime d = new DateTime(); d.c.setTime(date); return d; } public static DateTime fromTimestamp(long stamp) { DateTime d = new DateTime(); d.c.setTimeInMillis(stamp); return d; } public static DateTime fromCalendar(Calendar c) { DateTime d = new DateTime(); d.c = c; return d; } public static DateTime fromString(String date, String format) throws ParseException { DateTime d = new DateTime(); d.c.setTime(new SimpleDateFormat(format).parse(date)); return d; } public static DateTime fromString(String date, String format, Locale locale) throws ParseException { DateTime d = new DateTime(); d.c.setTime(new SimpleDateFormat(format, locale).parse(date)); return d; } public static DateTime latest(DateTime... dates) { TreeSet<DateTime> set = new TreeSet<DateTime>(); set.addAll(Arrays.asList(dates)); return set.last(); } public static DateTime oldest(DateTime... dates) { TreeSet<DateTime> set = new TreeSet<DateTime>(); set.addAll(Arrays.asList(dates)); return set.first(); } private Calendar c; public enum Field { ERA, // AD/BC YEAR, // MONTH, // WEEK_OF_YEAR, // WEEK_OF_MONTH, // AM_PM_MARKER, // AM/PM DATE, // DAY_OF_MONTH, // DAY_OF_WEEK, // DAY_OF_WEEK_IN_MONTH, // DAY_OF_YEAR, // HOUR, // MINUTE, // SECOND, // MILLISECOND, // TIMEZONE } public class Month { public static final int JANUARY = 0; public static final int FEBRUARY = 1; public static final int MARCH = 2; public static final int APRIL = 3; public static final int MAY = 4; public static final int JUNE = 5; public static final int JULY = 6; public static final int AUGUST = 7; public static final int SEPTEMBER = 8; public static final int OCTOBER = 9; public static final int NOVEMBER = 10; public static final int DECEMBER = 11; public static final int UNDECIMBER = 12; } public class Day { public static final int SUNDAY = 1; public static final int MONDAY = 2; public static final int TUESDAY = 3; public static final int WEDNESDAY = 4; public static final int THURSDAY = 5; public static final int FRIDAY = 6; public static final int SATURDAY = 7; } private DateTime() { this.c = Calendar.getInstance(); } public boolean after(DateTime datetime) { return this.toTimeInMillis() > datetime.toTimeInMillis(); } public boolean before(DateTime datetime) { return this.toTimeInMillis() < datetime.toTimeInMillis(); } public DateTime add(Field field, int amount) { switch (field) { case YEAR: this.c.add(Calendar.YEAR, amount); return this; case MONTH: this.c.add(Calendar.MONTH, amount); return this; case WEEK_OF_YEAR: case WEEK_OF_MONTH: this.c.add(Calendar.DATE, amount * 7); return this; case DATE: case DAY_OF_MONTH: case DAY_OF_WEEK: case DAY_OF_WEEK_IN_MONTH: case DAY_OF_YEAR: this.c.add(Calendar.DATE, amount); return this; case MINUTE: this.c.add(Calendar.MINUTE, amount); return this; case SECOND: this.c.add(Calendar.SECOND, amount); return this; case HOUR: this.c.add(Calendar.HOUR, amount); return this; case MILLISECOND: this.c.add(Calendar.MILLISECOND, amount); return this; default: throw new IllegalArgumentException("Unaccepted field."); } } public DateTime addYear(int amount) { return this.add(Field.YEAR, amount); } public DateTime addMonth(int amount) { return this.add(Field.MONTH, amount); } public DateTime addWeek(int amount) { return this.add(Field.WEEK_OF_YEAR, amount); } public DateTime addDay(int amount) { return this.add(Field.DAY_OF_YEAR, amount); } public DateTime addMinute(int amount) { return this.add(Field.MINUTE, amount); } public DateTime addSecond(int amount) { return this.add(Field.SECOND, amount); } public DateTime addHour(int amount) { return this.add(Field.HOUR, amount); } public DateTime addMilliSecond(int amount) { return this.add(Field.MILLISECOND, amount); } public DateTime set(Field field, int value) { switch (field) { // case ERA: case YEAR: this.c.set(Calendar.YEAR, value); return this; case MONTH: this.c.set(Calendar.MONTH, value); return this; // case WEEK_OF_YEAR: // case WEEK_OF_MONTH: // case AM_PM_MARKER: case DATE: this.c.set(Calendar.DATE, value); return this; // case DAY_OF_MONTH: // case DAY_OF_WEEK: // case DAY_OF_WEEK_IN_MONTH: // case DAY_OF_YEAR: case HOUR: this.c.set(Calendar.HOUR, value); return this; case MINUTE: this.c.set(Calendar.MINUTE, value); return this; case SECOND: this.c.set(Calendar.SECOND, value); return this; case MILLISECOND: this.c.set(Calendar.MILLISECOND, value); return this; // case TIMEZONE: default: throw new IllegalArgumentException("Unaccepted field."); } } public DateTime setYear(int value) { return this.set(Field.YEAR, value); } public DateTime setMonth(int value) { return this.set(Field.MONTH, value); } public DateTime setDate(int value) { return this.set(Field.DATE, value); } public DateTime setHour(int value) { return this.set(Field.HOUR, value); } public DateTime setMinute(int value) { return this.set(Field.MINUTE, value); } public DateTime setSecond(int value) { return this.set(Field.SECOND, value); } public DateTime setMilliSecond(int value) { return this.set(Field.MILLISECOND, value); } public int get(Field field) { switch (field) { case YEAR: return this.c.get(Calendar.YEAR); case MONTH: return this.c.get(Calendar.MONTH); case WEEK_OF_YEAR: return this.c.get(Calendar.WEEK_OF_YEAR); case WEEK_OF_MONTH: return this.c.get(Calendar.WEEK_OF_MONTH); case DATE: return this.c.get(Calendar.DATE); case DAY_OF_MONTH: return this.c.get(Calendar.DAY_OF_MONTH); case DAY_OF_WEEK: return this.c.get(Calendar.DAY_OF_WEEK); case DAY_OF_WEEK_IN_MONTH: return this.c.get(Calendar.DAY_OF_WEEK_IN_MONTH); case DAY_OF_YEAR: return this.c.get(Calendar.DAY_OF_YEAR); case MINUTE: return this.c.get(Calendar.MINUTE); case SECOND: return this.c.get(Calendar.SECOND); case HOUR: return this.c.get(Calendar.HOUR); case MILLISECOND: return this.c.get(Calendar.MILLISECOND); default: throw new IllegalArgumentException("Unaccepted field."); } } public int getYear() { return this.get(Field.YEAR); } public int getMonth() { return this.get(Field.MONTH); } public int getWeekOfYear() { return this.get(Field.WEEK_OF_YEAR); } public int getWeekOfMonth() { return this.get(Field.WEEK_OF_MONTH); } public int getDate() { return this.get(Field.DATE); } public int getDayOfMonth() { return this.get(Field.DAY_OF_MONTH); } public int getDayOfWeek() { return this.get(Field.DAY_OF_WEEK); } public int getDayOfWeekInMonth() { return this.get(Field.DAY_OF_WEEK_IN_MONTH); } public int getDayOfYear() { return this.get(Field.DAY_OF_YEAR); } public int getHour() { return this.get(Field.HOUR); } public int getMinute() { return this.get(Field.MINUTE); } public int getSecond() { return this.get(Field.SECOND); } public int getMilliSecond() { return this.get(Field.MILLISECOND); } public TimeZone getTimeZone() { return this.c.getTimeZone(); } public DateTime setTimeZone(TimeZone zone) { this.c.setTimeZone(zone); return this; } public long toTimeInMillis() { return this.c.getTimeInMillis(); } public Date toDate() { return this.c.getTime(); } public Calendar toCalendar() { return this.c; } @Override public String toString() { return this.c.getTime().toString(); } public String toString(String format) { SimpleDateFormat f = new SimpleDateFormat(format); return f.format(this.c.getTime()); } public String toString(String format, Locale locale) { SimpleDateFormat f = new SimpleDateFormat(format, locale); return f.format(this.c.getTime()); } @Override public int hashCode() { return c.getTime().hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DateTime other = (DateTime) obj; return this.c.getTimeInMillis() == other.toTimeInMillis(); } @Override public int compareTo(DateTime o) { return (int) (this.toTimeInMillis() - o.toTimeInMillis()); } }
StreamReader
package bruce.lib.io; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; /** * @author Bruce Tsai * */ public class StreamReader { private InputStream stream; public String encoding; /** * @param stream */ public StreamReader(InputStream stream) { this.stream = stream; } /** * @param stream * @param encoding */ public StreamReader(InputStream stream, String encoding) { this.stream = stream; this.encoding = encoding; } /** * @return * @throws IOException */ public String readAllText() throws IOException { return this.encoding == null || this.encoding.length() == 0 ? new String(readAllBytes()) : new String(readAllBytes(), this.encoding); } /** * @return * @throws IOException */ public byte[] readAllBytes() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[128]; int readed = -1; while ((readed = this.stream.read(buffer)) > -1) { baos.write(buffer, 0, readed); } baos.close(); this.stream.close(); return baos.toByteArray(); } }
ResourceReader
package bruce.lib; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; /** * @author NaNashi * */ public class ResourceReader { public static String readText(String path, String encoding) throws IOException { InputStream is = ResourceReader.class.getClassLoader().getResourceAsStream(path); StreamReader reader = new StreamReader(is, encoding); String content = reader.readToEnd(); is.close(); return content; } public static byte[] readBytes(String path) throws IOException { InputStream is = ResourceReader.class.getClassLoader().getResourceAsStream(path); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int value = -1; while ((value = is.read()) > -1) baos.write(value); baos.close(); is.close(); return baos.toByteArray(); } }
Validator
package bruce.lib; import java.util.regex.Pattern; public class Validator { public final static boolean isCreditCard(CharSequence input) { return input == null ? false : Pattern.matches("^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\\d{3})\\d{11})$", input); } public final static boolean isDomain(CharSequence input) { return input == null ? false : Pattern.matches("^[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\\.[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\\.[a-zA-Z]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)?$", input); } public final static boolean isFloatingPointNumber(CharSequence input) { return input == null ? false : Pattern.matches("[-+]?([0-9]+\\.?[0-9]*|\\.[0-9]+)([eE][-+]?[0-9]+)?", input); } public final static boolean isGUID(CharSequence input) { return input == null ? false : Pattern.matches("^[\\d\\w]{8}-[\\d\\w]{4}-[\\d\\w]{4}-[\\d\\w]{4}-[\\d\\w]{12}$", input); } public final static boolean isIPAddress(CharSequence input) { return input == null ? false : Pattern.matches("\\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b", input); } public final static boolean isLettersOnly(CharSequence input) { return input == null ? false : Pattern.matches("^[[:alpha:]]+$", input); } public final static boolean isMailAddress(CharSequence input) { return input == null ? false : Pattern.matches("\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*", input); } public final static boolean isNumeric(CharSequence input) { return input == null ? false : Pattern.matches("^\\d+$", input); } public final static boolean isPhoneNumber(CharSequence input) { return input == null ? false : Pattern.matches("^[\\d-]{7,15}$", input); } public final static boolean isSocialID(CharSequence input) { return input == null ? false : Pattern.matches("^[a-zA-Z]\\d{9}$", input); } public final static boolean isSymbolIncluded(CharSequence input) { return input == null ? false : Pattern.matches("[`~!@#$%^&*\\(\\)_+=-\\|\\[\\]{};':\",\\./<>?]", input); } public final static boolean isUrl(CharSequence input) { return input == null ? false : Pattern.matches("http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?", input); } }
2009/09/10
A simple work
public class Tri { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub int last = 5; for (int i = 1, n = 1; i <= last; i++) { int p = n; while (p-- > 0) System.out.print(Integer.toHexString(i)); n = i <= last / 2 ? n + 1 : n - 1; System.out.println(); } } }