Tuesday, December 27, 2005

Google Visit

This site can check the geographic location for ur visters

www.gvisit.com

Fill in ur site address

and copy the Script to ur site, e.g.



then u can trackback from the site given from Google. e.g.
http://www.gvisit.com/map.php?sid=aafff6d5240646d304ee6a4bfd9b2d3f

Done !!!

Friday, November 25, 2005

Java Regualr Expression for Alphabet only String

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
   public static void main(String[] args) {
      //[a-zA-Z] means from a to z or A to Z, * means many of none of them
      Pattern p = Pattern.compile("[a-zA-Z]*");
      Matcher m = p.matcher("aadddaaiiiii");
      boolean b = m.matches();
      System.out.println(b);
   }
}

Thursday, November 03, 2005

Javascripts

To add a print button to the HTML just adding the following link to ur page....

print this review

To add a link that return the user to the previous page ...

return Page

Tuesday, November 01, 2005

HKID Formula (HKID Number Check Digit) 香港身份證號碼計算

Click here for the English Version of HKID Formula 



香港身份證號碼有二個英文字母,一個六位數和一個加上括號的檢驗位。

你可用以下方法計算身份證號碼以確定身份證號碼的真確性。
請把身份證號上的英文字母用數字代表,如
空格=36 A = 10 B = 11 C = 12 D = 13 E = 14 F = 15
G = 16 H = 17 I = 18 J = 19 K = 20 L = 21
M = 22 N = 23 O = 24 P = 25 Q = 26 R = 27
S = 28 T = 29 U = 30 V = 31 W = 32 X = 33
Y = 34 Z = 35

方法:
1) 計算比重積和:

    A)如果為單字母開頭,如:E364912(5):
        E364912(5) = (空格)E364912(5)
        36 x 9 + 第一位x8 + 第二位x7 + 第三位x6 + 第四位x5 + 第五位x4 + 第六位x3 + 第七位x2 = 總和

    B)如果為雙字母開頭,如:AB987654(3):
       第一位x9 + 第二位x8 + 第三位x7 + 第四位x6 + 第五位x5 + 第六位x4 + 第七位x3 +第八位x2= 總和

    C)總和除以 11 得到餘數

2)計算檢驗位:
   A)如果餘數為0,檢驗位=0

   B)如果餘數為1,檢驗位=A

   C)如果餘數為2至10 [2—10]:
      檢驗位 = 11-餘數

例子:
身份證號碼:E364912(5)
(註:E 是第一位把它換成 14)

324 + 14x8 + 3x7 + 6x6 + 4x5 + 9x4 + 1x3 + 2x2 = 556

556 / 11 得餘數 6

11 - 6 = 5

所以這身份證號碼正確。

Tuesday, October 18, 2005

Top 10 Programmers Excuses

Source: http://www.cenriqueortiz.com/weblog/General/?permalink=Developers-Top-10-replies-when-code-doesnt-work.html

have fun !!!
Top 10 replies by developers when their programs don't work:
10. 'That's weird...'
9. 'It's never done that before.'
8. 'It worked yesterday.'
7. 'You must have the wrong version.'
6. 'It works, but it hasn't been tested.'
5. 'Somebody must have changed my code.'
4. 'Did you check for a virus?'
3. 'Where were you when the program blew up?'
2. 'Why do you want to do it that way?'

and finally ...

1. 'I thought I fixed that.'

Saturday, September 10, 2005

Remove your site from Search EngineS

Remove your entire website
If you wish to exclude your entire website from Google's index, you can place a file at the root of your server called robots.txt. This is the standard protocol that most web crawlers observe for excluding a web server or directory from an index. More information on robots.txt is available here: http://www.robotstxt.org/wc/norobots.html. Please note that Googlebot does not interpret a 401/403 response ("Unauthorized"/"Forbidden") to a robots.txt fetch as a request not to crawl any pages on the site.
To remove your site from search engines and prevent all robots from crawling it in the future, place the following robots.txt file in your server root:
User-agent: *
Disallow: /
To remove your site from Google only and prevent just Googlebot from crawling your site in the future, place the following robots.txt file in your server root:
User-agent: Googlebot
Disallow: /
Each port must have its own robots.txt file. In particular, if you serve content via both http and https, you'll need a separate robots.txt file for each of these protocols. For example, to allow Googlebot to index all http pages but no https pages, you'd use the robots.txt files below.
For your http protocol (http://yourserver.com/robots.txt):
User-agent: *
Allow: /
For the https protocol (https://yourserver.com/robots.txt): User-agent: *
Disallow: /


Note: If you believe your request is urgent and cannot wait until the next time Google crawls your site, use our automatic URL removal system. In order for this automated process to work, the webmaster must first create and place a robots.txt file on the site in question.
Google will continue to exclude your site or directories from successive crawls if the robots.txt file exists in the web server root. If you do not have access to the root level of your server, you may place a robots.txt file at the same level as the files you want to remove. Doing this and submitting via the automatic URL removal system will cause a temporary, 180 day removal of your site from the Google index, regardless of whether you remove the robots.txt file after processing your request. (Keeping the robots.txt file at the same level would require you to return to the URL removal system every 180 days to reissue the removal.)

Sunday, September 04, 2005

Flash Version of Google

Macromedia employee created a Flash version of Google Maps to demonstrate how much better it would be in Flash.

Not a bad idea.

Thursday, August 18, 2005

L&F library - L2FProd

Selecting fonts and directories
Editing properties
Building task oriented applications
Build the nextgen e-mail client
活用JAVA的L&F把畫面變美了,也更好運用了....
當然前提您要會使用它的API囉...
一定要看它的DEMO啊!!
>>Link:http://common.l2fprod.com/

Wednesday, August 17, 2005

Java : 剪貼簿


jeffwang711 wrote:
請問一下
java中有沒有方法
可以將剪貼簿的內容清除掉
痲煩解答
謝謝


所謂清除掉是指讓剪貼簿沒有內容可供貼上?
不 考慮 JNI 的話你可以把廢料放上剪貼簿,因為剪貼簿有獨佔性,而廢料指沒有人知道怎麼使用之,這樣一來任何程式都不知道怎麼處理剪貼簿裡的資料(實際也是真的沒有資 料可言),"貼上"的菜單or 工具鈕, hotkey 雖是 valid 但執行後不會貼上資料(MS Excel 的話則是連 Paste 菜單都變成 disabled,理論上一個應用程式若不懂如何處理 clipboard 裡的 data 都應該 disable 掉 "Paste" 選項)。

若你只是不想讓其他程式取得你的程式最後放到 clipboard 的數據,其實你的程式離開前放空字串(或其他無關緊要的數據)進 clipboard 就可以了。

package com.jsptw.j2se;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
public class None implements Transferable {
public DataFlavor[] getTransferDataFlavors()
{
return new DataFlavor[0];
}
public boolean isDataFlavorSupported(DataFlavor flavor)
{
return false;
}
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException
{
throw new UnsupportedFlavorException(flavor);
}
}


java.awt.Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new com.jsptw.j2se.None(), null);

Sunday, July 24, 2005

Matissee the GUI Builder that i never saw before

Matissee is a GUI builder in Ntebean that can assist the GUI building process

Demo Here

Just d/l the lastest version of Netbean 4.2 development build and add the add -J-Dnetbeans.form.new_layout=true to the netbeans_default_options property

Done !!!

Tuesday, June 21, 2005

Fraction Class

Today, I read some help request on writting a Fraction class, It is pretty suprise to me that the requester doesn't understand the requirement of the class, but the more ridiculous isszue that shocked me its that someone say:

"if u are in deep trouble understanding the above, you may consider pm me to get the code for some cost"

How bullshit it is !!!!

IMHO forumer should help each other with free and respect. it is meanless that these guys help only the people who pay their money. This lose the meaning of forum it lose the spirite comunity. ..

Any way here is source code of Fraction class:

public class Fraction {

final int numerator;

final int denominator;

public static final Fraction ZeroFraction = new Fraction(0, 0);

public Fraction(int numerator, int denominator)
throws IllegalArgumentException {
if (denominator == 0) {
throw new ArithmeticException("Divide by zero");
}
int simplier = Fraction.simplify(numerator, denominator);
this.numerator = numerator / simplier;
this.denominator = denominator / simplier;
}

public int getDenominator() {
return denominator;
}

public int getNumerator() {
return numerator;
}

public double toDouble() {
return numerator / denominator;
}

public String toString() {
return numerator + "/" + denominator;
}

/* a/ b + c / d = (ad + bc) / bd */
public Fraction add(Fraction f1, Fraction f2) {
int newNumerator = f1.numerator * f2.denominator + f1.denominator
* f2.numerator;
int newDenominator = (f1.denominator * f2.denominator);
return new Fraction(newNumerator, newDenominator);
}

/* a/ b - c / d = (ad - bc) / bd */
public Fraction subtract(Fraction f1, Fraction f2) {
int newNumerator = f1.numerator * f2.denominator - f1.denominator
* f2.numerator;
int newDenominator = (f1.denominator * f2.denominator);
return new Fraction(newNumerator, newDenominator);
}

/* a/ b x c / d = ac / bd */
public Fraction multiply(Fraction f1, Fraction f2) {
int newNumerator = f1.numerator * f2.numerator;
int newDenominator = f1.denominator * f2.denominator;
return new Fraction(newNumerator, newDenominator);
}

/* (a/ b )/ (c / d) = ad /bc , where c/d not equal to 0 */
public Fraction divide(Fraction f1, Fraction f2) {
if (f2.toDouble() == 0) {
throw new ArithmeticException("Divide by zero");
}
int newNumerator = f1.numerator * f2.denominator;
int newDenominator = f1.denominator * f2.numerator;
return new Fraction(newNumerator, newDenominator);
}

private static int simplify(int a, int b) {
if (a % b > 0)
return simplify(b, a % b);
else
return b;
}

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

}

}

Saturday, May 28, 2005

Reading Date in Excel

We can use Jakarta COMMON POI to do it:

E.g. of Itertate over a file:

// load the excel
FileInputStream fin = new FileInputStream("simple1.xls");
POIFSFileSystem fs = new POIFSFileSystem(fin);
//create a Workbook
HSSFWorkbook wb = new HSSFWorkbook(fs);

// get a reference to the worksheet
int numberPage = wb.getNumberOfSheets();
// TODO:debug information
out.printf("Number Of Page %s%n", numberPage);

//read each sheet
for (int i = 0; i < numberPage; ++i) {
HSSFSheet sheet = wb.getSheetAt(i);

// TODO:debug information
int firstRow = sheet.getFirstRowNum();
int lastRow = sheet.getLastRowNum();
out.printf("FirstRow: %s, LastRow: %s%n", firstRow, lastRow);
out.printf("Physical Row: %s%n", sheet.getPhysicalNumberOfRows());

//read each Row
for (int j = firstRow; j <= lastRow; ++j) {
HSSFRow row = sheet.getRow(j);

//read each Cell
for (short k = row.getFirstCellNum(); k < row.getLastCellNum(); ++k) {
HSSFCell cell = (HSSFCell) row.getCell(k);

switch (cell.getCellType()) {

case (HSSFCell.CELL_TYPE_STRING): {
out.print(cell.getStringCellValue() + "\t");
break;
}

case (HSSFCell.CELL_TYPE_NUMERIC): {
out.print(cell.getNumericCellValue() + "\t");
break;
}

case (HSSFCell.CELL_TYPE_BOOLEAN): {
out.print(cell.getBooleanCellValue() + "\t");
break;
}

}
}
out.println();
}
}
fin.close();

Sunday, May 15, 2005

Security

http://java.sun.com/j2se/1.5.0/docs/api/index.html
http://java.sun.com/j2se/1.5.0/docs/guide/security/doprivileged.html
http://java.sun.com/j2se/1.5.0/docs/guide/security/PolicyFiles.html#DefaultLocs

STill working add more later..

Upload file in a JSP

利用 Oreilly MultiPartRequest 做的範例

http://www.javaworld.com.tw/Old/High/Upload.htm

利用 jspsmart SmartUpload 做的範例

http://www.javaworld.com.tw/Old/High/S_Upload.htm

Jakarta 當然也不能缺席嘛, 來個利用 Jakarta Commons FileUpload 做的範例 Tongue

都是拿 browser 大大的東西來改的, 所以 File.html 拿這裡的就對了 Big Smile

http://www.javaworld.com.tw/Old/High/Upload.htm

也請參閱 jini 葛格的電子報

http://mychannel.pchome.com.tw/channel/class/class_paper_open.htm?d=2003-07-04&e=jakarta&t=.htm&j=17&f=main&v=1

解決了有些瀏覽器會傳送 path + filename 的問題

在電子報這行

// 因為不同的瀏覽器會造成傳遞 path + filename, 有些則只有 filename

註解下就是 jini 葛格加的程式碼

File.jsp (2.36k)

Sunday, May 08, 2005

Call other program in Java

Today some one asked me about calling other porgram in Java. In java 5.0 beside Runtime.exec() we can use the class Process and ProcessBuilder to have a better control on the execute:

ProcessBuilder:
This class is used to create operating system processes.
Note that this class is not synchronized.
When calling the ProcessBuilder().start() we can get a Process object and monitor the output thru it.

Process p = new ProcessBuilder("ping", "localhost").start();
String line = null;
Scanner in = new Scanner(p.getInputStream());
while (in.hasNextLine()) {
line = in.nextLine();
System.out.printf("%s\n", line);
}
Beside when can get the Environment variables by Map ProcessBuilder().environment() and set our own variable to it, usually the values is a copy of the environment of the current process System.getenv() :
PS. o start a process with an explicit set of environment variables, first call Map.clear() before adding environment variables.
 ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
Map env = pb.environment();
env.put("VAR1", "myValue");
env.remove("OTHERVAR");
env.put("VAR2", env.get("VAR1") + "suffix");
pb.directory("myDir");
Process p = pb.start();

Process

It provides Process.getInputStream() and Process.getOutputStream() to read and write data.

Friday, April 29, 2005

Jude Alternative to JavaDoc

Today Computer:

1)Simple Host Authentication for Java (Shaj):
- MS Windows version:
- Unix-like system version:
With this wrapper It is able to write program with authorization function from the Domain Control!!!

Today Focus:

2) Jude:
A replacement to JavaDoc:

Installation:
After downloading you can run:
java -jar jude.jar -autojuice
to generate javadoc data for Jude
However, be remind the following:
1) java file in the above file should be the one of JDK and the src.zip should be in the JDK directory
2) You can Download the SUn's Javadoc file and unzip them in the JDK directory so Jude will have richer Information

Run:
Type the following command in command line or write then to a Batch/Command file
java -jar jude.jar
The Default Listening port is 2009 but you can change it this way:
java -jar jude.jar -port 80
Beside, you can specific the Jude's javadoc data:
java -jar jude.jar myapi.jude

After running, I found the DOS prompt from that execute java is very ugly, and It can't find the java.jude file in its data directory!!! so i wrote my run.bat as below:

Run.bat
javaw -jar "c:\Jude\jude.jar" "c:\Jude\java.jude" -port 80


Then you can close the ugly DOS prompt without closing Jude and able to access Jude by typing "localhost" or "127.0.0.1" in your Mozilia !!!! (of course if you have an apache server you can change port 80 to port 8888 :)

More On JAAS

Someone may unahppy with writting a ungly config to tell JAAS to use which module. However, up to now there is no easy solution to prevent the JAAS config file.....(we can't hard code it into the program anyway).... and itis unpleasent to write a long start command( a lot of maintance work!!)
so my solution is to pass a URL to the class and set the corresponding system property. Although this way is not prefect....(the prefect way it to pass it as a annotation or in a centralic configuration file)... but it look better then typing a long parameters ^_^..


For Example:

NT.config:
NT {
com.tagish.auth.win32.NTSystemLogin required returnNames=true returnSIDs=true defaultDomain="c08913";
};


In the code add this:

URL loginConfigUrl = ClassLoader.getSystemResource("NT.config");
String loginConfigFile = loginConfigUrl.getFile();
System.err.println(loginConfigFile);
System.setProperty("java.security.auth.login.config",
loginConfigFile);
lc = new LoginContext("NT", new MyCallbackHandler());

Eliminate the -Djava.library.path argument in command line for Native Library
Beside, as I tried to pack the natve library into my LoginBeam , So i would like to load the native libraray automatically without specific the native library class path. The System.load() run sucessfully without exception. However, It reported to me that It fail to find the Native library while calling it ........... "Cannot create LoginContext. java.lang.UnsatisfiedLinkError: no NTSystem in java.library.path"

I will investingate it later after the exam......XD

public static void main(String[] args) {
LoginContext lc;
Subject subject = null;

try {
//Load the Native library NTSystem.dll
//-Djava.library.path=C:\Data\eclipse\workspace\NTLoginSystem\bin\lib //load successfully for the native library
URL nativeLib = ClassLoader.getSystemResource("lib/NTSystem.dll");
System.load(nativeLib.getFile());

// find the login config file in the classpath
//Load the NT.config, so we don't need to specific the NT.config at command line
URL loginConfigUrl = ClassLoader.getSystemResource("lib/NT.config");
String loginConfigFile = loginConfigUrl.getFile();
System.setProperty("java.security.auth.login.config",
loginConfigFile);

lc = new LoginContext("NT", new MyCallbackHandler());
lc.login();//Exception here
subject = lc.getSubject();
System.out.println("Login Success");
System.out.println(subject);
} catch (LoginException le) {
System.err
.println("Cannot create LoginContext. " + le.getMessage());
} catch (SecurityException se) {
System.err
.println("Cannot create LoginContext. " + se.getMessage());
}
}





Wednesday, April 27, 2005

JAAS

JavaTM Authentication and Authorization Service (JAAS)
- Sun Offical JAAS Site

- JavaDoc of sun JAAS Package here
- JAAS Tutorial here

After two data investingate.. I found that JAAS is extremely non-user friendly...
Anyway, Here are soem tips and tricks.
First, the NTLoginModule moudle provided by Sun can't allow user to input the domain anme, username and password..... The API takes these information from the underlayer OS and Subject with this input,authenticated and passed on Successfully!!!!!!!!!! If a user can login it's computer he can denfinly pass this test.... So, what is of use of this module...??
I guess it is used for Singel-Sign-On if a user can login their windows their can enjoy the SSO service. What the programers can do is to specify the right principals in the policy and manage the right of differrent group of users!!

If you just want to use the Authentication service from the Domain Controller there still some solutions:

1) Using the NTActiveLoginModule from IBM

Config file setting:
 MyLoginModules {
   com.ibm.security.auth.module.NTActiveLoginModule REQUIRED;
 };
This LoginModule - com.ibm.security.auth.module.NTActiveLoginModule permits using our Callbackhandler. We can then setUsername and setPassword and get it authenticated.

IMPORTANT
http://www-106.ibm.com/developerworks/java/jdk/security/142/secguides/securityg uide.win32.html#wq10

Some forum link that would help:
http://www-106.ibm.com/developerworks/forums/dw_expandTree.jsp?thread=72629& ;forum=178&cat=10&message=12026825#12026825
http://www.mooreds.com/jaas.html
http://www.theserverside.com/blogs/showblog.tss?id=ServletApp
http://java.sun.com/security/jaas/doc/module.html
http://www.ibm.com/developerworks/java/jdk/security/index.html

To make use of this functioanlity, you should have IBM's JDK. Particularly the jaas_activelm.jar, jaas.jar and jaasal.dll . I had Websphere. Hence I got this. I am not sure how to get it otherwise.

2)Using the JAAS Module from Tagish.net

- Tagish Documentation

If you think using IBM JDK is a bit clumbersome or troublesome, you can just download a module from Tagish, However, the update is on 2003/02/17, the library is a bit old but I can still runnning it on my JDK1.5 and MS Windows XP(SR2). The source code is included is downloadable, if everyone can compile it on their compiler!!!

Here is my simple code using Tahish:

Run Command:

java -cp classes -Djava.security.auth.login.config=C:\Data\eclipse\workspace\NTLoginSystem\NT.config -Djava.library.path=C:\Data\eclipse\workspace\NTLoginSystem
Config file Setting:
NTLogin
{
com.tagish.auth.win32.NTSystemLogin required returnNames=true returnSIDs=false defaultDomain="domain";
};

Some Test Code:
Main class:
public class Main {
  public static void main(String[] args) {
      LoginContext lc;
      Subject subject = null;
      try {
          lc = new LoginContext( "NT", new MyCallbackHandler() );
          lc.login();
          subject = lc.getSubject();
    System.out.println("Login Success");
      } catch ( LoginException le ) {
          System.err.println( "Cannot create LoginContext. "
                  + le.getMessage() );
      } catch ( SecurityException se ) {
          System.err.println( "Cannot create LoginContext. "
                  + se.getMessage() );
      }

      System.out.println("Subject: " + subject);
  }
}

MyCallbackHandler class:
class MyCallbackHandler implements CallbackHandler {
public void handle(Callback[] callbacks)
throws IOException, UnsupportedCallbackException {

for (int i = 0; i <>
if (callbacks[i] instanceof TextOutputCallback) {

// display the message according to the specified type
TextOutputCallback toc = (TextOutputCallback)callbacks[i];
switch (toc.getMessageType()) {
case TextOutputCallback.INFORMATION:
System.out.println(toc.getMessage());
break;
case TextOutputCallback.ERROR:
System.out.println("ERROR: " + toc.getMessage());
break;
case TextOutputCallback.WARNING:
System.out.println("WARNING: " + toc.getMessage());
break;
default:
throw new IOException("Unsupported message type: " +
toc.getMessageType());
}

} else if (callbacks[i] instanceof NameCallback) {

// prompt the user for a username
NameCallback nc = (NameCallback)callbacks[i];

System.err.print(nc.getPrompt());
System.err.flush();
nc.setName((new BufferedReader
(new InputStreamReader(System.in))).readLine());

} else if (callbacks[i] instanceof PasswordCallback) {

// prompt the user for sensitive information
PasswordCallback pc = (PasswordCallback)callbacks[i];
System.err.print(pc.getPrompt());
System.err.flush();
pc.setPassword(readPassword(System.in));

} else {
throw new UnsupportedCallbackException
(callbacks[i], "Unrecognized Callback");
}
}
}

// Reads user password from given input stream.
private char[] readPassword(InputStream in) throws IOException {

char[] lineBuffer;
char[] buf;
int i;

buf = lineBuffer = new char[128];

int room = buf.length;
int offset = 0;
int c;

loop: while (true) {
switch (c = in.read()) {
case -1:
case '\n':
break loop;

case '\r':
int c2 = in.read();
if ((c2 != '\n') && (c2 != -1)) {
if (!(in instanceof PushbackInputStream)) {
in = new PushbackInputStream(in);
}
((PushbackInputStream)in).unread(c2);
} else
break loop;

default:
if (--room <>
buf = new char[offset + 128];
room = buf.length - offset - 1;
System.arraycopy(lineBuffer, 0, buf, 0, offset);
Arrays.fill(lineBuffer, ' ');
lineBuffer = buf;
}
buf[offset++] = (char) c;
break;
}
}

if (offset == 0) {
return null;
}

char[] ret = new char[offset];
System.arraycopy(buf, 0, ret, 0, offset);
Arrays.fill(buf, ' ');

return ret;
}
}

Result:
Login Success
Subject: 主題:
Principal: NTUserPrincipal: fcmmok [USER]
Principal: NTDomainPrincipal: HPFDCC3 [DOMAIN]
Principal: NTGroupPrincipal: Domain Users [GROUP]
Principal: NTGroupPrincipal: Everyone [GROUP]
Principal: NTGroupPrincipal: Users [GROUP]
Principal: NTGroupPrincipal: Domain Admins [GROUP]
Principal: NTGroupPrincipal: NETWORK [GROUP]
Principal: NTGroupPrincipal: Authenticated Users [GROUP]