Realhowto Java

810
Real's HowTo PDF version. This is the PDF version of the Real's HowTo Web site ( http://www.rgagnon.com/howto.html ). For up-to-date content, please refer to the Web site. There are 4 files : Real's Java , Real's Javascript, Real's Powerbuilder and Real's VBS and Misc Prog HowTo. Please don't make PDF versions available on the internet (it's ok in intranet) From the PDF, you can't run the examples and the links to other How-to's are not working. If you feel that effort has been useful to you, perhaps you will consider giving something back? You can make a donation through PayPal at https://www.paypal.com , make you donation to [email protected] Contributions via PayPal are accepted in any amount using a credit card or checking account. (Donations of any size gladly accepted) Real's Howto copyright notice ( [email protected] ) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions is met: * the source code is used in a development project Redistributions of source code or site content (even partially) in any publications (electronic or paper) is forbidden without permission. DISCLAIMER THIS SOFTWARE IS PROVIDED BY Real Gagnon "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Real Gagnon BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Transcript of Realhowto Java

Real's HowTo PDF version.This is the PDF version of the Real's HowTo Web site ( http://www.rgagnon.com/howto.html ). For uptodate content, please refer to the Web site. There are 4 files : Real's Java , Real's Javascript, Real's Powerbuilder and Real's VBS and Misc Prog HowTo. Please don't make PDF versions available on the internet (it's ok in intranet) From the PDF, you can't run the examples and the links to other Howto's are not working. If you feel that effort has been useful to you, perhaps you will consider giving something back? You can make a donation through PayPal at https://www.paypal.com , make you donation to [email protected] Contributions via PayPal are accepted in any amount using a credit card or checking account. (Donations of any size gladly accepted) Real's Howto copyright notice ( [email protected] ) Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions is met: * the source code is used in a development project Redistributions of source code or site content (even partially) in any publications (electronic or paper) is forbidden without permission. DISCLAIMER THIS SOFTWARE IS PROVIDED BY Real Gagnon "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Real Gagnon BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Real's [email protected] Applet..............................................................................................................................................1 . 1.1 javaapplet........................................................................................................................1 1.2 Goto to a new URL from an Applet....................................................................................1 1.3 Determine the host from where the Applet is loaded.........................................................3 1.4 Have a scrolling status line................................................................................................3 1.5 Use a search engine..........................................................................................................5 1.6 Have an onscreen clock..................................................................................................6 1.7 Have Applets on the same page communicate with each other........................................8 1.8 Have Applets on different frames communicates with each other.....................................9 1.9 Send a message from an Applet to another Applet on a different page..........................10 1.10 Have an applet launch an other applet..........................................................................12 1.11 Get the user name.........................................................................................................14 1.12 Access parameters passed in the URL ..........................................................................14 1.13 Convert an Applet to Application ....................................................................................16 1.14 Change the mouse cursor in Applet..............................................................................17 . 1.15 Use an Image as the Applet background.......................................................................17 1.16 Handle the new Control Activation mechanism in IE.....................................................18 1.16.1 Solution #1............................................................................................................19 1.16.2 Solution #2............................................................................................................19 1.16.3 Solution #3............................................................................................................20 1.17 Pass parameters to the Applet JVM (WIN)....................................................................21 1.18 See the Java Console Window Log (Java plugin).........................................................22 1.19 Display debugging infos for an Applet...........................................................................23 1.20 Have an invisible Applet................................................................................................23 . 2 Date and Time...............................................................................................................................24 2.1 javadate.........................................................................................................................24 2.2 Have year on 4 digits from a Date object.........................................................................24 2.3 Get the current Date and Time........................................................................................24 2.4 Compute days between 2 dates......................................................................................25 2.5 Get the number of days in a month ..................................................................................26 2.6 Validate a date.................................................................................................................27 2.6.1 Using DateFormat...................................................................................................27 2.6.2 Using GregorianCalendar.......................................................................................28 2.7 Determine to day of the week..........................................................................................29 2.8 Add/Substract Day/Month/Year to a Date........................................................................29 2.9 Get the correct TimeZone on DateFormat.......................................................................30 2.10 Simply format a date as "YYYYMMDD".........................................................................30 2.11 Compare 2 dates...........................................................................................................31 2.12 Parse a String to obtain a Date/GregorianCalendar object ...........................................31 . 2.13 Use System time to generate unique ID........................................................................32 2.14 Get the day name..........................................................................................................33 2.15 Find the current date format..........................................................................................33 . 2.16 Get a julian date.............................................................................................................34 2.17 Calculate the age...........................................................................................................36 2.18 Format a duration in ms into a string as "Days,Hours,minutes and seconds"...............37 2.19 Get the atomic time........................................................................................................38 2.20 Get a date interval.........................................................................................................40 . 2.21 Determine if an hour is between an interval..................................................................42 . 2.22 Set the computer clock..................................................................................................43

2.23 Use System time to generate unique ID

Real's [email protected] Date and Time 2.23 Use System time to generate unique ID........................................................................43 3 AWT ................................................................................................................................................45 3.1 javaawt ..........................................................................................................................45 . 3.2 Use The CardLayout manager........................................................................................45 . 3.3 Detect which card is visible with a CardLayout................................................................47 3.4 Use Popups.....................................................................................................................47 3.5 Use a File Dialog ..............................................................................................................49 3.6 Use TrueType font...........................................................................................................50 3.7 Display available fonts.....................................................................................................51 3.8 Font with 3D effect...........................................................................................................52 3.9 Use the System Clipboard...............................................................................................52 3.10 Maximize a Frame.........................................................................................................53 3.11 Center a Frame/Dialog ...................................................................................................54 3.12 Close a Frame...............................................................................................................55 3.13 Call events on a Frame from a Panel............................................................................56 3.14 Set the small topleft icon on a Frame..........................................................................58 3.15 Prevent a Frame to be resized .......................................................................................59 3.16 Embed an image into a Frame .......................................................................................60 3.17 Display a message box..................................................................................................62 3.18 Display a Splash screen................................................................................................63 3.19 Vibrate a Window...........................................................................................................65 3.20 Limit TextField input to numeric value...........................................................................67 3.21 Limit TextField input to a maximum length....................................................................69 3.22 React to the ENTER key in a Textfield..........................................................................70 3.23 Make the ENTER key act like the TAB key ....................................................................70 3.24 Reset all textfields in one shot.......................................................................................71 3.25 Limit a TextField to Uppercase......................................................................................72 3.26 Have an ImageButton....................................................................................................73 3.27 Reset a checkbox group................................................................................................76 3.28 Set the listbox width.......................................................................................................76 3.29 Align the column in a List...............................................................................................77 3.30 Have a srolling text display............................................................................................77 3.31 Label dynamic resizing..................................................................................................78 3.32 Make a TextArea "wordwrap"......................................................................................80 3.33 Synchronize a TextArea vs a Choice.............................................................................80 3.34 Display underlined text..................................................................................................80 . 3.35 Display vertical text........................................................................................................81 3.36 Have Label with many lines...........................................................................................82 3.37 Have a Label with underlined text..................................................................................86 3.38 Have a Label acting as HTML HREF (URLLabel).........................................................87 3.39 Display a GIF in a Canvas.............................................................................................88 3.40 Embed an image into a Frame .......................................................................................89 3.41 Load several images from a single GIF.........................................................................91 3.42 Load an Image from a JAR file......................................................................................92 3.43 Load an Icon from a jar (again)......................................................................................93 3.44 Scale an Image..............................................................................................................94 3.45 Fade an image...............................................................................................................95 3.46 Rotate an image .............................................................................................................97

Real's [email protected] AWT 3.47 Create a scrollable canvas .............................................................................................99 3.48 Use an Image as the Applet background.....................................................................103 3.49 Have a simple Image browser.....................................................................................104 3.50 Simulate a "mouse over" event to toggle an image.....................................................107 3.51 Hide the mouse cursor.................................................................................................108 3.52 Make a color transparent.............................................................................................109 3.53 Save an Image as a GIF or JPEG file..........................................................................110 3.54 Use the same background color as the browser .........................................................111 . 3.55 Do simple animation using Images..............................................................................112 3.56 Do simple animation to show "work in progress".........................................................113 3.57 Get the color of a specific pixel....................................................................................114 3.58 Do "rubberband" drawing ...........................................................................................115 3.59 Convert RGB value to Hexadecimal (to be used in HTML for example) .....................117 . 3.60 Draw a line or set a pixel in my own image ..................................................................117 3.61 Draw a dashed line......................................................................................................118 3.62 Draw a line with a thickness .........................................................................................119 3.63 Draw a pie chart...........................................................................................................121 3.64 Draw faster rectangles.................................................................................................123 3.65 Get a screen capture and save it as a JPEG...............................................................124 3.66 Display a TIF................................................................................................................124 3.67 Convert a multipage TIF into singlepage TIF ...........................................................126 3.68 Convert an Image to a BufferedImage.........................................................................127 3.69 Detect a double click vs simple click............................................................................128 3.70 Detect the mouse button used when clicking ...............................................................129 3.71 Exit an application from a menu ...................................................................................130 3.72 Trigger a click on a Button...........................................................................................131 4 Environment ................................................................................................................................133 4.1 javaenv........................................................................................................................133 4.2 Read environment variables from an application...........................................................133 4.3 Retrieve environment variables (JDK1.5)......................................................................137 4.4 Retrieve environment variable (JNI)..............................................................................137 4.5 Use a MAKE file.............................................................................................................138 4.6 Detect the browser/JVM type.........................................................................................139 4.7 Fix the "Wrong magic number" error message..............................................................141 4.8 Use a precompiler " la C" with Java.............................................................................141 4.9 Open source packages..................................................................................................141 4.10 Ant...............................................................................................................................141 . 4.11 Simple boolean flag.....................................................................................................142 4.12 Determine what are the classes actually used in a Java Applet or application ............143 4.13 Set the memory available to the JVM..........................................................................143 4.14 Generate the Javadoc "en franais"............................................................................143 4.15 Use JDK1.5 new features............................................................................................145 4.16 Check the class version...............................................................................................145 4.17 Get the system properties or the JVM uptime ..............................................................147 4.18 Detect if running in a 64bit JVM...................................................................................147 4.19 Set the default JVM type..............................................................................................148 4.20 Capture the output of JAVAC .......................................................................................149 4.21 Freeze the JVIEW window in MS VJ++.......................................................................150

4.22 Wrap a Java beans in a COM object

Real's [email protected] Environment 4.22 Wrap a Java beans in a COM object...........................................................................150 4.23 Know details about the JAVA at runtime...................................................................151 4.24 Detect the Microsoft JVM version installed..................................................................153 4.25 Run JAVA as a Windows service .................................................................................153 4.26 Execute a class from Windows Explorer .....................................................................153 . 4.27 Create an icon to launch java apps for Windows?.......................................................155 4.28 Fix the "out of environment" error when setting a new CLASSPATH..........................155 4.29 Query Windows registry...............................................................................................156 4.30 Quickly retrieve available Java JVM on a workstation (Windows)...............................158 4.31 Get the Windows "My Documents" path......................................................................159 4.32 Get a return code from a VBS ......................................................................................160 4.33 List currently running processes (Windows)................................................................161 4.33.1 Using TASKLIST.EXE .........................................................................................161 4.33.2 Using a VBS ........................................................................................................162 4.34 Check if a program or process is running (Windows)..................................................163 4.35 Windows registry vs. Java JDK/JRE installation..........................................................164 4.36 Create a Taglet to document database access (Javadoc) ..........................................165 . 4.36.1 newMethod .........................................................................................................165 4.37 Generate the Javadoc "en franais"............................................................................169 4.38 Document a package using Javadoc...........................................................................170 4.39 Display a comment in a Javadoc.................................................................................171 4.40 Display XML in a javadoc .............................................................................................172 4.41 Add a copyright notice to a Javadoc............................................................................172 4.42 Use a Log file...............................................................................................................173 4.43 Trace the execution.....................................................................................................175 4.44 Time the execution .......................................................................................................177 4.45 Log information efficiently (with Log4J).......................................................................178 . 4.46 Change the logging level onthefly (Log4J)..............................................................179 4.47 Use a JAR/ZIP/CAB file with an Applet.......................................................................180 . 4.48 Make ZIP/JAR file always accessible from applet.......................................................182 4.49 Make a JAR executable...............................................................................................182 4.50 Accessing jars from within a jar...................................................................................184 4.51 Access a JAR outside the CLASSPATH ......................................................................184 4.52 Extract a file from a Jar................................................................................................185 4.53 Determine if running from JAR .....................................................................................186 4.54 Get list of classes in package (in a Jar).......................................................................187 4.55 Add version to Jar packaging .......................................................................................188 4.56 Use ANT to Build a JAR with version/build number.....................................................190 4.57 Include all jars in the classpath definition .....................................................................193 4.58 Windows batch file.......................................................................................................194 4.59 JDK6............................................................................................................................194 4.60 JAR (and ANT)............................................................................................................195 . 4.61 Detect the browser/JVM type.......................................................................................196 4.62 Detect if Java is enabled from HTML...........................................................................198 4.63 See the Java Console Window Log (Java plugin).......................................................198 5 Internationalization .....................................................................................................................200 5.1 javainter.......................................................................................................................200 5.2 Load resources based upon client environment at startup............................................200

Real's [email protected] Internationalization 5.3 Load resources dynamically..........................................................................................203 5.4 Load resources via a resources file...............................................................................206 5.5 Display "special character" using Unicode .....................................................................210 5.6 Display chinese/japanese characters............................................................................211 5.7 Localize a JOptionPane dialog......................................................................................211 5.8 Validate/Convert a number using the current Locale()..................................................213 5.9 Localize a JFileChooser................................................................................................214 . 5.10 Disable localization......................................................................................................216 5.11 Generate the Javadoc "en franais"............................................................................217 5.12 Sort a String array........................................................................................................218 5.13 Accentuated characters in Properties/ResourceBundle file.........................................220 5.14 Compare accentuated letters.......................................................................................220 5.15 Unaccent letters...........................................................................................................221 5.16 Output french characters to the console......................................................................224 5.17 Get the default character set of the JVM.....................................................................225 5.18 Convert OEM (DOS) file to Ansi (Windows)................................................................225 5.19 Detect nonASCII character in a String.......................................................................226 6 IO..................................................................................................................................................228 6.1 javaio...........................................................................................................................228 6.2 Redirect output(stdout/stderr) to a frame.......................................................................228 6.3 Redirect printStackTrace() to a String ............................................................................229 6.4 Output french characters to the console........................................................................230 6.5 Clear the console and control attributes........................................................................231 6.6 Print text to a printer easily............................................................................................232 6.7 Print without a Dialog.....................................................................................................232 6.8 Simple input from the keyboard.....................................................................................233 6.9 Initialize and write to a serial port..................................................................................234 . 6.10 Redirect to a NULL device...........................................................................................235 6.11 Get the volume label....................................................................................................235 6.12 Easy keyboard input (JDK1.5).....................................................................................236 6.13 Open or close a CD/DVD drive....................................................................................236 6.14 Get faster console output (System.out.println() replacement).....................................238 6.15 Execute an external program.......................................................................................239 6.16 Using Runtime.exec()..................................................................................................239 6.17 Launch a Windows CMD (or BAT) file and retrieve the errorlevel or exitcode .............240 6.18 Launch a Unix script....................................................................................................241 6.19 Using the ProcessBuilder............................................................................................241 . 6.20 Windows rundll32 utility...............................................................................................242 6.21 PDF (Windows only)....................................................................................................242 6.22 PDF (Mac only)............................................................................................................242 6.23 Path to executable with spaces in them .......................................................................243 6.24 VBSCRIPT...................................................................................................................243 6.25 HTML Help (Windows only).........................................................................................243 6.26 Start Excel...................................................................................................................243 . 6.27 Start a Windows application under another account...................................................244 . 6.28 Windows : execute something in Program Files..........................................................245 6.29 Launch the application associated with a file extension..............................................245 6.30 Launch an application from another application..........................................................246

6.31 Start the default browser from an application

Real's [email protected] IO 6.31 Start the default browser from an application..............................................................248 6.32 Execute a Windows Shortcut (.lnk)..............................................................................250 6.33 Create a file association with a Java program.............................................................250 6.34 Capture the output from a VBS....................................................................................252 6.35 Get a return code from a VBS ......................................................................................253 6.36 Execute a CMD file stored in a JAR .............................................................................254 6.37 Read the content of a file.............................................................................................255 6.38 Read a text file from a jar.............................................................................................257 6.39 Extract a file from a Jar................................................................................................260 6.40 Read a data file with floats...........................................................................................261 6.41 Write to the end of a file...............................................................................................262 6.42 Write "real" ascii file.....................................................................................................263 6.43 Copy a file....................................................................................................................264 6.44 Use a "log file" ..............................................................................................................266 6.45 Delete files with a certain extension .............................................................................267 6.46 Insert a line in a file......................................................................................................268 6.47 Read a file into a variable in one shot..........................................................................269 6.48 Serialize an object to a file...........................................................................................269 6.49 Redirect stdout to a file................................................................................................271 6.50 Get the "last modified" date from a file .........................................................................271 6.51 Check if a file exists.....................................................................................................271 6.52 Detect file modification.................................................................................................272 6.53 File/directory polling to detect change.........................................................................274 6.54 jpoller (directory poller)................................................................................................274 6.55 JNotify..........................................................................................................................274 6.56 Java Native Access (JNA)...........................................................................................275 6.57 Call native methods in a DLL from Java (NativeCall)..................................................275 6.58 Java 7..........................................................................................................................275 6.59 The simple (and naive!) approach...............................................................................275 6.60 Get the current directory..............................................................................................275 6.61 Get the "root" of an application....................................................................................276 6.62 Get the content of a directory with a Filter...................................................................276 6.63 Get the content of a directory with subdirectories........................................................278 6.64 Make a directory..........................................................................................................279 6.65 Create a fixedlength file.............................................................................................280 6.66 Delete a nonempty directory......................................................................................280 6.67 Create a temporary file................................................................................................281 6.68 Get the default character set of the JVM.....................................................................282 6.69 Parse a pathname ........................................................................................................282 6.70 Handle Excel files........................................................................................................283 6.71 JDBCODBC Excel driver...........................................................................................283 6.72 JExcel..........................................................................................................................283 6.73 POI...............................................................................................................................284 6.74 JXLS............................................................................................................................285 6.75 xlSQL...........................................................................................................................285 6.76 JCOM...........................................................................................................................286 6.77 OpenXLS Java Spreadsheet SDK...............................................................................287 6.78 Handle CSV file ............................................................................................................289 6.79 com.Ostermiller.util CSV Utils......................................................................................289

Real's [email protected] IO 6.80 opencsv ........................................................................................................................289 6.81 ServingXML.................................................................................................................289 6.82 Super CSV...................................................................................................................289 6.83 csvreader.....................................................................................................................289 6.84 CSVFile........................................................................................................................289 6.85 FlatPack.......................................................................................................................289 6.86 Create an Excel file......................................................................................................290 6.87 Create or process a PDF file ........................................................................................290 6.88 Create a PDF...............................................................................................................292 6.89 iText.............................................................................................................................292 6.90 Convert OEM (DOS) file to Ansi (Windows)................................................................293 6.91 Close a stream in a try/catch block..............................................................................294 6.92 Rename a file extension..............................................................................................295 6.93 Remove HTML tags from a file to extract only the TEXT .............................................295 6.94 Using regular expression.............................................................................................296 6.95 Using javax.swing.text.html.HTMLEditorKit.................................................................296 6.96 Get the Mime Type from a File....................................................................................297 6.96.1 Using javax.activation.MimetypesFileTypeMap..................................................297 6.96.2 Using java.net.URL.............................................................................................298 6.96.3 Using JMimeMagic ..............................................................................................298 6.96.4 Using mimeutil..................................................................................................298 6.96.5 Using Droid.........................................................................................................299 6.96.6 Aperture framework .............................................................................................299 6.97 Sort a directory listing..................................................................................................299 6.98 Filter a directory listing by date....................................................................................300 6.99 Display a comment in a Javadoc.................................................................................301 6.100 Create a compressed (ZIP) file..................................................................................302 6.101 Display compressed (ZIP) file content.......................................................................303 6.102 Expand the compressed (ZIP) file ..............................................................................304 6.103 Emit a beep................................................................................................................305 6.104 Emit a Tone ................................................................................................................305 6.105 Play an audio file from an application........................................................................306 7 JDBC............................................................................................................................................308 7.1 javajdbc ........................................................................................................................308 7.2 Connect to a database via JDBCODBC......................................................................308 7.3 SELECT data from a table.............................................................................................309 7.4 INSERT data into a table...............................................................................................310 7.5 MODIFY data in a table.................................................................................................311 7.6 DELETE data in a table.................................................................................................312 7.7 Test for an empty ResultSet..........................................................................................312 7.8 Store and retrieve an object from a table.......................................................................313 7.9 Retrieve an Image ..........................................................................................................315 7.10 Insert an Image............................................................................................................315 7.11 Connect to an Oracle database with JDBC.................................................................315 7.12 Connect to Oracle using a connection pool.................................................................316 7.13 Get JDBC driver for major database vendors..............................................................319 7.14 Handle dates................................................................................................................319 7.15 Call a stored procedure ................................................................................................320

7.16 Stored procedure with Input/Output parms and a ResultSet

Real's [email protected] JDBC 7.16 Stored procedure with Input/Output parms and a ResultSet.......................................321 7.17 Fix incomplete field returned by the ResultSet............................................................322 7.18 Get a record count with a SQL Statement...................................................................322 7.19 Transfer a ResultSet to a JTable.................................................................................323 7.20 List tables in a database..............................................................................................323 7.21 Display ResultSet data in an HTML Table in Servlet...................................................324 7.22 Detect SQL errors or warnings....................................................................................325 7.23 Using DSNless connection........................................................................................326 7.24 Read data from Excel worksheet.................................................................................327 7.25 Handle Excel files........................................................................................................329 7.26 JDBCODBC Excel driver...........................................................................................329 7.27 JExcel..........................................................................................................................329 7.28 POI...............................................................................................................................330 7.29 JXLS............................................................................................................................330 7.30 xlSQL...........................................................................................................................331 7.31 JCOM...........................................................................................................................331 7.32 OpenXLS Java Spreadsheet SDK...............................................................................333 7.33 Specify a CharSet when connecting to a DBMS ..........................................................334 7.34 Get current date using JDBC.......................................................................................335 7.35 Enable JDBC logging...................................................................................................335 7.36 Detect if a table exists..................................................................................................337 7.37 Convert a ResultSet to XML........................................................................................337 7.38 Escape special character in a LIKE clause..................................................................339 7.39 Insert the current date..................................................................................................340 7.40 Log the SQL Statements ..............................................................................................340 7.41 Plain JDBC Logging.....................................................................................................340 7.42 P6Spy..........................................................................................................................340 7.43 Proxool.........................................................................................................................341 8 JNI................................................................................................................................................342 8.1 javajni ..........................................................................................................................342 . 8.2 Use native code through JNI.........................................................................................342 . 8.3 Pass a string to/from Java to/from C ..............................................................................342 8.4 Set the computer clock..................................................................................................344 8.5 Determine the signature of a method .............................................................................344 8.6 Use arrays ......................................................................................................................346 8.7 Load a DLL....................................................................................................................347 8.8 Use the MouseWheel....................................................................................................347 . 8.9 Throw an Exception (from JNI code).............................................................................347 8.10 Throw my own Exception (from JNI code)...................................................................348 8.11 JNI from a package......................................................................................................349 8.12 Make a Window "stay on top"......................................................................................349 8.13 Start a JVM from C......................................................................................................350 8.14 Retrieve environment variable (JNI)............................................................................351 8.15 Get the PID..................................................................................................................351 8.16 Clear the console, set color and cursor position (JNI).................................................352 8.17 Call Windows API (Open source solution)...................................................................355

Real's [email protected] Javascript interaction .................................................................................................................356 9.1 javajs ............................................................................................................................356 9.2 * Read me * ....................................................................................................................356 9.3 Wakeup a Java applet.................................................................................................356 9.4 Call a Java method from Javascript...............................................................................358 9.5 Calling Java applets methods using DOM and JavaScript............................................360 9.6 Access Java variables from Javascript..........................................................................360 9.7 Call Javascript from a Java applet.................................................................................361 9.8 Create dynamic HTML from a Java applet....................................................................364 9.9 Have Applets on different frames communicates with each other.................................365 9.10 Send a message from an Applet to another Applet on a different page......................366 9.11 Retrieve values from a Java applet for HTML form (CGI) ...........................................368 . 9.12 Detect if an Applet is ready..........................................................................................369 9.13 Read/Write HTML field values from JAVA...................................................................370 9.14 Detect if Java is enabled..............................................................................................372 9.15 Detect if Java 1.1 (with event delegation) is available.................................................372 9.16 Access Cookies from a Java Applet............................................................................372 9.17 Set Applet PARAM VALUE from javascript.................................................................375 9.18 Pass an Array between Java and Javascript...............................................................376 9.19 Interaction without LiveConnect...................................................................................378 9.20 Directory listing on the Web server in a Java Applet...................................................382 9.21 Have a Java button close the browser window............................................................384 9.22 Detect if cookies are enabled .......................................................................................385 9.23 Display a page after all applets are loaded..................................................................386 10 Servlet/JSP................................................................................................................................387 10.1 javajsp ........................................................................................................................387 10.2 Read me......................................................................................................................387 10.3 Get parameters passed to a servlet.............................................................................387 10.4 Detect no argument condition in a Servlet...................................................................388 10.5 Set a Cookie from a servlet.........................................................................................389 . 10.6 Read a Cookie from a servlet......................................................................................389 10.7 Delete (or expire) a Cookie from a servlet...................................................................390 10.8 Ask for a password from a Servlet...............................................................................390 10.9 Talk to a CGI/Servlet...................................................................................................390 . 10.10 Test for Cookies.........................................................................................................391 10.11 Display ResultSet data in an HTML Table in Servlet.................................................392 10.12 Specify the filename to be used for a file sent by a Servlet.......................................393 10.13 Pass information to another servlet/jsp......................................................................393 10.14 Handle PDF output....................................................................................................394 10.15 Detect if the connection is via a secure channel........................................................394 10.16 In a Servlet, check if Form Field is present................................................................394 10.17 Get the root dir of a web app.....................................................................................395 10.18 Get client IP address from JSP..................................................................................395 10.19 Output a binary stream from a JSP ............................................................................395 10.20 Use a connection cache from JSP.............................................................................396 10.21 Read a Web Application property..............................................................................397 10.22 Use EJB from JSP.....................................................................................................398 10.23 Define a method in a JSP page.................................................................................398 10.24 Precompile JSP pages ...............................................................................................399

10.25 Get a list of directories for JSP

Real's [email protected] Servlet/JSP 10.25 Get a list of directories for JSP..................................................................................400 10.26 Use and share a class in JSP pages.........................................................................400 10.27 Get the root dir of a web app.....................................................................................402 10.28 Launch an applet from a JSP .....................................................................................402 10.29 Prevent caching of a JSP output...............................................................................403 . 10.30 Call another EJB........................................................................................................403 10.31 Keep java files generated from JSP (BEA WLS).......................................................404 10.32 Get the server version (BEA WLS)............................................................................404 10.33 Quickly create a Web application with BEA WLS......................................................405 10.34 Nicely display WEB.XML informations.......................................................................405 10.35 Reverse the CLASSLOADER order (BEA)................................................................406 10.36 Detect change in JSP and recompile (BEA)..............................................................407 11 Language ...................................................................................................................................408 11.1 javalanguage.............................................................................................................408 11.2 * Read me * ..................................................................................................................408 11.3 Obtain from where a Class is loaded...........................................................................409 11.4 Get the class name in a static method.........................................................................410 11.5 Get the current method name......................................................................................410 11.6 Call a method dynamically (Reflection) .......................................................................411 . 11.7 Detect if a package is available...................................................................................413 11.8 Create an object from a string ......................................................................................414 11.9 Get a variable value from the variable name...............................................................415 11.10 Make methods that have unspecified number of parameters....................................416 11.11 Create a java source dynamically, compile and call..................................................417 11.12 Launch an application from another application........................................................418 11.13 Access the enclosing class from an inner class .........................................................419 11.14 Access inner class from outside................................................................................420 11.15 Use globally defined constants..................................................................................421 11.16 Serialize an Object.....................................................................................................422 11.17 Serialize an Object over a socket..............................................................................424 11.18 Easily remove my debugging code............................................................................424 11.19 Have a singleton........................................................................................................425 11.20 Multiple expressions in for loops................................................................................426 11.21 Handle the List conflict...............................................................................................426 11.22 Use a generic toString().............................................................................................426 11.23 Use Object.clone().....................................................................................................428 11.24 Static field, constructor and exception.......................................................................429 11.25 Use a Label break......................................................................................................430 11.26 Put printStackTrace() into a String.............................................................................431 11.27 Use a Hashtable........................................................................................................431 11.28 Scan the content of a hashtable................................................................................432 11.29 Sort an array..............................................................................................................432 11.30 Initialize multidimensional array.................................................................................434 11.31 Get array upperbound................................................................................................434 11.32 Convert a String to an array.......................................................................................435 11.33 Sort in reverse order..................................................................................................436 11.34 Resize an array..........................................................................................................436 11.35 Dump array content...................................................................................................437

Real's [email protected] Language 11.36 Initialize a static array................................................................................................438 11.37 Sort an Hashtable......................................................................................................439 11.38 Eliminate "[unchecked] unchecked call ..." compiler warning....................................440 12 ANT............................................................................................................................................442 12.1 Sort on many fields......................................................................................................442 12.2 Optimize Collection usage...........................................................................................444 12.3 Sort an HashMap.........................................................................................................446 12.4 Get a key from value with an HashMap.......................................................................446 12.5 Iterate a Collection and remove an item......................................................................447 12.6 Count distinct elements in a Vector.............................................................................448 12.7 Dump the content of a Collection (JDK 1.5)................................................................450 . 12.8 Use an INI file (properties)...........................................................................................450 12.9 Load a properties file...................................................................................................452 12.10 Accentuated characters in Properties/ResourceBundle file.......................................452 12.11 Have a multiline value in a properties file................................................................453 12.12 Use XML with Properties...........................................................................................453 12.13 Use the Registry to store informations (Preferences API).........................................454 12.14 Sort Properties when saving......................................................................................455 13 Networking................................................................................................................................457 13.1 javanet.......................................................................................................................457 13.2 Extract network card address......................................................................................457 13.3 Get the workstation name/ip........................................................................................459 13.4 Find port number not in use.........................................................................................461 13.5 Disable DNS caching...................................................................................................461 13.6 Encode/Decode to/from Base64..................................................................................462 13.7 Using javax.mail.internet.MimeUtility...........................................................................463 13.8 Using Apache Commons Codec..................................................................................463 13.9 MiGBase64..................................................................................................................464 13.10 Lookup using MX record to validate mail server........................................................464 13.11 Send an email using the SMTP protocol...................................................................472 . 13.12 Check if there is mail waiting.....................................................................................474 13.13 Receive email............................................................................................................475 13.14 Send email with an attachment..................................................................................477 13.15 Send email with JavaMail..........................................................................................483 13.16 Send email with authentication..................................................................................485 13.17 Send HTML mail with images (Javamail) ..................................................................486 . 13.18 Debug a Javamail Program.......................................................................................488 13.19 Send email with SMTPS (eg. Google GMail) (Javamail)...........................................489 13.19.1 Settings for well known mail providers..............................................................490 13.20 Mix plain text and HTML content in a mail.................................................................490 13.21 Read an Outlook MSG file.........................................................................................491 13.22 msgparser..................................................................................................................491 13.23 Apache POI HSMF....................................................................................................492 13.24 jmbox.........................................................................................................................492 13.25 Handle EML file with JavaMail...................................................................................492 13.26 Check if a file was modified on the server.................................................................493 13.27 Check if a page exists................................................................................................494

13.28 Connect through a Proxy

Real's [email protected] Networking 13.28 Connect through a Proxy...........................................................................................495 13.29 Identify yourself using HTTP Authentification............................................................498 13.30 Talk to a CGI/Servlet.................................................................................................500 . 13.31 Write/Read cookies using HTTP................................................................................501 13.32 Read a GIF or CLASS from an URL save it locally ....................................................503 13.33 Resolve a relative URL..............................................................................................504 13.34 File size from URL.....................................................................................................505 13.35 Use the HTTPS protocol............................................................................................505 13.36 Fetch a page from Google.........................................................................................506 13.37 Upload a file to a server.............................................................................................507 13.38 Connect through a Proxy...........................................................................................507 13.39 Have timeout on socket connection...........................................................................510 13.40 Ping a server..............................................................................................................510 13.41 Get the Date from server...........................................................................................511 13.42 Get the client IP address ............................................................................................512 13.43 Use the java.net.Socket.setSoLinger method............................................................512 13.44 Use the java.net.Socket.setTcpNoDelay method......................................................513 13.45 Find out who is accessing my ServerSocket.............................................................513 13.46 Transfer a file via Socket...........................................................................................513 14 Security ......................................................................................................................................516 14.1 javasecurity................................................................................................................516 14.2 Encrypt a password.....................................................................................................516 14.3 Create a checksum......................................................................................................518 14.4 Get the user name.......................................................................................................521 14.5 Get username using NT Challenge (NTLM)................................................................521 14.6 Check if the current user belongs a specific Windows group/role...............................523 14.7 Prompt for password from the console........................................................................523 14.8 Prevent XSS exploit.....................................................................................................524 14.9 Sanitize the input by removing suspicious tags...........................................................525 14.10 Sanitize the output by removing suspicious characters.............................................525 14.11 Display a simple username/password Dialog from an Applet....................................526 15 Swing.........................................................................................................................................529 15.1 javaswing...................................................................................................................529 15.2 * Read me * ..................................................................................................................529 15.3 Change component default font...................................................................................529 15.4 Repaint problem under the mouse cursor (JDK1.2)....................................................530 15.5 Set the LookAndFeel...................................................................................................530 15.6 Use any LookAndFeel on any plateform......................................................................530 15.7 Use a Timer.................................................................................................................531 15.8 Share ActionEvent handler..........................................................................................531 15.9 Get default values for Swingbased user interface.....................................................533 15.10 Have a systray icon (Windows) .................................................................................534 . 15.11 Close a JFrame under condition................................................................................536 15.12 Maximize a JFrame ....................................................................................................537 15.13 Capture System.out into a JFrame............................................................................538 15.14 Remove the titlebar of JInternalFrame .......................................................................540 15.15 Have borders on a JWindow/JFrame .........................................................................540

Real's [email protected] Swing 15.16 Display HTML in a JScrollPane.................................................................................541 15.17 Use a JOptionPane....................................................................................................542 15.18 Localize a JOptionPane dialog..................................................................................543 15.19 Customize JOptionPane buttons...............................................................................545 15.20 Localize a JFileChooser............................................................................................545 . 15.21 Select a directory with a JFileChooser ......................................................................548 . 15.22 Disable the JFileChooser's "New folder" button .........................................................549 15.23 Validate a filename from a JFileChooser...................................................................550 15.24 Make a JFrame looks like a JDialog..........................................................................552 15.25 Based on JTextField content, enable or disable a JButton........................................553 15.26 Apply special filter to a JtextField ...............................................................................553 15.27 Limit JTextField input to a maximum length ...............................................................556 15.28 Validate a value on the lostFocus event....................................................................557 15.29 Make sure that my jTextfield has the focus when a JFrame is created.....................559 15.30 Stop the beep on JFormattedTextField ......................................................................560 15.31 Right justified JTextfield content................................................................................560 15.32 Set the focus on a particuliar JTextField....................................................................561 15.33 Make JTextField unselectable...................................................................................561 15.34 Use a JTree to navigate in a site...............................................................................562 15.35 Expand or collapse a JTree.......................................................................................568 15.36 Have a popup attached to a JTree .............................................................................570 15.37 Traverse a JTree ........................................................................................................572 15.38 Show dotted lines in a JTree ......................................................................................574 15.39 Explore directories with a JTree .................................................................................574 15.40 Prevent JTree collapsing...........................................................................................575 15.41 Single selection in a JTree.........................................................................................576 15.42 Reduce JTree children indentation............................................................................576 15.43 Use + or for JTree Icons.........................................................................................576 15.44 Change the JTable header color...............................................................................578 . 15.45 Double click on a JTable............................................................................................578 15.46 Read a data file into a JTable....................................................................................580 15.47 Disable row selection in a JTable..............................................................................583 15.48 Read a data file into a JTable and reload if data file have changed..........................583 15.49 Hide a column in JTable............................................................................................585 15.50 Scroll a JTable to the last row....................................................................................586 15.51 Transfer a ResultSet to a JTable...............................................................................587 15.52 Have on a JScrollPane/JTable an horizontal JScrollbar............................................587 15.53 Make a JList select an item on doubleclick or the ENTER key..................................588 15.54 Make a JList like a scrolling text display....................................................................589 15.55 Have images in a JList...............................................................................................590 15.56 Add a row and clear a JList.......................................................................................592 . 15.57 Sort a JList.................................................................................................................593 15.58 Double click on a JList...............................................................................................595 15.59 Have a PopUp on a JList...........................................................................................596 15.60 Make a JLabel selectable with the mouse.................................................................597 15.61 Change JLabel background color..............................................................................598 15.62 Bold / Unbold a JLabel...............................................................................................598 15.63 Multiline JLabel........................................................................................................598 15.64 Underline a string.......................................................................................................598

15.65 Update a JLabel

Real's [email protected] Swing 15.65 Update a JLabel.........................................................................................................599 15.66 Display a blinking JLabel...........................................................................................599 15.67 Set the cursor position in a JTextArea.......................................................................601 15.68 Have Multiline string in a JToolTip...........................................................................601 15.69 Change Tooltip color..................................................................................................602 15.70 Change a JTooltip font...............................................................................................602 15.71 Keep a JTooltip visible...............................................................................................603 15.72 Display icon associated with an executable ...............................................................603 15.73 Have items in JMenubar at rightmost position...........................................................605 15.74 Have an JButton with an Image.................................................................................606 15.75 Trigger a click on a Button.........................................................................................607 16 Thread ........................................................................................................................................609 16.1 javathread..................................................................................................................609 16.2 Pipe the output of a thread to the input of another one ................................................609 16.3 Pipe the output of a thread to the input of other threads ..............................................611 16.4 Wait the for the completion of a thread........................................................................613 16.5 Control a thread from outside......................................................................................614 16.6 Create a Timer object..................................................................................................615 16.7 Pause the execution....................................................................................................616 16.8 Execute a method at a specified time interval.............................................................616 16.9 Execute a process at regular interval..........................................................................618 . 16.10 Handle concurrent read/write.....................................................................................619 16.11 Communicate between threads using a Queue.........................................................620 16.12 Get a unique identifier................................................................................................625 16.13 Using java.rmi.dgc.VMID...........................................................................................625 16.14 Using java.util.UUID...................................................................................................625 16.15 Using Apache commons............................................................................................626 16.16 Using java.util.concurrent.AtomicLong .......................................................................626 17 Varia...........................................................................................................................................627 17.1 javavaria....................................................................................................................627 17.2 Use System time to generate unique ID......................................................................627 17.3 Get a unique identifier..................................................................................................627 17.4 Using java.rmi.dgc.VMID.............................................................................................627 17.5 Using java.util.UUID.....................................................................................................628 17.6 Using Apache commons..............................................................................................628 17.7 Using java.util.concurrent.AtomicLong .........................................................................628 17.8 Get the hard disk serial number or Motherboard serial number..................................629 17.9 Motherboard serial number..........................................................................................629 17.10 Hard disk serial number.............................................................................................630 17.11 Sort an array..............................................................................................................631 17.12 Sort a String array......................................................................................................632 17.13 Do a selection sort.....................................................................................................634 17.14 Validate a Social Security Number (canadian)..........................................................635 17.15 Validate a Credit Card Number..................................................................................636 17.16 Obtain from where a Class is loaded.........................................................................639 17.17 Get the class name with or without the package.......................................................640 17.18 See the generated bytecode......................................................................................641

Real's [email protected] Varia 17.19 Self replicating programs...........................................................................................644 17.20 A curiosity (strange Java code).................................................................................645 . 17.21 Classic bugs ...............................................................................................................646 17.22 Number of the beast!.................................................................................................647 17.23 Preventing multiple instances of an application.........................................................648 17.24 Trap JVM shutdown...................................................................................................651 17.25 Use Java scripting engine (JDK 1.6).........................................................................651 . 18 XML............................................................................................................................................653 18.1 javaxml ......................................................................................................................653 . 18.2 Read me......................................................................................................................653 18.3 Display XML using plain HTML....................................................................................654 18.4 Transform XML into HTML using XSLT.......................................................................655 18.5 Parse using SAX or DOM............................................................................................656 18.6 Parse an XML string....................................................................................................658 18.7 Create an XML document with DOM...........................................................................659 18.8 Attach a stylesheet to an XML file ................................................................................661 18.9 Create an XML file and attach an XSL .........................................................................662 18.10 Nicely display WEB.XML informations.......................................................................665 18.11 Serialize an object using XML ....................................................................................666 18.12 Convert a flat file to XML (SAX).................................................................................667 18.13 Convert a flat file to XML (DOM)................................................................................669 18.14 Convert a ResultSet to XML......................................................................................672 18.15 Parse with XPath.......................................................................................................674 18.16 Strip extra spaces in a XML string.............................................................................675 18.17 Create an XML file and attach an XSL .......................................................................676 18.18 Use XML with Properties...........................................................................................679 18.19 Change a particular node in XML..............................................................................680 18.20 Create a RSS feed (part 1)........................................................................................681 18.20.1 RSS 2.0 .............................................................................................................681 18.20.2 Atom ..................................................................................................................682 18.20.3 Creating a feed ..................................................................................................683 18.20.4 Creating a feed with Apache Commons Digester.............................................683 18.20.5 Creating a feed with Rome ................................................................................685 18.21 Creating an RSS Feed (part 2)..................................................................................686 18.22 Parse a RSS XML file................................................................................................692 18.22.1 Parsing a feed with Apache Commons Digester..............................................692 . 18.22.2 P