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
Spinner Sample
  1. import java.awt.Dimension;
  2. import java.awt.GridBagConstraints;
  3. import java.awt.GridBagLayout;
  4. import java.awt.Insets;
  5. import java.awt.Point;
  6. import java.awt.Toolkit;
  7.  
  8. import javax.swing.JFrame;
  9. import javax.swing.JSpinner;
  10. import javax.swing.SpinnerDateModel;
  11. import javax.swing.SpinnerListModel;
  12. import javax.swing.SpinnerNumberModel;
  13. import javax.swing.UIManager;
  14. import javax.swing.UnsupportedLookAndFeelException;
  15.  
  16. public class SpinnerSample extends JFrame {
  17.  
  18.     public SpinnerSample() {
  19.         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  20.         this.setSize(new Dimension(500, 500));
  21.         Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
  22.         this.setLocation(new Point((d.width - this.getWidth()) / 2, (d.height - this.getHeight()) / 2));
  23.  
  24.         GridBagLayout layout = new GridBagLayout();
  25.         GridBagConstraints cons = new GridBagConstraints();
  26.         this.setLayout(layout);
  27.  
  28.         cons.insets = new Insets(5, 5, 5, 5);
  29.         cons.gridx = 0;
  30.         cons.gridy = 0;
  31.         cons.anchor = GridBagConstraints.WEST;
  32.         cons.fill = GridBagConstraints.HORIZONTAL;
  33.  
  34.         JSpinner spinner = null;
  35.  
  36.         spinner = new JSpinner(new SpinnerDateModel());
  37.         //spinner.setEditor(new JSpinner.DateEditor(spinner, "yyyy/MM/dd HH:mm"));
  38.         this.add(spinner);
  39.         layout.setConstraints(spinner, cons);
  40.  
  41.         cons.gridy++;
  42.         spinner = new JSpinner(new SpinnerListModel(new String[] { "日曜日", "月曜日", "火曜日", "水曜日", "木曜日", "金曜日", "土曜日" }));
  43.         this.add(spinner);
  44.         layout.setConstraints(spinner, cons);
  45.  
  46.         cons.gridy++;
  47.         spinner = new JSpinner(new SpinnerNumberModel());
  48.         this.add(spinner);
  49.         layout.setConstraints(spinner, cons);
  50.  
  51.         this.setVisible(true);
  52.         this.pack();
  53.     }
  54.  
  55.     public static void main(String[] args) {
  56.         try {
  57.             UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
  58.         } catch (ClassNotFoundException e) {
  59.             // TODO Auto-generated catch block
  60.             e.printStackTrace();
  61.         } catch (InstantiationException e) {
  62.             // TODO Auto-generated catch block
  63.             e.printStackTrace();
  64.         } catch (IllegalAccessException e) {
  65.             // TODO Auto-generated catch block
  66.             e.printStackTrace();
  67.         } catch (UnsupportedLookAndFeelException e) {
  68.             // TODO Auto-generated catch block
  69.             e.printStackTrace();
  70.         }
  71.         new SpinnerSample();
  72.     }
  73. }
Formatter review
  1. // %[argument_index$][flags][width][.precision]conversion
  2.  
  3. // (b/B) boolean
  4. System.out.printf("result : %1$b %2$b %3$b %n", false, new Boolean(true), null);
  5. // result : false true false
  6.  
  7. // (h/H) Integer.toHexString(arg.hashCode())
  8. System.out.printf("result : %1$h %2$h %n", "bruce", 12);
  9. // result : 59a9547 c
  10.  
  11. // (s/S) arg.toString()
  12. System.out.printf("result : %1$s %2$s %n", 10, "bruce");
  13. // result : 10 bruce
  14.  
  15. // (c/C) character
  16. System.out.printf("result : %1$c %2$c %n", 'c', '\u0051');
  17. // result : c Q
  18.  
  19. // (d, o, x/X) integral
  20. System.out.printf("result : %1$d %1$o %1$x %n", 1024);
  21. // result : 1024 2000 400
  22. System.out.printf("result : %1$d %1$o %1$x %n", 1024);
  23. // result : 1024 ( 1024) 0001024
  24.  
  25. // (e/E, f, g/G, a/A) floating point
  26. System.out.printf("result : %1$e %1$f %1$g %1$a %n", 1234.567);
  27. // result : 1.234567e+03 1234.567000 1234.57 0x1.34a449ba5e354p10
  28. System.out.printf("result : %1$f (%1$7.2f) %1$07.0f %1$07.2f%n", 1234.567);
  29. // result : 1234.567000 (1234.57) 0001235 1234.57
  30.  
  31. // date/time (R, T, r, D, F, c)
  32. System.out.printf("result : %tR %n", Calendar.getInstance());
  33. // result : 09:53
  34. System.out.printf("result : %tT %n", Calendar.getInstance());
  35. // result : 09:53:18
  36. System.out.printf("result : %tr %n", Calendar.getInstance());
  37. // result : 09:53:18 上午
  38. System.out.printf("result : %tD %n", Calendar.getInstance());
  39. // result : 06/10/10
  40. System.out.printf("result : %tF %n", Calendar.getInstance());
  41. // result : 2010-06-10
  42. System.out.printf("result : %tc %n", Calendar.getInstance());
  43. // result : 星期四 六月 10 09:53:18 CST 2010
  44. System.out.printf("result : %1$tY/%1$tm/%1$td %1$tH:%1$tM:%1$tS", Calendar.getInstance());
  45. // result : 2010/06/10 11:02:38
other date args http://java.sun.com/j2se/1.5.0/docs/api/java/util/Formatter.html#dt
LogonUser Function : impersonate a windows user
  1. // This sample demonstrates the use of the WindowsIdentity class to impersonate a user.
  2. // IMPORTANT NOTES: 
  3. // This sample can be run only on Windows XP.  The default Windows 2000 security policy 
  4. // prevents this sample from executing properly, and changing the policy to allow
  5. // proper execution presents a security risk. 
  6. // This sample requests the user to enter a password on the console screen.
  7. // Because the console window does not support methods allowing the password to be masked, 
  8. // it will be visible to anyone viewing the screen.
  9. // The sample is intended to be executed in a .NET Framework 1.1 environment.  To execute
  10. // this code in a 1.0 environment you will need to use a duplicate token in the call to the
  11. // WindowsIdentity constructor. See KB article Q319615 for more information.
  12.  
  13. using System;
  14. using System.Runtime.InteropServices;
  15. using System.Security.Principal;
  16. using System.Security.Permissions;
  17.  
  18. [assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode = true)]
  19. [assembly: PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]
  20. public class ImpersonationDemo
  21. {
  22.     const int LOGON32_LOGON_INTERACTIVE = 2;
  23.     const int LOGON32_LOGON_NETWORK = 3;
  24.     const int LOGON32_LOGON_BATCH = 4;
  25.     const int LOGON32_LOGON_SERVICE = 5;
  26.     const int LOGON32_LOGON_UNLOCK = 7;
  27.     const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8;
  28.     const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
  29.  
  30.     const int LOGON32_PROVIDER_DEFAULT = 0;
  31.     const int LOGON32_PROVIDER_WINNT50 = 3;
  32.     const int LOGON32_PROVIDER_WINNT40 = 2;
  33.     const int LOGON32_PROVIDER_WINNT35 = 1;
  34.  
  35.     [DllImport("advapi32.dll", SetLastError = true)]
  36.     public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
  37.         int dwLogonType, int dwLogonProvider, ref IntPtr phToken);
  38.  
  39.     //[DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
  40.     //private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource,
  41.     //    int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr* Arguments);
  42.  
  43.     [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  44.     public extern static bool CloseHandle(IntPtr handle);
  45.  
  46.     [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
  47.     public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
  48.         int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);
  49.  
  50.     // Test harness.
  51.     // If you incorporate this code into a DLL, be sure to demand FullTrust.
  52.     [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
  53.     public static void Main2(string[] args)
  54.     {
  55.         IntPtr tokenHandle = new IntPtr(0);
  56.         IntPtr dupeTokenHandle = new IntPtr(0);
  57.         try
  58.         {
  59.             string userName, domainName;
  60.             // Get the user token for the specified user, domain, and password using the 
  61.             // unmanaged LogonUser method.  
  62.             // The local machine name can be used for the domain name to impersonate a user on this machine.
  63.             Console.Write("Enter the name of the domain on which to log on: ");
  64.             domainName = Console.ReadLine();
  65.  
  66.             Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
  67.             userName = Console.ReadLine();
  68.  
  69.             Console.Write("Enter the password for {0}: ", userName);
  70.  
  71.             tokenHandle = IntPtr.Zero;
  72.  
  73.             // Call LogonUser to obtain a handle to an access token.
  74.             bool returnValue = LogonUser(userName, domainName, Console.ReadLine(),
  75.                 LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT,
  76.                 ref tokenHandle);
  77.  
  78.             Console.WriteLine("LogonUser called.");
  79.  
  80.             if (false == returnValue)
  81.             {
  82.                 int ret = Marshal.GetLastWin32Error();
  83.                 Console.WriteLine("LogonUser failed with error code : {0}", ret);
  84.                 throw new System.ComponentModel.Win32Exception(ret);
  85.             }
  86.  
  87.             Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
  88.             Console.WriteLine("Value of Windows NT token: " + tokenHandle);
  89.  
  90.             // Check the identity.
  91.             Console.WriteLine("Before impersonation: "
  92.                 + WindowsIdentity.GetCurrent().Name);
  93.             // Use the token handle returned by LogonUser.
  94.             WindowsIdentity newId = new WindowsIdentity(tokenHandle);
  95.             WindowsImpersonationContext impersonatedUser = newId.Impersonate();
  96.  
  97.             // Check the identity.
  98.             Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name);
  99.  
  100.             // Stop impersonating the user.
  101.             impersonatedUser.Undo();
  102.  
  103.             // Check the identity.
  104.             Console.WriteLine("After Undo: " + WindowsIdentity.GetCurrent().Name);
  105.  
  106.             // Free the tokens.
  107.             if (tokenHandle != IntPtr.Zero)
  108.                 CloseHandle(tokenHandle);
  109.  
  110.         }
  111.         catch (Exception ex)
  112.         {
  113.             Console.WriteLine("Exception occurred. " + ex.Message);
  114.         }
  115.  
  116.         Console.Read();
  117.     }
  118.  
  119. }
or
  1. public class ImpersonateIdentity : IDisposable
  2. {
  3.     [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
  4.     public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);
  5.  
  6.     [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
  7.     public extern static bool CloseHandle(IntPtr handle);
  8.  
  9.     [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
  10.     public static ImpersonateIdentity Impersonate(string userName, string password, string domainName)
  11.     {
  12.         ImpersonateIdentity identity = new ImpersonateIdentity();
  13.  
  14.         const int LOGON32_PROVIDER_DEFAULT = 0;
  15.         //This parameter causes LogonUser to create a primary token.
  16.         const int LOGON32_LOGON_INTERACTIVE = 2;
  17.  
  18.         // Call LogonUser to obtain a handle to an access token.
  19.         bool returnValue = LogonUser(userName, domainName, password,
  20.             LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
  21.             out identity.safeTokenHandle);
  22.  
  23.         if (false == returnValue)
  24.         {
  25.             int ret = Marshal.GetLastWin32Error();
  26.             throw new System.ComponentModel.Win32Exception(ret);
  27.         }
  28.  
  29.         identity.impersonatedUser = WindowsIdentity.Impersonate(identity.safeTokenHandle.DangerousGetHandle());
  30.         return identity;
  31.     }
  32.  
  33.     WindowsImpersonationContext impersonatedUser;
  34.     SafeTokenHandle safeTokenHandle;
  35.  
  36.     private ImpersonateIdentity() { }
  37.  
  38.     public void Dispose()
  39.     {
  40.         if (impersonatedUser != null) impersonatedUser.Dispose();
  41.         if (safeTokenHandle != null) safeTokenHandle.Dispose();
  42.     }
  43. }
  44.  
  45. public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
  46. {
  47.     private SafeTokenHandle()
  48.         : base(true)
  49.     {
  50.     }
  51.  
  52.     [DllImport("kernel32.dll")]
  53.     [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
  54.     [SuppressUnmanagedCodeSecurity]
  55.     [return: MarshalAs(UnmanagedType.Bool)]
  56.     private static extern bool CloseHandle(IntPtr handle);
  57.  
  58.     protected override bool ReleaseHandle()
  59.     {
  60.         return CloseHandle(handle);
  61.     }
  62. }
reference : or
  1. using System;
  2. using System.IO;
  3. using System.Runtime.InteropServices;
  4. using System.Security.Principal;
  5. using System.Security.Permissions;
  6.  
  7. [assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode = true)]
  8. [assembly: PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]
  9. namespace ConsoleApplication1
  10. {
  11.     class Class1
  12.     {
  13.         //登入
  14.         [DllImport("advapi32.dll", SetLastError = true)]
  15.         public static extern bool LogonUser(
  16.             string lpszUsername,
  17.             string lpszDomain,
  18.             string lpszPassword,
  19.             int dwLogonType,
  20.             int dwLogonProvider,
  21.             ref IntPtr phToken
  22.         );
  23.             
  24.         //登出
  25.         [DllImport("kernel32.dll")]
  26.         public extern static bool CloseHandle(IntPtr hToken);
  27.  
  28.         public Class1()
  29.         {
  30.             string UserName = "username";
  31.             string MachineName = "192.168.0.10";
  32.             string Pw = "password";
  33.             string IPath = @"\\" + MachineName + @"\shared";
  34.             
  35.             const int LOGON32_PROVIDER_DEFAULT = 0;
  36.             const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
  37.             
  38.             IntPtr tokenHandle = new IntPtr(0);
  39.             tokenHandle = IntPtr.Zero;
  40.             
  41.             //將登入的Token放在tokenHandle
  42.             bool returnValue = LogonUser(
  43.                 UserName,
  44.                 MachineName,
  45.                 Pw,
  46.                 LOGON32_LOGON_NEW_CREDENTIALS,
  47.                 LOGON32_PROVIDER_DEFAULT,
  48.                 ref tokenHandle
  49.             );
  50.  
  51.             //讓程式模擬登入的使用者
  52.             WindowsIdentity w = new WindowsIdentity(tokenHandle);
  53.             w.Impersonate();
  54.             if (false == returnValue)
  55.             {
  56.                 //登入失敗的處理
  57.                 return;
  58.             }
  59.             //取得該目錄下的所有檔案名稱
  60.             DirectoryInfo dir = new DirectoryInfo(IPath);
  61.             FileInfo[] inf = dir.GetFiles();
  62.             for (int i = 0; i < inf.Length; i++)
  63.             {
  64.                 Console.WriteLine(inf[i].Name);
  65.             }
  66.         }
  67.     }
  68. }
Condition : in a domain
  1. LogonUser(
  2.     UserName,
  3.     "myDomain",
  4.     Pw,LOGON32_LOGON_NEW_CREDENTIALS,
  5.     LOGON32_PROVIDER_DEFAULT,
  6.     ref tokenHandle
  7. );
reference : [C#]在程式中模擬特定的windows帳號存取網路芳鄰
Active Directory authentication
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data;
  6. using System.Data.OleDb;
  7. using System.Runtime.Serialization;
  8. using System.Runtime.Serialization.Json;
  9. using System.IO;
  10. using System.DirectoryServices;
  11. using System.DirectoryServices.AccountManagement;
  12.  
  13. class Program
  14. {
  15.     static void Main(string[] args)
  16.     {
  17.         string domain = "mydomain";
  18.         string account = "bruce";
  19.         string password = "12345678";
  20.  
  21.         Console.WriteLine(IsAuthenticated1(domain, account, password));
  22.         Console.WriteLine(IsAuthenticated2(domain, account, password));
  23.         Console.WriteLine(IsAuthenticated3(domain, account, password));
  24.         Console.Read();
  25.     }
  26.  
  27.     static bool IsAuthenticated1(string domain, string account, string password)
  28.     {
  29.         bool isAuthenticated = false;
  30.         DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domain), account, password);
  31.         try
  32.         {
  33.             object o = entry.NativeObject;
  34.             isAuthenticated = true;
  35.             entry.Close();
  36.         }
  37.         catch (Exception ex)
  38.         {
  39.             entry.Close();
  40.         }
  41.         return isAuthenticated;
  42.     }
  43.  
  44.     static bool IsAuthenticated2(string domain, string account, string password)
  45.     {
  46.         bool isAuthenticated = false;
  47.         DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domain), account, password);
  48.         try
  49.         {
  50.             DirectorySearcher searcher = new DirectorySearcher(entry);
  51.             searcher.Filter = string.Format("(sAMAccountName={0})", account);
  52.             SearchResult result = searcher.FindOne();
  53.             entry.Close();
  54.             isAuthenticated = true;
  55.         }
  56.         catch (Exception ex)
  57.         {
  58.             entry.Close();
  59.         }
  60.         return isAuthenticated;
  61.     }
  62.  
  63.     static bool IsAuthenticated3(string domain, string account, string password)
  64.     {
  65.         try
  66.         {
  67.             PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain);
  68.             return pc.ValidateCredentials(account, password);
  69.         }
  70.         catch (Exception ex)
  71.         {
  72.             return false;
  73.         }
  74.     }
  75. }
Searialize object as JSON
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Data;
  6. using System.Data.OleDb;
  7. using System.Runtime.Serialization;
  8. using System.Runtime.Serialization.Json;
  9. using System.IO;
  10.  
  11. class Program
  12. {
  13.     static void Main(string[] args)
  14.     {
  15.         Person person = new Person("Bruce", "Tsai");
  16.         DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Person));
  17.         MemoryStream ms = new MemoryStream();
  18.         serializer.WriteObject(ms, person);
  19.         ms.Close();
  20.         string json = Encoding.Default.GetString(ms.ToArray());
  21.         Console.WriteLine(json);
  22.         Console.Read();
  23.     }
  24. }
  25.  
  26.  
  27. [DataContract]
  28. public class Person
  29. {
  30.     public Person() { }
  31.     public Person(string firstname, string lastname)
  32.     {
  33.         this.FirstName = firstname;
  34.         this.LastName = lastname;
  35.     }
  36.  
  37.     [DataMember]
  38.     public string FirstName { get; set; }
  39.  
  40.     [DataMember]
  41.     public string LastName { get; set; }
  42. }
JSONHelper
  1. public class JSONHelper
  2. {
  3.  
  4.     public static string ToJson(object obj)
  5.     {
  6.         DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
  7.         MemoryStream ms = new MemoryStream();
  8.         serializer.WriteObject(ms, obj);
  9.         ms.Close();
  10.         string json = Encoding.UTF8.GetString(ms.ToArray());
  11.         return json;
  12.     }
  13.  
  14.     public static T ParseJson<T>(string json)
  15.     {
  16.         T obj = Activator.CreateInstance<T>();
  17.         MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
  18.         DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());
  19.         obj = (T)ser.ReadObject(ms);
  20.         ms.Close();
  21.         return obj;
  22.     }
  23. }
Query index data
1. Start window service Indexing Service
2. Create a new category and start indexing.
  1. class Program
  2. {
  3.     static void Main(string[] args)
  4.     {
  5.         // reference : http://msdn.microsoft.com/en-us/library/ms690516
  6.         string strCatalog = "TestIndexing";
  7.         string strKeyword = "readme";  // search keyword
  8.         string strQuery = string.Format(
  9.             @"SELECT path, FileName, size, write, attrib FROM SCOPE() WHERE FREETEXT('{0}')",
  10.             //@"SELECT * FROM FILEINFO WHERE FREETEXT('{0}')",
  11.             strKeyword
  12.         );
  13.  
  14.         string connstring = "Provider=MSIDXS.1;Integrated Security .='';Data Source=" + strCatalog;
  15.  
  16.         DataSet set = null;
  17.         try
  18.         {
  19.             using (OleDbDataAdapter adapter = new OleDbDataAdapter(strQuery, connstring))
  20.             {
  21.                 adapter.Fill(set = new DataSet());
  22.             }
  23.         }
  24.         catch (Exception ex)
  25.         {
  26.             Console.WriteLine(ex.Message);
  27.             return;
  28.         }
  29.  
  30.         foreach (DataRow row in set.Tables[0].Rows)
  31.         {
  32.             Console.WriteLine("{0} |{1} @{2}", row["FileName"], row["size"], row["write"]);
  33.         }
  34.         Console.Read();
  35.     }
  36. }
Create barcode
  1. import java.io.File;
  2. import java.io.FileNotFoundException;
  3.  
  4. import net.sourceforge.barbecue.Barcode;
  5. import net.sourceforge.barbecue.BarcodeException;
  6. import net.sourceforge.barbecue.BarcodeFactory;
  7. import net.sourceforge.barbecue.BarcodeImageHandler;
  8. import net.sourceforge.barbecue.output.OutputException;
  9.  
  10. public class Program {
  11.  
  12.     /**
  13.      * @param args
  14.      * @throws FileNotFoundException
  15.      * @throws BarcodeException
  16.      * @throws OutputException
  17.      */
  18.     public static void main(String[] args) throws FileNotFoundException, BarcodeException, OutputException {
  19.         // TODO Auto-generated method stub
  20.  
  21.         Barcode code = BarcodeFactory.create3of9("123456789", true);
  22.         BarcodeImageHandler.savePNG(code, new File("barcode.png"));
  23.  
  24.     }
  25.  
  26. }
Library : http://barbecue.sourceforge.net/
Simple Web snapshot
  1. import java.util.Date;
  2.  
  3. import org.eclipse.swt.SWT;
  4. import org.eclipse.swt.browser.Browser;
  5. import org.eclipse.swt.graphics.GC;
  6. import org.eclipse.swt.graphics.Image;
  7. import org.eclipse.swt.graphics.ImageData;
  8. import org.eclipse.swt.graphics.ImageLoader;
  9. import org.eclipse.swt.layout.FillLayout;
  10. import org.eclipse.swt.widgets.Display;
  11. import org.eclipse.swt.widgets.Shell;
  12.  
  13. public class WebSnap {
  14.  
  15.     public static final int PNG = SWT.IMAGE_PNG;
  16.     public static final int BMP = SWT.IMAGE_BMP;
  17.     public static final int JPG = SWT.IMAGE_JPEG;
  18.     public static final int GIF = SWT.IMAGE_GIF;
  19.     public static final int TIFF = SWT.IMAGE_TIFF;
  20.  
  21.     private Display display;
  22.     private Shell shell;
  23.     private Browser browser;
  24.  
  25.     /**
  26.      * 截圖寬度
  27.      */
  28.     private int width;
  29.     /**
  30.      * 截圖高度
  31.      */
  32.     private int height;
  33.  
  34.     /**
  35.      * @param width
  36.      *            截圖寬度
  37.      * @param height
  38.      *            截圖高度
  39.      * @param url
  40.      *            目標網址URL
  41.      */
  42.     public WebSnap(int width, int height, String url) {
  43.         this.width = width;
  44.         this.height = height;
  45.         this.display = new Display();
  46.  
  47.         this.shell = new Shell(this.display);
  48.         this.shell.setLayout(new FillLayout());
  49.         this.shell.setSize(width, height);
  50.         this.shell.setText("Web Snap");
  51.  
  52.         this.browser = new Browser(this.shell, SWT.NONE);
  53.         this.browser.setSize(width, height);
  54.         this.browser.setUrl(url);
  55.     }
  56.  
  57.     /**
  58.      * @param file
  59.      *            圖片存檔路徑
  60.      * @param swtImageType
  61.      *            圖片存檔類型
  62.      */
  63.     private void snap(String file, int swtImageType) {
  64.         Image data = new Image(this.display, this.width, this.height);
  65.         this.browser.print(new GC(data));
  66.         ImageLoader il = new ImageLoader();
  67.         il.data = new ImageData[] { data.getImageData() };
  68.         il.save(file, swtImageType);
  69.         data.dispose();
  70.     }
  71.  
  72.     /**
  73.      * @param file
  74.      *            圖片存檔路徑
  75.      * @param swtImageType
  76.      *            圖片存檔類型
  77.      * @param sleepTick
  78.      *            延遲時間
  79.      */
  80.     public void asynSnap(final String file, final int type, final long sleepTick) {
  81.         new Thread() {
  82.             public void run() {
  83.                 try {
  84.                     Thread.sleep(sleepTick);
  85.                 } catch (InterruptedException e) {
  86.                     // TODO Auto-generated catch block
  87.                     e.printStackTrace();
  88.                 }
  89.                 WebSnap.this.display.asyncExec(new Runnable() {
  90.                     public void run() {
  91.                         WebSnap.this.snap(file, type);
  92.                         WebSnap.this.shell.dispose();
  93.                     }
  94.                 });
  95.             };
  96.         }.start();
  97.         this.waitForDispose();
  98.     }
  99.  
  100.     private void waitForDispose() {
  101.         while (!this.shell.isDisposed()) {
  102.             if (!this.display.readAndDispatch()) {
  103.                 this.display.sleep();
  104.             }
  105.         }
  106.         this.display.dispose();
  107.     }
  108.  
  109.     public static void main(String[] args) {
  110.         int width = 1024, height = 768;
  111.         String url = "http://tw.yahoo.com";
  112.         String file = String.format("w%d.png", new Date().getTime());
  113.  
  114.         WebSnap ws = new WebSnap(width, height, url);
  115.         ws.asynSnap(file, WebSnap.PNG, 18000);
  116.     }
  117.  
  118. }
File operation at SMB / UNC (network neighborhood)
  1. import java.io.IOException;
  2. import java.io.OutputStreamWriter;
  3.  
  4. import jcifs.Config;
  5. import jcifs.smb.SmbFile;
  6. import jcifs.smb.SmbFileOutputStream;
  7.  
  8. public class Program {
  9.  
  10.     /**
  11.      * @param args
  12.      * @throws IOException
  13.      */
  14.     public static void main(String[] args) throws IOException {
  15.         // TODO Auto-generated method stub
  16.  
  17.         StringBuilder sb = new StringBuilder("<html><head><title>9 x 9</title></head><body><table border='1'>");
  18.         sb.append(System.getProperty("line.separator"));
  19.         for (int i = 1; i < 10; i++) {
  20.             sb.append("<tr>");
  21.             for (int j = 1; j < 10; j++) {
  22.                 sb.append(String.format("<td>%d x %d = %d</td>", i, j, i * j));
  23.             }
  24.             sb.append("</tr>");
  25.             sb.append(System.getProperty("line.separator"));
  26.         }
  27.         sb.append("</table></body></html>");
  28.  
  29.         Config.setProperty("jcifs.smb.client.domain", "mydomain");
  30.         Config.setProperty("jcifs.smb.client.username", "bruce");
  31.         Config.setProperty("jcifs.smb.client.password", "12345678");
  32.  
  33.         SmbFile remotePath = new SmbFile("file://computer_name/mis/subfolder/test.html");
  34.         // SmbFile remotePath = new SmbFile("smb://hostname/upload$/test.html");
  35.  
  36.         SmbFileOutputStream sfos = new SmbFileOutputStream(remotePath);
  37.         OutputStreamWriter osw = new OutputStreamWriter(sfos);
  38.         osw.write(sb.toString());
  39.         osw.close();
  40.         sfos.close();
  41.     }
  42.  
  43. }
Library : http://jcifs.samba.org/
Export excel using html format cause leading zero disappeared
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace ConsoleApplication4
  7. {
  8.     class Program
  9.     {
  10.         static char[] vs = "qazxswedcvfrtgb nhyujmkioplPLOKIJU HYGTFRDESWSQAZXCVBNM ".ToCharArray();
  11.  
  12.         static void Main(string[] args)
  13.         {
  14.             StringBuilder sb = new StringBuilder(@"<html xmlns:o=""urn:schemas-microsoft-com:office:office""
  15. xmlns:x=""urn:schemas-microsoft-com:office:excel""
  16. xmlns=""http://www.w3.org/TR/REC-html40"">
  17. <head>
  18. </head><table border=""1""><thead><tr><th>column A</th><th>column B</th><th>column C</th><th>column D</th></tr></thead><tbody>");
  19.             Random r = new Random();
  20.             for (int i = 0; i < 10; i++)
  21.             {
  22.                     sb.AppendFormat(
  23.                         @"<tr><td>{0}</td><td>{1}</td><td x:str=""{2:0000000000}"">{2:0000000000}</td><td>{3}</td></tr>",
  24.                         getRandomWord(r),
  25.                         r.NextDouble(),
  26.                         r.Next(10000000),
  27.                         "test"
  28.                     ).AppendLine();
  29.             }
  30.             sb.Append("</tbody></body></html>");
  31.  
  32.             System.IO.File.WriteAllText("z:/test.xls", sb.ToString());
  33.         }
  34.  
  35.         static string getRandomWord(Random r)
  36.         {
  37.             int length = r.Next(5, 15);
  38.             StringBuilder sb = new StringBuilder();
  39.             while (length-- > 0)
  40.             {
  41.                 sb.Append(vs[r.Next(vs.Length - 1)]);
  42.             }
  43.             return sb.ToString();
  44.         }
  45.     }
  46. }
(export without x:str attribute)
(export with x:str attribute)

Use xml format example

  1. <?xml version="1.0"?>
  2. <?mso-application progid="Excel.Sheet"?>
  3. <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
  4.           xmlns:o="urn:schemas-microsoft-com:office:office"
  5.           xmlns:x="urn:schemas-microsoft-com:office:excel"
  6.           xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
  7.           xmlns:html="http://www.w3.org/TR/REC-html40">
  8.   <Worksheet ss:Name="Sheet1">
  9.     <Table  ss:DefaultColumnWidth="54" ss:DefaultRowHeight="16.5">
  10.       <Row>
  11.         <Cell>
  12.           <Data ss:Type="String">KPmBYSAYyugQe</Data>
  13.         </Cell>
  14.         <Cell>
  15.           <Data ss:Type="Number">0.96726507412608</Data>
  16.         </Cell>
  17.         <Cell>
  18.           <Data ss:Type="String">0000197334</Data>
  19.         </Cell>
  20.         <Cell>
  21.           <Data ss:Type="String">test</Data>
  22.         </Cell>
  23.       </Row>
  24.       <Row>
  25.         <Cell>
  26.           <Data ss:Type="String">XdpptxEYqEf</Data>
  27.         </Cell>
  28.         <Cell>
  29.           <Data ss:Type="Number">0.734600760850404</Data>
  30.         </Cell>
  31.         <Cell>
  32.           <Data ss:Type="String">0001564744</Data>
  33.         </Cell>
  34.         <Cell>
  35.           <Data ss:Type="String">test</Data>
  36.         </Cell>
  37.       </Row>
  38.       <Row>
  39.         <Cell>
  40.           <Data ss:Type="String">RbkWExnsMfJNHS</Data>
  41.         </Cell>
  42.         <Cell>
  43.           <Data ss:Type="Number">0.666254851346023</Data>
  44.         </Cell>
  45.         <Cell>
  46.           <Data ss:Type="String">0003279746</Data>
  47.         </Cell>
  48.         <Cell>
  49.           <Data ss:Type="String">test</Data>
  50.         </Cell>
  51.       </Row>
  52.       <Row>
  53.         <Cell>
  54.           <Data ss:Type="String">OBbRffRJP</Data>
  55.         </Cell>
  56.         <Cell>
  57.           <Data ss:Type="Number">0.721114829052759</Data>
  58.         </Cell>
  59.         <Cell>
  60.           <Data ss:Type="String">0007181989</Data>
  61.         </Cell>
  62.         <Cell>
  63.           <Data ss:Type="String">test</Data>
  64.         </Cell>
  65.       </Row>
  66.       <Row>
  67.         <Cell>
  68.           <Data ss:Type="String">ZHdLm MohfByWd</Data>
  69.         </Cell>
  70.         <Cell>
  71.           <Data ss:Type="Number">0.270307757551925</Data>
  72.         </Cell>
  73.         <Cell>
  74.           <Data ss:Type="String">0008739388</Data>
  75.         </Cell>
  76.         <Cell>
  77.           <Data ss:Type="String">test</Data>
  78.         </Cell>
  79.       </Row>
  80.       <Row>
  81.         <Cell>
  82.           <Data ss:Type="String">kNqGnHE</Data>
  83.         </Cell>
  84.         <Cell>
  85.           <Data ss:Type="Number">0.895800942506548</Data>
  86.         </Cell>
  87.         <Cell>
  88.           <Data ss:Type="String">0001980657</Data>
  89.         </Cell>
  90.         <Cell>
  91.           <Data ss:Type="String">test</Data>
  92.         </Cell>
  93.       </Row>
  94.       <Row>
  95.         <Cell>
  96.           <Data ss:Type="String">xYr yJdeKp</Data>
  97.         </Cell>
  98.         <Cell>
  99.           <Data ss:Type="Number">0.462409074633573</Data>
  100.         </Cell>
  101.         <Cell>
  102.           <Data ss:Type="String">0002466265</Data>
  103.         </Cell>
  104.         <Cell>
  105.           <Data ss:Type="String">test</Data>
  106.         </Cell>
  107.       </Row>
  108.       <Row>
  109.         <Cell>
  110.           <Data ss:Type="String">GZvyMV</Data>
  111.         </Cell>
  112.         <Cell>
  113.           <Data ss:Type="Number">0.921151050795406</Data>
  114.         </Cell>
  115.         <Cell>
  116.           <Data ss:Type="String">0000487429</Data>
  117.         </Cell>
  118.         <Cell>
  119.           <Data ss:Type="String">test</Data>
  120.         </Cell>
  121.       </Row>
  122.       <Row>
  123.         <Cell>
  124.           <Data ss:Type="String">AysRFgIMuUfwCE</Data>
  125.         </Cell>
  126.         <Cell>
  127.           <Data ss:Type="Number">0.102547224193135</Data>
  128.         </Cell>
  129.         <Cell>
  130.           <Data ss:Type="String">0009025478</Data>
  131.         </Cell>
  132.         <Cell>
  133.           <Data ss:Type="String">test</Data>
  134.         </Cell>
  135.       </Row>
  136.       <Row>
  137.         <Cell>
  138.           <Data ss:Type="String">RYaFkSvWhWd</Data>
  139.         </Cell>
  140.         <Cell>
  141.           <Data ss:Type="Number">0.313286157936457</Data>
  142.         </Cell>
  143.         <Cell>
  144.           <Data ss:Type="String">0007754057</Data>
  145.         </Cell>
  146.         <Cell>
  147.           <Data ss:Type="String">test</Data>
  148.         </Cell>
  149.       </Row>
  150.     </Table>
  151.     <WorksheetOptions xmlns="urn:schemas-microsoft-com:office:excel">
  152.       <ProtectObjects>False</ProtectObjects>
  153.       <ProtectScenarios>False</ProtectScenarios>
  154.     </WorksheetOptions>
  155.   </Worksheet>
  156. </Workbook>
Reference : http://msdn.microsoft.com/en-us/library/bb226687%28v=office.11%29.aspx
Object serialize/ deserialize
  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.io.Serializable;
  7.  
  8. public class TransientMember {
  9.  
  10.     /**
  11.      * @param args
  12.      * @throws IOException
  13.      * @throws ClassNotFoundException
  14.      */
  15.     public static void main(String[] args) throws IOException, ClassNotFoundException {
  16.         // create new user with account & password
  17.         User user = new User();
  18.         user.account = "bruce";
  19.         user.password = "mypassword";
  20.         System.out.println(user);
  21.         // serialize
  22.         byte[] buffer = user.serialize();
  23.  
  24.         // deserialize from byte array
  25.         User user2 = User.deserialize(buffer);
  26.         System.out.println(user2);
  27.     }
  28.  
  29. }
  30.  
  31. class User implements Serializable {
  32.     public String account;
  33.     transient public String password;  // would not be serialize
  34.  
  35.     @Override
  36.     public String toString() {
  37.         return String.format("<user account:%s password:%s>", this.account, this.password);
  38.     }
  39.  
  40.     public byte[] serialize() throws IOException {
  41.         ByteArrayOutputStream baos = new ByteArrayOutputStream();
  42.         ObjectOutputStream oos = new ObjectOutputStream(baos);
  43.         oos.writeObject(this);
  44.         oos.close();
  45.         baos.close();
  46.         return baos.toByteArray();
  47.     }
  48.  
  49.     public static User deserialize(byte[] buf) throws IOException, ClassNotFoundException {
  50.         ByteArrayInputStream bais = new ByteArrayInputStream(buf);
  51.         ObjectInputStream ois = new ObjectInputStream(bais);
  52.         Object o = ois.readObject();
  53.         ois.close();
  54.         bais.close();
  55.         return (User) o;
  56.     }
  57. }