Popular Posts
Tick Start tick Java Javascript .net Tick = 0 (GMT+0) 1970/01/01 00:00:00 1970/01/01 00:00:00 1601/01/01 00:00:00... SwiXml - JTextBox (Customized JTextField) LimitedDocument.java package swixml.sample; import javax.swing.text.AttributeSet; import javax.swing.text.BadLocationException; import jav... 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...
Stats
ListSelectionListener & ItemListener
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Toolkit;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.DefaultListModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

public class StatusChange extends JFrame {

    public StatusChange() {
        getContentPane().setLayout(new FlowLayout());

        DefaultListModel model = new DefaultListModel();
        JList list = new JList(model);
        model.addElement("one");
        model.addElement("two");
        model.addElement("three");
        model.addElement("four");
        model.addElement("five");
        model.addElement("six");
        model.addElement("seven");
        model.addElement("eight");
        model.addElement("nine");
        list.addListSelectionListener(new ListSelectionListener() {
            @Override
            public void valueChanged(ListSelectionEvent e) {
                JList list = (JList) e.getSource();

                // execute twice
                System.out.printf("=====%s=====%n", list.getSelectedValue());
                if (list.getValueIsAdjusting()) {
                    // execute once
                    System.out.println(list.getSelectedValue());
                }
            }
        });
        getContentPane().add(new JScrollPane(list));

        JComboBox combo = new JComboBox();
        combo.addItem("one");
        combo.addItem("two");
        combo.addItem("three");
        combo.addItem("four");
        combo.addItem("five");
        combo.addItem("six");
        combo.addItem("seven");
        combo.addItem("eight");
        combo.addItem("nine");

        combo.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                JComboBox combo = (JComboBox) e.getSource();
                // execute twice (occurs on selected & deselected)
                System.out.printf("-----%s-----%n", combo.getSelectedItem());
                if (e.getStateChange() == e.SELECTED) {
                    // execute once
                    System.out.println(combo.getSelectedItem());
                }
            }
        });
        getContentPane().add(combo);

        pack();
        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        setLocation((screen.width - this.getWidth()) / 2, (screen.height - this.getHeight()) / 2);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
    }

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

}
Start JBoss failed on eclipse (timeout)

jboss-4.0.5.GA\server\default\deploy\jbossweb-tomcat55.sar\server.xml
<Connector port="8888" address="${jboss.bind.address}"
 maxThreads="250" strategy="ms" maxHttpHeaderSize="8192"
 emptySessionPath="true"
 enableLookups="false" redirectPort="8443" acceptCount="100"
 connectionTimeout="20000" disableUploadTimeout="true"/>
Server port must match with each other. If not matched, eclipse can't detect server status when jboss has been started.
Spinner Sample
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Toolkit;

import javax.swing.JFrame;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
import javax.swing.SpinnerListModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class SpinnerSample extends JFrame {

    public SpinnerSample() {
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(new Dimension(500, 500));
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
        this.setLocation(new Point((d.width - this.getWidth()) / 2, (d.height - this.getHeight()) / 2));

        GridBagLayout layout = new GridBagLayout();
        GridBagConstraints cons = new GridBagConstraints();
        this.setLayout(layout);

        cons.insets = new Insets(5, 5, 5, 5);
        cons.gridx = 0;
        cons.gridy = 0;
        cons.anchor = GridBagConstraints.WEST;
        cons.fill = GridBagConstraints.HORIZONTAL;

        JSpinner spinner = null;

        spinner = new JSpinner(new SpinnerDateModel());
        //spinner.setEditor(new JSpinner.DateEditor(spinner, "yyyy/MM/dd HH:mm"));
        this.add(spinner);
        layout.setConstraints(spinner, cons);

        cons.gridy++;
        spinner = new JSpinner(new SpinnerListModel(new String[] { "日曜日", "月曜日", "火曜日", "水曜日", "木曜日", "金曜日", "土曜日" }));
        this.add(spinner);
        layout.setConstraints(spinner, cons);

        cons.gridy++;
        spinner = new JSpinner(new SpinnerNumberModel());
        this.add(spinner);
        layout.setConstraints(spinner, cons);

        this.setVisible(true);
        this.pack();
    }

    public static void main(String[] args) {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InstantiationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedLookAndFeelException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        new SpinnerSample();
    }
}
Formatter review
// %[argument_index$][flags][width][.precision]conversion

// (b/B) boolean
System.out.printf("result : %1$b %2$b %3$b %n", false, new Boolean(true), null);
// result : false true false

// (h/H) Integer.toHexString(arg.hashCode())
System.out.printf("result : %1$h %2$h %n", "bruce", 12);
// result : 59a9547 c

// (s/S) arg.toString()
System.out.printf("result : %1$s %2$s %n", 10, "bruce");
// result : 10 bruce

// (c/C) character
System.out.printf("result : %1$c %2$c %n", 'c', '\u0051');
// result : c Q

// (d, o, x/X) integral
System.out.printf("result : %1$d %1$o %1$x %n", 1024);
// result : 1024 2000 400
System.out.printf("result : %1$d %1$o %1$x %n", 1024);
// result : 1024 (   1024) 0001024 

// (e/E, f, g/G, a/A) floating point
System.out.printf("result : %1$e %1$f %1$g %1$a %n", 1234.567);
// result : 1.234567e+03 1234.567000 1234.57 0x1.34a449ba5e354p10
System.out.printf("result : %1$f (%1$7.2f) %1$07.0f %1$07.2f%n", 1234.567);
// result : 1234.567000 (1234.57) 0001235 1234.57

// date/time (R, T, r, D, F, c)
System.out.printf("result : %tR %n", Calendar.getInstance());
// result : 09:53
System.out.printf("result : %tT %n", Calendar.getInstance());
// result : 09:53:18
System.out.printf("result : %tr %n", Calendar.getInstance());
// result : 09:53:18 上午
System.out.printf("result : %tD %n", Calendar.getInstance());
// result : 06/10/10
System.out.printf("result : %tF %n", Calendar.getInstance());
// result : 2010-06-10
System.out.printf("result : %tc %n", Calendar.getInstance());
// result : 星期四 六月 10 09:53:18 CST 2010
System.out.printf("result : %1$tY/%1$tm/%1$td %1$tH:%1$tM:%1$tS", Calendar.getInstance());
// 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
// This sample demonstrates the use of the WindowsIdentity class to impersonate a user.
// IMPORTANT NOTES: 
// This sample can be run only on Windows XP.  The default Windows 2000 security policy 
// prevents this sample from executing properly, and changing the policy to allow
// proper execution presents a security risk. 
// This sample requests the user to enter a password on the console screen.
// Because the console window does not support methods allowing the password to be masked, 
// it will be visible to anyone viewing the screen.
// The sample is intended to be executed in a .NET Framework 1.1 environment.  To execute
// this code in a 1.0 environment you will need to use a duplicate token in the call to the
// WindowsIdentity constructor. See KB article Q319615 for more information.

using System;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;

[assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode = true)]
[assembly: PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]
public class ImpersonationDemo
{
    const int LOGON32_LOGON_INTERACTIVE = 2;
    const int LOGON32_LOGON_NETWORK = 3;
    const int LOGON32_LOGON_BATCH = 4;
    const int LOGON32_LOGON_SERVICE = 5;
    const int LOGON32_LOGON_UNLOCK = 7;
    const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8;
    const int LOGON32_LOGON_NEW_CREDENTIALS = 9;

    const int LOGON32_PROVIDER_DEFAULT = 0;
    const int LOGON32_PROVIDER_WINNT50 = 3;
    const int LOGON32_PROVIDER_WINNT40 = 2;
    const int LOGON32_PROVIDER_WINNT35 = 1;

    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword,
        int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

    //[DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
    //private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource,
    //    int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr* Arguments);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public extern static bool CloseHandle(IntPtr handle);

    [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    public extern static bool DuplicateToken(IntPtr ExistingTokenHandle,
        int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);

    // Test harness.
    // If you incorporate this code into a DLL, be sure to demand FullTrust.
    [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
    public static void Main2(string[] args)
    {
        IntPtr tokenHandle = new IntPtr(0);
        IntPtr dupeTokenHandle = new IntPtr(0);
        try
        {
            string userName, domainName;
            // Get the user token for the specified user, domain, and password using the 
            // unmanaged LogonUser method.  
            // The local machine name can be used for the domain name to impersonate a user on this machine.
            Console.Write("Enter the name of the domain on which to log on: ");
            domainName = Console.ReadLine();

            Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName);
            userName = Console.ReadLine();

            Console.Write("Enter the password for {0}: ", userName);

            tokenHandle = IntPtr.Zero;

            // Call LogonUser to obtain a handle to an access token.
            bool returnValue = LogonUser(userName, domainName, Console.ReadLine(),
                LOGON32_LOGON_NEW_CREDENTIALS, LOGON32_PROVIDER_DEFAULT,
                ref tokenHandle);

            Console.WriteLine("LogonUser called.");

            if (false == returnValue)
            {
                int ret = Marshal.GetLastWin32Error();
                Console.WriteLine("LogonUser failed with error code : {0}", ret);
                throw new System.ComponentModel.Win32Exception(ret);
            }

            Console.WriteLine("Did LogonUser Succeed? " + (returnValue ? "Yes" : "No"));
            Console.WriteLine("Value of Windows NT token: " + tokenHandle);

            // Check the identity.
            Console.WriteLine("Before impersonation: "
                + WindowsIdentity.GetCurrent().Name);
            // Use the token handle returned by LogonUser.
            WindowsIdentity newId = new WindowsIdentity(tokenHandle);
            WindowsImpersonationContext impersonatedUser = newId.Impersonate();

            // Check the identity.
            Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name);

            // Stop impersonating the user.
            impersonatedUser.Undo();

            // Check the identity.
            Console.WriteLine("After Undo: " + WindowsIdentity.GetCurrent().Name);

            // Free the tokens.
            if (tokenHandle != IntPtr.Zero)
                CloseHandle(tokenHandle);

        }
        catch (Exception ex)
        {
            Console.WriteLine("Exception occurred. " + ex.Message);
        }

        Console.Read();
    }

}
or
public class ImpersonateIdentity : IDisposable
{
    [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
    public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, out SafeTokenHandle phToken);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public extern static bool CloseHandle(IntPtr handle);

    [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")]
    public static ImpersonateIdentity Impersonate(string userName, string password, string domainName)
    {
        ImpersonateIdentity identity = new ImpersonateIdentity();

        const int LOGON32_PROVIDER_DEFAULT = 0;
        //This parameter causes LogonUser to create a primary token.
        const int LOGON32_LOGON_INTERACTIVE = 2;

        // Call LogonUser to obtain a handle to an access token.
        bool returnValue = LogonUser(userName, domainName, password,
            LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
            out identity.safeTokenHandle);

        if (false == returnValue)
        {
            int ret = Marshal.GetLastWin32Error();
            throw new System.ComponentModel.Win32Exception(ret);
        }

        identity.impersonatedUser = WindowsIdentity.Impersonate(identity.safeTokenHandle.DangerousGetHandle());
        return identity;
    }

    WindowsImpersonationContext impersonatedUser;
    SafeTokenHandle safeTokenHandle;

    private ImpersonateIdentity() { }

    public void Dispose()
    {
        if (impersonatedUser != null) impersonatedUser.Dispose();
        if (safeTokenHandle != null) safeTokenHandle.Dispose();
    }
}

public sealed class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid
{
    private SafeTokenHandle()
        : base(true)
    {
    }

    [DllImport("kernel32.dll")]
    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
    [SuppressUnmanagedCodeSecurity]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CloseHandle(IntPtr handle);

    protected override bool ReleaseHandle()
    {
        return CloseHandle(handle);
    }
}
reference : or
using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Security.Permissions;

[assembly: SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode = true)]
[assembly: PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")]
namespace ConsoleApplication1
{
    class Class1
    {
        //登入
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern bool LogonUser(
            string lpszUsername,
            string lpszDomain,
            string lpszPassword,
            int dwLogonType,
            int dwLogonProvider,
            ref IntPtr phToken
        );
            
        //登出
        [DllImport("kernel32.dll")]
        public extern static bool CloseHandle(IntPtr hToken);

        public Class1()
        {
            string UserName = "username";
            string MachineName = "192.168.0.10";
            string Pw = "password";
            string IPath = @"\\" + MachineName + @"\shared";
            
            const int LOGON32_PROVIDER_DEFAULT = 0;
            const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
            
            IntPtr tokenHandle = new IntPtr(0);
            tokenHandle = IntPtr.Zero;
            
            //將登入的Token放在tokenHandle
            bool returnValue = LogonUser(
                UserName,
                MachineName,
                Pw,
                LOGON32_LOGON_NEW_CREDENTIALS,
                LOGON32_PROVIDER_DEFAULT,
                ref tokenHandle
            );

            //讓程式模擬登入的使用者
            WindowsIdentity w = new WindowsIdentity(tokenHandle);
            w.Impersonate();
            if (false == returnValue)
            {
                //登入失敗的處理
                return;
            }
            //取得該目錄下的所有檔案名稱
            DirectoryInfo dir = new DirectoryInfo(IPath);
            FileInfo[] inf = dir.GetFiles();
            for (int i = 0; i < inf.Length; i++)
            {
                Console.WriteLine(inf[i].Name);
            }
        }
    }
}
Condition : in a domain
LogonUser(
    UserName,
    "myDomain",
    Pw,LOGON32_LOGON_NEW_CREDENTIALS,
    LOGON32_PROVIDER_DEFAULT,
    ref tokenHandle
);
reference : [C#]在程式中模擬特定的windows帳號存取網路芳鄰
Active Directory authentication
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

class Program
{
    static void Main(string[] args)
    {
        string domain = "mydomain";
        string account = "bruce";
        string password = "12345678";

        Console.WriteLine(IsAuthenticated1(domain, account, password));
        Console.WriteLine(IsAuthenticated2(domain, account, password));
        Console.WriteLine(IsAuthenticated3(domain, account, password));
        Console.Read();
    }

    static bool IsAuthenticated1(string domain, string account, string password)
    {
        bool isAuthenticated = false;
        DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domain), account, password);
        try
        {
            object o = entry.NativeObject;
            isAuthenticated = true;
            entry.Close();
        }
        catch (Exception ex)
        {
            entry.Close();
        }
        return isAuthenticated;
    }

    static bool IsAuthenticated2(string domain, string account, string password)
    {
        bool isAuthenticated = false;
        DirectoryEntry entry = new DirectoryEntry(string.Format("LDAP://{0}", domain), account, password);
        try
        {
            DirectorySearcher searcher = new DirectorySearcher(entry);
            searcher.Filter = string.Format("(sAMAccountName={0})", account);
            SearchResult result = searcher.FindOne();
            entry.Close();
            isAuthenticated = true;
        }
        catch (Exception ex)
        {
            entry.Close();
        }
        return isAuthenticated;
    }

    static bool IsAuthenticated3(string domain, string account, string password)
    {
        try
        {
            PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain);
            return pc.ValidateCredentials(account, password);
        }
        catch (Exception ex)
        {
            return false;
        }
    }
}
Searialize object as JSON
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        Person person = new Person("Bruce", "Tsai");
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Person));
        MemoryStream ms = new MemoryStream();
        serializer.WriteObject(ms, person);
        ms.Close();
        string json = Encoding.Default.GetString(ms.ToArray());
        Console.WriteLine(json);
        Console.Read();
    }
}


[DataContract]
public class Person
{
    public Person() { }
    public Person(string firstname, string lastname)
    {
        this.FirstName = firstname;
        this.LastName = lastname;
    }

    [DataMember]
    public string FirstName { get; set; }

    [DataMember]
    public string LastName { get; set; }
}
JSONHelper
public class JSONHelper
{

    public static string ToJson(object obj)
    {
        DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
        MemoryStream ms = new MemoryStream();
        serializer.WriteObject(ms, obj);
        ms.Close();
        string json = Encoding.UTF8.GetString(ms.ToArray());
        return json;
    }

    public static T ParseJson<T>(string json)
    {
        T obj = Activator.CreateInstance<T>();
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json));
        DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());
        obj = (T)ser.ReadObject(ms);
        ms.Close();
        return obj;
    }
}
Query index data
1. Start window service Indexing Service
2. Create a new category and start indexing.
class Program
{
    static void Main(string[] args)
    {
        // reference : http://msdn.microsoft.com/en-us/library/ms690516
        string strCatalog = "TestIndexing";
        string strKeyword = "readme";  // search keyword
        string strQuery = string.Format(
            @"SELECT path, FileName, size, write, attrib FROM SCOPE() WHERE FREETEXT('{0}')",
            //@"SELECT * FROM FILEINFO WHERE FREETEXT('{0}')",
            strKeyword
        );
 
        string connstring = "Provider=MSIDXS.1;Integrated Security .='';Data Source=" + strCatalog;
 
        DataSet set = null;
        try
        {
            using (OleDbDataAdapter adapter = new OleDbDataAdapter(strQuery, connstring))
            {
                adapter.Fill(set = new DataSet());
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            return;
        }
 
        foreach (DataRow row in set.Tables[0].Rows)
        {
            Console.WriteLine("{0} |{1} @{2}", row["FileName"], row["size"], row["write"]);
        }
        Console.Read();
    }
}
Create barcode
import java.io.File;
import java.io.FileNotFoundException;

import net.sourceforge.barbecue.Barcode;
import net.sourceforge.barbecue.BarcodeException;
import net.sourceforge.barbecue.BarcodeFactory;
import net.sourceforge.barbecue.BarcodeImageHandler;
import net.sourceforge.barbecue.output.OutputException;

public class Program {

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

        Barcode code = BarcodeFactory.create3of9("123456789", true);
        BarcodeImageHandler.savePNG(code, new File("barcode.png"));

    }

}
Library : http://barbecue.sourceforge.net/