Popular Posts
Enable SSL connection for Jsoup import org.jsoup.Connection; import org.jsoup.Jsoup; import javax.net.ssl.*; import java.io.IOException; import java.security.KeyManagement... Simple Web snapshot import java.util.Date; import org.eclipse.swt.SWT; import org.eclipse.swt.browser.Browser; import org.eclipse.swt.graphics.GC; import org.e... Tired of Hibernate? Try JDBI in your code JDBI Quick sample ICategoryDAO.java : create a data access interface (implement is not required) package com.prhythm.erotic.task.data....
Blog Archive
Stats
SwiXml Xml schema
<?xml version="1.0" encoding="UTF-8"?>
<frame xmlns="http://www.swixml.org/2007/SwixmlTags" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.swixml.org/2007/SwixmlTags http://www.swixml.org/2007/swixml.xsd"
    title="Config Editor" DefaultCloseOperation="JFrame.EXIT_ON_CLOSE"
    size="800,600">
    <menubar>
        ....
    </menubar>
    <scrollpane id="spEditPane" constraints="BorderLayout.CENTER">
        ....
    </scrollpane>
</frame>
XML Schema for Swixml
CKEditor compact implement guid
implement way 1 : use css
<textarea id="editor" class="ckeditor"></textarea>
implement way 2 : use javascript
<textarea id="editor"></textarea>
<script type="text/javascript">
// default
CKEDITOR.replace("editor");
// with settings
CKEDITOR.replace("editor", {skin:"office2003", toolbar:"Basic"});
</script>
implement way 3 : use jQuery
<textarea id="editor"></textarea>
<script type="text/javascript">
// default
$("#editor").ckeditor();
// with settings
$("#editor").ckeditor(
    function(){
        // callback code
    },
    {
        uiColor: "pink",
        skin: "kama",
        toolbar: [
            ["Source", "Preview"],
            "/",  // line break
            ["Cut", "Copy", "Paste", "PasteText", "PasteFromWord", "Print", "SpellChecker", "Scayt"]
        ]
    }
);
</script>
toolbar properties
"Source"
"Save" "NewPage" "Preview" "Templates"
"Cut" "Copy" "Paste" "PasteText" "PasteFromWord" "Print" "SpellChecker" "Scayt"
"Undo" "Redo" "Find" "Replace" "SelectAll" "RemoveFormat"
"Form" "Checkbox" "Radio" "TextField" "Textarea" "Select" "Button" "ImageButton" "HiddenField"
"Bold" "Italic" "Underline" "Strike" "Subscript" "Superscript"
"NumberedList" "BulletedList" "Outdent" "Indent" "Blockquote"
"JustifyLeft" "JustifyCenter" "JustifyRight" "JustifyBlock"
"Link" "Unlink" "Anchor"
"Image" "Flash" "Table" "HorizontalRule" "Smiley" "SpecialChar" "PageBreak"
"Styles" "Format" "Font" "FontSize"
"TextColor" "BGColor"
"Maximize" "ShowBlocks" "About"

CKEditor 3 JavaScript API Documentation

jQuery UI, adjust font size
.ui-widget { font-family: Verdana, Arial, sans-serif; font-size: 10pt; }
File properties
FOR %%? IN (file_to_be_queried) DO (
    ECHO File Name Only       : %%~n?
    ECHO File Extension       : %%~x?
    ECHO Name in 8.3 notation : %%~sn?
    ECHO File Attributes      : %%~a?
    ECHO Located on Drive     : %%~d?
    ECHO File Size            : %%~z?
    ECHO Last-Modified Date   : %%~t?
    ECHO Parent Folder        : %%~dp?
    ECHO Fully Qualified Path : %%~f?
    ECHO FQP in 8.3 notation  : %%~sf?
    ECHO Location in the PATH : %%~dp$PATH:?
)
Get class name in static method
public class Parent {

    public static String getClassName() {
        return new Object() {
        }.getClass().getEnclosingClass().getName();
    }

    public static void main(String[] args) {
        System.out.println(getClassName());
    }
}
Dynamic Proxy
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Date;

public class MathObj implements IMath {

    @Override
    public double sum(Number... value) {
        double sum = 0;
        for (int i = 0; i < value.length; i++) {
            System.out.print(value[i]);
            if (i < value.length - 1)
                System.out.print(" + ");
            sum += value[i].doubleValue();
        }
        System.out.printf(" = %f%n", sum);
        return sum;
    }

    public static void main(String[] args) throws ClassNotFoundException {
        // 建立代理物件
        Object deleagate = Proxy.newProxyInstance(
                ObjectHandler.class.getClassLoader(),
                new Class[] { IMath.class },
                new ObjectHandler(new MathObj())
        );

        // 利用代理執行
        double sum = ((IMath) deleagate).sum(1, 2, 3, 4, 5, 6, 7);

        System.out.printf("Invoke result: %f%n", sum);
    }

}

// 定義代理程式
class ObjectHandler implements InvocationHandler {

    // 原始物件
    Object o;

    public ObjectHandler(Object o) {
        this.o = o;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 委派代理呼叫方法時, 要處理的動作
        System.out.println("Start at " + new Date());
        Object result = method.invoke(o, args);
        System.out.println("End at " + new Date());
        return result;
    }

}

// 定義介面
interface IMath {
    double sum(Number... value);
}
感想: 不好用xd
Test file exist in batch
@echo off
SET file=mes.log
SET filename=mes

for /f %%a in ('dir /b /a-d %file%') do (
 if %%~na==%filename% GOTO :FileFound
)
GOTO :FileNotFound

:FileFound
ECHO FILE FOUND
GOTO :BatchEnd

:FileNotFound
ECHO FILE NOT FOUND

:BatchEnd
ECHO END
SQL Server T-SQL Cheat Sheet
DECLARE and SET Varibales
DECLARE @Mojo int
SET @Mojo = 1
SELECT @Mojo = Column FROM Table WHERE id=1
IF / ELSE IF / ELSE Statement
IF @Mojo < 1
  BEGIN
 PRINT 'Mojo Is less than 1'
  END
ELSE IF @Mojo = 1
  BEGIN
    PRINT 'Mojo Is 1'
  END
ELSE
  BEGIN
 PRINT 'Mojo greater than 1'
  END
CASE Statement
SELECT Day = CASE 
  WHEN (DateAdded IS NULL) THEN 'Unknown'
  WHEN (DateDiff(day, DateAdded, getdate()) = 0) THEN 'Today'
  WHEN (DateDiff(day, DateAdded, getdate()) = 1) THEN 'Yesterday'
  WHEN (DateDiff(day, DateAdded, getdate()) = -1) THEN 'Tomorrow'
  ELSE DATENAME(dw , DateAdded) 
END
FROM Table
Add A Column
ALTER TABLE YourTableName ADD [ColumnName] [int] NULL;
Rename a Column
EXEC sp_rename 'TableName.OldColName', 'NewColName','COLUMN';
Rename a Table
EXEC sp_rename 'OldTableName', 'NewTableName';
Add a Foreign Key
ALTER TABLE Products WITH CHECK 
ADD CONSTRAINT [FK_Prod_Man] FOREIGN KEY(ManufacturerID)
REFERENCES Manufacturers (ID);
Add a NULL Constraint
ALTER TABLE TableName ALTER COLUMN ColumnName int NOT NULL;
Set Default Value for Column
ALTER TABLE TableName ADD CONSTRAINT 
DF_TableName_ColumnName DEFAULT 0 FOR ColumnName;
Create an Index
CREATE INDEX IX_Index_Name ON Table(Columns)
Check Constraint
ALTER TABLE TableName
ADD CONSTRAINT CK_CheckName CHECK (ColumnValue > 1)
DROP a Column
ALTER TABLE TableName DROP COLUMN ColumnName;
Single Line Comments
SET @mojo = 1 --THIS IS A COMMENT
Multi-Line Comments
/* This is a comment
 that can span
 multiple lines
*/
Try / Catch Statements
BEGIN TRY
 -- try / catch requires SQLServer 2005 
 -- run your code here
END TRY
BEGIN CATCH
 PRINT 'Error Number: ' + str(error_number()) 
 PRINT 'Line Number: ' + str(error_line())
 PRINT error_message()
 -- handle error condition
END CATCH
While Loop
DECLARE @i int
SET @i = 0
WHILE (@i < 10)
BEGIN
 SET @i = @i + 1
 PRINT @i
 IF (@i >= 10)
  BREAK
 ELSE
  CONTINUE
END
CREATE a Table
CREATE TABLE TheNameOfYourTable (
  ID INT NOT NULL IDENTITY(1,1),
  DateAdded DATETIME DEFAULT(getdate()) NOT NULL,
  Description VARCHAR(100) NULL,
  IsGood BIT DEFAULT(0) NOT NULL,
  TotalPrice MONEY NOT NULL,  
  CategoryID int NOT NULL REFERENCES Categories(ID),
  PRIMARY KEY (ID)
);
User Defined Function
CREATE FUNCTION dbo.DoStuff(@ID int)
RETURNS int
AS
BEGIN
  DECLARE @result int
  IF @ID = 0
 BEGIN
  RETURN 0
 END
  SELECT @result = COUNT(*) 
  FROM table WHERE ID = @ID
  RETURN @result
END
GO
SELECT dbo.DoStuff(0)
Reference : SQL Server T-SQL Cheat Sheet
Log4j : Conversion Pattern
ConversionPattern參數的格式含義 
格式名 含義 
%c     輸出日誌資訊所屬的類的全名 
%d     輸出日誌時間點的日期或時間,默認格式為ISO8601,也可以在其後指定格式,比如:%d{yyy-MM-dd HH:mm:ss },輸出類似:2002-10-18- 22:10:28 
%f     輸出日誌資訊所屬的類的類名 
%l     輸出日誌事件的發生位置,即輸出日誌資訊的語句處於它所在的類的第幾行 
%m     輸出代碼中指定的資訊,如log(message)中的message 
%n     輸出一個回車換行符,Windows平臺為“rn”,Unix平臺為“n” 
%p     輸出優先順序,即DEBUG,INFO,WARN,ERROR,FATAL。如果是調用debug()輸出的,則為DEBUG,依此類推 
%r     輸出自應用啟動到輸出該日誌資訊所耗費的毫秒數 
%t     輸出產生該日誌事件的線程名
Level : OFF、FATAL、ERROR、WARN、INFO、DEBUG、ALL
JDBC: oracle date type missing "time"
Class.forName(jdbc_driver);
Properties prop = new Properties();
prop.setProperty("user", user);
prop.setProperty("password", password);
// 解決使用 ojdbc14.jar 連某些版本的資料庫,若使用 getObject() 來取得 DATE TYPE 欄位資料時,會有取不到時間的問題
prop.setProperty("oracle.jdbc.V8Compatible", "true");
Connection conn = DriverManager.getConnection(url, prop);
JavaMail sample
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.Properties;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class JavaMailSample {

    static String smtpHost = "smtp.bruce.com.tw";
    static int smtpPort = 25;

    static String[] from = new String[] { "bruce@bruce.com.tw", "Bruce Tasi" };
    static String to = "nanashi@bruce.com.tw";
    static String account = "account";
    static String password = "password";

    static String subject = "信件主旨";
    static String contentType = "text/html;charset=utf-8";
    static String body = "<html><body><h1 style=\"color:blue;\">Mail test</h1><img src=\"cid:image01\" /></body></html>";

    static Message getMessage(Session session) throws MessagingException, UnsupportedEncodingException {
        Message msg = new MimeMessage(session);
        // 寄件者
        msg.setFrom(new InternetAddress(from[0], from[1]));
        // msg.setFrom(new InternetAddress(String.format("\"%s\"<%s>", from[1], from[0])));
        // 收件者
        InternetAddress[] address = InternetAddress.parse(to, false);
        msg.setRecipients(Message.RecipientType.TO, address);
        // 主旨 (需編碼)
        msg.setSubject(MimeUtility.encodeText(subject, "utf-8", "B"));
        // 寄件時間
        msg.setSentDate(new Date());

        // 附件
        File file = new File("write.png");
        if (file.exists()) {
            // 內文
            MimeBodyPart contentBody = new MimeBodyPart();
            // 內容與格式
            contentBody.setContent(body, contentType);

            // 附件
            MimeBodyPart attachment = new MimeBodyPart();
            FileDataSource fds = new FileDataSource(file.getName());
            attachment.setDataHandler(new DataHandler(fds));
            // 附件名稱 (需編碼)
            attachment.setFileName(MimeUtility.encodeText(fds.getName(), "utf-8", "B"));
            // 附件代號, 用於顯示郵件內文
            attachment.setHeader("Content-ID", "<image01>");

            // 組成郵件
            MimeMultipart mp = new MimeMultipart();
            // 內容顯示附件圖片時, 必須設定為related
            mp.setSubType("related");
            mp.addBodyPart(contentBody);
            mp.addBodyPart(attachment);
            msg.setContent(mp);
        } else {
            // 若沒有檔案時,就直接存郵件內容
            msg.setContent(body, contentType);
        }
        return msg;
    }

    static void sendMail1() throws MessagingException, UnsupportedEncodingException {
        // 建立工作階段
        Session session = Session.getDefaultInstance(new Properties(), null);
        // 開啟除錯模式
        session.setDebug(true);

        Message msg = getMessage(session);

        Transport transport = session.getTransport("smtp");
        transport.connect(smtpHost, smtpPort, account, password);
        transport.sendMessage(msg, msg.getAllRecipients());
        transport.close();
    }

    static void sendMail2() throws UnsupportedEncodingException, MessagingException {
        Properties props = new Properties();

        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", smtpPort);
        props.put("mail.smtp.auth", "true");
        // props.put("mail.smtp.socketFactory.port", smtpPort);
        // props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(account, password);
            }
        });
        session.setDebug(true);

        Message msg = getMessage(session);

        Transport.send(msg);
    }

}
JavaMail
Dynamic load class & invoke method
import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.JarEntry;
import java.util.jar.JarInputStream;

public class ClassLoaderSample {

    public static void main(String[] args) throws Exception {
        String jarFile = "C:/workspace/bruce.lib/Blib.jar";

        URLClassLoader dynamicLoader = URLClassLoader.newInstance(new URL[] { new URL("file", null, jarFile) }, ClassLoaderTest.class.getClassLoader());

        // List content
        JarInputStream jis = new JarInputStream(new FileInputStream(jarFile));
        JarEntry entry = null;

        while ((entry = jis.getNextJarEntry()) != null) {
            String name = entry.getName();
            System.out.println(name);
        }

        System.out.println("=====");

        // Inovke method
        Class objClass = Class.forName("aaa.bbb.PrintTable", true, dynamicLoader);
        Object obj = objClass.newInstance();
        Method objMethod = objClass.getDeclaredMethod("print");
        objMethod.invoke(obj);

        // Field value
        Field objField = objClass.getDeclaredField("tableName");
        System.out.println(objField.get(obj));
        // Change field value
        objField.set(obj, "myTable");
    }

}