Popular Posts
javax.net.ssl.SSLHandshakeException: Connection closed by peer in Android 5.0 Lollipop Recently, there is a error occurs when access website via ssl connection like below although it worked fine several days ago. // Enable SSL... 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... 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
List remote share folder
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Management;
  6. using System.Runtime.InteropServices;
  7.  
  8. namespace ConsoleApplication1
  9. {
  10.     class Class1
  11.     {
  12.         #region Get remote share folder name, use Windows API NetShareEnum
  13.         [DllImport("Netapi32.dll", CharSet = CharSet.Unicode)]
  14.         private static extern NET_API_STATUS NetShareEnum(
  15.              StringBuilder serverName,
  16.              int level,
  17.              ref IntPtr bufPtr,
  18.              uint prefMaxLen,
  19.              ref int entriesRead,
  20.              ref int totalEntries,
  21.              ref int resumeHandle
  22.              );
  23.  
  24.         [DllImport("Netapi32.dll", SetLastError = true)]
  25.         static extern int NetApiBufferFree(IntPtr Buffer);
  26.  
  27.         public enum NET_API_STATUS : uint
  28.         {
  29.             NERR_Success = 0,
  30.             NERR_InvalidComputer = 2351,
  31.             NERR_NotPrimary = 2226,
  32.             NERR_SpeGroupOp = 2234,
  33.             NERR_LastAdmin = 2452,
  34.             NERR_BadPassword = 2203,
  35.             NERR_PasswordTooShort = 2245,
  36.             NERR_UserNotFound = 2221,
  37.             ERROR_ACCESS_DENIED = 5,
  38.             ERROR_NOT_ENOUGH_MEMORY = 8,
  39.             ERROR_INVALID_PARAMETER = 87,
  40.             ERROR_INVALID_NAME = 123,
  41.             ERROR_INVALID_LEVEL = 124,
  42.             ERROR_MORE_DATA = 234,
  43.             ERROR_SESSION_CREDENTIAL_CONFLICT = 1219
  44.         }
  45.  
  46.         [StructLayoutAttribute(LayoutKind.Sequential)]
  47.         public struct _SHARE_INFO_0
  48.         {
  49.             [MarshalAsAttribute(UnmanagedType.LPWStr)]
  50.             public string shi0_netname;
  51.         }
  52.  
  53.         public static void EnumNetShares(string remoteMachineName)
  54.         {
  55.             StringBuilder serverName = new StringBuilder(remoteMachineName);
  56.             int level = 0;
  57.             IntPtr bufPtr = IntPtr.Zero;
  58.             uint prefMaxLen = 0xFFFFFFFF;
  59.             int entriesRead = 0;
  60.             int totalEntries = 0;
  61.             int resumeHandle = 0;
  62.             int structSize = Marshal.SizeOf(typeof(_SHARE_INFO_0));
  63.  
  64.             NET_API_STATUS result = NetShareEnum(serverName, level, ref bufPtr, prefMaxLen, ref entriesRead, ref totalEntries, ref resumeHandle);
  65.             if (result == NET_API_STATUS.NERR_Success)
  66.             {
  67.                 IntPtr current = bufPtr;
  68.                 for (int i = 0; i < entriesRead; i++)
  69.                 {
  70.                     _SHARE_INFO_0 shareInfo = (_SHARE_INFO_0)Marshal.PtrToStructure(current, typeof(_SHARE_INFO_0));
  71.                     Console.WriteLine(shareInfo.shi0_netname);
  72.                     current = new IntPtr(current.ToInt32() + structSize);
  73.                 }
  74.             }
  75.             else if (result == NET_API_STATUS.ERROR_MORE_DATA)
  76.             {
  77.                 NetApiBufferFree(bufPtr);
  78.             }
  79.             else
  80.             {
  81.                 // Something else.
  82.             }
  83.         }
  84.         #endregion
  85.  
  86.         #region Get remote share folder name, use WMI
  87.         private static void DisplayShareFolders(string computerName, string userName, string password)
  88.         {
  89.             string queryStr = "select * from Win32_Share";
  90.  
  91.             ConnectionOptions co = new ConnectionOptions();
  92.             co.Username = userName;
  93.             co.Password = password;
  94.  
  95.             ManagementScope ms = new ManagementScope(string.Format(@"\\{0}\root\cimv2", computerName), co);
  96.             ms.Connect();
  97.             if (ms.IsConnected)
  98.             {
  99.                 ObjectQuery query = new ObjectQuery(queryStr);
  100.                 using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(ms, query))
  101.                 {
  102.                     using (ManagementObjectCollection searchResult = searcher.Get())
  103.                     {
  104.                         foreach (ManagementObject mo in searchResult)
  105.                         {
  106.                             foreach (PropertyData property in mo.Properties)
  107.                             {
  108.                                 Console.WriteLine("Name:{0}\tPath:{1}", mo.Properties["Name"].Value.ToString(), mo.Properties["Path"].Value.ToString());
  109.                             }
  110.                         }
  111.                     }
  112.                 }
  113.             }
  114.         }
  115.         #endregion
  116.     }
  117. }
RETURNING : return value from query
  1. SET SERVEROUTPUT ON;
  2. DECLARE 
  3.     v_column VARCHAR2(100);
  4. BEGIN
  5.     DBMS_OUTPUT.ENABLE;
  6.     INSERT INTO table1(column1) VALUES ('TEST VALUE') RETURNING column1 INTO v_column;
  7.     DBMS_OUTPUT.PUT_LINE(v_column);
  8. END;
EXECUTE IMMEDIATE : execute string query
  1. SET SERVEROUTPUT ON;
  2.  
  3. /* execute query */
  4. DECLARE
  5. BEGIN
  6.     EXECUTE IMMEDIATE 'SELECT CURRENT_DATE FROM DUAL';
  7. END;
  8.  
  9. /* execute query & set value */
  10. DECLARE
  11.     v_time DATE;
  12. BEGIN
  13.     DBMS_OUTPUT.ENABLE;
  14.     EXECUTE IMMEDIATE 'SELECT CURRENT_DATE FROM DUAL' INTO v_time;
  15.     DBMS_OUTPUT.PUT_LINE(v_time);
  16. END;
  17.  
  18. /* execute query with parameter */
  19. DECLARE
  20.     v_emp_id VARCHAR2(20);
  21.     v_name VARCHAR2(20);
  22. BEGIN
  23.     v_name := 'Bruce';
  24.     v_emp_id := '00987';
  25.     EXECUTE IMMEDIATE 'UPDATE employee SET employee_name = :1 WHERE employee_id = :2'
  26.     USING v_name, v_emp_id;
  27.     COMMIT;
  28. END;
  29.  
  30. /* execute procedure */
  31. DECLARE
  32.     v_start_index NUMBER := 24;
  33.     v_end_index NUMBER:= 587;
  34.     v_sum NUMBER;
  35.     v_status NUMBER(1,0);
  36. BEGIN
  37.     DBMS_OUTPUT.ENABLE;
  38.     EXECUTE IMMEDIATE 'BEGIN get_lot_amount(:1, :2, :3); END;'
  39.     USING IN v_start_index, IN v_end_index, OUT v_sum, IN OUT v_status;
  40.  
  41.     IF v_status = 0 THEN
  42.         DBMS_OUTPUT.PUT_LINE('ERROR');
  43.     END IF;
  44. END;
Memorize xml document operation
I have not write codes about operating xml document by C# for months. Almost forget all...
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.IO;
  7. using Sportingbet.net;
  8. using Sportingbet.util;
  9. using System.Xml.Linq;
  10. using System.Xml.XPath;
  11. using System.Xml;
  12.  
  13. class Program
  14. {
  15.     static void Main(string[] args)
  16.     {
  17.         string xml = File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "tmp.xml");
  18.         XDocument xDoc = XDocument.Parse(xml);
  19.         var nodes = from e in xDoc.XPathSelectElements("//myTag")
  20.                     select e;
  21.         foreach (var e in nodes)
  22.         {
  23.             Console.WriteLine(e);
  24.         }
  25.  
  26.         XmlDocument xmlDoc = new XmlDocument();
  27.         xmlDoc.LoadXml(xml);
  28.         XmlNodeList nodelist = xmlDoc.SelectNodes("//myTag");
  29.         foreach (XmlNode e in nodelist)
  30.         {
  31.             Console.WriteLine(e.OuterXml);
  32.         }
  33.     }
  34. }
Clone any object
  1. import java.io.ByteArrayInputStream;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.IOException;
  4. import java.io.ObjectInputStream;
  5. import java.io.ObjectOutputStream;
  6. import java.util.logging.Level;
  7. import java.util.logging.Logger;
  8.  
  9. import bruce.lib.swing.JTextBox;
  10.  
  11. public class CloneObject {
  12.  
  13.     public static Object clone(Object source) {
  14.         Object newObject = new Object();
  15.         ObjectOutputStream ooStr = null;
  16.         try {
  17.             ByteArrayOutputStream baoStr = new ByteArrayOutputStream();
  18.             ooStr = new ObjectOutputStream(baoStr);
  19.             ooStr.writeObject(source);
  20.             ooStr.flush();
  21.             ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(baoStr.toByteArray()));
  22.             newObject = in.readObject();
  23.         } catch (ClassNotFoundException ex) {
  24.             Logger.getLogger(CloneObject.class.getName()).log(Level.SEVERE, null, ex);
  25.         } catch (IOException ex) {
  26.             Logger.getLogger(CloneObject.class.getName()).log(Level.SEVERE, null, ex);
  27.         } finally {
  28.             try {
  29.                 ooStr.close();
  30.             } catch (IOException ex) {
  31.                 Logger.getLogger(CloneObject.class.getName()).log(Level.SEVERE, null, ex);
  32.             }
  33.         }
  34.         return newObject;
  35.  
  36.     }
  37.  
  38.     /**
  39.      * @param args
  40.      */
  41.     public static void main(String[] args) {
  42.         // TODO Auto-generated method stub
  43.  
  44.         JTextBox textbox = new JTextBox("A simple textbox", 20);
  45.         System.out.printf("Hashcode : %d%n", textbox.hashCode());
  46.  
  47.         JTextBox clonedTextBox = (JTextBox) clone(textbox);
  48.         System.out.printf("Cloned hashcode : %d%n", clonedTextBox.hashCode());
  49.         System.out.printf("Cloned text : %s%n", clonedTextBox.getText());
  50.  
  51.     }
  52.  
  53. }
Print multiple image
  1. import java.awt.Graphics;
  2. import java.awt.image.BufferedImage;
  3. import java.awt.print.PageFormat;
  4. import java.awt.print.Printable;
  5. import java.awt.print.PrinterException;
  6. import java.awt.print.PrinterJob;
  7.  
  8. public class PringMultipleImage implements Printable {
  9.  
  10.     @Override
  11.     public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
  12.         // 要列印的圖片
  13.         BufferedImage[] images = this.getPrintImages();
  14.         if (images.length == 0)
  15.             return Printable.NO_SUCH_PAGE;
  16.  
  17.         // 固定寬度(以符合掃描器大小)
  18.         double stickerWidth = 220;
  19.         double maxStickerHeight = 0; // 最大高度
  20.         for (int i = 0; i < images.length; i++) {
  21.             maxStickerHeight = Math.max(maxStickerHeight, stickerWidth / images[i].getWidth() * images[i].getHeight());
  22.         }
  23.         // 計算頁面可列印張數, 每頁張數 : c*r
  24.         int c = (int) (pageFormat.getImageableWidth() / stickerWidth);
  25.         int r = (int) (pageFormat.getImageableHeight() / maxStickerHeight);
  26.         int p = (int) Math.ceil(1.0 * images.length / c / r); // 頁數
  27.  
  28.         if (pageIndex < p) {
  29.             // 計算cell大小
  30.             double cellWidth = pageFormat.getImageableWidth() / c;
  31.             double cellHeight = pageFormat.getImageableHeight() / r;
  32.             // 計算位置
  33.             double translateX = (cellWidth - stickerWidth) / 2;
  34.  
  35.             // 
  36.             int cellx = 0;
  37.             int celly = 0;
  38.  
  39.             for (int i = 0 + pageIndex * c * r; i < images.length; i++) {
  40.                 double stickerHeight = stickerWidth / images[i].getWidth() * images[i].getHeight();
  41.                 double translateY = (cellHeight - stickerHeight) / 2;
  42.  
  43.                 graphics.drawImage(images[i], //
  44.                         (int) (translateX + cellx * cellWidth), //
  45.                         (int) (translateY + celly * cellHeight), //
  46.                         (int) stickerWidth, //
  47.                         (int) stickerHeight, //
  48.                         null);
  49.  
  50.                 // 下一個cell
  51.                 if (cellx + 1 == c) {
  52.                     cellx = 0;
  53.                     celly++;
  54.                 } else {
  55.                     cellx++;
  56.                 }
  57.             }
  58.             return Printable.PAGE_EXISTS;
  59.         } else {
  60.             return Printable.NO_SUCH_PAGE;
  61.         }
  62.     }
  63.  
  64.     private BufferedImage[] getPrintImages() {
  65.         // Generate image here
  66.         return null;
  67.     }
  68.  
  69.     public static void main(String[] args) {
  70.         PrinterJob job = PrinterJob.getPrinterJob();
  71.         job.setPrintable(new PringMultipleImage());
  72.         if (job.printDialog()) {
  73.             try {
  74.                 job.print();
  75.             } catch (PrinterException e) {
  76.                 // TODO Auto-generated catch block
  77.                 e.printStackTrace();
  78.             }
  79.         }
  80.     }
  81. }
reference:
Lesson: Printing (The Java™ Tutorials > 2D Graphics)
Java Print Service API User Guide
Convert swing component to image
  1. package y11.m03;
  2.  
  3. import java.awt.Graphics2D;
  4. import java.awt.GridLayout;
  5. import java.awt.geom.AffineTransform;
  6. import java.awt.image.BufferedImage;
  7. import java.io.ByteArrayInputStream;
  8. import java.io.ByteArrayOutputStream;
  9. import java.io.File;
  10. import java.io.IOException;
  11. import java.io.ObjectInputStream;
  12. import java.io.ObjectOutputStream;
  13. import java.io.Serializable;
  14.  
  15. import javax.imageio.ImageIO;
  16. import javax.swing.JButton;
  17. import javax.swing.JComponent;
  18. import javax.swing.JFrame;
  19. import javax.swing.JLabel;
  20. import javax.swing.JPanel;
  21. import javax.swing.JSpinner;
  22. import javax.swing.JTextField;
  23.  
  24. public class PrintTester {
  25.  
  26.     public static void main(String[] args) throws IOException {
  27.         JPanel p = new JPanel(new GridLayout(2, 2));
  28.         p.add(new JTextField("wwww", 20));
  29.         p.add(new JLabel("dfdfdf"));
  30.         p.add(new JSpinner());
  31.         p.add(new JButton("fdfdf"));
  32.  
  33.         BufferedImage image = createImage(p);
  34.         ImageIO.write(image, "png", new File("PrintTest2.png"));
  35.     }
  36.  
  37.     // if component is rendered
  38.     public static BufferedImage createImage(JComponent component) {
  39.         int w = component.getWidth();
  40.         int h = component.getHeight();
  41.         BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
  42.         Graphics2D g = img.createGraphics();
  43.         component.paint(g);
  44.         return img;
  45.     }
  46.  
  47.     // if component is not rendered
  48.     public static BufferedImage createImage(JComponent component, AffineTransform transform) throws IOException, ClassNotFoundException {
  49.         if (component == null)
  50.             return null;
  51.         JFrame f = new JFrame(); // for paint
  52.         JComponent clone = (JComponent) clone(component);
  53.         f.add(clone);
  54.         f.pack();
  55.  
  56.         BufferedImage image = new BufferedImage(clone.getWidth(), clone.getHeight(), BufferedImage.TYPE_INT_ARGB);
  57.         Graphics2D g = image.createGraphics();
  58.         if (transform != null)
  59.             g.setTransform(transform);
  60.         clone.paint(g);
  61.         f.dispose();
  62.         return image;
  63.     }
  64.  
  65.     public static <extends Serializable> T clone(T source) throws IOException, ClassNotFoundException {
  66.         Object newObject = new Object();
  67.         ObjectOutputStream ooStr = null;
  68.         ByteArrayOutputStream baoStr = new ByteArrayOutputStream();
  69.         ooStr = new ObjectOutputStream(baoStr);
  70.         ooStr.writeObject(source);
  71.         ooStr.flush();
  72.         ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(baoStr.toByteArray()));
  73.         newObject = in.readObject();
  74.         ooStr.close();
  75.         return (T) newObject;
  76.     }
  77. }
DownloadProcess
ProxyConfig.cs
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. public class ProxyConfig
  7. {
  8.     public static ProxyConfig DefaultProxy;
  9.  
  10.     public string Host { get; set; }
  11.     public int Port { get; set; }
  12.     public string Account { get; set; }
  13.     public string Password { get; set; }
  14.  
  15.     public ProxyConfig(string host, int port, string account, string password)
  16.     {
  17.         this.Host = host;
  18.         this.Port = port;
  19.         this.Account = account;
  20.         this.Password = password;
  21.     }
  22. }
DownloadProcess.cs
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Net;
  6. using System.IO;
  7. using System.Threading;
  8. using System.Text.RegularExpressions;
  9.  
  10. public class DownloadProcess
  11. {
  12.     public static string GetHtmlSource(string url, ProxyConfig proxy)
  13.     {
  14.         HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
  15.         // 設置代理伺服器
  16.         if (proxy != null)
  17.         {
  18.             WebProxy p = new WebProxy(proxy.Host, proxy.Port);
  19.             p.Credentials = new NetworkCredential(proxy.Account, proxy.Password);
  20.             request.Proxy = p;
  21.         }
  22.  
  23.         HttpWebResponse response = request.GetResponse() as HttpWebResponse;
  24.         Stream s = response.GetResponseStream();
  25.         StreamReader reader = new StreamReader(s);
  26.         string source = reader.ReadToEnd();
  27.         reader.Close();
  28.         s.Close();
  29.         response.Close();
  30.  
  31.         return source;
  32.     }
  33.  
  34.     /// <summary>
  35.     /// 目標網址
  36.     /// </summary>
  37.     public string Url { get; set; }
  38.     /// <summary>
  39.     /// 儲存的目錄位置
  40.     /// </summary>
  41.     public string StorePath { get; set; }
  42.     /// <summary>
  43.     /// 儲存的檔名 (Optional)
  44.     /// </summary>
  45.     public string StoreFilename
  46.     {
  47.         get { return this._StoreFilename; }
  48.         set
  49.         {
  50.             this._IsFilenameCustomized = true;
  51.             this._StoreFilename = value;
  52.         }
  53.     }
  54.     /// <summary>
  55.     /// 代理伺服器設定
  56.     /// </summary>
  57.     public ProxyConfig Proxy { get; set; }
  58.     /// <summary>
  59.     /// 串流(資料)長度
  60.     /// </summary>
  61.     public long Length { get; private set; }
  62.     /// <summary>
  63.     /// 已收到的串流(資料)長度
  64.     /// </summary>
  65.     public long AcceptedLength { get; private set; }
  66.     /// <summary>
  67.     /// 開始下載時間
  68.     /// </summary>
  69.     public DateTime BeginTime { get; private set; }
  70.     /// <summary>
  71.     /// 完成下載時間
  72.     /// </summary>
  73.     public DateTime EndTime { get; private set; }
  74.     /// <summary>
  75.     /// 處理完成
  76.     /// </summary>
  77.     public bool IsCompleted { get; private set; }
  78.  
  79.     /// <summary>
  80.     /// 儲存檔名
  81.     /// </summary>
  82.     private string _StoreFilename;
  83.     /// <summary>
  84.     /// 自訂儲存檔名
  85.     /// </summary>
  86.     private bool _IsFilenameCustomized = false;
  87.     /// <summary>
  88.     /// 停止下載標記
  89.     /// </summary>
  90.     private bool _StopFlag = false;
  91.     /// <summary>
  92.     /// 讀取時的Buffer大小
  93.     /// </summary>
  94.     private int _ReadBuffer = 128;
  95.     /// <summary>
  96.     /// 寫入磁碟間隔(sec)
  97.     /// </summary>
  98.     private int _FlushInterval = 5;
  99.     /// <summary>
  100.     /// 執行寫入磁碟旗標
  101.     /// </summary>
  102.     private bool _IsFlushing = false;
  103.     /// <summary>
  104.     /// 記錄寫入磁碟時間
  105.     /// </summary>
  106.     private DateTime _LastFlushTime;
  107.  
  108.     public DownloadProcess()
  109.     {
  110.         this._LastFlushTime = DateTime.Now;
  111.     }
  112.     public DownloadProcess(string url, string storePath)
  113.         : this()
  114.     {
  115.         this.Url = url;
  116.         this.StorePath = storePath;
  117.     }
  118.     public DownloadProcess(string url, string storePath, ProxyConfig proxy)
  119.         : this(url, storePath)
  120.     {
  121.         this.Proxy = proxy;
  122.     }
  123.     /// <summary>
  124.     /// 開始下載
  125.     /// </summary>
  126.     public void Start()
  127.     {
  128.         new Thread(() =>
  129.         {
  130.             this.AcceptedLength = 0;
  131.             this.IsCompleted = false;
  132.             this.BeginTime = DateTime.Now;
  133.             this.EndTime = DateTime.MinValue;
  134.  
  135.             // 解析檔名
  136.             this.ParseFileName();
  137.  
  138.             HttpWebRequest request = WebRequest.Create(this.Url) as HttpWebRequest;
  139.             // 設置代理伺服器
  140.             if (this.Proxy != null)
  141.             {
  142.                 WebProxy p = new WebProxy(this.Proxy.Host, this.Proxy.Port);
  143.                 p.Credentials = new NetworkCredential(this.Proxy.Account, this.Proxy.Password);
  144.                 request.Proxy = p;
  145.             }
  146.             HttpWebResponse response = request.GetResponse() as HttpWebResponse;
  147.             // 檢查附件名稱
  148.             this.ParseAttachmentName(response);
  149.  
  150.             // 嘗試取得串流長度
  151.             this.Length = response.ContentLength;
  152.  
  153.             // 讀取位元數
  154.             int readed = 0;
  155.             // Buffer
  156.             byte[] buf = new byte[this._ReadBuffer];
  157.             // 暫存資料
  158.             MemoryStream ms = new MemoryStream();
  159.  
  160.             Stream stream = response.GetResponseStream();
  161.             while ((readed = stream.Read(buf, 0, buf.Length)) > 0)
  162.             {
  163.                 // 記錄接收的串流長度
  164.                 this.AcceptedLength += readed;
  165.                 // 寫入暫存
  166.                 ms.Write(buf, 0, readed);
  167.  
  168.                 // 寫入磁碟
  169.                 if (!this._IsFlushing && DateTime.Now.AddSeconds(-1 * this._FlushInterval) > this._LastFlushTime)
  170.                 {
  171.                     ms.Close();
  172.                     this.FlushToDisk(ms.ToArray());
  173.                     ms = new MemoryStream();
  174.                 }
  175.  
  176.                 // 強迫中斷
  177.                 if (this._StopFlag) break;
  178.             }
  179.  
  180.             stream.Close();
  181.             ms.Close();
  182.             // 等待未完成寫入作業
  183.             while (this._IsFlushing)
  184.             {
  185.                 Thread.Sleep(100);
  186.             }
  187.             this.FlushToDisk(ms.ToArray());
  188.             this.EndTime = DateTime.Now;
  189.             this.IsCompleted = true;
  190.         }).Start();
  191.     }
  192.     /// <summary>
  193.     /// 中斷下載
  194.     /// </summary>
  195.     public void Stop()
  196.     {
  197.         this._StopFlag = true;
  198.     }
  199.     /// <summary>
  200.     /// 由輸入網址產生檔名
  201.     /// </summary>
  202.     private void ParseFileName()
  203.     {
  204.         if (!this._IsFilenameCustomized && !string.IsNullOrWhiteSpace(Url))
  205.         {
  206.             Uri url = new Uri(this.Url);
  207.             this.StoreFilename = url.Segments[url.Segments.Length - 1];
  208.         }
  209.     }
  210.     /// <summary>
  211.     /// 檢查是否有附件名稱
  212.     /// </summary>
  213.     /// <param name="res"></param>
  214.     private void ParseAttachmentName(HttpWebResponse res)
  215.     {
  216.         if (!string.IsNullOrWhiteSpace(res.Headers["Content-Disposition"]))
  217.         {
  218.             string filename = Regex.Match(
  219.                 res.Headers["Content-Disposition"],
  220.                 "filename=(.+)",
  221.                 RegexOptions.IgnoreCase
  222.             ).Groups[1].Value;
  223.  
  224.             if (!string.IsNullOrWhiteSpace(filename))
  225.             {
  226.                 this.StoreFilename = filename;
  227.             }
  228.         }
  229.     }
  230.     /// <summary>
  231.     /// 將暫存資料寫入磁碟
  232.     /// </summary>
  233.     /// <param name="buffer"></param>
  234.     private void FlushToDisk(byte[] buffer)
  235.     {
  236.         new Thread(() =>
  237.         {
  238.             // 標記為寫入中
  239.             this._IsFlushing = true;
  240.             FileStream fs = new FileStream(
  241.                 Path.Combine(this.StorePath, this.StoreFilename),
  242.                 FileMode.Append, FileAccess.Write, FileShare.Write
  243.             );
  244.             fs.Write(buffer, 0, buffer.Length);
  245.             fs.Close();
  246.             // 延遲
  247.             Thread.Sleep(100);
  248.             // 記錄寫入時間
  249.             this._LastFlushTime = DateTime.Now;
  250.             this._IsFlushing = false;
  251.         }).Start();
  252.     }
  253.     /// <summary>
  254.     /// 以適當單位顯示大小
  255.     /// </summary>
  256.     /// <param name="length">位元數</param>
  257.     /// <param name="ext">單位</param>
  258.     /// <returns></returns>
  259.     private string toSize(double length, SizeExtension ext)
  260.     {
  261.         if (ext == SizeExtension.Byte && length < 1) return "0 Byte";
  262.         if (ext == SizeExtension.GB) return string.Format("{0:00.00} {1}", length, ext);
  263.         if (length < 1024)
  264.         {
  265.             return string.Format("{0:##.##} {1}", length, ext);
  266.         }
  267.         else
  268.         {
  269.             return toSize(length / 1024, (SizeExtension)(ext + 1));
  270.         }
  271.     }
  272.     /// <summary>
  273.     /// 串流(資料)長度
  274.     /// </summary>
  275.     /// <returns></returns>
  276.     public string GetLength()
  277.     {
  278.         return this.toSize(this.Length, SizeExtension.Byte);
  279.     }
  280.     /// <summary>
  281.     /// 已收到的串流(資料)長度
  282.     /// </summary>
  283.     /// <returns></returns>
  284.     public string GetAcceptedLenght()
  285.     {
  286.         return this.toSize(this.AcceptedLength, SizeExtension.Byte);
  287.     }
  288. }
Java: ResultSet on store procedure
Oracle
  1. CREATE OR REPLACE PROCEDURE get_result (
  2.     start_pattern IN VARCHAR2,
  3.     end_pattern IN VARCHAR2,
  4.     result_set OUT SYS_REFCURSOR
  5. ) IS
  6. BEGIN
  7.     OPEN result_set FOR
  8.         SELECT
  9.             sheet_id
  10.         FROM checksheet_with_process
  11.         WHERE
  12.             sheet_id >= start_pattern
  13.             AND sheet_id <= end_pattern
  14.         ORDER BY sheet_id DESC;
  15.  
  16. END;
  17.  
  18. -- test 
  19. SET SERVEROUTPUT ON;
  20. DECLARE
  21. result_set SYS_REFCURSOR;
  22. sheet_id VARCHAR2(50);
  23. BEGIN
  24.     DBMS_OUTPUT.ENABLE;
  25.     get_sheet_print_list('20100923','20101023',result_set);
  26.     
  27.     LOOP
  28.         FETCH result_set INTO
  29.             sheet_id
  30.         ;
  31.         EXIT WHEN result_set%NOTFOUND;
  32.         DBMS_OUTPUT.PUT_LINE(sheet_id);
  33.     END LOOP;
  34. END;
ProcedureResult.java
  1. import java.sql.CallableStatement;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6.  
  7. public class ProcedureResult {
  8.  
  9.     /**
  10.      * @param args
  11.      */
  12.     public static void main(String[] args) {
  13.         // TODO Auto-generated method stub
  14.         Connection conn = null;
  15.         CallableStatement stmt = null;
  16.         ResultSet rs = null;
  17.  
  18.         try {
  19.             conn = DriverManager.getConnection("connection string");
  20.             stmt = conn.prepareCall("CALL get_result(?,?,?)");
  21.             stmt.setString(1, "20101001");
  22.             stmt.setString(2, "20101031");
  23.             stmt.registerOutParameter(3, oracle.jdbc.driver.OracleTypes.CURSOR);
  24.             stmt.execute();
  25.             rs = (ResultSet) stmt.getObject(3);
  26.  
  27.             while (rs != null && rs.next()) {
  28.                 System.out.println(rs.getString("sheet_id"));
  29.             }
  30.         } catch (Exception ex) {
  31.             ex.printStackTrace();
  32.         } finally {
  33.             if (rs != null)
  34.                 try {
  35.                     rs.close();
  36.                 } catch (SQLException e2) {
  37.                     // TODO Auto-generated catch block
  38.                     e2.printStackTrace();
  39.                 }
  40.             if (stmt != null)
  41.                 try {
  42.                     stmt.close();
  43.                 } catch (SQLException e1) {
  44.                     // TODO Auto-generated catch block
  45.                     e1.printStackTrace();
  46.                 }
  47.             if (conn != null)
  48.                 try {
  49.                     conn.close();
  50.                 } catch (SQLException e) {
  51.                     // TODO Auto-generated catch block
  52.                     e.printStackTrace();
  53.                 }
  54.         }
  55.     }
  56.  
  57. }
Default checkbox renderer in JTabel
  1. import java.awt.BorderLayout;
  2. import java.awt.Dimension;
  3. import java.awt.Toolkit;
  4.  
  5. import javax.swing.JFrame;
  6. import javax.swing.JScrollPane;
  7. import javax.swing.JTable;
  8. import javax.swing.table.DefaultTableModel;
  9.  
  10. public class CheckBoxCellinTable extends JFrame {
  11.  
  12.     JTable table;
  13.  
  14.     public CheckBoxCellinTable() {
  15.  
  16.         this.setLayout(new BorderLayout());
  17.         this.initTable();
  18.  
  19.         setSize(400, 300);
  20.         Dimension sc = Toolkit.getDefaultToolkit().getScreenSize();
  21.         setLocation((sc.width - getWidth()) / 2, (sc.height - getHeight()) / 2);
  22.         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  23.         setVisible(true);
  24.     }
  25.  
  26.     void initTable() {
  27.         Object[] columnNames = { "First Name", "Last Name", "Married" };
  28.         Object[][] data = { { "Harry", "Smith", true }, { "Sally", "Jones", false }, { "Bob", "Clark", true }, { "Eric", "Burke", true } };
  29.  
  30.         DefaultTableModel model = new DefaultTableModel(data, columnNames) {
  31.             @Override
  32.             public boolean isCellEditable(int row, int column) {
  33.                 return column == 2;
  34.             }
  35.  
  36.             @Override
  37.             public Class<?> getColumnClass(int columnIndex) {
  38.                 return columnIndex == 2 ? Boolean.class : super.getColumnClass(columnIndex);
  39.             }
  40.         };
  41.         table = new JTable(model);
  42.  
  43.         this.add(new JScrollPane(table), BorderLayout.CENTER);
  44.     }
  45.  
  46.     /**
  47.      * @param args
  48.      */
  49.     public static void main(String[] args) {
  50.         // TODO Auto-generated method stub
  51.         new CheckBoxCellinTable();
  52.     }
  53.  
  54. }
Cursor with parameter
  1. SET SERVEROUTPUT ON;
  2. DECLARE 
  3.     id_start VARCHAR2(200);
  4.     CURSOR get_old_id(id_pattern VARCHAR2) IS
  5.         SELECT
  6.         column1
  7.         FROM table1
  8.         WHERE column1 LIKE id_pattern
  9.         ORDER BY column1 ASC
  10.     ;
  11.  
  12. BEGIN
  13.     DBMS_OUTPUT.ENABLE;
  14.     OPEN get_old_id('2010%');
  15.     FETCH get_old_id INTO id_start;
  16.     DBMS_OUTPUT.PUT_LINE(id_start);
  17.     CLOSE get_old_id;
  18. END;
DBMS_OUTPUT in Oracle SQL Developer
  1. SET SERVEROUTPUT ON FORMAT WRAPED;
  2. BEGIN
  3.     DBMS_OUTPUT.ENABLE;
  4.     DBMS_OUTPUT.PUT_LINE('Hello oracle!');
  5. END;