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... Word break tag : <wbr/> (HTML5) The  HTML  <wbr>  tag  is  used  defines  a  potential  line  break  point  if  needed.  This  stands  for  Word  BReak. This  is  u... Build an OpenVPN server on android device Preparation An android device, in this case, Sony xperia Z is used Root permission required Linux Deploy for deploy i...
Blog Archive
Stats
Tomcat GET encoding
edit server.xml :
<Connector
    URIEncoding="UTF-8"
    connectionTimeout="20000"
    port="8080"
    protocol="HTTP/1.1"
    redirectPort="8443"
    />
記得以前只要在 filter 裡設定 request 的 encoding 就可以正常處理
這次怎麼弄 GET 的編碼就是不對...
找到一篇 舊文 說明了此一問題, 還真是一點都沒進步啊...
jQuery serialize form to json
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};
jQuery metadata
$(document).ready(function(){
    var data = $("#message").metadata();
    var i; 
    for(i in data){
        $("#message").append("<div>"+i+"="+data[i]+"</div>");
    }
});
<div id="message" class="mess {firstName:'Bruce',lastName:'Tsai'}"></div>
jQuery validate
利用 css (class屬性), 只能處理預設驗證規則(required, email....)
*Account :
*e-mail :
利用 rules 加入驗證規則與自訂錯誤訊息
Cell Phone :
驗證成功與失敗時的處置
Age1 :
Age2 :
新增移除規則
Test email1:
Test email2:
搭配 Matadata 在 class 屬性中設定驗證規則
Number1 :
自訂驗證規則
Number2 :
Social ID :
驗證規則依存性
address :
(function(){
    $("#form01").validate({
        debug: true  // 除錯模式
    });
    
    $("#form02").validate({
        rules: {
            cellphone: {  // form.name
                required: true,
                digits: true,
                minlength: 5
            }
        },
        messages: {
            cellphone: {  // form.name
                required: "請填寫電話!",
                digits: "請填寫電話號碼!",
                minlength: $.format("至少填入 {0} 個數值")  // 對應驗證的參數
            }
        },
        debug: true
    });
    
    $("#form03").validate({
        submitHandler: function(form){
            alert("Age1 value : " + $("#age1").val());
            form.submit();
            //$(form).ajaxSubmit();
        },
        invalidHandler: function(form, validator){
            var errors = validator.numberOfInvalids();
            alert($.format("錯誤數 : {0}", errors));
        }
    });
    
    $("#form04").validate();
    $("#testemail1").rules("add", {required:true});
    
    $("#form05").validate();
    
    // 新增驗證規則, 作法一
    $.validator.methods.lessThanSquare = function(value, element, param){
        // @value 輸入的值
        // @element 驗證的目標元件
        // @param 設定規則時的參數
        return value * value < param;
    };
    // 新增驗證規則, 作法二
    $.validator.addMethod("testSocialId", function(value, element, param){
        return /\w\d{9}/.test(value);
    }, "身份證號驗證錯誤");
    $("#form06").validate({
        rules: {
            number2: {
                required: true,
                digits: true,
                lessThanSquare: 100
            },
            socialid: {
                required: true,
                testSocialId: true
            }
        },
        messages: {
            number2: {
                lessThanSquare: "數值錯誤"
            }
        }
    });
    
    $("#form07").validate({
        rules: {
            address: {
                required: "#requiredaddresscheck:checked"
            }
        }
    });
})();
Hierarchical Query
Start with connect by prior 階層式查詢用法
SELECT
  s.role_id,
  s.role_name,
  s.role_base_on,
  b.role_name role_base_on_name
FROM m_usr_role s
LEFT JOIN m_usr_role b ON b.role_id = s.role_base_on
ROLE_ID                              ROLE_NAME                                          ROLE_BASE_ON                         ROLE_BASE_ON_NAME                                  
------------------------------------ -------------------------------------------------- ------------------------------------ -------------------------------------------------- 
system.administrator                 系統管理員                                          common.logon.user                    登入帳號                                            
85e9953c-00fd-4a0c-979c-7a41bd3f085a 初學者                                             231570cd-832f-40e3-b198-fb2336245926 訪客                                               
868a17dd-7d21-48a6-b2d5-f9a80313414a 初級專家                                            85e9953c-00fd-4a0c-979c-7a41bd3f085a 初學者                                             
3e9a45b1-82f5-49df-8be6-d67df54760c9 中級專家                                            868a17dd-7d21-48a6-b2d5-f9a80313414a 初級專家                                            
bd6eb9b1-05a3-4059-bc99-90258a7e8d86 高級專家                                            3e9a45b1-82f5-49df-8be6-d67df54760c9 中級專家                                            
886cd029-db55-48ca-8835-d9c2e02fccad 初級顧問                                            bd6eb9b1-05a3-4059-bc99-90258a7e8d86 高級專家                                            
0dec42e1-7de3-4a67-be15-97fbea759771 中級顧問                                            886cd029-db55-48ca-8835-d9c2e02fccad 初級顧問                                            
f5648453-32a5-42c3-8ec1-3b31d0d812fd 高級顧問                                            0dec42e1-7de3-4a67-be15-97fbea759771 中級顧問                                            
231570cd-832f-40e3-b198-fb2336245926 訪客                                                                                                                                       
common.logon.user                    登入帳號                                                                                                                                    

10 個資料列已選取


SELECT
  role_id,
  role_name,
  role_base_on
FROM m_usr_role
START WITH role_name = '高級顧問'
CONNECT BY PRIOR role_base_on = role_id
ROLE_ID                              ROLE_NAME                                          ROLE_BASE_ON                         
------------------------------------ -------------------------------------------------- ------------------------------------ 
f5648453-32a5-42c3-8ec1-3b31d0d812fd 高級顧問                                            0dec42e1-7de3-4a67-be15-97fbea759771 
0dec42e1-7de3-4a67-be15-97fbea759771 中級顧問                                            886cd029-db55-48ca-8835-d9c2e02fccad 
886cd029-db55-48ca-8835-d9c2e02fccad 初級顧問                                            bd6eb9b1-05a3-4059-bc99-90258a7e8d86 
bd6eb9b1-05a3-4059-bc99-90258a7e8d86 高級專家                                            3e9a45b1-82f5-49df-8be6-d67df54760c9 
3e9a45b1-82f5-49df-8be6-d67df54760c9 中級專家                                            868a17dd-7d21-48a6-b2d5-f9a80313414a 
868a17dd-7d21-48a6-b2d5-f9a80313414a 初級專家                                            85e9953c-00fd-4a0c-979c-7a41bd3f085a 
85e9953c-00fd-4a0c-979c-7a41bd3f085a 初學者                                             231570cd-832f-40e3-b198-fb2336245926 
231570cd-832f-40e3-b198-fb2336245926 訪客                                                                                    
8 個資料列已選取

reference : Start with connect by prior 階層式查詢用法
Catch unhandled exception
public class ErrorHandler implements Thread.UncaughtExceptionHandler {

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        System.err.printf("Thread ID : %s%n", t.getId());
        System.err.printf("Message : %s%n", e.getMessage());
    }

    public static void main(String[] args) {
        // register handler
        Thread.setDefaultUncaughtExceptionHandler(new ErrorHandler());

        // throw error
        throw new RuntimeException("My exception!");
    }

}

Know the JVM Series – 1 – The Uncaught Exception Handler

Execute dos command
import java.io.IOException;

public class ExecuteDosCommand {

    public static void main(String[] args) throws IOException, InterruptedException {

        String cmd = null;
        try {
            String s = "command.exe";
            Runtime.getRuntime().exec(s);
            cmd = s;
        } catch (Exception ex) {
            // ex.printStackTrace();
        }
        try {
            String s = "cmd.exe";
            Runtime.getRuntime().exec(s);
            cmd = s;
        } catch (Exception ex) {
            // ex.printStackTrace();
        }

        String s = String.format("%s /C start %s", cmd, "c:\\新增文字文件.txt");
        System.err.println(s);
        Runtime.getRuntime().exec(s);
    }
}

When Runtime.exec() won't

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");
    }

}
List remote share folder
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;
using System.Runtime.InteropServices;

namespace ConsoleApplication1
{
    class Class1
    {
        #region Get remote share folder name, use Windows API NetShareEnum
        [DllImport("Netapi32.dll", CharSet = CharSet.Unicode)]
        private static extern NET_API_STATUS NetShareEnum(
             StringBuilder serverName,
             int level,
             ref IntPtr bufPtr,
             uint prefMaxLen,
             ref int entriesRead,
             ref int totalEntries,
             ref int resumeHandle
             );

        [DllImport("Netapi32.dll", SetLastError = true)]
        static extern int NetApiBufferFree(IntPtr Buffer);

        public enum NET_API_STATUS : uint
        {
            NERR_Success = 0,
            NERR_InvalidComputer = 2351,
            NERR_NotPrimary = 2226,
            NERR_SpeGroupOp = 2234,
            NERR_LastAdmin = 2452,
            NERR_BadPassword = 2203,
            NERR_PasswordTooShort = 2245,
            NERR_UserNotFound = 2221,
            ERROR_ACCESS_DENIED = 5,
            ERROR_NOT_ENOUGH_MEMORY = 8,
            ERROR_INVALID_PARAMETER = 87,
            ERROR_INVALID_NAME = 123,
            ERROR_INVALID_LEVEL = 124,
            ERROR_MORE_DATA = 234,
            ERROR_SESSION_CREDENTIAL_CONFLICT = 1219
        }

        [StructLayoutAttribute(LayoutKind.Sequential)]
        public struct _SHARE_INFO_0
        {
            [MarshalAsAttribute(UnmanagedType.LPWStr)]
            public string shi0_netname;
        }

        public static void EnumNetShares(string remoteMachineName)
        {
            StringBuilder serverName = new StringBuilder(remoteMachineName);
            int level = 0;
            IntPtr bufPtr = IntPtr.Zero;
            uint prefMaxLen = 0xFFFFFFFF;
            int entriesRead = 0;
            int totalEntries = 0;
            int resumeHandle = 0;
            int structSize = Marshal.SizeOf(typeof(_SHARE_INFO_0));

            NET_API_STATUS result = NetShareEnum(serverName, level, ref bufPtr, prefMaxLen, ref entriesRead, ref totalEntries, ref resumeHandle);
            if (result == NET_API_STATUS.NERR_Success)
            {
                IntPtr current = bufPtr;
                for (int i = 0; i < entriesRead; i++)
                {
                    _SHARE_INFO_0 shareInfo = (_SHARE_INFO_0)Marshal.PtrToStructure(current, typeof(_SHARE_INFO_0));
                    Console.WriteLine(shareInfo.shi0_netname);
                    current = new IntPtr(current.ToInt32() + structSize);
                }
            }
            else if (result == NET_API_STATUS.ERROR_MORE_DATA)
            {
                NetApiBufferFree(bufPtr);
            }
            else
            {
                // Something else.
            }
        }
        #endregion

        #region Get remote share folder name, use WMI
        private static void DisplayShareFolders(string computerName, string userName, string password)
        {
            string queryStr = "select * from Win32_Share";

            ConnectionOptions co = new ConnectionOptions();
            co.Username = userName;
            co.Password = password;

            ManagementScope ms = new ManagementScope(string.Format(@"\\{0}\root\cimv2", computerName), co);
            ms.Connect();
            if (ms.IsConnected)
            {
                ObjectQuery query = new ObjectQuery(queryStr);
                using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(ms, query))
                {
                    using (ManagementObjectCollection searchResult = searcher.Get())
                    {
                        foreach (ManagementObject mo in searchResult)
                        {
                            foreach (PropertyData property in mo.Properties)
                            {
                                Console.WriteLine("Name:{0}\tPath:{1}", mo.Properties["Name"].Value.ToString(), mo.Properties["Path"].Value.ToString());
                            }
                        }
                    }
                }
            }
        }
        #endregion
    }
}
RETURNING : return value from query
SET SERVEROUTPUT ON;
DECLARE 
    v_column VARCHAR2(100);
BEGIN
    DBMS_OUTPUT.ENABLE;
    INSERT INTO table1(column1) VALUES ('TEST VALUE') RETURNING column1 INTO v_column;
    DBMS_OUTPUT.PUT_LINE(v_column);
END;
EXECUTE IMMEDIATE : execute string query
SET SERVEROUTPUT ON;

/* execute query */
DECLARE
BEGIN
    EXECUTE IMMEDIATE 'SELECT CURRENT_DATE FROM DUAL';
END;

/* execute query & set value */
DECLARE
    v_time DATE;
BEGIN
    DBMS_OUTPUT.ENABLE;
    EXECUTE IMMEDIATE 'SELECT CURRENT_DATE FROM DUAL' INTO v_time;
    DBMS_OUTPUT.PUT_LINE(v_time);
END;

/* execute query with parameter */
DECLARE
    v_emp_id VARCHAR2(20);
    v_name VARCHAR2(20);
BEGIN
    v_name := 'Bruce';
    v_emp_id := '00987';
    EXECUTE IMMEDIATE 'UPDATE employee SET employee_name = :1 WHERE employee_id = :2'
    USING v_name, v_emp_id;
    COMMIT;
END;

/* execute procedure */
DECLARE
    v_start_index NUMBER := 24;
    v_end_index NUMBER:= 587;
    v_sum NUMBER;
    v_status NUMBER(1,0);
BEGIN
    DBMS_OUTPUT.ENABLE;
    EXECUTE IMMEDIATE 'BEGIN get_lot_amount(:1, :2, :3); END;'
    USING IN v_start_index, IN v_end_index, OUT v_sum, IN OUT v_status;

    IF v_status = 0 THEN
        DBMS_OUTPUT.PUT_LINE('ERROR');
    END IF;
END;
Memorize xml document operation
I have not write codes about operating xml document by C# for months. Almost forget all...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Sportingbet.net;
using Sportingbet.util;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Xml;

class Program
{
    static void Main(string[] args)
    {
        string xml = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "tmp.xml");
        XDocument xDoc = XDocument.Parse(xml);
        var nodes = from e in xDoc.XPathSelectElements("//myTag")
                    select e;
        foreach (var e in nodes)
        {
            Console.WriteLine(e);
        }

        XmlDocument xmlDoc = new XmlDocument();
        xmlDoc.LoadXml(xml);
        XmlNodeList nodelist = xmlDoc.SelectNodes("//myTag");
        foreach (XmlNode e in nodelist)
        {
            Console.WriteLine(e.OuterXml);
        }
    }
}
Clone any object
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;

import bruce.lib.swing.JTextBox;

public class CloneObject {

    public static Object clone(Object source) {
        Object newObject = new Object();
        ObjectOutputStream ooStr = null;
        try {
            ByteArrayOutputStream baoStr = new ByteArrayOutputStream();
            ooStr = new ObjectOutputStream(baoStr);
            ooStr.writeObject(source);
            ooStr.flush();
            ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(baoStr.toByteArray()));
            newObject = in.readObject();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(CloneObject.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(CloneObject.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                ooStr.close();
            } catch (IOException ex) {
                Logger.getLogger(CloneObject.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return newObject;

    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        JTextBox textbox = new JTextBox("A simple textbox", 20);
        System.out.printf("Hashcode : %d%n", textbox.hashCode());

        JTextBox clonedTextBox = (JTextBox) clone(textbox);
        System.out.printf("Cloned hashcode : %d%n", clonedTextBox.hashCode());
        System.out.printf("Cloned text : %s%n", clonedTextBox.getText());

    }

}
Print multiple image
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

public class PringMultipleImage implements Printable {

    @Override
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
        // 要列印的圖片
        BufferedImage[] images = this.getPrintImages();
        if (images.length == 0)
            return Printable.NO_SUCH_PAGE;

        // 固定寬度(以符合掃描器大小)
        double stickerWidth = 220;
        double maxStickerHeight = 0; // 最大高度
        for (int i = 0; i < images.length; i++) {
            maxStickerHeight = Math.max(maxStickerHeight, stickerWidth / images[i].getWidth() * images[i].getHeight());
        }
        // 計算頁面可列印張數, 每頁張數 : c*r
        int c = (int) (pageFormat.getImageableWidth() / stickerWidth);
        int r = (int) (pageFormat.getImageableHeight() / maxStickerHeight);
        int p = (int) Math.ceil(1.0 * images.length / c / r); // 頁數

        if (pageIndex < p) {
            // 計算cell大小
            double cellWidth = pageFormat.getImageableWidth() / c;
            double cellHeight = pageFormat.getImageableHeight() / r;
            // 計算位置
            double translateX = (cellWidth - stickerWidth) / 2;

            // 
            int cellx = 0;
            int celly = 0;

            for (int i = 0 + pageIndex * c * r; i < images.length; i++) {
                double stickerHeight = stickerWidth / images[i].getWidth() * images[i].getHeight();
                double translateY = (cellHeight - stickerHeight) / 2;

                graphics.drawImage(images[i], //
                        (int) (translateX + cellx * cellWidth), //
                        (int) (translateY + celly * cellHeight), //
                        (int) stickerWidth, //
                        (int) stickerHeight, //
                        null);

                // 下一個cell
                if (cellx + 1 == c) {
                    cellx = 0;
                    celly++;
                } else {
                    cellx++;
                }
            }
            return Printable.PAGE_EXISTS;
        } else {
            return Printable.NO_SUCH_PAGE;
        }
    }

    private BufferedImage[] getPrintImages() {
        // Generate image here
        return null;
    }

    public static void main(String[] args) {
        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPrintable(new PringMultipleImage());
        if (job.printDialog()) {
            try {
                job.print();
            } catch (PrinterException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
reference:
Lesson: Printing (The Java™ Tutorials > 2D Graphics)
Java Print Service API User Guide
Convert swing component to image
package y11.m03;

import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;

public class PrintTester {

    public static void main(String[] args) throws IOException {
        JPanel p = new JPanel(new GridLayout(2, 2));
        p.add(new JTextField("wwww", 20));
        p.add(new JLabel("dfdfdf"));
        p.add(new JSpinner());
        p.add(new JButton("fdfdf"));

        BufferedImage image = createImage(p);
        ImageIO.write(image, "png", new File("PrintTest2.png"));
    }

    // if component is rendered
    public static BufferedImage createImage(JComponent component) {
        int w = component.getWidth();
        int h = component.getHeight();
        BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = img.createGraphics();
        component.paint(g);
        return img;
    }

    // if component is not rendered
    public static BufferedImage createImage(JComponent component, AffineTransform transform) throws IOException, ClassNotFoundException {
        if (component == null)
            return null;
        JFrame f = new JFrame(); // for paint
        JComponent clone = (JComponent) clone(component);
        f.add(clone);
        f.pack();

        BufferedImage image = new BufferedImage(clone.getWidth(), clone.getHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g = image.createGraphics();
        if (transform != null)
            g.setTransform(transform);
        clone.paint(g);
        f.dispose();
        return image;
    }

    public static <T extends Serializable> T clone(T source) throws IOException, ClassNotFoundException {
        Object newObject = new Object();
        ObjectOutputStream ooStr = null;
        ByteArrayOutputStream baoStr = new ByteArrayOutputStream();
        ooStr = new ObjectOutputStream(baoStr);
        ooStr.writeObject(source);
        ooStr.flush();
        ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(baoStr.toByteArray()));
        newObject = in.readObject();
        ooStr.close();
        return (T) newObject;
    }
}
DownloadProcess
ProxyConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

public class ProxyConfig
{
    public static ProxyConfig DefaultProxy;

    public string Host { get; set; }
    public int Port { get; set; }
    public string Account { get; set; }
    public string Password { get; set; }

    public ProxyConfig(string host, int port, string account, string password)
    {
        this.Host = host;
        this.Port = port;
        this.Account = account;
        this.Password = password;
    }
}
DownloadProcess.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Threading;
using System.Text.RegularExpressions;

public class DownloadProcess
{
    public static string GetHtmlSource(string url, ProxyConfig proxy)
    {
        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        // 設置代理伺服器
        if (proxy != null)
        {
            WebProxy p = new WebProxy(proxy.Host, proxy.Port);
            p.Credentials = new NetworkCredential(proxy.Account, proxy.Password);
            request.Proxy = p;
        }

        HttpWebResponse response = request.GetResponse() as HttpWebResponse;
        Stream s = response.GetResponseStream();
        StreamReader reader = new StreamReader(s);
        string source = reader.ReadToEnd();
        reader.Close();
        s.Close();
        response.Close();

        return source;
    }

    /// <summary>
    /// 目標網址
    /// </summary>
    public string Url { get; set; }
    /// <summary>
    /// 儲存的目錄位置
    /// </summary>
    public string StorePath { get; set; }
    /// <summary>
    /// 儲存的檔名 (Optional)
    /// </summary>
    public string StoreFilename
    {
        get { return this._StoreFilename; }
        set
        {
            this._IsFilenameCustomized = true;
            this._StoreFilename = value;
        }
    }
    /// <summary>
    /// 代理伺服器設定
    /// </summary>
    public ProxyConfig Proxy { get; set; }
    /// <summary>
    /// 串流(資料)長度
    /// </summary>
    public long Length { get; private set; }
    /// <summary>
    /// 已收到的串流(資料)長度
    /// </summary>
    public long AcceptedLength { get; private set; }
    /// <summary>
    /// 開始下載時間
    /// </summary>
    public DateTime BeginTime { get; private set; }
    /// <summary>
    /// 完成下載時間
    /// </summary>
    public DateTime EndTime { get; private set; }
    /// <summary>
    /// 處理完成
    /// </summary>
    public bool IsCompleted { get; private set; }

    /// <summary>
    /// 儲存檔名
    /// </summary>
    private string _StoreFilename;
    /// <summary>
    /// 自訂儲存檔名
    /// </summary>
    private bool _IsFilenameCustomized = false;
    /// <summary>
    /// 停止下載標記
    /// </summary>
    private bool _StopFlag = false;
    /// <summary>
    /// 讀取時的Buffer大小
    /// </summary>
    private int _ReadBuffer = 128;
    /// <summary>
    /// 寫入磁碟間隔(sec)
    /// </summary>
    private int _FlushInterval = 5;
    /// <summary>
    /// 執行寫入磁碟旗標
    /// </summary>
    private bool _IsFlushing = false;
    /// <summary>
    /// 記錄寫入磁碟時間
    /// </summary>
    private DateTime _LastFlushTime;

    public DownloadProcess()
    {
        this._LastFlushTime = DateTime.Now;
    }
    public DownloadProcess(string url, string storePath)
        : this()
    {
        this.Url = url;
        this.StorePath = storePath;
    }
    public DownloadProcess(string url, string storePath, ProxyConfig proxy)
        : this(url, storePath)
    {
        this.Proxy = proxy;
    }
    /// <summary>
    /// 開始下載
    /// </summary>
    public void Start()
    {
        new Thread(() =>
        {
            this.AcceptedLength = 0;
            this.IsCompleted = false;
            this.BeginTime = DateTime.Now;
            this.EndTime = DateTime.MinValue;

            // 解析檔名
            this.ParseFileName();

            HttpWebRequest request = WebRequest.Create(this.Url) as HttpWebRequest;
            // 設置代理伺服器
            if (this.Proxy != null)
            {
                WebProxy p = new WebProxy(this.Proxy.Host, this.Proxy.Port);
                p.Credentials = new NetworkCredential(this.Proxy.Account, this.Proxy.Password);
                request.Proxy = p;
            }
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
            // 檢查附件名稱
            this.ParseAttachmentName(response);

            // 嘗試取得串流長度
            this.Length = response.ContentLength;

            // 讀取位元數
            int readed = 0;
            // Buffer
            byte[] buf = new byte[this._ReadBuffer];
            // 暫存資料
            MemoryStream ms = new MemoryStream();

            Stream stream = response.GetResponseStream();
            while ((readed = stream.Read(buf, 0, buf.Length)) > 0)
            {
                // 記錄接收的串流長度
                this.AcceptedLength += readed;
                // 寫入暫存
                ms.Write(buf, 0, readed);

                // 寫入磁碟
                if (!this._IsFlushing && DateTime.Now.AddSeconds(-1 * this._FlushInterval) > this._LastFlushTime)
                {
                    ms.Close();
                    this.FlushToDisk(ms.ToArray());
                    ms = new MemoryStream();
                }

                // 強迫中斷
                if (this._StopFlag) break;
            }

            stream.Close();
            ms.Close();
            // 等待未完成寫入作業
            while (this._IsFlushing)
            {
                Thread.Sleep(100);
            }
            this.FlushToDisk(ms.ToArray());
            this.EndTime = DateTime.Now;
            this.IsCompleted = true;
        }).Start();
    }
    /// <summary>
    /// 中斷下載
    /// </summary>
    public void Stop()
    {
        this._StopFlag = true;
    }
    /// <summary>
    /// 由輸入網址產生檔名
    /// </summary>
    private void ParseFileName()
    {
        if (!this._IsFilenameCustomized && !string.IsNullOrWhiteSpace(Url))
        {
            Uri url = new Uri(this.Url);
            this.StoreFilename = url.Segments[url.Segments.Length - 1];
        }
    }
    /// <summary>
    /// 檢查是否有附件名稱
    /// </summary>
    /// <param name="res"></param>
    private void ParseAttachmentName(HttpWebResponse res)
    {
        if (!string.IsNullOrWhiteSpace(res.Headers["Content-Disposition"]))
        {
            string filename = Regex.Match(
                res.Headers["Content-Disposition"],
                "filename=(.+)",
                RegexOptions.IgnoreCase
            ).Groups[1].Value;

            if (!string.IsNullOrWhiteSpace(filename))
            {
                this.StoreFilename = filename;
            }
        }
    }
    /// <summary>
    /// 將暫存資料寫入磁碟
    /// </summary>
    /// <param name="buffer"></param>
    private void FlushToDisk(byte[] buffer)
    {
        new Thread(() =>
        {
            // 標記為寫入中
            this._IsFlushing = true;
            FileStream fs = new FileStream(
                Path.Combine(this.StorePath, this.StoreFilename),
                FileMode.Append, FileAccess.Write, FileShare.Write
            );
            fs.Write(buffer, 0, buffer.Length);
            fs.Close();
            // 延遲
            Thread.Sleep(100);
            // 記錄寫入時間
            this._LastFlushTime = DateTime.Now;
            this._IsFlushing = false;
        }).Start();
    }
    /// <summary>
    /// 以適當單位顯示大小
    /// </summary>
    /// <param name="length">位元數</param>
    /// <param name="ext">單位</param>
    /// <returns></returns>
    private string toSize(double length, SizeExtension ext)
    {
        if (ext == SizeExtension.Byte && length < 1) return "0 Byte";
        if (ext == SizeExtension.GB) return string.Format("{0:00.00} {1}", length, ext);
        if (length < 1024)
        {
            return string.Format("{0:##.##} {1}", length, ext);
        }
        else
        {
            return toSize(length / 1024, (SizeExtension)(ext + 1));
        }
    }
    /// <summary>
    /// 串流(資料)長度
    /// </summary>
    /// <returns></returns>
    public string GetLength()
    {
        return this.toSize(this.Length, SizeExtension.Byte);
    }
    /// <summary>
    /// 已收到的串流(資料)長度
    /// </summary>
    /// <returns></returns>
    public string GetAcceptedLenght()
    {
        return this.toSize(this.AcceptedLength, SizeExtension.Byte);
    }
}