tag:blogger.com,1999:blog-165110272024-03-13T22:35:50.854-07:00Employing J2EEAll about Javaserver Faces, Java Bean, JSP, JSTL, SOAP, WSDL and etc!Avatar Nghttp://www.blogger.com/profile/17532077659766019555noreply@blogger.comBlogger8125tag:blogger.com,1999:blog-16511027.post-1140845269231324772006-02-24T21:26:00.000-08:002006-02-24T21:27:49.366-08:00JFreeChart 1.0.1A new release of JFreeChart is available for download from:<br /><br /><a href="http://www.jfree.org/jfreechart/">http://www.jfree.org/jfreechart/</a><br /><br />This release contains a number of minor bug fixes and a few API adjustments (additions and deprecations only). JFreeChart is free software under the terms of the GNU Lesser General Public License.<br /><br />by <a href="http://avatar21.superihost.com/">Avatar Ng</a>Avatar Nghttp://www.blogger.com/profile/17532077659766019555noreply@blogger.com2tag:blogger.com,1999:blog-16511027.post-1140844582487419192006-02-24T21:16:00.000-08:002006-02-24T21:22:06.716-08:00Chart a new course with JFreeChartCreating a Pie Chart by using the famous JFreeChart library.<br /><br />Read more at <a href="http://www.javaworld.com/javaworld/jw-12-2002/jw-1227-opensourceprofile.html">www.javaworld.com/javaw...</a><br /><br />Although creating graph in Servlets and server-side is easy, but it burden the server and it is certainly not the big thing now.<br /><br />Moreover, to draw some realtime charts, you need client-side scripting combining AJAX to stream the data for a real dynamic chart!<br /><br /><br />By <a href="http://avatar21.superihost.com/">Avatar Ng</a>Avatar Nghttp://www.blogger.com/profile/17532077659766019555noreply@blogger.com0tag:blogger.com,1999:blog-16511027.post-1140843683254065562006-02-24T21:01:00.000-08:002006-02-24T21:15:32.216-08:00Dynamic Double Combo -- Chapter 9 of Ajax in Action<div xmlns="http://purl.org/atom/ns#"> <p>Ajax in Action!</p> See how this example of double "combo box" works in "Ajax in Action" book! The example actually take an "onchange()" event on the first "combo box" to triggle the Ajax to populate data into the second "combo box" depending on the selected value.<br /><p> Read more at <a href="http://searchvb.techtarget.com/tip/1,289483,sid8_gci1156676,00.html">searchvb.techtarget.com...</a></p><p><br /></p><p>by Avatar Ng<br /></p></div>Avatar Nghttp://www.blogger.com/profile/17532077659766019555noreply@blogger.com0tag:blogger.com,1999:blog-16511027.post-1134423412003084292005-12-12T13:28:00.000-08:002005-12-12T13:37:03.046-08:00What is JUG?<a href="http://java.sun.com/jugs">Java User Group</a> or JUG, is part of <a href="http://developers.sun.com/">Sun Developer Network</a> (SDN) . It's a community, bulletin board for Java developer to gather and share ideas.<br /><br />I've just created a local JUG for Malaysian's KL Java group, feel free to join the family!Avatar Nghttp://www.blogger.com/profile/17532077659766019555noreply@blogger.com1tag:blogger.com,1999:blog-16511027.post-1132331362770216322005-11-18T08:29:00.001-08:002005-11-18T08:52:19.876-08:00Encryption Algorithm<span style="font-size:180%;"><strong><u>Encryption Algorithm in Java</u></strong></span><br /><br />Today, I will be discussing about protecting data by using Java encryption methods. This article also explains different algorithms used for the encryption process.<br /><br /><span style=";font-family:Verdana;font-size:85%;" >Most of the </span>web sites<span style=";font-family:Verdana;font-size:85%;" > today have some sort of a registration module where a user is asked to choose a username/password combination. This data gets stored in the </span><a href="http://www.mysql.com">database</a><span style=";font-family:Verdana;font-size:85%;" >. You might wonder if the </span>password<span style=";font-family:Verdana;font-size:85%;" > you provide will be kept well-protected (read encrypted). In case you are the person designing such backend registration component, why not give your users peace of mind by encrypting their passwords?<br /><br /></span><strong><span style=";font-family:Verdana;font-size:85%;" >One-way Hash Encryption</span></strong><br /><span style=";font-family:Verdana;font-size:85%;" >This scenario is a perfect candidate for "one-way hash encryption" also known as a <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/security/MessageDigest.html">message digest</a>, <a href="http://en.wikipedia.org/wiki/Digital_signature">digital signature</a>, <a href="http://www.freevbcode.com/ShowCode.asp?ID=972">one-way encryption</a>, <a href="http://www.digitalfingerprint.ca/">digital fingerprint</a>, or <a href="http://en.wikipedia.org/wiki/Cryptographic_hash_function">cryptographic hash</a>. It is referred to as "one-way" because although you can calculate a <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/security/MessageDigest.html">message digest</a>, given some data, you can't figure out what data produced a given message digest. This is also a collision-free mechanism that guarantees that no two different values will produce the same digest. Another property of this digest is that it is a condensed representation of a message or a data file and as such it has a fixed length. </span><br /><span style=";font-family:Verdana;font-size:85%;" >There are several message-digest algorithms used widely today. </span><br /><strong><span style="font-size:85%;"></span></strong><br /><strong><span style="font-size:85%;"></span></strong><br /> <table class="MsoNormalTable" style="width: 100%;" border="1" cellpadding="0" width="100%"> <tbody><tr style=""> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"><b> </b><b><span style="font-size: 10pt;">Algorithm</span></b><o:p></o:p></p> </td> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"><b> </b><b><span style="font-size: 10pt;">Strength</span></b><span style="font-size: 10pt;"> </span><o:p></o:p></p> </td> </tr> <tr style=""> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"> <span style="font-size: 10pt;">MD5</span><o:p></o:p></p> </td> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"> <span style="font-size: 10pt;">128 bit</span><o:p></o:p></p> </td> </tr> <tr style=""> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"> <span style="font-size: 10pt;">SHA-1</span><o:p></o:p></p> </td> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"> <span style="font-size: 10pt;">160 bit</span><o:p></o:p></p> </td> </tr> </tbody> </table> <br /><span style=";font-family:Verdana;font-size:85%;" > SHA-1 (</span><a href="http://www.secure-hash-algorithm-md5-sha-1.co.uk/">Secure</a><span style=";font-family:Verdana;font-size:85%;" ><a href="http://www.secure-hash-algorithm-md5-sha-1.co.uk/"> Hash Algorithm 1</a>) is slower than <a href="http://en.wikipedia.org/wiki/MD5">MD5</a>, but the message digest is larger, which makes it more resistant to brute force attacks. Therefore, it is recommended that Secure Hash Algorithm is preferred to MD5 for all of your digest needs. Note, SHA-1 now has even higher strength brothers, <a href="http://csrc.nist.gov/CryptoToolkit/tkhash.html">SHA-256</a>, <a href="http://csrc.nist.gov/CryptoToolkit/tkhash.html">SHA-384</a>, and <a href="http://csrc.nist.gov/CryptoToolkit/tkhash.html">SHA-512</a> for 256, 384 and 512-bit digests respectively.<br /> </span><br /><strong><span style=";font-family:Verdana;font-size:85%;" >Typical Registration Scenario</span></strong><span style=";font-family:Verdana;font-size:85%;" ><br />Here is a typical flow of how our message digest algorithm can be used to provide one-way password hashing:<br /><br /></span><span style=";font-family:Verdana;font-size:85%;" >1) User registers with some site by submitting the following data: </span><br /><strong></strong><br /> <table class="MsoNormalTable" style="width: 100%;" border="1" cellpadding="0" width="100%"> <tbody><tr style=""> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"> <b><span style="font-size: 10pt;">Username</span></b><o:p></o:p></p> </td> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"><b> </b><b><span style="font-size: 10pt;">password</span></b><o:p></o:p></p> </td> </tr> <tr style=""> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"> <span style="font-size: 10pt;">Jsmith</span><o:p></o:p></p> </td> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"> <span style="font-size: 10pt;">mypass </span><o:p></o:p></p> </td> </tr> </tbody> </table> <br /><span style=";font-family:Verdana;font-size:85%;" >2) before storing the data, a one-way hash of the password is created: "mypass" is transformed into "5yfRRkrhJDbomacm2lsvEdg4GyY=" .</span><br /><span style=";font-family:Verdana;font-size:85%;" >The data stored in the database ends up looking like this: </span><br /><strong><span style="font-size:85%;"></span></strong><br /><strong></strong> <table class="MsoNormalTable" style="width: 100%;" border="1" cellpadding="0" width="100%"> <tbody><tr style=""> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"> <b><span style="font-size: 10pt;">username</span></b><o:p></o:p></p> </td> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"><b> </b><b><span style="font-size: 10pt;">password</span></b><o:p></o:p></p> </td> </tr> <tr style=""> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"> <span style="font-size: 10pt;">jsmith</span><o:p></o:p></p> </td> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"> <span style="font-size: 10pt;">5yfRRkrhJDbomacm2lsvEdg4GyY=</span><o:p></o:p></p> </td> </tr> </tbody> </table> <br /><span style=";font-family:Verdana;font-size:85%;" >3) When jsmith comes back to this site later and decides to login using his credentials (jsmith/mypass), the password hash is created in memory (session) and is compared to the one stored in the database. Both values are equal to "5yfRRkrhJDbomacm2lsvEdg4GyY=" since the same password value "mypass" was used both times when submitting his credentials. Therefore, his login will be successful.<br /><br /></span><span style=";font-family:Verdana;font-size:85%;" >Note, any other plaintext password value will produce a different sequence of characters. Even using a similar password value ("mypast") with only one-letter difference, results in an entirely different hash: "<span style="color: rgb(0, 153, 0);">hXdvNSKB5Ifd6fauhUAQZ4jA7o8=</span>" .</span><br /><strong><span style="font-size:85%;"></span></strong><br /><strong></strong> <table class="MsoNormalTable" style="width: 100%;" border="1" cellpadding="0" width="100%"> <tbody><tr style=""> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"><b> </b><b><span style="font-size: 10pt;">plaintext password</span></b><o:p></o:p></p> </td> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"><b> </b><b><span style="font-size: 10pt;">encrypted password</span></b><span style="font-size: 10pt;"> </span><o:p></o:p></p> </td> </tr> <tr style=""> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"> <span style="font-size: 10pt;">mypass</span><o:p></o:p></p> </td> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"> <span style="font-size: 10pt;">5yfRRkrhJDbomacm2lsvEdg4GyY= </span><o:p></o:p></p> </td> </tr> <tr style=""> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"> <span style="font-size: 10pt;">mypast</span><o:p></o:p></p> </td> <td style="padding: 1.5pt;"> <p class="MsoNormal" style="text-align: center;" align="center"> <span style="font-size: 10pt;">hXdvNSKB5Ifd6fauhUAQZ4jA7o8= </span><o:p></o:p></p> </td> </tr> </tbody> </table> <br /><span style=";font-family:Verdana;font-size:85%;" > As mentioned above, given that strong encryption algorithm such as SHA is used, it is impossible to reverse-engineer the encrypted value from "5yfRRkrhJDbomacm2lsvEdg4GyY=" to "mypass". Therefore, even if a malicious hacker gets a hold of your password digest, he/she won't be able determine what your password is.<br /><br /></span><a href="http://www.devarticles.com/">Java Code</a><strong><span style=";font-family:Verdana;font-size:85%;" > that Implements One-way Hash Algorithm<br /><br /></span></strong><span style=";font-family:Verdana;font-size:85%;" >Let's assume that you are writing a </span><a href="http://www.devarticles.com/">web application</a><span style=";font-family:Verdana;font-size:85%;" > to be run in a servlet container. Your registration servlet might have the following portion (for clarity, I ommitted input validation steps and assume that a password value was passed in within the password form input field):<br /><br /></span><span style="color: rgb(0, 153, 0);font-family:Verdana;font-size:85%;" >[...]<br />public void doPost(HttpServletRequest request, HttpServletResponse response){<br /> User user = new org.myorg.registration.User(); user.setPassword(org.myorg.services.PasswordService.getInstance().encrypt(request.getParameter("password"));<br />[...]</span><br /><span style=";font-family:Verdana;font-size:85%;" ><br />Here is the definition of my PasswordService class that does the job of generating a one-way hash value:<br /><br /> </span><span style="color: rgb(0, 153, 0);font-family:Verdana;font-size:85%;" >package org.myorg.services;<br /><br />import java.io.UnsupportedEncodingException;<br />import java.security.MessageDigest;<br />import java.security.NoSuchAlgorithmException;<br />import org.myorg.SystemUnavailableException;<br />import sun.misc.BASE64Encoder;<br />import sun.misc.CharacterEncoder;<br /><br />public final class PasswordService{<br /> private static PasswordService instance;<br /> private PasswordService() { }<br /> public synchronized String encrypt(String plaintext) throws SystemUnavailableException {<br /> MessageDigest md = null;<br /> try {<br /> md = MessageDigest.getInstance("SHA"); //step 2<br /> }<br /> catch(NoSuchAlgorithmException e) {<br /> throw new SystemUnavailableException(e.getMessage());<br /> }<br /> try {<br /> md.update(plaintext.getBytes("UTF-8")); //step 3<br /> }<br /> catch(UnsupportedEncodingException e) {<br /> throw new SystemUnavailableException(e.getMessage());<br /> }<br /><br /> byte raw[] = md.digest(); //step 4<br /> String hash = (new BASE64Encoder()).encode(raw); //step 5<br /><br /> return hash; //step 6<br /> }<br /><br /> public static synchronized PasswordService getInstance() //step 1 {<br /> if(instance == null) {<br /> return new PasswordService();<br /> }<br /> else {<br /> return instance;<br /> }<br /> }<br /><br />}</span><br /><span style=";font-family:Verdana;font-size:85%;" ><br />The method of interest here is encrypt(). I chose to make this class a singleton in order to ensure that there is only one instance of it at any given time to avoid concurrency issues and conflicts between generated hash values. For an explanation of this design pattern, try a google search for "java singleton pattern".<br /><br /></span><span style=";font-family:Verdana;font-size:85%;" >Let's step through the code above to see what's going on:<br /><br /></span><strong><span style=";font-family:Verdana;font-size:85%;" >Step 1: </span></strong><span style=";font-family:Verdana;font-size:85%;" >The registration servlet will interface with our PasswordService class using this static getInstance() method. Whenever it is invoked, a check will be made to see if an instance of this service class already exists. If so, it will be returned back to the caller (registration servlet). Otherwise, a new instance will be created.<br /><br /></span><strong><span style=";font-family:Verdana;font-size:85%;" >Step 2: </span></strong><span style=";font-family:Verdana;font-size:85%;" >We are asking Java security API to obtain an instance of a message digest object using the algorithm supplied (in this case, SHA-1 message digest algorithm will be used. Both SHA and SHA-1 refer to the same thing, a revised SHA algorithm). Sun JDK includes JCA (Java Cryptography Architecture) which includes support for SHA algorithm. If your environment does not support SHA, NoSuchAlgorithmException will be thrown.<br /><br /></span><strong><span style=";font-family:Verdana;font-size:85%;" >Step 3: </span></strong><span style=";font-family:Verdana;font-size:85%;" >Feed the data:a) convert the plaintext password (eg, "jsmith") into a byte-representation using UTF-8 encoding format.b) apply this array to the message digest object created earlier. This array will be used as a source for the message digest object to operate on.<br /><br /></span><strong><span style=";font-family:Verdana;font-size:85%;" >Step 4: </span></strong><span style=";font-family:Verdana;font-size:85%;" >Do the transformation: generate an array of bytes that represent the digested (encrypted) password value.<br /><br /></span><strong><span style=";font-family:Verdana;font-size:85%;" >Step 5: </span></strong><span style=";font-family:Verdana;font-size:85%;" >Create a String representation of the byte array representing the digested password value. This is needed to be able to store the password in the database. At this point, the hash value of the plaintext "<span style="color: rgb(51, 204, 0);">jsmith</span>" is "<span style="color: rgb(0, 153, 0);">5yfRRkrhJDbomacm2lsvEdg4GyY=</span>".<br /><br /></span><strong><span style=";font-family:Verdana;font-size:85%;" >Step 6: </span></strong><span style=";font-family:Verdana;font-size:85%;" >Return the String representation of the newly generated hash back to our registration servlet so that it can be stored in the database. The user.getPassword() method now returns "<span style="color: rgb(51, 204, 0);">5yfRRkrhJDbomacm2lsvEdg4GyY=</span>"<br /><br /></span><span style=";font-family:Verdana;font-size:85%;" >That's all. Your database password data is now encrypted and if an intruder gets a hold of it, he/she won't have much use of it. Note, you have to consider how you will handle "forgot password" functionality in this case as you now cannot simply send a password to the user's email address. (Well, you should not be doing things like that anyway) .</span>Avatar Nghttp://www.blogger.com/profile/17532077659766019555noreply@blogger.com1tag:blogger.com,1999:blog-16511027.post-1130598610198853552005-10-29T07:44:00.000-07:002005-10-30T00:36:45.930-07:00JSF-Database Demo<style><br />code{<br />color: rgb(51, 102, 255);<br />}<br /></style><strong><strong><span style="color: rgb(51, 0, 51);font-size:180%;" ><span style="font-weight: bold;font-family:courier new;" >J<span style="color: rgb(102, 51, 102);">S<span style="color: rgb(153, 51, 153);">F<span style="color: rgb(204, 51, 204);">-<span style="color: rgb(204, 102, 204);">Da<span style="color: rgb(255, 153, 255);">t<span style="color: rgb(255, 204, 255);">ab</span>a</span>se </span>D</span>e</span>m</span>o</span></span><br /><br /></strong></strong>Well it has been a hot topic now people talking about <b>`JavaServer Faces`</b>, and there are a few implementation (RI) of <b>`JSR-000127`</b> (e.g.: <span style="color: rgb(51, 51, 255);">MyFaces</span>, <span style="color: rgb(0, 153, 0);">JSF</span>).<br /><span style="font-style: italic;"><span style="font-weight: bold;"><br /></span></span><span style="font-weight: bold; color: rgb(255, 0, 0);">Ingredients</span><br />- JSF(JSR-000127) RI (<a href="http://myfaces.apache.org/" target="_blank">MyFaces</a> / <a href="http://myfaces.apache.org/tomahawk/overview.html" target="_blank">Tomahawk</a>) 1.1.0<br />- Server/Servlet Container (<a href="http://tomcat.apache.org/" target="_blank">Apache Tomcat 5.5</a>)<br />- Java Developement Kit (<a href="http://java.sun.com/j2se/1.5.0/" target="_blank">JDK 5.0</a>)<br /><span style="font-style: italic;"><span style="font-weight: bold;"><br /></span></span><span style="font-weight: bold; color: rgb(255, 0, 0);">Introduction</span><br />The reason I picked MyFaces instead of pure JSF is because I'm<br />using Apache Tomcat as my Servlet Container, but that isn't the main<br />reason; its because MyFaces had lots more cool UI to pick from than the<br />official JSF RI (e.g.: Calendar, WSIWYG Editor, Menu, Tree, ...)!<br /><br />So what is so great about the concept? I will describe it as a<br />web-based Swing (for those who code in Java desktop b4, you should be<br />familiar with the swing package)!<br /><br />JSF is really a technology to separate <i>presentation layer</i> from <i>logic layer</i>, and the content developer need not know programming at all (or at least only know how to use which JavaBean).<br /><h5 style="color: rgb(255, 0, 0);font-family:times new roman;"><span style="font-size:130%;">Installation</span></h5> I'm assuming that you are using Windows XP as your developement environment.<br />- <a href="http://apache.leakage.org/myfaces/binaries/myfaces-1.1.0.zip" target="_blank">download MyFaces 1.1.0</a><br />- <a href="http://apache.leakage.org/tomcat/tomcat-5/v5.5.12/bin/apache-tomcat-5.5.12.zip" target="_blank">download Apache Tomcat 5.5</a><br />- go <a href="http://java.sun.com/j2se/1.5.0/download.jsp" target="_blank">here</a> to download JDK 5.0 (it was JDK 5.0 Update 5 by the time I'm writing this)<br /><br />When you have all the ingredients ready, install them by following the official guide or my simple steps(windows only):<br /><i style="color: rgb(255, 102, 0);"><h5>(1)Installing JDK</h5></i>- Start installation by excuting the file `<b>jdk-1_5_0_05-windows-i586-p.exe</b>`, choose the path `<b>c:\dev\jdk5</b>` when it ask you `Where to install JDK?`; for the JVM just leave by the default path!<br />- Second thing to do is to set the environment variable for the JDK:<br />- right click on `<b>My Computer</b>`->choose `<b>Properties</b>`->click on `<b>Advance</b>` tab->click `<b>Environment Variables</b>` on the lower left->create a new variable name by clicking `<b>New</b>` under section `<b>User variables for xxx</b>`)->put `<b>Variable name</b>` as `<b>JAVA_HOME</b>` put the `<b>Variable value</b>` as `<b>c:\dev\jdk5</b>`->click `<b>Ok</b>` ... `<b>Ok</b>` all the way back<br />- To make compilation and execution java application easier, create a new entry for Windows to lookup java, edit the `<b>PATH</b>` variable by appending `<b>;c:\dev\jdk5\bin</b>`<br />- Test the instalation by keying in <b>echo %JAVA_HOME%</b> in command prompt, and you should get this: `<b>c:\dev\jdk5</b>`<br />- Further test the java command by using <b>java</b> in command prompt, and you should get something like this:<br /><br /><b>Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_04-b05)<br />Java HotSpot(TM) Client VM (build 1.5.0_04-b05, mixed mode, sharing)</b><br /><br />- Done!<br /><i style="color: rgb(255, 102, 0);"> <h5>(2)Installing Tomcat</h5> </i>- <a href="http://tomcat.apache.org/tomcat-5.5-doc/setup.html" target="_blank">official guide to install tomcat </a><br />- unzip the file `<b>apache-tomcat-5.5.12.zip</b>` to directory `<b>c:\dev\</b>`, and you will get something like `<b>c:\dev\apache-tomcat-5.5.12</b>`. Rename it to `<b>c:\dev\tomcat</b>`.<br />- Set your environment variables `<b>CATALINA_HOME</b>` and `<b>CATALINA_BASE</b>` to `<b>c:\dev\tomcat</b>`.<br />- To make server startup/shutdown easier, create a new entry for Windows to lookup tomcat, edit the `<b>PATH</b>` variable by appending `<b>;c:\dev\tomcat\bin</b>`<br /><br />- To start your server, type `<b>startup.bat</b>` in command prompt, and you should see some message like below and a command prompt will popup:<br /><br /><b>Using CATALINA_BASE: E:\dev\tomcat<br />Using CATALINA_HOME: E:\dev\tomcat<br />Using CATALINA_TMPDIR: E:\dev\tomcat\temp<br />Using JAVA_HOME: C:\Program Files\Java\jdk1.5.0_04</b><br /><br />- Navigate your server by pointing you browser to `<a href="http://localhost:8080/" target="_blank">http://localhost:8080</a>`<br />- To shutdown your server, type `<b>shutdown.bat</b>` in command prompt, and you should see same message as well and the popup should be close by itself after a while.<br />- Done!<br /><i><h5><span style="color: rgb(255, 102, 0);">(3)Installing MyFaces - A dataTable Example</span><br /></h5></i>Extract `<b>myfaces-1.1.0.zip</b>` to any directory<br />(e.g.:C:\dev\myfaces-1.1.0) for javadoc reference. For real<br />development, download the example package -<br />`myfaces-1.1.1RC2-examples.zip` and unzip it to `<b>C:\dev\myfaces-1.1.1RC2-examples</b>`. You will find some examples web applications like `<b>simple.war</b>`,`<b>blank.war</b>`, and so on, extract `<b>blank.war</b>` into `<b>C:\dev\myfaces-1.1.1RC2-examples\blank</b>` using <a href="http://www.win-rar.com/affdownload/index.php?AffID=200019932" target="_blank">Winrar</a> or similar software. Now copy all the jars files from `<b>C:\dev\myfaces-1.1.1RC2-examples\blank\WEB-INF\lib</b>`<br />to your web application's library directory(e.g.:<br />C:\dev\tomcat\webapps\myfaces-demo\WEB-INF\lib)). To follow my tutorial<br />and avoid confusion, just create a demo web application in tomcat with<br />the following directory structure:<br /><br />- C:\dev\tomcat\webapps\myfaces-demo<br />- C:\dev\tomcat\webapps\myfaces-demo\META-INF<br />- C:\dev\tomcat\webapps\myfaces-demo\WEB-INF\lib<br />- C:\dev\tomcat\webapps\myfaces-demo\WEB-INF\classes<br /><br />Create a `<b>web.xml</b>` file in your `<b>C:\dev\tomcat\webapps\myfaces-demo\WEB-INF</b>` directory, with following content:<br /><br /><code style="color: rgb(51, 102, 255);"><?xml version='1.0' encoding='UTF-8'?><br /><!DOCTYPE web-app PUBLIC<br />"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"<br />"http://java.sun.com/dtd/web-app_2_3.dtd"><br /><web-app><br /><display-name>MyFaces Demo</display-name><br /><description>a Myfaces demo page</description><br /><context-param><br /><param-name>javax.faces.application.CONFIG_FILES</param-name><br /><param-value><br /> /WEB-INF/faces-config.xml<br /></param-value><br /></context-param><br /><context-param><br /><param-name>javax.faces.STATE_SAVING_METHOD</param-name><br /><param-value>client</param-value><br /></context-param><br /><context-param><br /><param-name>myfaces_allow_javascript</param-name><br /><param-value>true</param-value><br /></context-param><br /><context-param><br /><param-name>myfaces_pretty_html</param-name><br /><param-value>true</param-value><br /></context-param><br /><!-- Faces Servlet --><br /><servlet><br /><servlet-name>Faces Servlet</servlet-name><br /><servlet-class>javax.faces.webapp.FacesServlet</servlet-class><br /><load-on-startup>1</load-on-startup><br /></servlet><br /><!-- Faces Servlet Mapping --><br /><servlet-mapping><br /><servlet-name>Faces Servlet</servlet-name><br /><url-pattern>*.faces</url-pattern><br /></servlet-mapping><br /><resoure-ref><br /><res-ref-name>jdbc/mysql</res-ref-name><br /><res-type>javax.sql.DataSource</res-type><br /><res-auth>Container</res-auth><br /></resoure-ref><br /><welcome-file-list><br /><welcome-file>index.html</welcome-file><br /></welcome-file-list><br /></web-app></code><br /><br />Now we investigate the line below:<br /><br /><code><span style="color: rgb(51, 102, 255);"><resoure-ref></span><br /><span style="color: rgb(51, 102, 255);"> <res-ref-name>jdbc/mysql</res-ref-name></span><br /><span style="color: rgb(51, 102, 255);"> <res-type>javax.sql.DataSource</res-type></span><br /><span style="color: rgb(51, 102, 255);"> <res-auth>Container</res-auth></span><br /><span style="color: rgb(51, 102, 255);"></resoure-ref></span><br /></code><br />Notice that I have registered an resource for the datatbase here<br />wit h the JNDI=`jdbc/mysql`. Actually we have to create an context of<br />this before we could use this ... so let's make the configure the<br />database.<br /><br />For this example I'm using <a href="http://www.mysql.com/" target="_blank">Mysql</a> as my database, I will not discuss a little on that later when we touched on it.<br /><br />Now for making a pool of database resources, we have to make a file called `<b>context.xml</b>` in `<b>C:\dev\tomcat\webapps\myfaces-demo\META-INF</b>`<br />directory. Below is how it should be looking like (Notes: this context<br />configuration file is for Tomcat 5.0 and above, for others version<br />please refer to tomcat <a href="http://tomcat.apache.org/" target="_blank">official site</a>):<br /><br /><code style="color: rgb(51, 102, 255);"><!-- MySQL database context --><br /><Context path="/myfaces-demo"<br />docBase="myfaces-demo"<br />debug="5"<br />reloadable="true"<br />crossContext="true"><br /><Resource name="jdbc/mysql"<br /> auth="Container"<br /> type="javax.sql.DataSource"<br /> username="root"<br /> password=""<br /> driverClassName="com.mysql.jdbc.Driver"<br /> url="jdbc:mysql://localhost:3306/test"<br /> maxActive="8"<br /> maxIdle="4"/><br /></Context></code><br /><br />Once we have that, the database should be working well when you<br />call from the JNDI. Now there is one more ingredient to add in - the `<b>faces-config.xml</b>`. Refer the following code:<br /><br /><code style="color: rgb(51, 102, 255);"><?xml version="1.0"?><br /><!DOCTYPE faces-config PUBLIC<br />"-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.0//EN"<br />"http://java.sun.com/dtd/web-facesconfig_1_0.dtd" ><br /><faces-config><br /><!-- managed beans of the simple hello world app --><br /><managed-bean><br /><managed-bean-name>user</managed-bean-name><br /><managed-bean-class>com.avatar21.bean.UserBean</managed-bean-class><br /><managed-bean-scope>request</managed-bean-scope><br /></managed-bean><br /></faces-config></code><br /><br />We have to code a little java from this point, create a javabean by the name `<b>UserBean.java</b>`.<br /><br />-> <b>UserBean.java</b> listing:<br /><pre><code><br /><span style="color: rgb(51, 102, 255);">package com.avatar21.bean;</span><br /><br /><span style="color: rgb(51, 102, 255);">import java.util.Map;</span><br /><span style="color: rgb(51, 102, 255);">import java.util.HashMap;</span><br /><span style="color: rgb(51, 102, 255);">import java.sql.Connection;</span><br /><span style="color: rgb(51, 102, 255);">import java.sql.PreparedStatement;</span><br /><span style="color: rgb(51, 102, 255);">import java.sql.ResultSet;</span><br /><span style="color: rgb(51, 102, 255);">import java.sql.SQLException;</span><br /><span style="color: rgb(51, 102, 255);">import java.util.logging.Level;</span><br /><span style="color: rgb(51, 102, 255);">import java.util.logging.Logger;<br />import javax.faces.context.FacesContext;<br />import javax.faces.event.ValueChangeEvent;<br /></span><span style="color: rgb(51, 102, 255);">import javax.naming.Context;</span><br /><span style="color: rgb(51, 102, 255);">import javax.naming.InitialContext;</span><br /><span style="color: rgb(51, 102, 255);">import javax.naming.NamingException;</span><br /><span style="color: rgb(51, 102, 255);">import javax.sql.DataSource;</span><br /><br /><span style="color: rgb(51, 102, 255);">public class UserBean{</span><br /><span style="color: rgb(51, 102, 255);"> private Map users = null;<br />private String email;<br /></span><span style="color: rgb(51, 102, 255);"> private Logger logger = Logger.getLogger("com.portfolio");</span><br /><br /><span style="color: rgb(51, 102, 255);"> // email</span><br /><span style="color: rgb(51, 102, 255);"> public String getEmail(){</span><br /><span style="color: rgb(51, 102, 255);"> return email;</span><br /><span style="color: rgb(51, 102, 255);"> }</span><br /><span style="color: rgb(51, 102, 255);"> public void setEmail(String email){</span><br /><span style="color: rgb(51, 102, 255);"> this.email = email;</span><br /><span style="color: rgb(51, 102, 255);"> }</span><br /><br /><span style="color: rgb(51, 102, 255);"> public Map getUsers(){</span><br /><span style="color: rgb(51, 102, 255);"> if(users==null){</span><br /><span style="color: rgb(51, 102, 255);"> try{</span><br /><span style="color: rgb(51, 102, 255);"> populateAction();</span><br /><span style="color: rgb(51, 102, 255);"> }</span><br /><span style="color: rgb(51, 102, 255);"> catch(SQLException sqlEx){</span><br /><span style="color: rgb(51, 102, 255);"> logger.log(Level.SEVERE, "loginAction", sqlEx);</span><br /><span style="color: rgb(51, 102, 255);"> }</span><br /><span style="color: rgb(51, 102, 255);"> catch(NamingException nameEx){</span><br /><span style="color: rgb(51, 102, 255);"> logger.log(Level.SEVERE, "loginAction", nameEx);</span><br /><span style="color: rgb(51, 102, 255);"> }</span><br /><span style="color: rgb(51, 102, 255);"> finally{</span><br /><span style="color: rgb(51, 102, 255);"> return users;</span><br /><span style="color: rgb(51, 102, 255);"> }</span><br /><span style="color: rgb(51, 102, 255);"> }</span><br /><span style="color: rgb(51, 102, 255);"> return users;</span><br /><span style="color: rgb(51, 102, 255);"> }<br /><br />public void emailSelected(ValueChangeEvent e) {<br />FacesContext context = FacesContext.getCurrentInstance();<br />setEmail((String) e.getNewValue());<br /><br />context.renderResponse();<br />}<br /></span><br /><span style="color: rgb(51, 102, 255);"> public void populateAction() throws SQLException, NamingException{</span><br /><span style="color: rgb(51, 102, 255);"> Context ctx = new InitialContext();</span><br /><span style="color: rgb(51, 102, 255);"> if(ctx==null){</span><br /><span style="color: rgb(51, 102, 255);"> throw new NamingException("No initial context");</span><br /><span style="color: rgb(51, 102, 255);"> }</span><br /><span style="color: rgb(51, 102, 255);"> </span><br /><span style="color: rgb(51, 102, 255);"> Context envContext = (Context)ctx.lookup("java:/comp/env");</span><br /><span style="color: rgb(51, 102, 255);"> if(envContext==null){</span><br /><span style="color: rgb(51, 102, 255);"> throw new NamingException("No environment context");</span><br /><span style="color: rgb(51, 102, 255);"> }</span><br /><span style="color: rgb(51, 102, 255);"> </span><br /><span style="color: rgb(51, 102, 255);"> DataSource ds = (DataSource)envContext.lookup("jdbc/mysql");</span><br /><span style="color: rgb(51, 102, 255);"> if(ds==null){</span><br /><span style="color: rgb(51, 102, 255);"> throw new NamingException("No data source");</span><br /><span style="color: rgb(51, 102, 255);"> }</span><br /><span style="color: rgb(51, 102, 255);"> </span><br /><span style="color: rgb(51, 102, 255);"> Connection conn = ds.getConnection();</span><br /><span style="color: rgb(51, 102, 255);"> if(conn==null){</span><br /><span style="color: rgb(51, 102, 255);"> throw new SQLException("No database connection");</span><br /><span style="color: rgb(51, 102, 255);"> }</span><br /><span style="color: rgb(51, 102, 255);"> </span><br /><span style="color: rgb(51, 102, 255);"> try{</span><br /><span style="color: rgb(51, 102, 255);"> PreparedStatement newsQuery = conn.prepareStatement(</span><br /><span style="color: rgb(51, 102, 255);"> "SELECT user_name, user_email FROM test.user ORDER BY user_name");</span><br /><span style="color: rgb(51, 102, 255);"> </span><br /><span style="color: rgb(51, 102, 255);"> ResultSet result = newsQuery.executeQuery();</span><br /><span style="color: rgb(51, 102, 255);"> </span><br /><span style="color: rgb(51, 102, 255);"> if(!result.next()){</span><br /><span style="color: rgb(51, 102, 255);"> return;</span><br /><span style="color: rgb(51, 102, 255);"> }</span><br /><span style="color: rgb(51, 102, 255);"> else{</span><br /><span style="color: rgb(51, 102, 255);"> channels = new HashMap();</span><br /><span style="color: rgb(51, 102, 255);"> </span><br /><span style="color: rgb(51, 102, 255);"> while(result.next()){</span><br /><span style="color: rgb(51, 102, 255);"> users.put(result.getString("user_name"),result.getString("user_email"));</span><br /><span style="color: rgb(51, 102, 255);"> }</span><br /><span style="color: rgb(51, 102, 255);"> }</span><br /><span style="color: rgb(51, 102, 255);"> }</span><br /><span style="color: rgb(51, 102, 255);"> finally{</span><br /><span style="color: rgb(51, 102, 255);"> conn.close();</span><br /><span style="color: rgb(51, 102, 255);"> }</span><br /><span style="color: rgb(51, 102, 255);"> }</span><br /><span style="color: rgb(51, 102, 255);">}</span><br /><br /></code></pre>Compile the class and put the `<b>UserBean.class</b>` in `<b>C:\dev\tomcat\webapps\myfaces-demo\WEB-INF\classes\com.avatar21.bean</b>`<br /><br />Create a load page: `<b>index.html</b>` in `<b>C:\dev\tomcat\webapps\myfaces-demo</b>`<br /><code style="color: rgb(51, 102, 255);"><br /><html><br /><head><br /><title>Loading Page</title><br /><meta http-equiv="Refresh" content="0; URL=index.faces" /><br /></head><br /><body><br /><font color="#ff0000">Application starting ...</font><br /></body><br /></html><br /></code><br />The JSF test file: `<b>testSelectOneMenu.jsp</b>` in `<b>C:\dev\tomcat\webapps\myfaces-demo</b>`<br /><br /><code><span style="color: rgb(51, 102, 255);"><%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %></span><br /><span style="color: rgb(51, 102, 255);"><%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %></span><br /><span style="color: rgb(51, 102, 255);"><html></span><br /><span style="color: rgb(51, 102, 255);"><head></span><br /><span style="color: rgb(51, 102, 255);"><title>Test selectOneMenu</title></span><br /><span style="color: rgb(51, 102, 255);"></head></span><br /><span style="color: rgb(51, 102, 255);"><body></span><br /><span style="color: rgb(51, 102, 255);"><f:view></span><br /><span style="color: rgb(51, 102, 255);"><h:form><br /></span></code><code><span style="color: rgb(51, 102, 255);"><h:outputText value="#{user.email}" onchange="submit();" immediate="true" valueChangeListener="#{user.emailSelected}"/></span></code><br /><code><span style="color: rgb(51, 102, 255);"><f:verbatim><br/></f:verbatim></span><br /><span style="color: rgb(51, 102, 255);"><h:selectOneMenu value="#{user.email}"></span><br /><span style="color: rgb(51, 102, 255);"><f:selectItems value="#{user.users}"/></span><br /><span style="color: rgb(51, 102, 255);"></h:selectOneMenu></span><br /><span style="color: rgb(51, 102, 255);"><h:commandButton value="#{msgs.sync}" action="#{user.populateAction}"/></span><br /><span style="color: rgb(51, 102, 255);"></h:form></span><br /><span style="color: rgb(51, 102, 255);"></f:view></span><br /><span style="color: rgb(51, 102, 255);"></body></span><br /><span style="color: rgb(51, 102, 255);"></html></span><br /><br /></code>Now in order to let the code works, create a table named `<b>user</b>` in `<b>test</b>` database, below is the Mysql scripts for doing this.<br /><br /><code><span style="color: rgb(51, 102, 255);">USE test;</span><br /><br /><span style="color: rgb(51, 102, 255);">CREATE TABLE test.user(</span><br /><span style="color: rgb(51, 102, 255);">user_id INT NOT NULL AUTO_INCREMENT, </span><br /><span style="color: rgb(51, 102, 255);">user_name VARCHAR(255),</span><br /><span style="color: rgb(51, 102, 255);">user_email VARCHAR(255),</span><br /><span style="color: rgb(51, 102, 255);">PRIMARY KEY (user_id)</span><br /><span style="color: rgb(51, 102, 255);">); </span><br /><br /></code>It should be up and running by now when you point your browser to `<a href="http://localhost:8080/myfaces-demo" target="_blank">http://localhost:8080/myfaces-demo</a>`!<br /><br />I have not run this example on my server, please send me some screenshot if you able to run it, Thanks!<br /><br /><br />By Avatar<br /><br />ngavarta@gmail.comAvatar Nghttp://www.blogger.com/profile/17532077659766019555noreply@blogger.com4tag:blogger.com,1999:blog-16511027.post-1127542147347779632005-09-23T23:01:00.000-07:002005-09-23T23:09:07.360-07:00Writing a XMPP chat client in Java (Google Talk)<div class="entry-content"> <div class="entry-body"> <p><span style="font-size: 0.8em;">I think I just start off to the topic, firstly u need a 3rd-party library "smack.jar"+"smackx.jar" which extracted from "smack-2.0.0.zip". Get the file from <a href="http://jivesoftware.org/downloads.jsp">here</a> !</span></p> <p><span style="font-size: 0.8em;">I'm using "javax.swing" classes to build the UI, below is a brief design layout:<br />+-----------------------------------------------+<br />| Login : __________ | <---- login name (e.g.: yourmail.google.com)<br />| Password: ________ | Login| | <---- password (e.g.: google mail password)<br />+-----------------------------------------------+<br />| +------------------------------+ | Send | |<br />| | | |<br />| | | |<br />| +------------------------------+ | quit | |<br />| _____________________________ V | <--- friend's list<br />| _______________________________ | <---- chat message here<br />+-----------------------------------------------+</span></p> <p><span style="font-size: 0.8em;">Now u get what u needed, put the libraries in a the classpath so that your Java compiler can find it.<br />Here's the code and I'll explains line by line in comments (codes are meant to be small to save up space, simply cut and paste to a textpad for the aid of reading):<br />____________________________________________________________________________</span><br /><span style="font-size: 0.8em; color: rgb(0, 0, 0);">ChatClient.java</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br />____________________________________________________________________________</span><br /><span style="font-size: 0.8em; color: rgb(0, 0, 153);">package com.avatar.chat;</span><br /><br /><span style="font-size: 0.8em; color: rgb(0, 102, 51);">// import swing classes</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br />import java.util.*;<br />import java.awt.*;<br />import java.awt.event.*;<br />import javax.swing.*;<br />import javax.swing.event.*;</span><br /><span style="font-size: 0.8em; color: rgb(0, 102, 51);">// import smack classes</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br />import org.jivesoftware.smack.*;<br />import org.jivesoftware.smack.packet.*;<br />import org.jivesoftware.smack.filter.*;</span><br /><br /><span style="font-size: 0.8em; color: rgb(0, 102, 51);">// packet listener will required you to implement a</span><span style="font-size: 0.8em; color: rgb(0, 102, 51);"> method<br />// called </span><span style="font-size: 0.8em; color: rgb(0, 102, 51);"> </span><span style="font-size: 0.8em; color: rgb(0, 102, 51);">"processPacket(Packet packet)" which lets you<br />// go lower level to handle the in/out packets better</span><br /><span style="font-size: 0.8em; color: rgb(0, 0, 153);">public class ChatClient extends JFrame implements ActionListener, PacketListener{<br /> private JButton btnLogin, btnSend, btnQuit;<br /> private JTextArea taChatArea;<br /> private JTextField tfChatMessage, tfLoginName;<br /> private JComboBox cbOpponent;<br /> private JPasswordField pfLoginPassword;</span><br /><span style="font-size: 0.8em; color: rgb(0, 102, 51);">// GoogleTalkConnection is one of the class by Smack</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br /> private GoogleTalkConnection con = null;</span><br /><span style="font-size: 0.8em; color: rgb(0, 102, 51);">// GroupChat will allowed you to listen to more than 1 opponent</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br /> private GroupChat chat = null;<br /> private String login_name = "";<br /> private String login_password = "";<br /> private String opponent = "";<br /> private boolean isLogin = false;</span><br /><span style="font-size: 0.8em; color: rgb(0, 102, 51);">// require class -- </span><span style="font-size: 0.8em; color: rgb(0, 102, 51);">PacketFilter and </span><span style="font-size: 0.8em; color: rgb(0, 102, 51);">PacketCollector</span><span style="font-size: 0.8em; color: rgb(0, 102, 51);">, explain below</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br /> private PacketFilter filter = null;<br /> private PacketCollector myCollector = null;</span><br /><span style="font-size: 0.8em; color: rgb(0, 102, 51);">// Message is a class to hold all data which extracted from the packet,<br />// e.g. sender, receiver, timestamp, message ... etc</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br /> private Message msg = null;<br /> <br /> public ChatClient(){<br /> super("Chat Client");<br /> <br /> setSize(400,300);<br /> setResizable(true);<br /> setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);<br /> setLayout(new BorderLayout(0,0));<br /> initComponents();<br /><br /> setVisible(true);<br /> }<br /> <br /> public void initComponents(){<br /> btnLogin = new JButton("Login");<br /> btnLogin.addActionListener(this); <br /> btnSend = new JButton("Send");<br /> btnSend.setMnemonic(KeyEvent.VK_ENTER);<br /> btnSend.addActionListener(this);<br /> btnQuit = new JButton("Quit");<br /> btnQuit.addActionListener(this);<br /> taChatArea = new JTextArea(10,40);<br /> taChatArea.setEditable(false);<br /> JScrollPane chatScroller = new JScrollPane(taChatArea);<br /> chatScroller.setPreferredSize(new Dimension(300, 200));<br /> chatScroller.setMinimumSize(new Dimension(300, 200));<br /> chatScroller.setAlignmentX(Component.LEFT_ALIGNMENT);<br /> tfChatMessage = new JTextField(40);<br /> tfLoginName = new JTextField(10);<br /> cbOpponent = new JComboBox();<br /> cbOpponent.setEditable(true);<br /> pfLoginPassword = new JPasswordField(10);<br /> <br /> JPanel pnlButton = new JPanel(new GridLayout(2,1,0,0));<br /> JPanel pnlLogin = new JPanel(new GridLayout(3,2,0,0));<br /> JPanel pnlMessage = new JPanel(new GridLayout(2,1,0,0));<br /> <br /> pnlLogin.add(new JLabel("User Name:"));<br /> pnlLogin.add(tfLoginName);<br /> pnlLogin.add(new JLabel("Password:"));<br /> pnlLogin.add(pfLoginPassword);<br /> pnlLogin.add(new JLabel("press here to login ->"));<br /> pnlLogin.add(btnLogin);<br /> pnlButton.add(btnSend);<br /> pnlButton.add(btnQuit);<br /> pnlMessage.add(cbOpponent);<br /> pnlMessage.add(tfChatMessage);<br /> <br /> setChat(false);<br /> <br /> add(pnlLogin, BorderLayout.NORTH);<br /> add(pnlButton, BorderLayout.EAST);<br /> add(chatScroller, BorderLayout.CENTER);<br /> add(pnlMessage, BorderLayout.SOUTH);<br /> }<br /> </span><br /><span style="font-size: 0.8em; color: rgb(0, 102, 51);">// disable sending meassage when variable 'mark' is false (offline), and vice-versa</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br /> public void setChat(boolean mark){<br /> tfChatMessage.setEnabled(mark);<br /> cbOpponent.setEnabled(mark);<br /> btnSend.setEnabled(mark);<br /> }<br /> </span><br /><span style="font-size: 0.8em; color: rgb(0, 102, 51);">// clean up jobs appoint exit</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br /> public void logout(){<br /> if(con!=null){<br /> con.close();<br /> }<br /> cbOpponent.removeAllItems();<br /> }<br /> </span><br /><span style="font-size: 0.8em; color: rgb(0, 102, 51);">// when user logged in, set the flag to true (online)</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br /> public boolean login(String login_name,String login_password){</span><br /><span style="font-size: 0.8em; color: rgb(0, 102, 51);"> // get textfield's username</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br /> this.login_name = login_name;</span><br /><span style="font-size: 0.8em; color: rgb(51, 102, 0);"> // get passwordfield's password</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br /> this.login_password = login_password;<br /> boolean flag = false;<br /> <br /> try{<br /> con = new GoogleTalkConnection();<br /> con.login(login_name, login_password);<br /> </span><br /><span style="font-size: 0.8em; color: rgb(51, 102, 0);"> // filter the XML packet into a PacketCollector (much like a queue),<br /> // so that you can get them back later</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br /> filter = new AndFilter(<br /> new PacketTypeFilter(Message.class),<br /> new FromContainsFilter(opponent));<br /> myCollector = con.createPacketCollector(filter);<br /> </span><br /><span style="font-size: 0.8em; color: rgb(51, 102, 0);"> // </span><span style="font-size: 0.8em; color: rgb(0, 102, 51);">initialise</span><span style="font-size: 0.8em; color: rgb(51, 102, 0);"> your chatgroup</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br /> chat = con.createGroupChat(login_name+"'s Chat");</span><br /><span style="font-size: 0.8em; color: rgb(0, 102, 51);"> // initialise your message</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br /> msg = new Message();<br /> </span><br /><span style="font-size: 0.8em; color: rgb(0, 102, 51);"> // get all user from your friends list</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br /> Roster roster = con.getRoster();<br /> for (Iterator i=roster.getEntries(); i.hasNext(); ) {<br /> RosterEntry re = (RosterEntry)i.next();<br /> cbOpponent.addItem(re.getUser());</span><br /><span style="font-size: 0.8em; color: rgb(0, 102, 51);"> // Register the listener. </span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br /> }<br /> <br /> con.addPacketListener(this, filter);<br /> <br /> setChat(true);<br /> flag = true;<br /> }catch(Exception ex){<br /> ex.printStackTrace();</span><br /><span style="font-size: 0.8em; color: rgb(0, 102, 51);"> // any thing during login, disable user to send message</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br /> setChat(false);<br /> flag = false;<br /> }finally{<br /> return flag;<br /> }<br /> }<br /> <br /> public void windowClosing(WindowEvent we){<br /> logout();<br /> }</span><br /><br /><span style="font-size: 0.8em; color: rgb(0, 102, 51);"> // implementing processPacket for PacketListener interface</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br /> public void processPacket(Packet packet) {<br /> </span><span style="font-size: 0.8em; color: rgb(51, 102, 0);">// Put the incoming message on the chat history or chat board.</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br /> Message msg = (Message)packet;<br /> taChatArea.append(msg.getFrom()+<br /> ": "+msg.getBody()+"\n");<br /> }<br /> <br /> public void actionPerformed(ActionEvent e){<br /> if(e.getSource()==btnLogin){<br /> String test = btnLogin.getLabel();<br /> if(test.equals("Login")){<br /> isLogin = login(tfLoginName.getText().toString().trim(),<br /> pfLoginPassword.getText().toString().trim());<br /> btnLogin.setLabel("Logout");<br /> }else if(test.equals("Logout")){<br /> logout();<br /> setChat(false);<br /> isLogin = false;<br /> btnLogin.setLabel("Login");<br /> } <br /> }else if(e.getSource()==btnSend){<br /> opponent = cbOpponent.getSelectedItem().toString();<br /> String content = tfChatMessage.getText().toString();<br /> if(isLogin){<br /> try{<br /> msg.setTo(opponent);<br /> msg.setBody(content); <br /> chat.sendMessage(msg);</span><br /><span style="font-size: 0.8em; color: rgb(0, 102, 51);"> // append your sent message to chat board</span><span style="font-size: 0.8em; color: rgb(0, 0, 153);"><br /> taChatArea.append(login_name+": "+tfChatMessage.getText()+"\n");<br /> }catch(Exception ex){<br /> ex.printStackTrace();<br /> }<br /> }<br /> }<br /> else if(e.getSource()==btnQuit){<br /> logout();<br /> System.exit(0);<br /> }<br /> }<br /> <br /> public static void main(String[] args){<br /> ChatClient c = new ChatClient();<br /> }<br />}</span><span style="font-size: 0.8em;"><br />___________________________________________________________<br />End of </span><span style="font-size: 0.8em; color: rgb(0, 0, 0);">"ChatClient.java"</span><span style="font-size: 0.8em;"><br />___________________________________________________________<br />Thanks to Smack by JiveSoftware, online messager never got easier to write!</span></p> <p><span style="font-size: 0.8em;">The final output should looks like <a onclick="window.open(this.href, '_blank', 'width=585,height=321,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0'); return false" href="http://avatar21.blogs.friendster.com/.shared/image.html?/photos/uncategorized/chatclient_4.PNG">this</a>, still depends on platform and versioning of JDK.</span></p> <p><span style="font-size: 0.8em;">Other resoures:</span></p> <ul><li><span style="font-size: 0.8em;"><a href="http://www.anrdoezrs.net/click-1804574-10305994">Computing eBooks</a></span></li></ul> <ul><li><span style="font-size: 0.8em;"><a href="http://www.amazon.com/exec/obidos/redirect?link_code=ur2&camp=1789&tag=personalmon04-20&creative=9325&path=tg/browse/-/5">Get some refrence books</a></span></li></ul> <p><span style="font-size: 0.8em;">[NOTE: Smack is a trademark of Jive Software, Google Talk is a trademark of Google.]</span></p> </div> </div>Avatar Nghttp://www.blogger.com/profile/17532077659766019555noreply@blogger.com11tag:blogger.com,1999:blog-16511027.post-1126195537360507882005-09-08T09:04:00.000-07:002005-09-08T09:36:54.043-07:00WSDL SampleBefore porting the web service module into a J2EE application, firstly lets look at how I get a stock quote in a normal Java concole.<br /><br />As I will continue on application of WSDL on my next post ... .<br /><br />Below is the full generic code to demostrate on calling a WSDL:<br /><br /><table style="width: 460px; height: 679px;" align="left" border="0" cellpadding="1" cellspacing="1"><tbody><tr><td bgcolor="#cccccc"><small> <pre>//<br />// XMethods sample client for the Stock Quote service<br />//<br /><br />import java.io.*;<br />import java.net.*;<br />import java.util.*;<br />import org.apache.soap.util.xml.*;<br />import org.apache.soap.*;<br />import org.apache.soap.rpc.*;<br /><br />public class StockQuoteClient{<br /><br /> public static float getQuote (URL url, String symbol) throws Exception {<br /><br /> Call call = new Call ();<br /><br /> // Service uses standard SOAP encoding<br /> String encodingStyleURI = Constants.NS_URI_SOAP_ENC;<br /> call.setEncodingStyleURI(encodingStyleURI);<br /><br /> // Set service locator parameters<br /> call.setTargetObjectURI ("urn:xmethods-delayed-quotes");<br /> call.setMethodName ("getQuote");<br /><br /> // Create input parameter vector<br /> Vector params = new Vector ();<br /> params.addElement (new Parameter("symbol", String.class, symbol, null));<br /> call.setParams (params);<br /><br /> // Invoke the service ....<br /> Response resp = call.invoke (url,"");<br /><br /> // ... and evaluate the response<br /> if (resp.generatedFault ()) {<br />throw new Exception();<br /> } else {<br /> // Call was successful. Extract response parameter and return result<br /> Parameter result = resp.getReturnValue ();<br /> Float rate=(Float) result.getValue();<br /> return rate.floatValue();<br /> }<br /> }<br /><br />// Driver to illustrate service invocation<br /> public static void main(String[] args) {<br /> try {<br /> URL url=new URL("http://services.xmethods.net:80/soap");<br /> String symbol= args[0];<br /> float quote = getQuote(url,symbol);<br /> System.out.println(quote);<br /> }<br /> catch (Exception e) {e.printStackTrace();}<br /> }<br />}</pre> </small></td></tr></tbody></table>Avatar Nghttp://www.blogger.com/profile/17532077659766019555noreply@blogger.com0