Realhowto Java
Realhowto Java
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
real@rgagnon.com
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 ( real@rgagnon.com )
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 HowTo@www.rgagnon.com
1 Applet...............................................................................................................................................1
1.1 javaapplet........................................................................................................................1
1.2 Goto to a new URL from an AppletTag(s): Applet.............................................................1
1.3 Determine the host from where the Applet is loadedTag(s): Applet..................................3
1.4 Have a scrolling status lineTag(s): Applet..........................................................................3
1.5 Use a search engineTag(s): Applet...................................................................................5
1.6 Have an onscreen clockTag(s): Applet............................................................................6
1.7 Have Applets on the same page communicate with each otherTag(s): Applet.................8
1.8 Have Applets on different frames communicates with each otherTag(s): Applet..............9
1.9 Send a message from an Applet to another Applet on a different pageTag(s): Applet....11
1.10 Have an applet launch an other appletTag(s): Applet....................................................13
1.11 Get the user nameTag(s): Applet Security.....................................................................14
1.12 Access parameters passed in the URLTag(s): Applet...................................................15
1.13 Convert an Applet to Application Tag(s): Applet............................................................17
1.14 Change the mouse cursor in AppletTag(s): Applet........................................................18
1.15 Use an Image as the Applet backgroundTag(s): Applet AWT.......................................19
1.16 Handle the new Control Activation mechanism in IETag(s): Applet...............................20
1.16.1 Solution #1............................................................................................................20
1.16.2 Solution #2............................................................................................................21
1.16.3 Solution #3............................................................................................................22
1.17 Pass parameters to the Applet JVM (WIN)Tag(s): Applet.............................................23
1.18 See the Java Console Window Log (Java plugin)Tag(s): Applet Environment..............24
1.19 Display debugging infos for an AppletTag(s): Applet.....................................................24
1.20 Have an invisible Applet Tag(s): Applet.........................................................................25
1.21 Keep the JVM loadedTag(s): Applet..............................................................................25
1.22 Detect browser type from an AppletTag(s): Applet Environment Javascript
interaction.............................................................................................................................25
1.23 Call a Javascript from the Applet...................................................................................26
1.24 Get the value from the serverside................................................................................27
2 Date and Time...............................................................................................................................28
2.1 javadate.........................................................................................................................28
2.2 Have year on 4 digits from a Date objectTag(s): Date and Time.....................................28
2.3 Get the current Date and TimeTag(s): Date and Time....................................................28
2.4 Compute days between 2 datesTag(s): Date and Time..................................................29
2.5 Get the number of days in a monthTag(s): Date and Time..............................................31
2.6 Validate a dateTag(s): Date and Time.............................................................................31
2.6.1 Using DateFormat...................................................................................................31
2.6.2 Using GregorianCalendar.......................................................................................33
2.7 Determine to day of the weekTag(s): Date and Time......................................................33
2.8 Add/Substract Day/Month/Year to a DateTag(s): Date and Time....................................34
2.9 Get the correct TimeZone on DateFormatTag(s): Date and Time...................................35
2.10 Simply format a date as "YYYYMMDD"Tag(s): Date and Time.....................................35
2.11 Compare 2 datesTag(s): Date and Time.......................................................................36
2.12 Parse a String to obtain a Date/GregorianCalendar objectTag(s): Date and Time........37
2.13 Use System time to generate unique IDTag(s): Date and Time Date and Time
Varia.......................................................................................................................................38
2.14 Get the day nameTag(s): Date and Time......................................................................38
2.15 Find the current date formatTag(s): Date and Time.......................................................39
2.16 Get a julian dateTag(s): Date and Time.........................................................................40
Real's HowTo@www.rgagnon.com
2 Date and Time
2.17 Calculate the ageTag(s): Date and Time.......................................................................43
2.18 Format a duration in milliseconds into a humanreadable formatTag(s): Date and
Time......................................................................................................................................43
2.19 Get the atomic timeTag(s): Date and Time....................................................................46
2.20 Get a date intervalTag(s): Date and Time......................................................................48
2.21 Determine if an hour is between an intervalTag(s): Date and Time...............................50
2.22 Set the computer clockTag(s): Date and Time JNI........................................................51
2.23 Use System time to generate unique IDTag(s): Date and Time Date and Time
Varia.......................................................................................................................................52
2.24 Get the month (or day) name (localized)Tag(s): Date and Time Internationalization....52
2.25 Detect a leap yearTag(s): Date and Time......................................................................53
3 AWT................................................................................................................................................55
3.1 javaawt...........................................................................................................................55
3.2 Use The CardLayout managerTag(s): AWT....................................................................55
3.3 Detect which card is visible with a CardLayoutTag(s): AWT...........................................57
3.4 Use PopupsTag(s): AWT.................................................................................................58
3.5 Use a File DialogTag(s): AWT.........................................................................................60
3.6 Use TrueType fontTag(s): AWT.......................................................................................61
3.7 Display available fontsTag(s): AWT.................................................................................62
3.8 Font with 3D effectTag(s): AWT.......................................................................................62
3.9 Use the System ClipboardTag(s): AWT...........................................................................63
3.10 Maximize a FrameTag(s): AWT.....................................................................................64
3.11 Center a Frame/DialogTag(s): AWT..............................................................................65
3.12 Close a FrameTag(s): AWT...........................................................................................66
3.13 Call events on a Frame from a PanelTag(s): AWT........................................................68
3.14 Set the small topleft icon on a FrameTag(s): AWT......................................................70
3.15 Prevent a Frame to be resizedTag(s): AWT..................................................................70
3.16 Embed an image into a FrameTag(s): AWT AWT.........................................................72
3.17 Display a message boxTag(s): AWT.............................................................................74
3.18 Display a Splash screenTag(s): AWT............................................................................75
3.19 Vibrate a WindowTag(s): AWT......................................................................................77
3.20 Limit TextField input to numeric valueTag(s): AWT.......................................................79
3.21 Limit TextField input to a maximum lengthTag(s): AWT................................................81
3.22 React to the ENTER key in a TextfieldTag(s): AWT......................................................82
3.23 Make the ENTER key act like the TAB keyTag(s): AWT...............................................83
3.24 Reset all textfields in one shotTag(s): AWT...................................................................83
3.25 Limit a TextField to UppercaseTag(s): AWT..................................................................84
3.26 Have an ImageButtonTag(s): AWT................................................................................85
3.27 Reset a checkbox groupTag(s): AWT............................................................................88
3.28 Set the listbox widthTag(s): AWT...................................................................................89
3.29 Align the column in a ListTag(s): AWT...........................................................................90
3.30 Have a srolling text displayTag(s): AWT........................................................................90
3.31 Label dynamic resizingTag(s): AWT..............................................................................91
3.32 Make a TextArea "wordwrap"Tag(s): AWT..................................................................93
3.33 Synchronize a TextArea vs a ChoiceTag(s): AWT........................................................93
3.34 Display underlined textTag(s): AWT..............................................................................94
3.35 Display vertical textTag(s): AWT....................................................................................94
3.36 Have Label with many linesTag(s): AWT.......................................................................95
Real's HowTo@www.rgagnon.com
3 AWT
3.37 Have a Label with underlined text Tag(s): AWT............................................................99
3.38 Have a Label acting as HTML HREF (URLLabel)Tag(s): AWT...................................100
3.39 Display a GIF in a CanvasTag(s): AWT.......................................................................102
3.40 Embed an image into a FrameTag(s): AWT AWT.......................................................103
3.41 Load several images from a single GIFTag(s): AWT...................................................105
3.42 Load an Image from a JAR fileTag(s): AWT................................................................106
3.43 Load an Icon from a jar (again)Tag(s): AWT...............................................................107
3.44 Scale an ImageTag(s): AWT........................................................................................107
3.45 Fade an imageTag(s): AWT.........................................................................................109
3.46 Rotate an imageTag(s): AWT......................................................................................111
3.47 Create a scrollable canvasTag(s): AWT......................................................................113
3.48 Use an Image as the Applet backgroundTag(s): Applet AWT.....................................117
3.49 Have a simple Image browserTag(s): AWT.................................................................118
3.50 Simulate a "mouse over" event to toggle an imageTag(s): AWT.................................121
3.51 Hide the mouse cursorTag(s): AWT............................................................................123
3.52 Make a color transparentTag(s): AWT.........................................................................123
3.53 Save an Image as a GIF or JPEG fileTag(s): AWT.....................................................124
3.54 Use the same background color as the browserTag(s): AWT.....................................126
3.55 Do simple animation using ImagesTag(s): AWT..........................................................126
3.56 Do simple animation to show "work in progress"Tag(s): AWT.....................................128
3.57 Get the color of a specific pixelTag(s): AWT................................................................129
3.58 Do "rubberband" drawingTag(s): AWT......................................................................130
3.59 Convert RGB value to Hexadecimal (to be used in HTML for example)Tag(s):
AWT....................................................................................................................................132
3.60 Draw a line or set a pixel in my own imageTag(s): AWT.............................................133
3.61 Draw a dashed lineTag(s): AWT..................................................................................133
3.62 Draw a line with a thicknessTag(s): AWT....................................................................134
3.63 Draw a pie chartTag(s): AWT......................................................................................136
3.64 Draw faster rectanglesTag(s): AWT.............................................................................138
3.65 Get a screen capture and save it as a JPEGTag(s): AWT..........................................139
3.66 Detect a double click vs simple clickTag(s): AWT.......................................................140
3.67 Detect the mouse button used when clickingTag(s): AWT..........................................141
3.68 Exit an application from a menuTag(s): AWT..............................................................142
3.69 Trigger a click on a ButtonTag(s): AWT Swing............................................................143
3.70 Display a TIFTag(s): AWT...........................................................................................144
3.71 Convert a multipage TIF into singlepage TIFTag(s): AWT......................................146
3.72 Convert many singlepage TIF into one multipage TIF Tag(s): AWT.......................147
3.73 Convert an Image to a BufferedImageTag(s): AWT....................................................148
3.74 Detect if a TIF is blank Tag(s): AWT............................................................................149
3.75 Convert TIF to PDFTag(s): AWT IO IO Open Source..................................................152
3.76 Convert a TIF to a JPGTag(s): AWT............................................................................153
4 Environment................................................................................................................................155
4.1 javaenv........................................................................................................................155
4.2 Read environment variables from an applicationTag(s): Environment..........................155
4.3 Retrieve environment variables (JDK1.5)Tag(s): Environment......................................159
4.4 Retrieve environment variable (JNI)Tag(s): Environment JNI.......................................159
4.5 Use a MAKE fileTag(s): Environment............................................................................160
4.6 Detect the browser/JVM type (deprecated)Tag(s): Environment DEPRECATED.........161
Real's HowTo@www.rgagnon.com
4 Environment
4.7 Fix the "Wrong magic number" error messageTag(s): Environment.............................163
4.8 Use a precompiler " la C" with JavaTag(s): Environment............................................164
4.9 Open source packages..................................................................................................164
4.10 Ant................................................................................................................................164
4.11 Simple boolean flag.....................................................................................................165
4.12 Determine what are the classes actually used in a Java Applet or application
Tag(s): Environment............................................................................................................165
4.13 Set the memory available to the JVMTag(s): Environment..........................................166
4.14 Generate the Javadoc "en franais"Tag(s): Environment Environment
Internationalization...............................................................................................................166
4.15 Use JDK1.5 new featuresTag(s): Environment............................................................167
4.16 Check the class versionTag(s): Environment..............................................................168
4.17 Get the system properties or the JVM uptimeTag(s): Environment.............................169
4.18 Detect if running in a 64bit JVMTag(s): Environment..................................................170
4.19 Set the default JVM typeTag(s): Environment.............................................................171
4.20 Select a particular JRE from the command lineTag(s): Environment..........................172
4.21 Get the PID (pure Java solution)Tag(s): Environment.................................................173
4.22 Get the PIDTag(s): Environment JNI...........................................................................174
4.23 Set default value for java property (system wide)Tag(s): Environment.......................175
4.24 Detect if running in a debug modeTag(s): Environment..............................................176
4.25 Capture the output of JAVACTag(s): Environment......................................................176
4.26 Freeze the JVIEW window in MS VJ++Tag(s): Environment.......................................177
4.27 Wrap a Java beans in a COM objectTag(s): Environment...........................................177
4.28 Know details about the JAVA at runtimeTag(s): Environment...................................179
4.29 Detect the Microsoft JVM version installedTag(s): Environment.................................180
4.30 Run JAVA as a Windows serviceTag(s): Environment Open Source..........................181
4.31 Execute a class from Windows ExplorerTag(s): Environment.....................................181
4.32 Create an icon to launch java apps for Windows?Tag(s): Environment......................183
4.33 Fix the "out of environment" error when setting a new CLASSPATHTag(s):
Environment........................................................................................................................183
4.34 Query Windows registryTag(s): Environment..............................................................184
4.35 Read/Write the Registry (Windows)Tag(s): Environment............................................186
4.36 Quickly retrieve available Java JVM on a workstation (Windows)Tag(s):
Environment........................................................................................................................194
4.37 Using regedit................................................................................................................194
4.38 Using a CMD file..........................................................................................................195
4.39 Get a return code from a VBSTag(s): IO Environment................................................196
4.40 List currently running processes (Windows)Tag(s): Environment................................197
4.40.1 Using TASKLIST.EXE.........................................................................................197
4.40.2 Using a VBS........................................................................................................198
4.41 Check if a program or process is running (Windows)Tag(s): Environment..................199
4.42 Detect if a process is running using WMIC Tag(s): Misc Prog HowTo Java
Environment........................................................................................................................201
4.43 Windows registry vs. Java JDK/JRE installationTag(s): Environment.........................202
4.44 Get the current Java version from a BAT fileTag(s): Environment..............................203
4.45 Get the Windows "My Documents" pathTag(s): Environment.....................................204
4.46 Get the Windows Desktop pathTag(s): Environment...................................................204
4.47 Get the Windows Special FoldersTag(s): Environment...............................................206
4.48 Create an Internet Shortcut (Windows)Tag(s): Environment.......................................207
Real's HowTo@www.rgagnon.com
4 Environment
4.49 Detect if running in remote session (Windows)Tag(s): Environment...........................208
4.50 Detect if running a Citrix session (Windows)Tag(s): IO...............................................210
4.51 Create a Taglet to document database access (Javadoc)Tag(s): Environment..........210
4.51.1 newMethod.........................................................................................................211
4.52 Generate the Javadoc "en franais"Tag(s): Environment Environment
Internationalization...............................................................................................................214
4.53 Document a package using Javadoc Tag(s): Environment.........................................215
4.54 Display a comment in a JavadocTag(s): Environment.................................................216
4.55 Display XML in a javadocTag(s): Environment............................................................217
4.56 Add a copyright notice to a JavadocTag(s): Environment...........................................218
4.57 Use a Log fileTag(s): Environment..............................................................................218
4.58 Trace the executionTag(s): Environment.....................................................................221
4.59 Time the executionTag(s): Environment......................................................................222
4.60 Log information efficiently (with Log4J)Tag(s): Environment.......................................223
4.61 Change the logging level onthefly (Log4J)Tag(s): Environment..............................224
4.62 Enable debug log level on OpenSource package(Apache Commons Logging)
Tag(s): Environment............................................................................................................225
4.63 Use a JAR/ZIP/CAB file with an AppletTag(s): Environment.......................................226
4.64 Make ZIP/JAR file always accessible from appletTag(s): Environment.......................228
4.65 Make a JAR executableTag(s): Environment..............................................................228
4.66 Accessing jars from within a jarTag(s): Environment...................................................230
4.67 Access a JAR outside the CLASSPATHTag(s): Environment.....................................230
4.68 Extract a file from a JarTag(s): IO Environment...........................................................231
4.69 Determine if running from JARTag(s): Environment....................................................232
4.70 Get list of classes in package (in a Jar)Tag(s): Environment.......................................234
4.71 Add version to Jar packagingTag(s): Environment......................................................235
4.72 Use ANT to Build a JAR with version/build numberTag(s): Environment....................237
4.73 Include all jars in the classpath definitionTag(s): Environment....................................241
4.74 Windows batch file.......................................................................................................241
4.75 JDK6............................................................................................................................242
4.76 JAR (and ANT).............................................................................................................242
4.77 Detect browser type from an AppletTag(s): Applet Environment Javascript
interaction...........................................................................................................................244
4.78 Call a Javascript from the Applet.................................................................................244
4.79 Get the value from the serverside..............................................................................245
4.80 Detect if Java is enabled from HTMLTag(s): Environment..........................................245
4.81 See the Java Console Window Log (Java plugin)Tag(s): Applet Environment............246
5 Internationalization.....................................................................................................................247
5.1 javainter.......................................................................................................................247
5.2 Load resources based upon client environment at startupTag(s):
Internationalization..............................................................................................................247
5.3 Load resources dynamicallyTag(s): Internationalization................................................250
5.4 Load resources via a resources fileTag(s): Internationalization.....................................253
5.5 Display "special character" using UnicodeTag(s): Internationalization..........................257
5.6 Display chinese/japanese charactersTag(s): Internationalization..................................258
5.7 Localize a JOptionPane dialogTag(s): Internationalization Swing.................................258
5.8 Validate/Convert a number using the current Locale()Tag(s): Internationalization
String/Number......................................................................................................................260
Real's HowTo@www.rgagnon.com
5 Internationalization
5.9 Localize a JFileChooserTag(s): Internationalization Swing...........................................261
5.10 Disable localizationTag(s): Internationalization............................................................264
5.11 Generate the Javadoc "en franais"Tag(s): Environment Environment
Internationalization...............................................................................................................264
5.12 Sort a String arrayTag(s): Internationalization Varia....................................................266
5.13 Accentuated characters in Properties/ResourceBundle fileTag(s):
Internationalization Language.............................................................................................268
5.14 Compare accentuated lettersTag(s): Internationalization String/Number....................268
5.15 Unaccent lettersTag(s): Internationalization String/Number........................................270
5.15.1 Using java.text.Normalizer..................................................................................270
5.15.2 Using String.replaceAll().....................................................................................271
5.15.3 The String.indexOf()............................................................................................271
5.16 Output accentuated characters to the consoleTag(s): IO Internationalization.............273
5.17 Java 1.6 or more..........................................................................................................273
5.18 Java 1.5 or less............................................................................................................274
5.19 Get the default character set of the JVMTag(s): IO Internationalization......................274
5.20 Convert OEM (DOS) file to Ansi (Windows)Tag(s): IO Internationalization.................275
5.21 Detect nonASCII character in a StringTag(s): Internationalization String/Number....276
5.22 Get the month (or day) name (localized)Tag(s): Date and Time
Internationalization...............................................................................................................277
6 IO..................................................................................................................................................279
6.1 javaio...........................................................................................................................279
6.2 Redirect output(stdout/stderr) to a frameTag(s): IO.......................................................279
6.3 Redirect printStackTrace() to a StringTag(s): IO...........................................................280
6.4 Redirect to a NULL deviceTag(s): IO.............................................................................281
6.5 Print a text file using the javax.print APITag(s): IO........................................................282
6.6 Print a String to a printer Tag(s): IO...............................................................................284
6.7 Print text to a printer easilyTag(s): IO............................................................................285
6.8 Print without a DialogTag(s): IO.....................................................................................286
6.9 Initialize and write to a serial portTag(s): IO..................................................................286
6.10 Open or close a CD/DVD driveTag(s): IO....................................................................287
6.11 Get the volume labelTag(s): IO....................................................................................288
6.12 Detect the storage device typeTag(s): IO....................................................................289
6.13 Turn on MQ Debug mode Tag(s): IO...........................................................................290
6.14 Get faster console output (System.out.println() replacement)Tag(s): IO.....................291
6.15 Simple input from the keyboardTag(s): IO...................................................................292
6.16 Output accentuated characters to the consoleTag(s): IO Internationalization.............294
6.17 Java 1.6 or more..........................................................................................................294
6.18 Java 1.5 or less............................................................................................................294
6.19 Clear the console and control attributesTag(s): IO Open Source................................295
6.20 Jansi.............................................................................................................................295
6.21 JCurses........................................................................................................................296
6.22 Easy keyboard input (JDK1.5)Tag(s): IO.....................................................................297
6.23 Force keyboard input in CAPS LOCK onTag(s): IO.....................................................298
6.24 Automatic conversion of System.out output Tag(s): IO...............................................299
6.25 Execute an external programTag(s): IO.......................................................................301
6.26 Using Runtime.exec()..................................................................................................301
6.27 Launch a Windows CMD (or BAT) file and retrieve the errorlevel or exitcode.............302
Real's HowTo@www.rgagnon.com
6 IO
6.28 Launch a Unix script....................................................................................................303
6.29 Using the ProcessBuilder.............................................................................................303
6.30 Windows rundll32 utility...............................................................................................303
6.31 PDF (Windows only)....................................................................................................304
6.32 PDF (Mac only)............................................................................................................304
6.33 Path to executable with spaces in them.......................................................................304
6.34 VBSCRIPT...................................................................................................................305
6.35 HTML Help (Windows only).........................................................................................305
6.36 Start Excel....................................................................................................................305
6.37 Start a Windows application under another account....................................................306
6.38 Windows : execute something in Program Files..........................................................306
6.39 Launch the application associated with a file extensionTag(s): IO..............................307
6.40 Launch an application from another applicationTag(s): IO Language.........................308
6.41 Start the default browser from an applicationTag(s): IO..............................................310
6.42 Execute a Windows Shortcut (.lnk)Tag(s): IO..............................................................312
6.43 Create a file association with a Java programTag(s): IO Misc Prog HowTo................312
6.44 Capture the output from a VBSTag(s): IO....................................................................314
6.45 Get a return code from a VBSTag(s): IO Environment................................................315
6.46 Execute a CMD file stored in a JARTag(s): IO............................................................316
6.47 Open the default file explorerTag(s): IO.......................................................................318
6.48 Read the content of a fileTag(s): IO.............................................................................318
6.49 From a Java application...............................................................................................318
6.50 From a Java applet......................................................................................................319
6.51 Read a text file from a jarTag(s): IO.............................................................................321
6.52 Read a file from the internet Tag(s): Networking IO....................................................323
6.53 Extract a file from a JarTag(s): IO Environment...........................................................324
6.54 Read a data file with floatsTag(s): IO...........................................................................325
6.55 Write to the end of a fileTag(s): IO...............................................................................326
6.56 Write "real" ascii fileTag(s): IO.....................................................................................327
6.57 Copy a fileTag(s): IO....................................................................................................328
6.58 Use a "log file"Tag(s): IO.............................................................................................330
6.59 Delete files with a certain extensionTag(s): IO............................................................332
6.60 Insert a line in a fileTag(s): IO......................................................................................333
6.61 Read a file into a variable in one shotTag(s): IO..........................................................334
6.62 Serialize an object to a fileTag(s): IO...........................................................................334
6.63 Redirect stdout to a fileTag(s): IO................................................................................336
6.64 Get the "last modified" date from a fileTag(s): IO........................................................336
6.65 Check if a file existsTag(s): IO.....................................................................................337
6.66 Detect file modificationTag(s): IO.................................................................................337
6.67 File/directory polling to detect changeTag(s): IO Open Source...................................340
6.68 jpoller (directory poller)................................................................................................340
6.69 JNotify..........................................................................................................................340
6.70 Java Native Access (JNA)...........................................................................................340
6.71 Call native methods in a DLL from Java (NativeCall)..................................................341
6.72 Java 7..........................................................................................................................341
6.73 The simple (and naive!) approach...............................................................................341
6.74 Get the current directoryTag(s): IO..............................................................................341
6.75 Get the "root" of an applicationTag(s): IO....................................................................342
6.76 Get the content of a directory with a FilterTag(s): IO...................................................342
Real's HowTo@www.rgagnon.com
6 IO
6.77 Get the content of a directory with subdirectoriesTag(s): IO........................................345
6.78 Get directory content faster with many files Tag(s): IO................................................346
6.79 Make a directoryTag(s): IO..........................................................................................348
6.80 Create a fixedlength fileTag(s): IO.............................................................................348
6.81 Delete a nonempty directoryTag(s): IO......................................................................349
6.82 Create a temporary fileTag(s): IO................................................................................349
6.83 Get the default character set of the JVMTag(s): IO Internationalization......................350
6.84 Parse a pathnameTag(s): IO.......................................................................................351
6.85 Handle CSV fileTag(s): IO Open Source.....................................................................352
6.86 com.Ostermiller.util CSV Utils......................................................................................352
6.87 opencsv........................................................................................................................352
6.88 ServingXML.................................................................................................................352
6.89 Super CSV...................................................................................................................352
6.90 csvreader.....................................................................................................................352
6.91 CSVFile........................................................................................................................352
6.92 FlatPack.......................................................................................................................352
6.93 CSVJDBC....................................................................................................................353
6.94 FFP..............................................................................................................................353
6.95 Convert OEM (DOS) file to Ansi (Windows)Tag(s): IO Internationalization.................353
6.96 Close a stream in a try/catch blockTag(s): IO..............................................................354
6.97 Rename a file extensionTag(s): IO..............................................................................355
6.98 Remove file extension Tag(s): IO................................................................................357
6.99 Remove HTML tags from a file to extract only the TEXTTag(s): IO String/Number
Networking...........................................................................................................................357
6.100 Using regular expression...........................................................................................357
6.101 Using javax.swing.text.html.HTMLEditorKit...............................................................358
6.102 Using an HTML parser...............................................................................................358
6.103 Using Apache Tika.....................................................................................................359
6.104 Get the Mime Type from a FileTag(s): IO..................................................................360
6.104.1 Using Java 7.....................................................................................................360
6.104.2 Using javax.activation.MimetypesFileTypeMap................................................360
6.104.3 Using java.net.URL...........................................................................................361
6.104.4 Using Apache Tika............................................................................................362
6.104.5 Using JMimeMagic............................................................................................363
6.104.6 Using mimeutil................................................................................................363
6.104.7 Using Droid.......................................................................................................363
6.104.8 Aperture framework...........................................................................................364
6.105 Sort a directory listing (based on the last modified timestamp)Tag(s): IO.................364
6.106 Sort files by the extensionTag(s): IO..........................................................................365
6.107 Filter a directory listing by dateTag(s): IO..................................................................367
6.108 Convert wildcard to a regex expressionTag(s): IO.....................................................368
6.109 Shorten a long pathTag(s): IO String/Number...........................................................369
6.110 Force a valid Windows filenameTag(s): IO................................................................373
6.111 Check if filename is validTag(s): IO...........................................................................374
6.112 Dump a file to a HEX fileTag(s): IO............................................................................375
6.113 List all files in the classpath or in a JarTag(s): IO......................................................376
6.114 Handle UTF8 file with BOMTag(s): IO.......................................................................377
6.115 Touch a file Tag(s): IO...............................................................................................380
6.116 Handle Excel filesTag(s): IO JDBC Open Source......................................................380
Real's HowTo@www.rgagnon.com
6 IO
6.117 JDBCODBC Excel driver.........................................................................................381
6.118 JExcel........................................................................................................................381
6.119 POI.............................................................................................................................382
6.120 JXLS..........................................................................................................................382
6.121 xlSQL.........................................................................................................................383
6.122 JCOM.........................................................................................................................383
6.123 OpenXLS Java Spreadsheet SDK.............................................................................385
6.124 Create an Excel fileTag(s): IO....................................................................................387
6.125 Detect if a XLS Excel file contains a macro (using POI)Tag(s): IO............................387
6.126 Create or process a PDF fileTag(s): IO Open Source...............................................388
6.127 Create a PDFTag(s): IO Open Source.......................................................................390
6.128 iText...........................................................................................................................390
6.129 Split a PDF file (using iText)Tag(s): IO Open Source................................................392
6.130 Concatenate PDF files (using iText)Tag(s): IO Open Source....................................393
6.131 Convert TIF to PDFTag(s): AWT IO IO Open Source................................................394
6.132 Convert HTML to PDF using iTextTag(s): IO Open Source.......................................396
6.133 Convert HTML to PDF using YAHP Tag(s): IO OpenSource.....................................398
6.134 Convert a png/jpg/gif file to PDF using iTextTag(s): IO Open Source.......................400
6.135 Print a PDFTag(s): IO Open Source..........................................................................401
6.136 Extract text from a PDF (with Apache Tika) Tag(s): IO OpenSource........................402
6.137 Create a compressed (ZIP) fileTag(s): IO..................................................................402
6.138 Display compressed (ZIP) file contentTag(s): IO.......................................................403
6.139 Expand the compressed (ZIP) fileTag(s): IO.............................................................405
6.140 Emit a beepTag(s): IO................................................................................................405
6.141 Emit a ToneTag(s): IO...............................................................................................406
6.142 Play an audio file from an applicationTag(s): IO........................................................407
6.143 Produce special sound effectTag(s): IO.....................................................................409
6.144 Use the Java Speech API (JSPAPI)Tag(s): IO..........................................................412
6.145 Play a Windows sound Tag(s): IO.............................................................................414
7 JDBC............................................................................................................................................416
7.1 javajdbc........................................................................................................................416
7.2 Get JDBC driver for major database vendorsTag(s): JDBC..........................................416
7.3 Connect to a database via JDBCODBCTag(s): JDBC.................................................416
7.4 SELECT data from a tableTag(s): JDBC.......................................................................417
7.5 INSERT data into a tableTag(s): JDBC.........................................................................419
7.6 Tag(s): JDBC.................................................................................................................420
7.7 Tag(s): JDBC.................................................................................................................421
7.8 Test for an empty ResultSetTag(s): JDBC.....................................................................421
7.9 Get a record count with a SQL StatementTag(s): JDBC...............................................422
7.10 Store and retrieve an object from a tableTag(s): JDBC...............................................422
7.11 Retrieve an ImageTag(s): JDBC..................................................................................424
7.12 Insert an ImageTag(s): JDBC......................................................................................425
7.13 Call a stored procedureTag(s): JDBC..........................................................................425
7.14 Stored procedure with Input/Output parms and a ResultSetTag(s): JDBC..................426
7.15 Fix incomplete field returned by the ResultSetTag(s): JDBC.......................................427
7.16 Transfer a ResultSet to a JTableTag(s): JDBC Swing.................................................427
7.17 Detect SQL errors or warningsTag(s): JDBC...............................................................428
7.18 Using DSNless connectionTag(s): JDBC...................................................................430
Real's HowTo@www.rgagnon.com
7 JDBC
7.19 Specify a CharSet when connecting to a DBMSTag(s): JDBC....................................430
7.20 List tables in a databaseTag(s): JDBC........................................................................431
7.21 Enable JDBC loggingTag(s): JDBC.............................................................................432
7.22 Detect if a table existsTag(s): JDBC............................................................................433
7.23 Convert a ResultSet to XMLTag(s): JDBC XML..........................................................434
7.24 Display ResultSet data in an HTML Table in ServletTag(s): JDBC Servlet/JSP.........436
7.25 Escape special character in a LIKE clauseTag(s): JDBC............................................436
7.26 Log the SQL StatementsTag(s): JDBC........................................................................437
7.27 Plain JDBC Logging.....................................................................................................437
7.28 P6Spy..........................................................................................................................437
7.29 Proxool.........................................................................................................................438
7.30 JDBC Logger...............................................................................................................438
7.31 Log4JDBC....................................................................................................................438
7.32 Oracle JDBC................................................................................................................438
7.33 Insert data in batch modeTag(s): JDBC.......................................................................438
7.34 Retrieve large ResultSetTag(s): JDBC........................................................................440
7.35 Handle datesTag(s): JDBC..........................................................................................442
7.36 Get current date using JDBCTag(s): JDBC.................................................................443
7.37 Insert the current dateTag(s): JDBC............................................................................444
7.38 Read data from Excel worksheetTag(s): JDBC...........................................................444
7.39 Handle Excel filesTag(s): IO JDBC Open Source........................................................446
7.40 JDBCODBC Excel driver...........................................................................................446
7.41 JExcel..........................................................................................................................446
7.42 POI...............................................................................................................................447
7.43 JXLS............................................................................................................................448
7.44 xlSQL...........................................................................................................................449
7.45 JCOM...........................................................................................................................449
7.46 OpenXLS Java Spreadsheet SDK...............................................................................450
7.47 Connect to an Oracle database with JDBCTag(s): JDBC............................................452
7.48 Connect to Oracle using a connection poolTag(s): JDBC...........................................454
7.49 Retrieve the generated keys (JDBC Oracle)Tag(s): JDBC..........................................457
7.50 Debug Oracle JDBC connectionTag(s): JDBC............................................................458
7.51 Connect to an Oracle database using KerberosTag(s): JDBC....................................460
7.52 Identify the connected program to an Oracle databaseTag(s): JDBC.........................461
7.53 Use a CHAR field in the WHERE clause in a PreparedStatementTag(s): JDBC........463
8 JNI................................................................................................................................................465
8.1 javajni...........................................................................................................................465
8.2 Use native code through JNITag(s): JNI........................................................................465
8.3 Pass a string to/from Java to/from CTag(s): JNI............................................................465
8.4 Set the computer clockTag(s): Date and Time JNI........................................................467
8.5 Determine the signature of a methodTag(s): JNI...........................................................468
8.6 Use arraysTag(s): JNI....................................................................................................469
8.7 Load a DLLTag(s): JNI...................................................................................................471
8.8 Use the MouseWheelTag(s): JNI...................................................................................471
8.9 Throw an Exception (from JNI code)Tag(s): JNI............................................................472
8.10 Throw my own Exception (from JNI code)Tag(s): JNI.................................................472
8.11 JNI from a packageTag(s): JNI....................................................................................473
8.12 Make a Window "stay on top"Tag(s): JNI....................................................................474
Real's HowTo@www.rgagnon.com
8 JNI
8.13 Start a JVM from CTag(s): JNI.....................................................................................474
8.14 Retrieve environment variable (JNI)Tag(s): Environment JNI.....................................475
8.15 Get the PIDTag(s): Environment JNI...........................................................................476
8.16 Clear the console, set color and cursor position (JNI)Tag(s): JNI...............................477
8.17 Call Windows API (Open source solution)Tag(s): JNI Open Source...........................480
8.18 Detect if a program is running (JNA)Tag(s): JNI/JNA..................................................480
8.19 Get Windows Special Folders (JNA) Tag(s): JNI/JNA.................................................481
9 Javascript interaction.................................................................................................................483
9.1 javajs............................................................................................................................483
9.2 * Read me *Tag(s): Javascript interaction.....................................................................483
9.3 Wakeup a Java appletTag(s): Javascript interaction...................................................483
9.4 Call a Java method from JavascriptTag(s): Javascript interaction.................................486
9.5 Calling Java applets methods using DOM and JavaScriptTag(s): Javascript
interaction...........................................................................................................................487
9.6 Access Java variables from JavascriptTag(s): Javascript interaction............................488
9.7 Call Javascript from a Java appletTag(s): Javascript interaction...................................489
9.8 Using the javascript: protocol.........................................................................................489
9.9 Using the netscape.javascript.JSObject package..........................................................490
9.10 Create dynamic HTML from a Java appletTag(s): Javascript interaction....................491
9.11 Have Applets on different frames communicates with each otherTag(s):
Javascript interaction..........................................................................................................492
9.12 Send a message from an Applet to another Applet on a different pageTag(s):
Javascript interaction..........................................................................................................494
9.13 Retrieve values from a Java applet for HTML form (CGI)Tag(s): Javascript
interaction...........................................................................................................................496
9.14 Detect if an Applet is readyTag(s): Javascript interaction............................................497
9.15 Read/Write HTML field values from JAVATag(s): Javascript interaction.....................498
9.16 Detect if Java is enabledTag(s): Javascript interaction................................................500
9.17 Detect if Java 1.1 (with event delegation) is availableTag(s): Javascript interaction...500
9.18 Access Cookies from a Java AppletTag(s): Javascript interaction..............................501
9.19 Set Applet PARAM VALUE from javascriptTag(s): Javascript interaction...................503
9.20 Pass an Array between Java and JavascriptTag(s): Javascript interaction.................504
9.21 Interaction without LiveConnectTag(s): Javascript interaction.....................................507
9.22 Directory listing on the Web server in a Java AppletTag(s): Javascript interaction.....512
9.23 Have a Java button close the browser windowTag(s): Javascript interaction..............514
9.24 Detect if cookies are enabledTag(s): Javascript interaction........................................515
9.25 Display a page after all applets are loadedTag(s): Javascript interaction....................516
9.26 Detect browser type from an AppletTag(s): Applet Environment Javascript
interaction...........................................................................................................................516
9.27 Call a Javascript from the Applet.................................................................................516
9.28 Get the value from the serverside..............................................................................518
10 Servlet/JSP................................................................................................................................519
10.1 javajsp........................................................................................................................519
10.2 Read meTag(s): Servlet/JSP.......................................................................................519
10.3 Get parameters passed to a servletTag(s): Servlet/JSP..............................................519
10.4 Detect no argument condition in a ServletTag(s): Servlet/JSP....................................520
10.5 Set a Cookie from a servletTag(s): Servlet/JSP..........................................................521
Real's HowTo@www.rgagnon.com
10 Servlet/JSP
10.6 Read a Cookie from a servletTag(s): Servlet/JSP.......................................................521
10.7 Delete (or expire) a Cookie from a servletTag(s): Servlet/JSP....................................522
10.8 Ask for a password from a ServletTag(s): Servlet/JSP................................................522
10.9 Talk to a CGI/ServletTag(s): Networking Servlet/JSP.................................................523
10.10 Test for CookiesTag(s): Servlet/JSP..........................................................................524
10.11 Display ResultSet data in an HTML Table in ServletTag(s): JDBC Servlet/JSP.......524
10.12 Specify the filename to be used for a file sent by a ServletTag(s): Servlet/JSP........525
10.13 Pass information to another servlet/jspTag(s): Servlet/JSP.......................................526
10.14 Handle PDF outputTag(s): Servlet/JSP.....................................................................526
10.15 Detect if the connection is via a secure channelTag(s): Servlet/JSP.........................527
10.16 In a Servlet, check if Form Field is presentTag(s): Servlet/JSP.................................527
10.17 Get the root dir of a web appTag(s): Servlet/JSP Servlet/JSP..................................527
10.18 Get client IP address from JSPTag(s): Servlet/JSP...................................................528
10.19 Output a binary stream from a JSPTag(s): Servlet/JSP............................................528
10.20 Use a connection cache from JSPTag(s): Servlet/JSP Jaguar/EAServer.................529
10.21 Read a Web Application propertyTag(s): Servlet/JSP...............................................531
10.22 Use EJB from JSPTag(s): Servlet/JSP......................................................................531
10.23 Define a method in a JSP pageTag(s): Servlet/JSP..................................................532
10.24 Precompile JSP pagesTag(s): Servlet/JSP...............................................................532
10.25 Get a list of directories for JSPTag(s): Servlet/JSP...................................................533
10.26 Use and share a class in JSP pages Tag(s): Servlet/JSP.........................................534
10.27 Get the root dir of a web appTag(s): Servlet/JSP Servlet/JSP..................................535
10.28 Launch an applet from a JSPTag(s): Servlet/JSP.....................................................536
10.29 Prevent caching of a JSP outputTag(s): Servlet/JSP................................................536
10.30 Launch an external program, capture its output and display it in a JSPTag(s):
Servlet/JSP.........................................................................................................................537
10.31 Call another EJBTag(s): Servlet/JSP Jaguar/EAServer............................................539
10.32 Keep java files generated from JSP (BEA WLS)Tag(s): Servlet/JSP........................539
10.33 Get the server version (BEA WLS)Tag(s): Servlet/JSP.............................................539
10.34 Quickly create a Web application with BEA WLSTag(s): Servlet/JSP.......................540
10.35 Nicely display WEB.XML informationsTag(s): Servlet/JSP XML Jaguar/EAServer...540
10.36 Reverse the CLASSLOADER order (BEA)Tag(s): Servlet/JSP.................................542
10.37 Detect change in JSP and recompile (BEA)Tag(s): Servlet/JSP...............................543
10.38 Obtain a remote connection to a DataSource or EJB (Weblogic)Tag(s):
Servlet/JSP.........................................................................................................................543
11 Language...................................................................................................................................546
11.1 javalanguage.............................................................................................................546
11.2 * Read me *Tag(s): Language String/Number.............................................................546
11.3 Obtain from where a Class is loadedTag(s): Language Varia.....................................547
11.4 Get the class name in a static methodTag(s): Language............................................548
11.5 Get the current method nameTag(s): Language..........................................................549
11.6 JDK1.4.........................................................................................................................549
11.7 JDK1.5.........................................................................................................................549
11.8 Call a method dynamically (Reflection)Tag(s): Language...........................................550
11.9 Detect if a package is availableTag(s): Language.......................................................552
11.10 Create an object from a stringTag(s): Language.......................................................553
11.11 Get a variable value from the variable nameTag(s): Language.................................554
11.12 Make methods that have unspecified number of parametersTag(s): Language........555
Real's HowTo@www.rgagnon.com
11 Language
11.13 Create a java source dynamically, compile and callTag(s): Language......................556
11.14 Java 1.6.....................................................................................................................556
11.15 Java 1.5 or less..........................................................................................................557
11.16 Launch an application from another applicationTag(s): IO Language.......................558
11.17 Access the enclosing class from an inner classTag(s): Language............................560
11.18 Access inner class from outsideTag(s): Language....................................................561
11.19 Use globally defined constantsTag(s): Language......................................................562
11.20 Serialize an ObjectTag(s): Language........................................................................563
11.21 Serialize an Object over a socketTag(s): Language..................................................565
11.22 Easily remove my debugging codeTag(s): Language................................................565
11.23 Have a singletonTag(s): Language............................................................................566
11.24 Multiple expressions in for loopsTag(s): Language...................................................566
11.25 Handle the List conflictTag(s): Language..................................................................567
11.26 Use a generic toString()Tag(s): Language.................................................................567
11.27 Use Object.clone()Tag(s): Language.........................................................................569
11.28 Static field, constructor and exceptionTag(s): Language...........................................570
11.29 Use a Label breakTag(s): Language.........................................................................571
11.30 Put printStackTrace() into a StringTag(s): Language................................................572
11.31 Iterate enum valuesTag(s): Language.......................................................................573
11.32 Get fields and values from an Object Tag(s): Language...........................................573
11.33 Use a HashtableTag(s): Language............................................................................575
11.34 Scan the content of a hashtableTag(s): Language....................................................575
11.35 Sort an arrayTag(s): Language Varia........................................................................575
11.36 Initialize multidimensional arrayTag(s): Language.....................................................577
11.37 Get array upperboundTag(s): Language...................................................................578
11.38 Convert a String to an array or an array to a stringTag(s): Language.......................578
11.38.1 String to Array...................................................................................................578
11.38.2 Array to String...................................................................................................579
11.39 Sort in reverse orderTag(s): Language......................................................................580
11.40 Resize an arrayTag(s): Language.............................................................................580
11.41 Dump array contentTag(s): Language.......................................................................582
11.42 Initialize a static arrayTag(s): Language....................................................................583
11.43 Sort an HashtableTag(s): Language..........................................................................583
11.44 Eliminate "[unchecked] unchecked call ..." compiler warning Tag(s): Language.......585
12 ANT............................................................................................................................................587
12.1 Sort on many fieldsTag(s): Language..........................................................................587
12.2 Optimize Collection usageTag(s): Language...............................................................589
12.3 Sort an HashMapTag(s): Language.............................................................................591
12.4 Get keys corresponding to a value from a MapTag(s): Language...............................592
12.5 Iterate a Collection and remove an itemTag(s): Language..........................................594
12.6 Count distinct elements in a VectorTag(s): Language.................................................595
12.7 Dump the content of a Collection (JDK 1.5)Tag(s): Language....................................596
12.7.1 List......................................................................................................................596
12.7.2 Map.....................................................................................................................597
12.8 Initialize a CollectionTag(s): Language........................................................................597
12.9 Merge (or add) two arrays into oneTag(s): Language.................................................600
12.10 Define an array (or Map, or ENUM) of functionsTag(s): Language...........................601
12.10.1 Using an interface.............................................................................................601
Real's HowTo@www.rgagnon.com
12 ANT
12.10.2 Using an enum..................................................................................................602
12.11 Join a List as a StringTag(s): Language....................................................................603
12.12 Remove duplicates from a List Tag(s): Language.....................................................604
12.13 Convert a Map to a Properties (or vice versa)Tag(s): Language...............................605
12.14 Use an INI file (properties)Tag(s): Language.............................................................606
12.15 Open Source packages.............................................................................................606
12.16 Using Properties........................................................................................................606
12.17 Load a properties fileTag(s): Language.....................................................................608
12.18 Accentuated characters in Properties/ResourceBundle fileTag(s):
Internationalization Language.............................................................................................609
12.19 Have a multiline value in a properties fileTag(s): Language....................................609
12.20 Use XML with PropertiesTag(s): Language XML.......................................................610
12.21 Use the Registry to store informations (Preferences API)Tag(s): Language.............611
12.22 Sort Properties when savingTag(s): Language..........................................................612
13 Networking................................................................................................................................614
13.1 javanet.......................................................................................................................614
13.2 Extract network card addressTag(s): Networking........................................................614
13.3 Get the workstation name/ipTag(s): Networking..........................................................617
13.4 Find port number not in useTag(s): Networking...........................................................618
13.5 Disable DNS cachingTag(s): Networking.....................................................................619
13.6 Allow user:password in URLTag(s): Networking Security Common problems
WinAPI/Registry...................................................................................................................620
13.7 Encode/Decode to/from Base64Tag(s): String/Number Networking...........................621
13.8 Using javax.mail.internet.MimeUtility...........................................................................621
13.9 Using Apache Commons Codec..................................................................................622
13.10 MiGBase64................................................................................................................622
13.11 Lookup using MX record to validate mail serverTag(s): Networking..........................622
13.12 Send an email using the SMTP protocolTag(s): Networking.....................................631
13.13 Check if there is mail waitingTag(s): Networking.......................................................632
13.14 Receive emailTag(s): Networking..............................................................................634
13.15 Send email with an attachmentTag(s): Networking...................................................636
13.16 Send email with JavaMailTag(s): Networking............................................................641
13.17 Send email with authenticationTag(s): Networking....................................................644
13.18 Send HTML mail with images (Javamail)Tag(s): Networking....................................645
13.19 Debug a JavaMail ProgramTag(s): Networking.........................................................647
13.20 JavaMail Debug mode...............................................................................................647
13.21 Verify connectivity to the MailServer with Telnet :.....................................................648
13.22 Use a JavaMail server mockup to act as "inmemory" mail server.........................648
13.23 Send email with SMTPS (eg. Google GMail) (Javamail)Tag(s): Networking.............648
13.23.1 Settings for well known mail providers..............................................................650
13.24 Mix plain text and HTML content in a mailTag(s): Networking...................................650
13.25 Read an Outlook MSG fileTag(s): Networking Open Source.....................................651
13.26 Apache POI HSMF....................................................................................................651
13.27 msgparser..................................................................................................................653
13.28 jmbox.........................................................................................................................654
13.29 Handle EML file with JavaMailTag(s): Networking.....................................................654
13.30 Loading an .EML file..................................................................................................654
13.31 Saving an email to .EML file......................................................................................655
Real's HowTo@www.rgagnon.com
13 Networking
13.32 Receive email using IMAPTag(s): Networking...........................................................656
13.33 Receive email using POP3Tag(s): Networking..........................................................659
13.34 Check if a file was modified on the serverTag(s): Networking...................................661
13.35 Check if a page existsTag(s): Networking.................................................................661
13.36 Connect through a ProxyTag(s): Networking Networking..........................................663
13.36.1 The Networking Properties................................................................................663
13.36.2 Proxy and Username/Password........................................................................664
13.36.3 Bypass a Proxy.................................................................................................666
13.37 Identify yourself using HTTP AuthentificationTag(s): Networking..............................666
13.38 Talk to a CGI/ServletTag(s): Networking Servlet/JSP...............................................668
13.39 Write/Read cookies using HTTPTag(s): Networking.................................................669
13.40 Read a file from the internet Tag(s): Networking IO..................................................671
13.41 Read a GIF or CLASS from an URL save it locallyTag(s): Networking.....................672
13.42 Resolve a relative URLTag(s): Networking................................................................674
13.43 File size from URLTag(s): Networking.......................................................................674
13.44 Use the HTTPS protocolTag(s): Networking..............................................................675
13.45 Fix certificate problem in HTTPSTag(s): Networking.................................................675
13.46 Fetch a page from GoogleTag(s): Networking...........................................................677
13.47 Upload a file to a serverTag(s): Networking...............................................................678
13.48 Remove HTML tags from a file to extract only the TEXTTag(s): IO
String/Number Networking...................................................................................................679
13.49 Using regular expression...........................................................................................679
13.50 Using javax.swing.text.html.HTMLEditorKit...............................................................679
13.51 Using an HTML parser...............................................................................................680
13.52 Using Apache Tika.....................................................................................................681
13.53 Extract links from an HTML pageTag(s): String/Number Networking........................682
13.54 Using javax.swing.text.html.HTMLEditorKit...............................................................682
13.55 Using an HTML parser...............................................................................................682
13.56 Call a web service (generated with BEA ServiceGen)Tag(s): Networking................683
13.57 Do basic authentication when calling a webservice Tag(s): Networking...................685
13.58 WS authentication from Weblogic..............................................................................686
13.59 Have a simple HTTP serverTag(s): Networking........................................................686
13.60 Connect through a ProxyTag(s): Networking Networking..........................................688
13.60.1 The Networking Properties................................................................................688
13.60.2 Proxy and Username/Password........................................................................690
13.60.3 Bypass a Proxy.................................................................................................691
13.61 Have timeout on socket connectionTag(s): Networking.............................................691
13.62 Ping a serverTag(s): Networking...............................................................................692
13.63 Get the Date from serverTag(s): Networking.............................................................693
13.64 Use the java.net.Socket.setSoLinger methodTag(s): Networking.............................694
13.65 Use the java.net.Socket.setTcpNoDelay methodTag(s): Networking........................694
13.66 Find out who is accessing my ServerSocketTag(s): Networking...............................695
13.67 Transfer a file via SocketTag(s): Networking.............................................................695
14 Security......................................................................................................................................698
14.1 javasecurity................................................................................................................698
14.2 Encrypt a passwordTag(s): Security............................................................................698
14.3 Transmit a password with MessageDigest..................................................................698
14.4 Store a password in a properties file............................................................................699
Real's HowTo@www.rgagnon.com
14 Security
14.5 Create a checksumTag(s): Security.............................................................................702
14.6 Get the user nameTag(s): Applet Security...................................................................706
14.7 Get username using NT Challenge (NTLM)Tag(s): Security.......................................707
14.8 Check if the current user belongs a specific Windows group/roleTag(s): Security
Powerscript..........................................................................................................................709
14.9 Allow user:password in URLTag(s): Networking Security Common problems
WinAPI/Registry...................................................................................................................709
14.10 Prompt for password from the consoleTag(s): Security.............................................710
14.11 Prevent XSS exploitTag(s): Security..........................................................................711
14.12 Sanitize the input by removing suspicious tags.........................................................711
14.13 Sanitize the input based on a policy file.....................................................................712
14.14 Sanitize the output by removing suspicious characters.............................................712
14.15 Display a simple username/password Dialog from an AppletTag(s): Security..........713
15 Swing.........................................................................................................................................716
15.1 javaswing...................................................................................................................716
15.2 * Read me *Tag(s): Swing...........................................................................................716
15.3 Change component default fontTag(s): Swing.............................................................716
15.4 Repaint problem under the mouse cursor (JDK1.2)Tag(s): Swing..............................717
15.5 Set the LookAndFeelTag(s): Swing.............................................................................717
15.6 Use any LookAndFeel on any plateformTag(s): Swing................................................718
15.7 Use a TimerTag(s): Swing...........................................................................................719
15.8 Share ActionEvent handlerTag(s): Swing....................................................................719
15.9 Get default values for Swingbased user interfaceTag(s): Swing...............................721
15.10 Have a systray icon (Windows)Tag(s): Swing...........................................................722
15.11 Close a JFrame under conditionTag(s): Swing..........................................................724
15.12 Maximize a JFrameTag(s): Swing.............................................................................725
15.13 Capture System.out into a JFrameTag(s): Swing......................................................725
15.14 Remove the titlebar of JInternalFrameTag(s): Swing................................................728
15.15 Have borders on a JWindow/JFrameTag(s): Swing..................................................728
15.16 Display HTML in a JScrollPaneTag(s): Swing...........................................................729
15.17 Use a JOptionPaneTag(s): Swing..............................................................................730
15.18 Localize a JOptionPane dialogTag(s): Internationalization Swing.............................731
15.19 Customize JOptionPane buttonsTag(s): Swing.........................................................733
15.20 Localize a JFileChooserTag(s): Internationalization Swing.......................................733
15.21 Select a directory with a JFileChooserTag(s): Swing................................................736
15.22 Disable the JFileChooser's "New folder" buttonTag(s): Swing..................................737
15.23 Validate a filename from a JFileChooserTag(s): Swing.............................................739
15.24 Make a JFrame looks like a JDialogTag(s): Swing....................................................740
15.25 Make a JFrame always visibleTag(s): Swing.............................................................741
15.26 Show a JFrame on a specific screen in a dual monitor configuration Tag(s):
Swing..................................................................................................................................742
15.27 Make a JFrame not visible in the the TaskBar Tag(s): Swing....................................742
15.28 Based on JTextField content, enable or disable a JButtonTag(s): Swing..................743
15.29 Apply special filter to a JtextFieldTag(s): Swing........................................................744
15.30 Limit JTextField input to a maximum lengthTag(s): Swing........................................747
15.31 Validate a value on the lostFocus eventTag(s): Swing..............................................748
15.32 Make sure that my jTextfield has the focus when a JFrame is createdTag(s):
Swing..................................................................................................................................751
Real's HowTo@www.rgagnon.com
15 Swing
15.33 Stop the beep on JFormattedTextFieldTag(s): Swing...............................................752
15.34 Right justified JTextfield contentTag(s): Swing..........................................................752
15.35 Set the focus on a particuliar JTextFieldTag(s): Swing..............................................752
15.36 Make JTextField unselectableTag(s): Swing.............................................................753
15.37 Disable copy paste functionality on JTextFieldTag(s): Swing....................................754
15.38 Use a JTree to navigate in a siteTag(s): Swing.........................................................755
15.39 Expand or collapse a JTreeTag(s): Swing.................................................................761
15.40 Have a popup attached to a JTreeTag(s): Swing......................................................763
15.41 Traverse a JTreeTag(s): Swing.................................................................................765
15.42 Show dotted lines in a JTreeTag(s): Swing...............................................................767
15.43 Explore directories with a JTreeTag(s): Swing..........................................................768
15.44 Prevent JTree collapsingTag(s): Swing.....................................................................769
15.45 Single selection in a JTreeTag(s): Swing...................................................................769
15.46 Reduce JTree children indentationTag(s): Swing......................................................770
15.47 Use + or for JTree IconsTag(s): Swing...................................................................770
15.48 Change the JTable header colorTag(s): Swing.........................................................772
15.49 Double click on a JTableTag(s): Swing......................................................................773
15.50 Read a data file into a JTableTag(s): Swing..............................................................775
15.51 Disable row selection in a JTableTag(s): Swing........................................................777
15.52 Read a data file into a JTable and reload if data file have changedTag(s): Swing....777
15.53 Hide a column in JTableTag(s): Swing......................................................................780
15.54 Scroll a JTable to the last rowTag(s): Swing..............................................................781
15.55 Transfer a ResultSet to a JTableTag(s): JDBC Swing...............................................782
15.56 Have on a JScrollPane/JTable an horizontal JScrollbarTag(s): Swing......................782
15.57 Make a JList select an item on doubleclick or the ENTER keyTag(s): Swing............783
15.58 Make a JList like a scrolling text displayTag(s): Swing..............................................784
15.59 Have images in a JListTag(s): Swing.........................................................................785
15.60 Add a row and clear a JListTag(s): Swing.................................................................787
15.61 Sort a JListTag(s): Swing...........................................................................................788
15.62 Double click on a JListTag(s): Swing.........................................................................790
15.63 Have a PopUp on a JListTag(s): Swing.....................................................................791
15.64 Make a JLabel selectable with the mouseTag(s): Swing...........................................792
15.65 Change JLabel background colorTag(s): Swing........................................................793
15.66 Bold / Unbold a JLabelTag(s): Swing.........................................................................794
15.67 Multiline JLabelTag(s): Swing..................................................................................794
15.68 Underline a stringTag(s): Swing.................................................................................794
15.69 Update a JLabelTag(s): Swing...................................................................................795
15.70 Display a blinking JLabelTag(s): Swing.....................................................................796
15.71 Set the cursor position in a JTextAreaTag(s): Swing.................................................797
15.72 Have Multiline string in a JToolTipTag(s): Swing.....................................................798
15.73 Change Tooltip colorTag(s): Swing............................................................................798
15.74 Change a JTooltip fontTag(s): Swing.........................................................................798
15.75 Keep a JTooltip visibleTag(s): Swing.........................................................................799
15.76 Display icon associated with an executableTag(s): Swing........................................800
15.77 Have items in JMenubar at rightmost positionTag(s): Swing.....................................802
15.78 Have an JButton with an ImageTag(s): Swing...........................................................803
15.79 Trigger a click on a ButtonTag(s): AWT Swing..........................................................804
16 Thread
Real's HowTo@www.rgagnon.com
16 Thread........................................................................................................................................806
16.1 javathread..................................................................................................................806
16.2 Pipe the output of a thread to the input of another oneTag(s): Thread........................806
16.3 Pipe the output of a thread to the input of other threadsTag(s): Thread......................808
16.4 Wait the for the completion of a threadTag(s): Thread................................................810
16.5 Control a thread from outsideTag(s): Thread...............................................................811
16.6 Create a Timer objectTag(s): Thread...........................................................................812
16.7 Pause the executionTag(s): Thread.............................................................................813
16.8 Execute a method at a specified time intervalTag(s): Thread......................................814
16.9 Execute a process at regular intervalTag(s): Thread...................................................815
16.10 Handle concurrent read/writeTag(s): Thread.............................................................816
16.11 Communicate between threads using a QueueTag(s): Thread.................................818
16.12 Get a unique identifierTag(s): String/Number Thread Varia......................................823
16.13 Using java.rmi.dgc.VMID...........................................................................................823
16.14 Using java.util.UUID...................................................................................................823
16.15 Using Apache commons............................................................................................824
16.16 Using java.util.concurrent.AtomicLong.......................................................................824
17 Varia...........................................................................................................................................825
17.1 javavaria....................................................................................................................825
17.2 Use System time to generate unique IDTag(s): Date and Time Date and Time
Varia.....................................................................................................................................825
17.3 Get a unique identifierTag(s): String/Number Thread Varia........................................825
17.4 Using java.rmi.dgc.VMID.............................................................................................825
17.5 Using java.util.UUID.....................................................................................................826
17.6 Using Apache commons..............................................................................................826
17.7 Using java.util.concurrent.AtomicLong.........................................................................826
17.8 Get the hard disk serial number or Motherboard serial numberTag(s): Varia..............827
17.9 Motherboard serial number..........................................................................................827
17.10 Hard disk serial number.............................................................................................828
17.11 Sort an arrayTag(s): Language Varia........................................................................829
17.12 Sort a String arrayTag(s): Internationalization Varia..................................................831
17.13 Do a selection sortTag(s): Varia................................................................................833
17.14 Validate a Social Security Number (canadian)Tag(s): Varia......................................834
17.15 Validate a Credit Card NumberTag(s): Varia.............................................................835
17.16 Obtain from where a Class is loadedTag(s): Language Varia...................................838
17.17 Get the class name with or without the packageTag(s): Varia...................................839
17.18 See the generated bytecodeTag(s): Varia.................................................................841
17.19 Self replicating programsTag(s): Varia......................................................................843
17.20 A curiosity (strange Java code)Tag(s): Varia.............................................................844
17.21 Classic bugsTag(s): Varia..........................................................................................846
17.22 Number of the beast!Tag(s): Varia.............................................................................846
17.23 Use Java scripting engine (JDK 1.6)Tag(s): Varia.....................................................847
17.24 Pass or retrieve values from a scripting engine (jdk1.6)Tag(s): Varia.......................848
17.25 Preventing multiple instances of an applicationTag(s): Varia....................................850
17.26 Trap JVM shutdownTag(s): Varia..............................................................................854
17.27 Minimize all programs on Windows to show the DesktopTag(s): Varia.....................854
17.28 Display a progress indicator in the consoleTag(s): Varia...........................................855
Real's HowTo@www.rgagnon.com
18 XML............................................................................................................................................857
18.1 javaxml.......................................................................................................................857
18.2 Read meTag(s): XML...................................................................................................857
18.3 Display XML using plain HTMLTag(s): XML................................................................858
18.4 Transform XML into HTML using XSLTTag(s): XML...................................................859
18.5 Parse using SAX or DOMTag(s): XML........................................................................860
18.6 Parse an XML stringTag(s): XML.................................................................................863
18.7 Create an XML document with DOMTag(s): XML.......................................................864
18.8 Attach a stylesheet to an XML fileTag(s): XML............................................................865
18.9 Create an XML file and attach an XSLTag(s): XML XML............................................866
18.10 Nicely display WEB.XML informationsTag(s): Servlet/JSP XML Jaguar/EAServer...869
18.11 Serialize an object using XMLTag(s): XML................................................................871
18.12 Convert a flat file to XML (SAX)Tag(s): XML.............................................................872
18.13 Convert a flat file to XML (DOM)Tag(s): XML............................................................874
18.14 Convert a ResultSet to XMLTag(s): JDBC XML........................................................876
18.15 Parse with XPathTag(s): XML....................................................................................878
18.16 Strip extra spaces in a XML stringTag(s): XML.........................................................882
18.17 Create an XML file and attach an XSLTag(s): XML XML..........................................882
18.18 Use XML with PropertiesTag(s): Language XML.......................................................885
18.19 Change a particular node in XMLTag(s): XML...........................................................886
18.20 Validate XML using a DTDTag(s): XML.....................................................................887
18.21 Validate XML using a XSD (XML Schema)Tag(s): XML............................................891
18.22 Sanitize XML String Tag(s): XML...............................................................................896
18.23 Produce HTML entities when using XSLTTag(s): XML.............................................897
18.24 Create a RSS feed (part 1)Tag(s): XML....................................................................897
18.24.1 RSS 2.0.............................................................................................................898
18.24.2 Atom..................................................................................................................899
18.24.3 Creating a feed..................................................................................................900
18.24.4 Creating a feed with Apache Commons Digester.............................................900
18.24.5 Creating a feed with Rome................................................................................901
18.25 Creating an RSS Feed (part 2)Tag(s): XML..............................................................903
18.26 Parse a RSS XML fileTag(s): XML............................................................................908
18.26.1 Parsing a feed with Apache Commons Digester...............................................909
18.26.2 Parsing a feed with ROME................................................................................910
18.26.3 RSSUTIL.TLD.................................................................................................910
18.27 Add a Live bookmarkTag(s): XML.............................................................................911
18.28 Validate a RSS feedTag(s): XML...............................................................................911
18.29 Attach a CSS to RSS feedTag(s): XML.....................................................................911
19 DEPRECATED...........................................................................................................................914
19.1 javadeprecated..........................................................................................................914
19.2 * Read me * (this howto is deprecated)Tag(s): DEPRECATED.................................914
19.3 Keep the console open after execution (this howto is deprecated)Tag(s):
DEPRECATED...................................................................................................................914
19.4 Read the Registry (this howto is deprecated)Tag(s): DEPRECATED.........................915
19.5 Call a Win API (this howto is deprecated)Tag(s): DEPRECATED...............................916
19.6 Display a BMP image (this howto is deprecated)Tag(s): DEPRECATED...................917
19.7 Play a WAV audio file (this howto is deprecated)Tag(s): DEPRECATED...................918
19.8 Detect if the MS JVM is used (this howto is deprecated)Tag(s): DEPRECATED........919
19.9 Get the latest MS JVM (this howto is deprecated)Tag(s): DEPRECATED..................919
Real's HowTo@www.rgagnon.com
19 DEPRECATED
19.10 Uninstalling the MS JVM (this howto is deprecated)Tag(s): DEPRECATED.............919
19.11 Wrap a Java class in a COM object (this howto is deprecated)Tag(s):
DEPRECATED...................................................................................................................920
19.12 Sign an applet (this howto is deprecated)Tag(s): DEPRECATED.............................921
19.13 Bypass the need for a certificate (this howto is deprecated)Tag(s):
DEPRECATED...................................................................................................................922
19.14 Start an executable on the client (this howto is deprecated)Tag(s):
DEPRECATED...................................................................................................................923
19.15 Get rid of the message "Warning unsigned applet window" (this howto is
deprecated)Tag(s): DEPRECATED....................................................................................924
19.16 Read/write a local file from an Applet (this howto is deprecated)Tag(s):
DEPRECATED...................................................................................................................924
19.17 Write "otherbrowserfriendly" code when using the Netscape Capabilities
package (this howto is deprecated)Tag(s): DEPRECATED...............................................926
19.18 Disable the JIT compiler in Netscape or IE (this howto is deprecated)Tag(s):
DEPRECATED...................................................................................................................926
19.19 Start automatically JAVA when opening Netscape (this howto is deprecated)
Tag(s): DEPRECATED........................................................................................................927
19.20 Use Netscape Java Console hidden commands (this howto is deprecated)
Tag(s): DEPRECATED........................................................................................................927
19.21 Avoid the Netscape "Couldn't connect to '' with origin from
'localclasspathclasses'" message. (this howto is deprecated)Tag(s): DEPRECATED...928
19.22 Get the client IP address (deprecated)Tag(s): DEPRECATED.................................928
19.23 Detect the browser/JVM type (deprecated)Tag(s): Environment DEPRECATED.....929
19.24 Post a message on a newsserver using NNTP protocol (this howto is
deprecated)Tag(s): DEPRECATED....................................................................................931
19.25 Read messages from a newsserver (this howto is deprecated)Tag(s):
DEPRECATED...................................................................................................................932
19.26 Get a list of headers from a newsgroup (this howto is deprecated)Tag(s):
DEPRECATED...................................................................................................................933
19.27 Get a list of all available newsgroup from a newsserver (this howto is
deprecated)Tag(s): DEPRECATED....................................................................................934
19.28 Detect if Swing is installed (this howto is deprecated)Tag(s): DEPRECATED..........935
19.29 Make Swing always available from Netscape (this howto is deprecated)Tag(s):
DEPRECATED...................................................................................................................935
19.30 Send email with attachment (DEPRECATED)Tag(s): DEPRECATED......................936
20 String/Number...........................................................................................................................937
20.1 javastringnumber.......................................................................................................937
20.2 * Read me *Tag(s): Language String/Number.............................................................937
20.3 Convert from type X to type YTag(s): String/Number String/Number..........................938
20.4 Strip certain characters from a StringTag(s): String/Number.......................................940
20.5 Replace/remove character in a StringTag(s): String/Number......................................941
20.6 Replace every occurences of a string within a stringTag(s): String/Number...............943
20.7 "Tokenize" a stringTag(s): String/Number...................................................................944
20.8 Split a string using String.split()Tag(s): String/Number................................................949
20.9 Optimize String operationsTag(s): String/Number.......................................................952
20.9.1 StringBuilder (JDK1.5)........................................................................................954
20.10 Remove spaces from a stringTag(s): String/Number.................................................954
Real's HowTo@www.rgagnon.com
20 String/Number
20.11 Test if a String starts with a digit or uppercase letterTag(s): String/Number.............955
20.12 Get InputStream from a StringTag(s): String/Number...............................................956
20.13 Easy String paddingTag(s): String/Number...............................................................956
20.14 Replace \r\n with the <br> tagTag(s): String/Number................................................958
20.15 Unaccent lettersTag(s): Internationalization String/Number......................................958
20.15.1 Using java.text.Normalizer................................................................................959
20.15.2 Using String.replaceAll()...................................................................................959
20.15.3 The String.indexOf()..........................................................................................960
20.16 Apply a mask to StringTag(s): String/Number...........................................................962
20.17 Format a String (JDK1.5)Tag(s): String/Number.......................................................963
20.18 Replace a "\" by "\\"Tag(s): String/Number................................................................964
20.19 Substitute tokens in a StringTag(s): String/Number...................................................965
20.20 Compare accentuated lettersTag(s): Internationalization String/Number..................965
20.21 Create a String with fixed length and filled with a specific characterTag(s):
String/Number.....................................................................................................................967
20.22 Unquote a StringTag(s): String/Number....................................................................967
20.23 Escape HTML special characters from a StringTag(s): String/Number.....................968
20.24 Unescape HTML special characters from a StringTag(s): String/Number.................970
20.25 Using HashMap.........................................................................................................970
20.26 Using Array................................................................................................................972
20.27 Detect nonASCII character in a StringTag(s): Internationalization
String/Number......................................................................................................................974
20.28 Remove HTML tags from a file to extract only the TEXTTag(s): IO
String/Number Networking...................................................................................................975
20.29 Using regular expression...........................................................................................975
20.30 Using javax.swing.text.html.HTMLEditorKit...............................................................976
20.31 Using an HTML parser...............................................................................................977
20.32 Using Apache Tika.....................................................................................................977
20.33 Extract links from an HTML pageTag(s): String/Number Networking........................978
20.34 Using javax.swing.text.html.HTMLEditorKit...............................................................978
20.35 Using an HTML parser...............................................................................................979
20.36 Convert a byte array to a Hex stringTag(s): String/Number.......................................980
20.37 Apply proper uppercase and lowercase on a StringTag(s): String/Number...............981
20.38 Encode/Decode to/from Base64Tag(s): String/Number Networking.........................982
20.39 Using javax.mail.internet.MimeUtility.........................................................................982
20.40 Using Apache Commons Codec................................................................................983
20.41 MiGBase64................................................................................................................984
20.42 Justify a string with wordwrapTag(s): String/Number................................................984
20.43 Shorten a long pathTag(s): IO String/Number...........................................................985
20.44 Ellipse a StringTag(s): String/Number.......................................................................989
20.45 Display Ascii Banner Tag(s): String...........................................................................990
20.46 Convert from type X to type YTag(s): String/Number String/Number........................991
20.47 Type conversion (JDK1.5)Tag(s): String/Number......................................................993
20.48 Round a doubleTag(s): String/Number......................................................................994
20.49 Display numbers with commasTag(s): String/Number...............................................995
20.50 Display numbers in scientific notationTag(s): String/Number....................................996
20.51 Display numbers with leading zeroesTag(s): String/Number.....................................997
20.52 Get a random numberTag(s): String/Number............................................................999
20.53 Convert an UNSIGNED byte to a JAVA typeTag(s): String/Number.........................999
Real's HowTo@www.rgagnon.com
20 String/Number
20.54 Deal with bigendian and littleendian orderTag(s): String/Number.......................1000
20.55 Pass an integer by referenceTag(s): String/Number...............................................1001
20.56 Pass floats as string literals to a methodTag(s): String/Number..............................1001
20.57 Get random numbersTag(s): String/Number...........................................................1002
20.58 Convert number into wordsTag(s): String/Number..................................................1002
20.59 Arithmetic with doubleTag(s): String/Number..........................................................1011
20.60 Detect even/odd numberTag(s): String/Number......................................................1011
20.61 Convert bytes to megabytesTag(s): String/Number.................................................1012
20.62 Validate a numberTag(s): String/Number................................................................1012
20.63 Get a unique identifierTag(s): String/Number Thread Varia....................................1013
20.64 Using java.rmi.dgc.VMID.........................................................................................1013
20.65 Using java.util.UUID.................................................................................................1014
20.66 Using Apache commons..........................................................................................1014
20.67 Using java.util.concurrent.AtomicLong.....................................................................1014
20.68 Validate/Convert a number using the current Locale()Tag(s):
Internationalization String/Number....................................................................................1015
20.69 Convert a fraction to a DoubleTag(s): String/Number..............................................1016
21 Open Source...........................................................................................................................1018
21.1 javaos......................................................................................................................1018
21.2 Call Windows API (Open source solution)Tag(s): JNI Open Source.........................1018
21.3 Call COM objectTag(s): Open Source.......................................................................1018
21.4 com4j.........................................................................................................................1018
21.5 jinterop.....................................................................................................................1019
21.6 jxchange..................................................................................................................1019
21.7 Run JAVA as a Windows serviceTag(s): Environment Open Source........................1019
21.8 Create entityrelation diagramTag(s): Open Source Open Source...........................1020
21.9 Java Remote desktop toolTag(s): Open Source........................................................1020
21.10 Create entityrelation diagramTag(s): Open Source Open Source.........................1021
21.11 Launch a java program as a Windows EXE fileTag(s): Open Source.....................1021
21.12 WinRun4J................................................................................................................1021
21.13 JSmooth...................................................................................................................1022
21.14 Launch4J.................................................................................................................1022
21.15 Handle CSV fileTag(s): IO Open Source.................................................................1022
21.16 com.Ostermiller.util CSV Utils..................................................................................1023
21.17 opencsv....................................................................................................................1023
21.18 ServingXML.............................................................................................................1023
21.19 Super CSV...............................................................................................................1023
21.20 csvreader.................................................................................................................1023
21.21 CSVFile....................................................................................................................1023
21.22 FlatPack...................................................................................................................1023
21.23 CSVJDBC................................................................................................................1023
21.24 FFP..........................................................................................................................1023
21.25 Handle Excel filesTag(s): IO JDBC Open Source....................................................1024
21.26 JDBCODBC Excel driver.......................................................................................1024
21.27 JExcel......................................................................................................................1024
21.28 POI...........................................................................................................................1025
21.29 JXLS........................................................................................................................1025
21.30 xlSQL.......................................................................................................................1026
Real's HowTo@www.rgagnon.com
21 Open Source
21.31 JCOM.......................................................................................................................1027
21.32 OpenXLS Java Spreadsheet SDK...........................................................................1028
21.33 Browse a Queue (JMS/MQ)Tag(s): Open Source...................................................1030
21.34 Convert a .class to .java file (decompiler)Tag(s): Open Source..............................1030
21.35 Jad...........................................................................................................................1030
21.36 JadClipse.................................................................................................................1031
21.37 JD Java decompiler..............................................................................................1031
21.38 JarPlug.....................................................................................................................1031
21.39 Deploy an application as only 1 jarTag(s): Open Source.........................................1032
21.40 OneJar...................................................................................................................1032
21.41 Fat Jar......................................................................................................................1032
21.42 Read an Outlook MSG fileTag(s): Networking Open Source...................................1032
21.43 Apache POI HSMF..................................................................................................1033
21.44 msgparser................................................................................................................1035
21.45 jmbox.......................................................................................................................1035
21.46 File/directory polling to detect changeTag(s): IO Open Source...............................1036
21.47 jpoller (directory poller)............................................................................................1036
21.48 JNotify......................................................................................................................1036
21.49 Java Native Access (JNA).......................................................................................1036
21.50 Call native methods in a DLL from Java (NativeCall)..............................................1036
21.51 Java 7......................................................................................................................1037
21.52 The simple (and naive!) approach...........................................................................1037
21.53 Clear the console and control attributesTag(s): IO Open Source............................1037
21.54 Jansi.........................................................................................................................1037
21.55 JCurses....................................................................................................................1038
21.56 Disable Checkstyle from code Tag(s): OpenSource................................................1039
21.57 Create or process a PDF fileTag(s): IO Open Source.............................................1040
21.58 Create a PDFTag(s): IO Open Source.....................................................................1042
21.59 iText.........................................................................................................................1042
21.60 Split a PDF file (using iText)Tag(s): IO Open Source..............................................1043
21.61 Concatenate PDF files (using iText)Tag(s): IO Open Source..................................1045
21.62 Convert TIF to PDFTag(s): AWT IO IO Open Source..............................................1046
21.63 Convert HTML to PDF using iTextTag(s): IO Open Source.....................................1048
21.64 Convert HTML to PDF using YAHP Tag(s): IO OpenSource...................................1050
21.65 Convert a png/jpg/gif file to PDF using iTextTag(s): IO Open Source.....................1052
21.66 Print a PDFTag(s): IO Open Source........................................................................1053
21.67 Extract text from a PDF (with Apache Tika) Tag(s): IO OpenSource......................1053
21.68 Detect and remove blank page in pdf (iText)Tag(s): PDF.......................................1054
1 Applet
1.1 javaapplet
or
getAppletContext().showDocument
(new URL("http://www.whatever.com"),"HTML FRAME ID");
If "HTML frame ID" do not exists then a new browser window will be opened. The following "HTML
frame ID" have special meanings :
"_self"
"_parent"
"_top"
"_blank"
current frame
parent frame
base frame
new window
For example, we want to display lowres.html page if resolution is 640x480 else the hires.html is
used.
import java.applet.*;
import java.awt.*;
import java.net.*;
public class whatres extends Applet {
public void init() {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
if (dim.width==640 &dim.height==480) {
try {
getAppletContext().showDocument
(new URL(getCodeBase()+"lowres.html"),"_top");
}
catch (Exception ex) {}
}
else {
try {
getAppletContext().showDocument
(new URL(getCodeBase()+"hires.html"),"_top");
}
catch (Exception ex) {}
}
1 Applet
}
}
NOTE: The previous example works only so long as the document was retrieved without specifying an actual document name, since
getDocumentBase() returns the full URL including the name of the document. If the document name was specified, you should try something
like this or specify the complete URL (thanks to Rob Judd): :
try {
String docString = getDocumentBase().toString();
if (docString.endsWith("/")) {
getAppletContext().showDocument
(new URL(getDocumentBase()+"lowres.html"), "_top");
}
else {
getAppletContext().showDocument
(new URL(getDocumentBase()+"/../lowres.html"), "_top");
}
}
catch (Exception e) {}
Another example, type a new URL in a textfield, and press a button to go to that page.
import
import
import
import
java.applet.*;
java.awt.*;
java.awt.event.*;
java.net.*;
Try it here.
1 Applet
Try it here
1.3 Determine the host from where the Applet is loadedTag(s): Applet
int width;
public void init(){
message = getParameter("message");
if(message == null)
message = " Isn't scrolling text in the status line annoying? ";
String ws = getParameter("width");
if(ws == null) {
width = 36;
}
else{
width = Integer.valueOf(ws).intValue();
}
if(width < 5 || width > 180) {
width = 36;
}
buffer = new StringBuffer(width);
buffer.setLength(width);
at = 0;
if(message.length() < width) {
char buf[] = new char[width];
for(int i = 0; i < width; ++i) {
buf[i] = ' ';
}
message.getChars
(0, message.length(), buf, (width message.length()) / 2);
message = new String(buf);
}
}
public void start(){
thread = new Thread(this);
thread.start();
}
public void stop(){
thread.stop();
}
public void scroll(){
int ml = message.length();
int k = at;
for(int i = 0; i < width; ++i, ++k){
if(k >= ml) {
k = 0;
}
buffer.setCharAt(i, message.charAt(k));
}
getAppletContext().showStatus(buffer.toString());
at++;
if(at >= ml) {
at = 0;
}
}
public void run(){
while(true){
scroll();
try{
Thread.sleep(25); // wait 25 ms
1.3 Determine the host from where the Applet is loadedTag(s): Applet
}
catch(InterruptedException e){
break;
}
}
}
}
Try it here.
Try it here.
It's not easy to call Google from an Applet but you can do it in application as seen in this HowTo.
java.applet.*;
java.awt.*;
java.util.*;
java.text.*;
SimpleDateFormat formatter;
String previousDateText = "";
String dateText;
MyPanel(String df) {
super();
formatter = new SimpleDateFormat(df);
validate();
setBackground(new Color(0).black);
setForeground(new Color(0).yellow);
b = this.getBackground();
f = this.getForeground();
mct = new MyClockThread(this);
mct.start();
}
public Dimension getPreferredSize() {
return new Dimension
(this.getFontMetrics(this.getFont()).stringWidth(getNow()) + 25, 30);
}
public void paint(Graphics g) {
if (g != null) {
g.setColor(b);
g.drawString(previousDateText,10,15);
g.setColor(f);
dateText = getNow();
g.drawString(dateText,10,15);
previousDateText = dateText;
}
}
public String getNow() {
return formatter.format(new Date());
}
}
class MyClockThread extends Thread {
MyPanel mp;
public MyClockThread(MyPanel a) {
mp = a;
}
public void run() {
while (true) {
try {
mp.repaint();
this.sleep(1000);
}
catch(InterruptedException e) { }
}
}
}
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="MyClock.class"
HEIGHT=25 WIDTH=200>
<PARAM NAME="format" VALUE="yyyyMMdd hh:mm:ss">
</APPLET><P>
<APPLET CODE="MyClock.class"
HEIGHT=25 WIDTH=200>
<PARAM NAME="format" VALUE="h:mm a">
</APPLET><P>
<APPLET CODE="MyClock.class"
HEIGHT=25 WIDTH=200>
<PARAM NAME="format" VALUE="yyyy.MMMMM.dd GGG hh:mm aaa">
</APPLET><P>
<APPLET CODE="MyClock.class"
HEIGHT=25 WIDTH=200>
<PARAM NAME="format" VALUE="H:mm:ss:SSS">
</APPLET><P>
/BODY/HTML
Try it here.
1.7 Have Applets on the same page communicate with each otherTag(s): Applet
[Applet2_0022.java]
import java.awt.*;
public class Applet2_0022 extends java.applet.Applet {
TextArea textBox;
public void init() {
setLayout(new FlowLayout());
textBox = new TextArea( 5, 40 );
add( textBox );
}
public void append( String msg ) {
textBox.append( msg );
textBox.append( "\n" );
}
}
[HTML]
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="Applet1_0022.class"
NAME="applet1"
HEIGHT=200 WIDTH=150>
</APPLET>
<APPLET CODE="Applet2_0022.class"
NAME="applet2"
HEIGHT=200 WIDTH=400>
</APPLET>
</BODY></HEAD>
Try it here.
1.8 Have Applets on different frames communicates with each otherTag(s): Applet
Try it here.
Check this DDJ article for a more elaborate way to implement this principle.
There is one way to do it by using a Javascript function as a bridge, take a look at this Howto.
1.8 Have Applets on different frames communicates with each otherTag(s): Applet
FirstAppletJ.java
import
import
import
import
java.applet.*;
java.awt.*;
java.awt.event.*;
java.net.*;
SecondAppletJ.html
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="SecondAppletJ.class"
HEIGHT=100
WIDTH=400>
/APPLET/BODY/HTML
1.9 Send a message from an Applet to another Applet on a different pageTag(s): Applet
SecondApplet.java
import java.applet.*;
import java.awt.*;
import java.net.*;
public class
public void
Label l =
add (l);
TextField
add(tf);
tf.setText(theMessage);
}
}
You can try it here! NOTE : On IE, you must be connected to the Internet
1.9 Send a message from an Applet to another Applet on a different pageTag(s): Applet
System.out.println( e );
}
validate();
}
public void start(){
appletThread = new Thread(this);
appletThread.start();
}
public void stop() {
appletThread.stop();
appletThread = null;
}
public void appletResize( int width, int height ){
resize( width, height );
}
}
try it here.
will print the current user. You can't use this technique to secure your application since it is very to
spoof.
1.11 Get the user nameTag(s): Applet Security
In Applet there is no way unless you ask for it or use a signed applet. If you have access to a
serverside, something like an ASP page can be used to detect the current NT user name if the
client and the server are configured correcty (SSO).
See this related HowTo for a JSP hack!
java.applet.Applet;
java.io.UnsupportedEncodingException;
java.util.HashMap;
java.util.Map;
@SuppressWarnings("serial")
public class AppletUrlParams extends Applet {
HashMap<String,String> parmsMap ;
public void init() {
/*
dump to the console the URL, the search and search values
the URL http://myserver.com/mypage.html?value1=x&value2=y&value3=z
the search value1=x&value2=y&value3=z
the values value1=x
value2=y
value3=z
then the values are stored in a map for easy reference.
ex. String name = parmsMap.get("name")
*/
try {
doit();
dumpMap(parmsMap);
Test it here.
The result in the Java console should be :
key : firsparam value : Hello
key : secondparam value : World
key : thirdparam value : Hello World
To be able to use the same class as an application, we simply extend a Panel instead of an Applet,
put it in Frame and call the init() method.
import java.awt.*;
public class UnderlineText extends Panel{
String s = "Java Howto";
int x=20;
int y=50;
public static void main(String[] args) {
Frame f = new Frame();
f.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent e) {
System.exit(0);
};
});
UnderlineText ut = new UnderlineText();
ut.setSize(100,100); // same size as defined in the HTML APPLET
f.add(ut);
f.pack();
ut.init();
f.setSize(100,100 + 20); // add 20, seems enough for the Frame title,
f.show();
}
public void init() {
add(new Button("Real's"));
}
public void paint(Graphics g) {
g.drawString(s, x,y);
g.drawLine(x , y+2 , x+getFontMetrics(getFont()).stringWidth(s) , y+2 );
}
}
CROSSHAIR_CURSOR, DEFAULT_CURSOR,
E_RESIZE_CURSOR, HAND_CURSOR
MOVE_CURSOR, N_RESIZE_CURSOR,
NE_RESIZE_CURSOR, NW_RESIZE_CURSOR;
S_RESIZE_CURSOR,SE_RESIZE_CURSOR,
SW_RESIZE_CURSOR, TEXT_CURSOR,
W_RESIZE_CURSOR, WAIT_CURSOR
[JDK1.1]
// setCursor is supported at the component level
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
TILE BACKGROUND
in the HTML use :
PARAM NAME="bgImage" VALUE="images/myImage.jpg"
in the APPLET tag
/HMTL
Try it here.
1.16.1 Solution #1
The workaround for an APPLET (to bypass the manual activation) is to generate in Javascript the
APPLET tag but you need to generate it from an outside JS page!
<html>
<body leftmargin=0 topmargin=0 scroll=no>
<script src="myapplet.js"></script>
</body>
</html>
NOTE If you uncheck the Disable Script Debugging (Internet Explorer) option in the Advanced Tab
of the Internet Options Control Panel, controls will still require activation.
NOTE: While inactive controls do not respond to direct user interaction; they do respond to script
commands.
Try a page with the regular APPLET tag here.
And now the same APPLET but with an external JS file here.
Both on the same page (same Applet), here!
The workaround suggested by Microsoft is fine with static APPLET tag but if your APPLET tag
needs to be generated by a JSP ou Servlet (to adjust the PARAM parameters for example) then
you're out of luck because the APPLET declaration is in a JS file which is a static file.
1.16.2 Solution #2
As seen in this article, all you need is to change the content from an outside file. So you need a
generic JS function to rewrite the APPLET tag with the original and that's it!
The main HTML (in BODY tag we call our "rewrite" function) :
<HTML><HEAD></HEAD>
<BODY onload="rewriteApplet();">
<p>This example "rewrite" the applet tag from an external JS.
This way you can generate the Applet tag from a JSP like before.
<P>
<script language="Javascript1.2" src="./rewriteapplet.js">
</script>
<APPLET CODE="TextFieldWithLimitApplet.class"
HEIGHT=100
WIDTH=300>
</APPLET>
</BODY></HTML>
Try it here!
The same principle can be used for the OBJECT tag.
This site http://www.ediy.co.nz/internetexplorerflashappletactivationfixxidc19237.html offers
a really small JS script (only 292 bytes long) to handle the situation.
IMPORTANT NOTES :
AFAIK, this trick does not work from a FRAME!
If you have PARAM tags associated with the applet then they will be replaced by two strange
PARAMS (_CX and _CY)! So beware... It looks that this behaviour has something to do with the
1.16.2 Solution #2
fact that the Java plugin is an ActiveX. PreXP SP2 installation are not supposed to do that kind
of substitution (not verified!).
For simple applet with no param, this is an interesting generic solution.
1.16.3 Solution #3
This solution is a little bit ugly but there is no better solution when you have dynamic APPLET
PARAM generated on the serverside.
The requirement is to write only the APPLET tag from an outside JS file, the PARAMS can be
handled by the main page like before! The trick is to have 2 external JS function, one to write the
<APPLET> tag (and the static PARAM if any) and a second function to write the </APPLET>. The
enclosed dynamic PARAM parameters are generated by the JSP (ASP page).
[rewriteapplet.js]
function writeHeader(urlApplet) {
document.write
('<applet codebase="' + urlApplet + '" code="myApplet.class"')
document.write
(' width="100%" height="98%" hspace="0" vspace="0" align="middle" >')
document.write
('
<PARAM NAME="printdialog" VALUE="false">')
}
function writeFooter() {
document.write('</applet>')
}
1.16.3 Solution #3
<script>
writeFooter();
/script
Next, on the Advanced tab, select Java Console > Display the console.
The next time when loading an applet, the java console will display with a full trace.
The log is stored in a file. For Windows, the file is C:\Documents and
Settings\[YourAccount]\Application Data\Sun\Java\Deployment\log\plugin[version].log/trace
1.18 See the Java Console Window Log (Java plugin)Tag(s): Applet Environment
.. or you can insert your Applet into an invisible frame. See this HowTo for an example.
or you unselect the new generation Java plugin option in the Java Panel.
java.applet.*;
java.awt.event.*;
java.awt.*;
netscape.javascript.*;
Don't forget the MAYSCRIPT parameter in the APPLET tag, it's required since the Applet is using
the JSObject to interact with the Javascript.
<html>
<head>
<script>
function getUserAgent() {
return navigator.userAgent;
}
</script>
</head><body>
<applet code="GetUserAgent.class" MAYSCRIPT height=100 width=500></Applet>
</body>
</html>
Try it here
You need to parse the returned value to detect browser type. Look at this utility,
http://code.google.com/p/useragentutils/ or at this code :
http://nerds.palmdrive.net/useragent/code.html to get the idea.
The getYear() method returns the number of years elapsed after the year 1900. So for year 2000,
mydate.getYear() will return 100. So 100 + 1900 = 2000.
2.3 Get the current Date and TimeTag(s): Date and Time
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java0106.html
import java.util.Calendar;
import java.text.SimpleDateFormat;
public class DateUtils {
public static final String DATE_FORMAT_NOW = "yyyyMMdd HH:mm:ss";
public static String now() {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
return sdf.format(cal.getTime());
}
public static void main(String arg[]) {
System.out.println("Now : " + DateUtils.now());
}
}
Another way would be to compute the julian day number of both dates and then do the substraction.
See this HowTo. Thanks to P. Hill for the tip.
The package java.util.concurrent.TimeUnit; provides a class to make conversion between
milliseconds and days easier.
import java.util.*;
import java.util.concurrent.TimeUnit;
public class DateUtils {
private DateUtils() { }
public static long getDifference(Calendar a, Calendar b, TimeUnit units) {
return
units.convert(b.getTimeInMillis() a.getTimeInMillis(), TimeUnit.MILLISECONDS);
}
/*
testing
*/
public static void main(String[] args) {
java.text.SimpleDateFormat sdf =
new java.text.SimpleDateFormat("yyyyMMdd");
Calendar augustfirst2008 = Calendar.getInstance();
augustfirst2008.set(2008, Calendar.AUGUST, 1); // 20080801
Calendar today = Calendar.getInstance();
// today
System.out.println
(getDifference(augustfirst2008,today,TimeUnit.DAYS)
+ " day(s) between "
+ sdf.format(augustfirst2008.getTime()) + " and "
+ sdf.format(today.getTime()));
}
/*
* output :
*
921 day(s) between 20080801 and 20110208
*/
}
Actually, the Calendar class provides a method to that very simply. For a given Calendar or
GregorianCalendar object :
calObject.getActualMaximum(calobject.DAY_OF_MONTH)
In the Java API documentation there is a note saying that The version (getActualMaximum()) of this
function on Calendar uses an iterative algorithm to determine the actual maximum value for the
field. There is almost always a more efficient way to accomplish this (in most cases, you can simply
return getMaximum()). GregorianCalendar overrides this function with a more efficient
implementation. So it looks like it's a lot more efficient to call getActualMaximum from a
GregorianCalendar object than a Calendar object. (Thanks to P. Harris for the tip)
gregCalObject.getActualMaximum(gregCalObject.DAY_OF_MONTH)
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(" 19001213 valid ? "
+ DateUtils.isValidDateStr("19001213"));
// "199012/13" throws a ParseException
System.out.println(" 190012/13 valid ? "
+ DateUtils.isValidDateStr("190012/13"));
// "19901312" throws a IllegalArgumentException
System.out.println(" 19001312 valid ? "
+ DateUtils.isValidDateStr("19001312"));
/*
* output :
* 19001213 valid ? true
* 190012/13 valid ? false
* 19001312 valid ? false
*/
}
}
Using SimpleDateFormat
package com.rgagnon.howto;
import java.text.*;
public class DateUtils {
public static boolean isValidDateStr(String date, String format) {
try {
SimpleDateFormat sdf = new SimpleDateFormat(format);
sdf.setLenient(false);
sdf.parse(date);
}
catch (ParseException e) {
return false;
}
catch (IllegalArgumentException e) {
return false;
}
return true;
}
public static void main(String[] args) {
System.out.println(" 19001213 valid ? "
+ DateUtils.isValidDateStr("19001213","yyyyMMdd"));
// "199012/13" throws a ParseException
System.out.println(" 190012/13 valid ? "
+ DateUtils.isValidDateStr("190012/13","yyyyMMdd"));
// "19901312" throws a IllegalArgumentException
System.out.println(" 19001312 valid ? "
+ DateUtils.isValidDateStr("19001312","yyyyMMdd"));
/*
* output :
* 19001213 valid ? true
* 190012/13 valid ? false
* 19001312 valid ? false
*/
}
+ sdf.format(c1.getTime()));
c1.set(1999, 0 , 20); // 1999 jan 20
System.out.println("Date is : " + sdf.format(c1.getTime()));
c1.add(Calendar.MONTH, 1); // substract 1 month
System.out.println
("Date minus 1 month : "
+ sdf.format(c1.getTime()));
/*
* output :
* Date is : 19990120
* Date roll down 1 month : 19991220
* Date is : 19990120
* Date minus 1 month : 19981220
*/
}
}
if (c1.equals(c2)) {
System.out.print(" same as ");
}
System.out.println(sdf.format(c2.getTime()));
}
}
java.util.Date;
java.util.Locale;
java.util.Calendar;
java.text.SimpleDateFormat;
2.13 Use System time to generate unique IDTag(s): Date and Time Date and Time Varia
e.printStackTrace();
return "";
}
}
}
An alternate way :
import
import
import
import
java.util.Calendar;
java.text.SimpleDateFormat;
java.text.DateFormat;
java.text.DateFormatSymbols;
ja = (int) julian
if (ja>= JGREG) {
jalpha = (int) (((ja 1867216) 0.25) / 36524.25);
ja = ja + 1 + jalpha jalpha / 4;
}
jb = ja + 1524;
jc = (int) (6680.0 + ((jb 2439870) 122.1) / 365.25);
jd = 365 * jc + jc / 4;
je = (int) ((jb jd) / 30.6001);
day = jb jd (int) (30.6001 * je);
month = je 1;
if (month > 12) month = month 12;
year = jc 4715;
if (month > 2) year;
if (year <= 0) year;
return new int[] {year, month, day};
}
public static void main(String args[]) {
// FIRST TEST reference point
System.out.println("Julian date for May 23, 1968 : "
+ toJulian( new int[] {1968, 5, 23 } ));
// output : 2440000
int results[] = fromJulian(toJulian(new int[] {1968, 5, 23 }));
System.out.println
("... back to calendar : " + results[0] + " "
+ results[1] + " " + results[2]);
// SECOND TEST today
Calendar today = Calendar.getInstance();
double todayJulian = toJulian
(new int[]{today.get(Calendar.YEAR), today.get(Calendar.MONTH)+1,
today.get(Calendar.DATE)});
System.out.println("Julian date for today : " + todayJulian);
results = fromJulian(todayJulian);
System.out.println
("... back to calendar : " + results[0] + " " + results[1]
+ " " + results[2]);
// THIRD TEST
double date1 = toJulian(new int[]{2005,1,1});
double date2 = toJulian(new int[]{2005,1,31});
System.out.println("Between 20050101 and 20050131 : "
+ (date2 date1) + " days");
/*
expected output :
Julian date for May 23, 1968 : 2440000.0
... back to calendar 1968 5 23
Julian date for today : 2453487.0
... back to calendar 2005 4 26
Between 20050101 and 20050131 : 30.0 days
*/
}
}
There is a lot of variation around the idea of a "Julian date". You can have the Modified Julian Date
(JD) or the Truncated Julian Date (TJD). The main difference is the starting for counting the days.
Before Y2K, many applications (especially mainframe systems) were storing dates in a format
called "the Julian format". This format is a 5 digit number, consisting of a 2 digit year and a 3 digit
dayofyear number. For example, 17July1998 is stored as 98221, since 17July is the 221th
day of the year. This format is not really useful since Y2K! The main reason for using the 5digits
Julian date was to save disk space and still have a format easy to use to handle. dates.
A variation of this idea is to used the first four digits for the year and 3 digits for dayofyear,
17July1998 will be represented by 1998221.
This is a very simple format which can be manipulated easily from Java.
import
import
import
import
java.util.Calendar;
java.util.Date;
java.text.ParseException;
java.text.SimpleDateFormat;
sb.append(cal.get(Calendar.YEAR))
.append(String.format("%03d", cal.get(Calendar.DAY_OF_YEAR)))
.toString();
}
public static void main(String[] args) throws Exception {
String test = "1998221";
Date d = DateUtils.getDateFromJulian7(test);
System.out.println(d);
System.out.println(DateUtils.getJulian7FromDate(d));
/*
* output :
*
Sun Aug 09 00:00:00 EDT 1998
*
1998221
*/
}
}
Using java.util.concurrent.TimeUnit
import java.util.concurrent.TimeUnit;
...
/**
* converts time (in milliseconds) to humanreadable format
* "<dd:>hh:mm:ss"
*/
java.io.*;
java.text.*;
java.util.*;
java.net.*;
}
}
System.out.println("DEBUG : " + atomicTime);
String[] fields = atomicTime.split(" ");
GregorianCalendar calendar = new GregorianCalendar();
String[] date = fields[1].split("");
calendar.set(Calendar.YEAR, 2000 + Integer.parseInt(date[0]));
calendar.set(Calendar.MONTH, Integer.parseInt(date[1])1);
calendar.set(Calendar.DATE, Integer.parseInt(date[2]));
// deals with the timezone and the daylightsavingtime
TimeZone tz = TimeZone.getDefault();
int gmt = (tz.getRawOffset() + tz.getDSTSavings()) / 3600000;
System.out.println("DEBUG : " + gmt);
String[] time = fields[2].split(":");
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]) + gmt);
calendar.set(Calendar.MINUTE, Integer.parseInt(time[1]));
calendar.set(Calendar.SECOND, Integer.parseInt(time[2]));
return calendar;
}
catch (IOException e){
throw e;
}
finally {
if (in != null) {
in.close();
}
}
}
public static void main(String args[]) throws IOException {
SimpleDateFormat sdf =
new SimpleDateFormat("yyyyMMdd HH:mm:ss");
System.out.println("Atomic time : " +
sdf.format(DateUtils.getAtomicTime().getTime()));
}
/*
ref : http://www.bldrdoc.gov/doctour/atomic_clock.html
49825 950418 22:24:11 50 0 0 50.0 UTC(NIST) *
|
These are the last +
five digits of the
Modified Julian Date
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
It's not possible to set your local computer clock in pure Java.
You need to use an external utility provided by the OS or call a JNI routine, see this HowTo.
Month, Week
}
return new Calendar[] { startDate, endDate };
}
public static void main(String[] args) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
System.out.println("** previous month (relative today)");
Calendar [] results = DateUtils.getDateIntervals(IntervalType.Month, null);
System.out.println(sdf.format(results[0].getTime()));
System.out.println(sdf.format(results[1].getTime()));
System.out.println("** previous week (relative today)");
results = DateUtils.getDateIntervals(IntervalType.Week, null);
System.out.println(sdf.format(results[0].getTime()));
System.out.println(sdf.format(results[1].getTime()));
System.out.println("** previous month (relative jan 1, 2007)");
results = DateUtils.getDateIntervals(IntervalType.Month,
new GregorianCalendar(2007, 00, 1));
System.out.println(sdf.format(results[0].getTime()));
System.out.println(sdf.format(results[1].getTime()));
System.out.println("** previous week (relative jan 1, 2007)");
results = DateUtils.getDateIntervals(IntervalType.Week,
new GregorianCalendar(2007, 00, 1));
System.out.println(sdf.format(results[0].getTime()));
System.out.println(sdf.format(results[1].getTime()));
}
catch (Exception e) {
e.printStackTrace();
}
}
/*
output :
** previous
20080601
20080630
** previous
20080630
20080706
** previous
20061201
20061231
** previous
20061225
20061231
*/
}
2.24 Get the month (or day) name (localized)Tag(s): Date and
Time Internationalization
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java0650.html
import java.text.DateFormatSymbols;
import java.util.Locale;
public class DateUtils {
private DateUtils() { }
public static String getMonthName(int month) {
return getMonthName(month, Locale.getDefault());
}
public static String getMonthName(int month, Locale locale) {
DateFormatSymbols symbols = new DateFormatSymbols(locale);
String[] monthNames = symbols.getMonths();
return monthNames[month 1];
}
2.23 Use System time to generate unique IDTag(s): Date and Time Date and Time Varia
args) {
DateUtils.isLeap0(1900));
DateUtils.isLeap0(1996));
DateUtils.isLeap0(2000));
DateUtils.isLeap0(2010));
DateUtils.isLeap1(1900));
DateUtils.isLeap1(1996));
DateUtils.isLeap1(2000));
DateUtils.isLeap1(2010));
DateUtils.isLeap2(1900));
DateUtils.isLeap2(1996));
DateUtils.isLeap2(2000));
DateUtils.isLeap2(2010));
3 AWT
3.1 javaawt
java.awt.Color;
java.awt.Dimension;
java.awt.LayoutManager;
java.awt.Panel;
and then
import
import
import
import
import
import
3 AWT
java.applet.Applet;
java.awt.Button;
java.awt.CardLayout;
java.awt.Choice;
java.awt.Color;
java.awt.Component;
import
import
import
import
import
java.awt.FlowLayout;
java.awt.Panel;
java.awt.TextField;
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
3 AWT
b3.addActionListener(this);
b4.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
//Show the first
((CardLayout)p0.getLayout()).show(p0, "First card");
}
else if (e.getSource() == b2) {
//Show the second
((CardLayout)p0.getLayout()).show(p0, "2nd card");
}
else if (e.getSource() == b3) {
//Show the third
((CardLayout)p0.getLayout()).show(p0, "3rd card");
}
else if (e.getSource() == b4) {
// get the current card
Component c[] = p0.getComponents();
int i = 0;
int j = c.length;
while (i < j) {
if (c[i].isVisible()) {
t2.setText("" + (i+1));
break;
}
else
i ++;
}
}
}
}
<HTML>
<TABLE><TR><TD>
<APPLET CODE=CardLayoutDemo.class WIDTH=300 HEIGHT=300>
</APPLET>
/HMTL
Try it here.
add(b, "South");
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
/*
** handle actions related to popup
*/
System.out.println("actionPerformed, event=" + e );
System.out.println(" command=" + e.getActionCommand());
System.out.println(" param=" + e.paramString());
System.out.println(" source=" + e.getSource());
}
}
void setHash(Component c, PopupMenu p) {
/*
** associate a Component with a particular Popup
*/
popupTable.put(c, p);
}
PopupMenu getHash(Component c) {
/*
** return a Popup associated with a particular Component
*/
return (PopupMenu)(popupTable.get(c));
}
public static void main (String argv[]) {
new PopupTest();
}
}
System.out.println
("Loading : "
+ ufd.loadFile(new Frame(), "Open...", ".\\", "*.java"));
System.out.println
("Saving : "
+ ufd.saveFile(new Frame(), "Save...", ".\\", "*.java"));
System.exit(0);
}
}
by
return fd.getDirectory() +
System.getProperty("file.separator") + fd.getFile();
[JDK1.5]
@todo
[JDK1.2]
import java.awt.*;
public class FontList {
public static void main(String args[]) {
GraphicsEnvironment ge =
GraphicsEnvironment.getLocalGraphicsEnvironment();
String fontNames[] = ge.getAvailableFontFamilyNames();
int j = fontNames.length;
for (int i = 0 ; i < j ;i++ ) {
System.out.println(fontNames[i]);
}
}
}
sm.checkSystemClipboardAccess();
}
catch (Exception e) {e.printStackTrace();}
}
Toolkit tk = Toolkit.getDefaultToolkit();
StringSelection st =
new StringSelection("Hello world from Java");
Clipboard cp = tk.getSystemClipboard();
cp.setContents(st, this);
}
public void lostOwnership(Clipboard clip, Transferable tr) {
System.out.println("Lost Clipboard Ownership?!?");
}
}
NOTE: You can only use text (no graphic) with this functionality provided by the current JDK (1.4).
The "fullscreen" Frame is in exclusive mode. In this mode you can change the resolution
import java.awt.*;
class ScreenRes {
public static void main(String args[]) {
new ScreenRes().doit();
}
public void doit() {
Frame frame = new Frame();
GraphicsDevice device;
device =
GraphicsEnvironment.
getLocalGraphicsEnvironment().
getDefaultScreenDevice();
if ( device.isFullScreenSupported() ) {
device.setFullScreenWindow(frame);
if (device.isDisplayChangeSupported()) {
device.setDisplayMode(
new DisplayMode( 1024, 768,
8, // bitDepth 8 bits 256 colors
DisplayMode.REFRESH_RATE_UNKNOWN ));
}
else {
System.err.println("Change display mode not supported");
}
}
else {
System.err.println("Full screen not supported");
}
}
}
SWING jdk1.3
JFrame frame = new JFrame();
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
// can be
// frame.setExtendedState(Frame.MAXIMIZED_HORIZ);
// frame.setExtendedState(Frame.MAXIMIZED_VERT);
New with JDK1.4, JDialog has method to position a JDialog relative to a parent. For a JWindow or a
JFrame with no parent, then
f.setSize(100,100);
f.setLocationRelativeTo(NULL);
System.exit(0);
return true;
}
return super.handleEvent(evt);
}
[JDK1.1 Method 1]
public aFrame extends Frame implements WindowListener {
public aFrame(){
addWindowListener( this );
}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
public void windowOpened(WindowEvent e){}
public void windowClosing(WindowEvent e){ System.exit(0); }
public void windowClosed(WindowEvent e){}
public void windowIconified(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
}
[JDK1.1 Method 2]
public class aFrame extends Frame {
public aFrame(){
addWindowListener( new Terminate() );
}
}
class Terminate extends WindowAdapter{
public void windowClosing(WindowEvent e){
System.exit(0);
}
}
[JDK1.1 Method 3]
public class aFrame extends Frame {
public aFrame() {
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
}
}
For a Dialog or a Window, a System.exit(0) may not be appropriate, call the dispose() method
instead.
class SimplePopUp extends Dialog
{
SimplePopUp() {
super(new Frame(), "simple popup");
this.addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
e.getWindow().dispose();
}
}
);
}
The Frame after adding the Panel, will act as an ActionListener for events for the 2 Panel buttons.
[TestEventFrame.java]
import java.awt.*;
import java.awt.event.*;
public class TestEventFrame extends Frame implements
ActionListener, WindowListener {
TestEventPanel p1;
Button b1;
TestEventFrame(String title){
super(title);
setLayout(new FlowLayout());
p1 = new TestEventPanel();
b1 = new Button("A dummy button");
add(b1);
}
{ }
{ }
}
and finally
[Java0268.java]
import java.awt.*;
public class Java0268 extends java.applet.Applet {
TestEventFrame myTestEventFrame;
public void init() {
myTestEventFrame =
new TestEventFrame("TestEvent Frame");
}
}
Try it here.
or
frame.setIconImage(
new ImageIcon(
YourApp.class.getResource("logo.png")
).getImage()
);
import java.awt.*;
import java.awt.event.*;
public class TestNoMaximize {
MyFrame theFrame;
public static void main (String args[]){
TestNoMaximize t = new TestNoMaximize();
t.theFrame = new MyFrame("A Dummy Frame");
t.theFrame.setVisible(true);
}
}
class MyFrame extends Frame {
public MyFrame(String title){
super(title);
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
// no minimize or maximize
this.setResizable(false);
this.setSize(200,200);
}
public void paint(Graphics g) {
g.drawString("try to resize me...", 50, 50);
}
}
There is no way to allow minimizing but not maximizing unless you trap the maximizing in the paint
method and then resize to the original size.
import java.awt.*;
import java.awt.event.*;
public class TestNoMaximize {
MyFrame theFrame;
public static void main (String args[]){
TestNoMaximize t = new TestNoMaximize();
t.theFrame = new MyFrame("A Dummy Frame");
t.theFrame.setVisible(true);
}
}
class MyFrame extends Frame {
public MyFrame(String title){
super(title);
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
this.setSize(200,200);
}
System.out.println("Bye.");
System.exit(0);
}
}
);
}
public void update( Graphics g) {
paint(g);
}
public void paint(Graphics g) {
if(image != null) {
int x = 0, y = 0;
while(y < getSize().height) {
x = 0;
while(x< getSize().width) {
g.drawImage(image, x, y, this);
x= x + image.getWidth(null);
}
y = y + image.getHeight(null);
}
}
else {
g.clearRect(0, 0, getSize().width, getSize().height);
}
}
static public void main(String[] args) {
ImageFrame iframe = new ImageFrame();
iframe.setVisible(true);
}
}
The result :
void createFrame() {
Dimension d = getToolkit().getScreenSize();
setLocation(d.width/3,d.height/3);
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == ok) {
isOk = true;
setVisible(false);
}
else if(ae.getSource() == can) {
setVisible(false);
}
}
public static void main(String args[]){
Frame f = new Frame();
f.setSize(200,200);
f.setVisible(true);
MsgBox message = new MsgBox
(f , "Hey you user, are you sure ?", true);
if (message.isOk)
System.out.println("Ok pressed");
if (!message.isOk)
System.out.println("Cancel pressed");
message.dispose();
}
}
this.imgName = imgName;
tk = Toolkit.getDefaultToolkit();
splashImage = loadSplashImage();
showSplashScreen();
f.addWindowListener(new WindowListener());
}
public Image loadSplashImage() {
MediaTracker tracker = new MediaTracker(this);
Image result;
result = tk.getImage(imgName);
tracker.addImage(result, 0);
try {
tracker.waitForAll();
}
catch (Exception e) {
e.printStackTrace();
}
imgWidth = result.getWidth(this);
imgHeight = result.getHeight(this);
return (result);
}
public void showSplashScreen() {
Dimension screenSize = tk.getScreenSize();
setBackground(BORDERCOLOR);
int w = imgWidth + (BORDERSIZE * 2);
int h = imgHeight + (BORDERSIZE * 2);
int x = (screenSize.width w) /2;
int y = (screenSize.height h) /2;
setBounds(x, y, w, h);
setVisible(true);
}
public void paint(Graphics g) {
g.drawImage(splashImage, BORDERSIZE, BORDERSIZE,
imgWidth, imgHeight, this);
}
class WindowListener extends WindowAdapter {
// was windowActivated, thanks to H.Grippa for the fix!
public void windowOpened(WindowEvent we) {
setVisible(false);
dispose();
}
}
}
theFrame.setVisible(true);
}
}
class MyFrame extends Frame {
Splash mySplash;
public MyFrame(String title){
super(title);
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
mySplash = new Splash(this, "jht.gif");
// dummy delay so we can see the Splash!
for(int i = 0; i < 3000; i++) {
System.out.println(i) ;
}
setSize(200,200);
}
}
To make it more Swingoriented, you change the method signature for a JFrame instead.
Here an example.
We display a small window. When a file is added or deleted, the window is shaking for a brief
moment and display the event. By default, the folder c:/temp is used but you can specify another
one on the command line.
First get the code to detect a file modfication in a folder (in this HowTo, you need the DirWatcher
and DirFilterWatcher classes). Plus the following classes.
import java.awt.*;
import java.awt.event.*;
public class DirWatchWindow extends Frame {
Label folder;
Label info;
public DirWatchWindow() {
setTitle("DirWatchWindow");
setSize(600, 100);
setLayout(new BorderLayout());
folder = new Label("");
info
= new Label("");
add(folder, BorderLayout.NORTH);
add(info, BorderLayout.SOUTH);
setVisible(true);
addWindowListener
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
}
public void setInfo(String text) {
info.setText(text);
}
public void setFolder(String dir) {
folder.setText("Watching folder : " + dir);
}
}
import java.util.*;
import java.io.*;
public class DirWatchTest {
public static void main(String args[]) {
String folderToWatch = "c:/temp";
if (args.length > 0) {
folderToWatch = args[0];
}
final DirWatchWindow dww = new DirWatchWindow();
dww.setFolder(folderToWatch);
TimerTask task = new DirWatcher(folderToWatch, "txt" ) {
protected void onChange( File file, String action ) {
// here we code the action on a change
dww.setInfo("File : "+ file.getName() +" action: " + action);
FrameUtils.vibrate(dww);
}
};
Timer timer = new Timer();
timer.schedule( task , new Date(), 1000 );
}
}
c:/myfolder
to specify your own folder. This demo is watching for files with the extension txt only.
[JDK1.1]
thanks to Lionel Giltay
import java.awt.TextField ;
import java.awt.event.KeyAdapter ;
import java.awt.event.KeyEvent ;
public class NumericTextField extends TextField
{
public NumericTextField (String _initialStr, int _col)
{
super (_initialStr, _col) ;
this.addKeyListener(new KeyAdapter()
{
public void keyTyped (KeyEvent e)
{
char c = e.getKeyChar() ;
if (!
((c==KeyEvent.VK_BACK_SPACE) || (c==KeyEvent.VK_DELETE)
|| (c== KeyEvent.VK_ENTER)
|| (c == KeyEvent.VK_TAB)
|| (Character.isDigit(c))))
{
e.consume() ;
}
}
});
}
public NumericTextField (int _col)
{
this ("", _col) ;
}
3.23 Make the ENTER key act like the TAB keyTag(s): AWT
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java0254.html
First create a TextField that listen to the Enter and react like a Tab key [JDK11]
import java.awt.*;
import java.awt.event.*;
public class MyTextField extends TextField {
MyTextField(int len) {
super(len);
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
int key = evt.getKeyCode();
if (key == KeyEvent.VK_ENTER)
transferFocus();}});
}
}
3.23 Make the ENTER key act like the TAB keyTag(s): AWT
Button b;
public void init() {
add(t1= new TextField(20));
add(t2= new TextField(20));
add(t3= new TextField(20));
t4onPanel = new TextField(20);
p1 = new Panel();
p1.setBackground(new Color(0).yellow);
p1.add(t4onPanel);
add(p1);
add(b = new Button("reset TextFields"));
b.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == b)
resetTextFields(this);
}
public static void resetTextFields(Container c) {
Component [] components = c.getComponents();
for (int i = 0; i <components.length; i++ ) {
if (components[i] instanceof Container)
resetTextFields((Container) components[i]) ;
else if (components[i] instanceof TextField)
((TextField) components[i]).setText("") ;
}
}
}
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="FirstApplet.class"
NAME="myApplet"
HEIGHT=200 WIDTH=200>
</APPLET></BODY></HTML>
add(tf);
tf.addKeyListener(
new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (Character.isLetter(e.getKeyChar()))
e.setModifiers(Event.SHIFT_MASK);
}
});
pack();
addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
}
public Dimension getPreferredSize() {
return new Dimension(200,200);
}
}
down=false;
enabled=true;
InitImage(up_b,down_b);
setSize(w,h);
addMouseListener(new ImageButtonMouseListener());
addMouseMotionListener(new ImageButtonMouseMotionListener());
}
public void InitImage(URL up, URL down) {
MediaTracker tracker;
try {
UPimage = getToolkit().getImage(up);
DOWNimage = getToolkit().getImage(down);
tracker = new MediaTracker(this);
tracker.addImage(UPimage,0);
tracker.addImage(DOWNimage,1);
tracker.waitForAll();
}
catch (InterruptedException e) {
e.printStackTrace();
}
disabledimage=createImage(new FilteredImageSource
(UPimage.getSource(),new ImageButtonDisableFilter()));
w=UPimage.getWidth(this);
h=UPimage.getHeight(this);
}
public void paint(Graphics g) {
if (down) {
g.drawImage(DOWNimage,0,0,this);
}
else {
if (enabled) {
g.drawImage(UPimage,0,0,this);
}
else {
g.drawImage(disabledimage,0,0,this);
}
}
}
public void setEnabled(boolean b) {
enabled=b;
repaint();
}
public boolean isEnabled() {
return (enabled);
}
public void addActionListener(ActionListener l) {
actionListener =
AWTEventMulticaster.add(actionListener,l);
}
public void removeActionListener(ActionListener l) {
actionListener =
AWTEventMulticaster.remove(actionListener, l);
}
public class ImageButtonMouseListener extends MouseAdapter {
public void mousePressed(MouseEvent e) {
Point p = e.getPoint();
if ((p.x < w)&&(p.y < h)&&(p.x > 0)&&(p.y > 0)&&(enabled==true)) {
clicked=true;
down=true;
repaint();
}
}
public void mouseReleased(MouseEvent e) {
Point p = e.getPoint();
if (down) {
down=false;
repaint();
}
if ((p.x < w)&&(p.y < h)&&(p.x > 0)&&(p.y > 0)&&(clicked==true)) {
ActionEvent ae =
new ActionEvent(e.getComponent(),0,"click");
if (actionListener != null) {
actionListener.actionPerformed(ae);
}
}
clicked=false;
}
}
public class ImageButtonMouseMotionListener extends
MouseMotionAdapter {
public void mouseDragged(MouseEvent e) {
Point p = e.getPoint();
if ((p.x < w)&&(p.y < h)&&(p.x > 0)&&(p.y > 0)&&(clicked==true)) {
if (down==false) {
down=true;
repaint();
}
}
else {
if (down==true) {
down=false;
repaint();
}
}
}
}
public Dimension getPreferredSize() {
return (new Dimension(UPimage.getWidth(this),
UPimage.getHeight(this)));
}
public Dimension getMinimumSize() {
return getPreferredSize();
}
class ImageButtonDisableFilter extends RGBImageFilter {
public ImageButtonDisableFilter() {
canFilterIndexColorModel=true;
}
public int filterRGB(int x, int y, int rgb) {
return (rgb &~0xff000000) | 0x80000000;
}
}
}
[TestImageButton.java]
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.net.*;
When inserting a line, we simply pad spaces as needed. Here the first column is 20 characters
wide, the second 10 and the last one the remaining.
insertItem(ml, "ARCHIVE", "STATUS", "PORT");
With a Layout Manager, you have to validate() the layout to redraw the components invalidated.
Label aLabel = new Label("short label");
aLabel.setText ("A very long label");
this.validate();
While this method works in Netscape or the Appletviewer, on IE4/5 there is no resizing. You may
want to try this instead (thanks to Dan for the tip):
Label aLabel = new Label("short label");
aLabel.setText(""A very long label");
aLabel.invalidate(); // make sure the component is marked as nonvalid
this.validate();
This example how to change a Label or a String drawn with the drawString method by clicking on a
button.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class TestPaint extends Applet
implements ActionListener {
MyPanel p;
Label l;
Button b1, b2;
TextField t1, t2;
public void init() {
setLayout(new FlowLayout());
t1 = new TextField(10);
b1 = new Button("Change Label");
add(t1); add(b1);
t2 = new TextField(10);
b2 = new Button("Change drawString");
add(t2); add(b2);
l = new Label("label text");
add(l);
// a Panel with a drawString call
p = new MyPanel();
add(p);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
l.setText(t1.getText());
l.invalidate();
validate();
}
if (e.getSource() == b2) {
p.someString = t2.getText();
p.repaint();
}
}
}
class MyPanel extends Panel {
String someString = "drawstring";
MyPanel() { super(); }
public void paint (Graphics g) {
g.drawString(someString, 10,50);
}
public Dimension getPreferredSize() {
return new Dimension (100,100);
}
}
g.drawString(s.substring(j,j+1),x, y+(j*v));
j++;
}
}
}
[JDK1.4]
import java.awt.geom.AffineTransform;
import java.awt.Graphics2D;
Dimension offDimension;
Image offImage;
Graphics offGraphics;
Color borderColor = new Color(0).black;
public MultiLineLabel(String s, int i, boolean b) {
// s the label
// i alignement MultiLineLabel.CENTER, MultiLineLabel.RIGHT,
//
MultiLineLabel.LEFT
//
default MultiLineLabel.LEFT
// b border present or not
setAlignment(i);
setText(s);
setBorder(b);
}
public MultiLineLabel(String string, int i) {
this(string, i, false);
}
public MultiLineLabel(String string) {
this(string, 0);
}
public MultiLineLabel() {
this("", 0);
}
public void addNotify() {
super.addNotify();
calc();
}
public void setX(int i) { x = i;
public void setY(int i) { y = i;
}
}
Font f = getFont();
if (f != null) {
FontMetrics fm = getFontMetrics(f);
if (fm != null) {
line_height = fm.getHeight();
line_ascent = fm.getAscent();
max_width = 0;
for (int i = 0; i < num_lines; i++) {
line_widths[i] =
fm.stringWidth(lines[i]);
if (line_widths[i] > max_width)
max_width = line_widths[i];
}
}
}
}
public void update(Graphics g) {
super.paint(g);
Dimension d = getSize();
if ( (offGraphics == null) ||
(d.width != offDimension.width) ||
(d.height != offDimension.height)
) {
offDimension = d;
offImage = createImage(d.width, d.height);
offGraphics = offImage.getGraphics();
}
offGraphics.setColor(getBackground());
offGraphics.fillRect
(x, y, getSize().width 1,
getSize().height 1);
if (border) {
offGraphics.setColor(borderColor);
offGraphics.drawRect
(x, y, getSize().width 1, getSize().height 1);
}
int j = line_ascent +
(d.height num_lines * line_height) / 2;
for (int k = 0; k < num_lines; ) {
int i;
switch (alignment) {
case 0:
i = 0;
break;
case 2:
i = d.width line_widths[k];
break;
default:
i = (d.width line_widths[k]) / 2;
break;
}
i += leftRightMargin;
offGraphics.setColor(getForeground());
offGraphics.drawString(lines[k], i + x, j + y);
k++;
j += line_height;
}
g.drawImage(offImage,0,0,this);
}
public void paint(Graphics g) {
update(g);
}
public static void main(String args[]){
Frame f = new Frame("Test MultiLineLabel");
f.setSize(200,200);
f.setLayout(new FlowLayout());
f.setVisible(true);
MultiLineLabel mll1 = new MultiLineLabel
("This a test!\nsecond line\nthird line",
MultiLineLabel.LEFT, true);
// mll1.setBorderColor(new Color(0).blue);
mll1.setLeftRightMargin(15);
mll1.setTopBottomMargin(15);
f.add(mll1);
Button b = new Button("Dummy");
f.add(b);
MultiLineLabel mll2 = new MultiLineLabel
("123\n4\n567", MultiLineLabel.RIGHT, false);
mll2.setForeground(new Color(0).yellow);
mll2.setBackground(new Color(0).black);
f.add(mll2);
f.validate();
}
}
this.getFontMetrics(this.getFont()).stringWidth(this.getText()),
r.height this.getFontMetrics(this.getFont()).getDescent());
}
}
[TestUnderlinedLabel.java]
import java.applet.*;
import java.awt.*;
public class TestUnderlinedLabel extends Applet {
public void init() {
UnderlinedLabel ul1 =
new UnderlinedLabel
("Java Howto");
add(ul1);
}
}
[testapplet.html]
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="TestUnderlinedLabel.class"
NAME="myApplet"
HEIGHT=200 WIDTH=200>
/APPLET/BODY/HTML
Check this Howto for underlined text in Swing.
java.applet.*;
java.awt.*;
java.awt.event.*;
java.net.*;
public URLLabel
(Applet applet , String url, String text, String target){
super(text);
setForeground(unvisitedURL);
try {
this.applet = applet;
this.url = new URL(url);
this.target = target;
addMouseListener( new Clicked() );
}
catch (Exception e) {
e.printStackTrace();
}
}
public void paint(Graphics g) {
Rectangle r;
super.paint(g);
r = g.getClipBounds();
g.drawLine(0,
r.height this.getFontMetrics(this.getFont()).getDescent(),
this.getFontMetrics(this.getFont()).stringWidth(this.getText()),
r.height this.getFontMetrics(this.getFont()).getDescent());
}
public void setUnvisitedURLColor(Color c) {
unvisitedURL = c;
}
public void setVisitedURLColor(Color c) {
visitedURL = c;
}
class Clicked extends MouseAdapter{
public void mouseClicked(MouseEvent me){
setForeground(visitedURL);
applet.getAppletContext().showDocument(url, target);
}
}
}
[TestURLLabel.java]
import java.applet.*;
import java.awt.*;
public class TestURLLabel extends Applet {
public void init() {
URLLabel ull1 = new URLLabel(this,
"http://www.rgagnon.com/howto.html",
"Java Howto");
add(ull1);
URLLabel ull2 = new URLLabel(this,
"http://www.rgagnon.com/bigindex.html",
"Java Howto BigIndex");
add(ull2);
URLLabel ull3 = new URLLabel(this,
"http://www.rgagnon.com/javadetails/java0001.html",
"Java Howto 0001");
add(ull3);
URLLabel ull4 = new URLLabel(this,
"http://www.rgagnon.com/javadetails/java0002.html",
"Java Howto 0002");
add(ull4);
validate();
}
}
[testapplet.html]
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="TestURLLabel.class"
NAME="myApplet"
HEIGHT=200 WIDTH=200>
</APPLET></BODY></HTML>
Try it here.
frame.resize(400,400);
frame.show();
}
}
}
public void update( Graphics g) {
paint(g);
}
public void paint(Graphics g) {
if(image != null) {
int x = 0, y = 0;
while(y < getSize().height) {
x = 0;
while(x< getSize().width) {
g.drawImage(image, x, y, this);
x= x + image.getWidth(null);
}
y = y + image.getHeight(null);
}
}
else {
g.clearRect(0, 0, getSize().width, getSize().height);
}
}
static public void main(String[] args) {
ImageFrame iframe = new ImageFrame();
iframe.setVisible(true);
}
}
The result :
java.applet.*;
java.awt.*;
java.io.*;
java.net.*;
{
this);
this);
this);
Remember that it is always possible to the Java builtin icons so that you don't have to include your
own standard icons.
public static Icon getIconForType(int iconType) {
switch (iconType) {
case 0:
return UIManager.getIcon("OptionPane.errorIcon");
case 1:
return UIManager.getIcon("OptionPane.informationIcon");
case 2:
return UIManager.getIcon("OptionPane.warningIcon");
case 3:
return UIManager.getIcon("OptionPane.questionIcon");
}
return null;
}
Image resizedImage;
public void init() {
MediaTracker media = new MediaTracker(this);
// java howto image for example, can be JPG
source = getImage(getDocumentBase(),"../images/jht.gif");
media.addImage(source,0);
try {
media.waitForID(0);
// scale down, half the original size
ImageFilter replicate =
new ReplicateScaleFilter
(source.getWidth(this)/2, source.getHeight(this)/2);
ImageProducer prod =
new FilteredImageSource(source.getSource(),replicate);
resizedImage = createImage(prod);
media.addImage(resizedImage,1);
media.waitForID(1);
}
catch(InterruptedException e) {}
}
public void paint(Graphics g) {
g.drawImage(source, 10,10,this);
g.drawImage(resizedImage,10, 80,this);
}
}
Try it here.
Modern JDK has now a complete library devoted to graphic manipulation.
The following exampe takes a JPG file as input , rescale it to the passed parameters and writes the
result in the specified output file.
import
import
import
import
import
java.awt.*;
java.awt.geom.*;
java.awt.image.*;
java.io.*;
javax.imageio.*;
catch (Exception e) {
e.printStackTrace();
}
}
else {
System.out.println("\nUsage: java ScaleJPG src width height dest\n");
}
}
}
Example :
>java ScaleJPG javahowto.jpg 250 70 javahowto2.jpg
Input:
Ouput:
java.applet.*;
java.awt.*;
java.awt.image.*;
java.net.*;
e.printStackTrace();
}
f = new AlphaFilter();
f.setLevel(level);
fis = new FilteredImageSource(img.getSource(), f) ;
FadeThread ft = new FadeThread();
ft.delayedFading(this, 20);
ft.start();
}
public void paint(Graphics g) {
if (faded != null) {
g.drawImage(faded,0,0,this);
}
}
public void fadeIt() {
Graphics g = this.getGraphics();
level += sign;
if (level < 0) {
level=0;
sign = sign * 1;
}
if (level > 255) {
level=255;
sign = sign * 1;
try {
Thread.sleep(1000);
}
catch (Exception e) {}
}
f.setLevel(level);
if (faded != null) faded.flush();
faded = this.createImage(fis);
tracker.addImage(faded,0);
try {
tracker.waitForID(0);
}
catch (Exception ex) {
ex.printStackTrace();
}
repaint();
}
class FadeThread extends Thread {
FadeImage fadeApplet;
int delay;
public void delayedFading(FadeImage f, int delay) {
this.fadeApplet = f;
this.delay = delay;
}
public void run() {
while (true) {
try {
sleep(delay);
fadeApplet.fadeIt();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
class AlphaFilter extends RGBImageFilter {
private int level;
public AlphaFilter() {
canFilterIndexColorModel = true;
}
public void setLevel(int lev) {
level = lev;
}
public int filterRGB(int x, int y, int rgb) {
int a = level * 0x01000000;
return (rgb &
0x00ffffff) | a;
}
}
}
Try it here.
import
import
import
import
java.applet.Applet;
java.awt.*;
java.awt.image.*;
java.net.*;
try {
grabber.grabPixels();
}
catch(InterruptedException e) {
e.printStackTrace();
}
for(int y = 0; y < 32; y++) {
for(int x = 0; x < 32; x++) {
rotate[((32x1)*32)+y] = buffer[(y*32)+x];
}
}
rot = createImage(new MemoryImageSource(32, 32, rotate, 0, 32));
}
catch (Exception e) {
e.printStackTrace();
}
}
public void update( Graphics g) {
paint(g);
}
public void paint(Graphics g) {
g.drawImage(img, 0, 0,this);
g.drawImage(rot,0, 40, this);
}
}
The next example will rotate a picture 5 degrees at a time. We are using the Java2D package (and
Swing).
import
import
import
import
java.awt.*;
java.awt.event.*;
java.awt.geom.*;
javax.swing.*;
switch (e.id) {
case Event.SCROLL_ABSOLUTE:
case Event.SCROLL_PAGE_DOWN:
case Event.SCROLL_PAGE_UP:
case Event.SCROLL_LINE_UP:
case Event.SCROLL_LINE_DOWN:
sc.redraw();
return true;
}
}
return super.handleEvent(e);
}
}
class ScrollCanvas extends Panel {
int vw,vh;
int rw,rh;
Color b,f;
myCanvas c;
Scrollbar sv, sh;
// constructor
//
visible h w
//
real
h w
//
background foreground
ScrollCanvas
(int vw1, int vh1, int rw1, int rh1, Color b1, Color f1) {
super();
vw = vw1; vh = vh1;
rh = rh1; rw = rw1;
b = b1; f = f1;
int ScrollIncrement = 10;
setLayout(new BorderLayout());
c = new myCanvas(vw, vh, rw, rh, b ,f);
add("West", c);
sv = new Scrollbar
(Scrollbar.VERTICAL,0, ScrollIncrement, 0, rh);
add("East", sv);
sh = new Scrollbar
(Scrollbar.HORIZONTAL, 0, ScrollIncrement, 0, rw);
add("South", sh);
}
public void redraw() {
int y = sv.getValue();
int x = sh.getValue();
c.draw(x,y);
}
public Dimension minimumSize() {
return new Dimension(vw,vh);
}
public Dimension preferredSize() {
return new Dimension(vw,vh);
}
}
class myCanvas extends Canvas {
int vw, vh;
int rw, rh;
Color b, f;
int x, y;
Image buffImage;
Graphics offscreen;
boolean initDone;
myCanvas
(int vw1, int vh1, int rw1, int rh1, Color b1, Color f1) {
super();
vw = vw1; vh = vh1;
rh = rh1; rw = rw1;
b = b1; f = f1;
initDone = false;
repaint();
}
public void paint(Graphics g) {
if (!initDone)
initpaint(g);
else
g.drawImage(buffImage, x, y, this);
}
public void update(Graphics g) {
g.drawImage(buffImage, x, y, this);
}
public void initpaint(Graphics g) {
try {
buffImage = this.createImage(rw, rh);
offscreen = buffImage.getGraphics();
offscreen.setColor(b);
offscreen.fillRect(0, 0, rw, rh);
offscreen.setColor(f);
offscreen.setFont(new Font("Courier", Font.ITALIC, 42));
offscreen.drawString("Hello World!", 0, 50);
initDone = true;
g.drawImage(buffImage,0,0, this);
}
catch (Exception e) {
System.out.println("oups...");
}
}
public void draw (int x1, int y1)
x = x1;
y = y1;
update(getGraphics());
}
TILE BACKGROUND
in the HTML use :
PARAM NAME="bgImage" VALUE="images/myImage.jpg"
in the APPLET tag
Try it here.
[application version]
import
import
import
import
java.awt.*;
java.awt.event.*;
java.net.*;
java.io.*;
[applet version]
import
import
import
import
import
java.applet.*;
java.awt.*;
java.awt.event.*;
java.net.*;
java.io.*;
}
}
class APanel extends Panel implements ActionListener {
private List lbx;
private MyCanvas can;
private Applet parent = null;
private String url[] = new String[50];
public APanel(Applet a) {
parent = a;
setLayout(new GridLayout(1,2));
lbx = new List();
can = new MyCanvas();
add(lbx); add(can);
initLbx();
// action on listbox double click
lbx.addActionListener(this);
setBackground(new Color(0).white);
}
public void actionPerformed (ActionEvent ae) {
try {
URL theUrl =
new URL(parent.getCodeBase(), url[lbx.getSelectedIndex()]);
MediaTracker media = new MediaTracker(this);
Image image =
Toolkit.getDefaultToolkit().getImage(theUrl);
media.addImage(image, 0);
media.waitForID(0);
can.setImage(image);
}
catch (Exception e) { e.printStackTrace();}
}
public void initLbx() {
int i = 0;
try {
String aLine = "";
URL source =
new URL(parent.getCodeBase(), "imagelist.txt");
BufferedReader in
= new BufferedReader
(new InputStreamReader(source.openStream()));;
while(null != (aLine = in.readLine())) {
java.util.StringTokenizer st =
new java.util.StringTokenizer(aLine, "|");
url[i++] = st.nextToken();
// lbx.addItem(st.nextToken());
lbx.add(st.nextToken());
}
}
catch(Exception e) { e.printStackTrace();}
}
}
class MyCanvas extends Canvas {
private Image image;
public MyCanvas() {
super();
}
public void setImage(Image i) {
image = i;
repaint();
}
public void paint(Graphics g) {
if (image != null)
g.drawImage(image, 0,0, this);
}
}
NOTE : You can try this example here
else {
g.drawImage(img2,0,0,this);
index;
}
}
}
public Dimension getPreferredSize (){
return new Dimension
(img1.getHeight(this), img2.getWidth(this));
}
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {
index = 1;
repaint();
}
public void mouseExited(MouseEvent e) {
index = 0;
repaint();
}
}
To use such Canvas, try something like this. This example needs our Gumby GIFs (
).
import java.applet.*;
import java.awt.*;
import java.net.*;
public class TestToogleGifCanvas extends Applet {
ToggleGifCanvas tgc;
public void init() {
try {
tgc = new ToggleGifCanvas
(new URL(getDocumentBase(),"images/gumby.gif"),
new URL(getDocumentBase(),"images/gumby2.gif"));
add(tgc);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Try it here.
and
a white background. All we have to do is to look for the blue color with the "Alpha bits" set to opaque
and make them transparent.
[Transparency.java]
import java.awt.*;
import java.awt.image.*;
public class Transparency {
public static Image makeColorTransparent
(Image im, final Color color) {
ImageFilter filter = new RGBImageFilter() {
// the color we are looking for... Alpha bits are set to opaque
public int markerRGB = color.getRGB() | 0xFF000000;
public final int filterRGB(int x, int y, int rgb) {
if ( ( rgb | 0xFF000000 ) == markerRGB ) {
// Mark the alpha bits as zero transparent
return 0x00FFFFFF &rgb;
}
else {
// nothing to do
return rgb;
}
}
};
ImageProducer ip = new FilteredImageSource(im.getSource(), filter);
return Toolkit.getDefaultToolkit().createImage(ip);
}
[app.java]
import java.awt.image.*;
import java.awt.*;
import java.net.*;
public class app extends java.applet.Applet {
Image GifOriginalWithWithBlueBackground;
Image GifModifiedWithTransparentBackground;
public void init() {
setBackground(new Color(0).white);
MediaTracker media = new MediaTracker(this);
// image of our friend, Gumby with a blue background
GifOriginalWithWithBlueBackground =
getImage(getDocumentBase(),"gumbyblu.gif");
media.addImage(GifOriginalWithWithBlueBackground,0);
try {
media.waitForID(0);
GifModifiedWithTransparentBackground =
Transparency.makeColorTransparent
(GifOriginalWithWithBlueBackground, new Color(0).blue);
}
catch(InterruptedException e) {}
}
public void paint(Graphics g) {
g.drawImage(GifOriginalWithWithBlueBackground, 10,10,this);
g.drawImage(GifModifiedWithTransparentBackground,10, 80,this);
}
}
[x.html]
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="app.class"
NAME="myApplet"
HEIGHT=200 WIDTH=200>
</APPLET>
</BODY></HTML>
Since JDK1.4.2, javax.imageio.ImageIO lets you save and restore Images to disk in a platform
independent format. "png" and "jpeg" format are supported. With ImageIO, instead of Image you
use BufferedImage which is a subclass of Image.
import java.io.*;
import javax.imageio.*;
import java.awt.image.*;
public class FileOperations {
public static BufferedImage readImageFromFile(File file)
throws IOException
{
return ImageIO.read(file);
}
public static void writeImageToJPG
(File file,BufferedImage bufferedImage)
throws IOException
{
ImageIO.write(bufferedImage,"jpg",file);
}
}
import
import
import
import
and
java.applet.*;
java.awt.*;
java.awt.image.*;
java.net.*;
Try it here.
java.applet.*;
java.awt.*;
java.awt.image.*;
java.awt.event.*;
java.net.*;
and
g.drawImage(img[index],68,0,this);
index = (index <maxImg) ? index + 1 : 0;
}
}
}
public void animate() {
repaint();
}
public void actionPerformed(ActionEvent ae) {
working = !working;
}
class AnimationThread extends Thread {
AnimationProgress animationApplet;
int delay;
public void delayedAnimation(AnimationProgress a, int delay) {
this.animationApplet = a;
this.delay = delay;
}
public void run() {
while (true) {
try {
sleep(delay);
animationApplet.animate();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
From here, individual pixel can be accessed via the pixels array.
3.57 Get the color of a specific pixelTag(s): AWT
/*
** rubberband effect
*/
g.setXORMode(getBackground());
setForeground(new Color(0).blue);
if (xl != 1){
// erase the old line
g.drawLine(x1, y1, xl, yl);
if (x2 != 1) {
// draw the new one
g.drawLine(x1, y1, x2, y2);
}
}
}
public void update(Graphics g) {
// draw an offScreen drawing
Dimension dim = getSize();
if (offGra == null) {
offImg = createImage(dim.width, dim.height);
offGra = offImg.getGraphics();
}
offGra.setColor(new Color(0).black);
offGra.fillRect(0,0,dim.width, dim.height);
offGra.setColor(new Color(0).white);
offGra.setPaintMode();
for (int i=0; i < np; i++) {
Rectangle p = (Rectangle)lines.elementAt(i);
if (p.width != 1) {
offGra.drawLine(p.x, p.y, p.width, p.height);
}
}
// put the OffScreen image OnScreen
g.drawImage(offImg,0,0,null);
}
public boolean handleEvent(Event e) {
switch (e.id) {
case Event.MOUSE_DOWN:
// new starting point
x1 = e.x;
y1 = e.y;
// begin an new drawing process
x2 = 1;
return true;
case Event.MOUSE_UP:
// end a drawing process
lines.addElement(new Rectangle(x1, y1, e.x, e.y));
np++;
x2 = xl = 1;
repaint();
return true;
case Event.MOUSE_DRAG:
// xl yl line to be erased
xl = x2;
yl = y2;
// x2 y2 last current point
x2 = e.x;
y2 = e.y;
Dragupdate(getGraphics());
return true;
}
return super.handleEvent(e);
}
public boolean action(Event e, Object o) {
if (e.target == btnClear) resetDrawing();
if (e.target == btnUndo) undo();
return true;
}
public void undo() {
if (np>0) {
lines.removeElementAt(np1);
np;
repaint();
}
}
public void resetDrawing() {
lines.removeAllElements();
np=0;
repaint();
}
}
3.59 Convert RGB value to Hexadecimal (to be used in HTML for example)Tag(s): AWT
double xincdash=(x2x1)/(linelength/(dashlength));
double yincdash=(y2y1)/(linelength/(dashlength));
int counter=0;
for (double i=0;i<linelengthdashlength;i+=dashlength+spacelength){
g.drawLine((int) (x1+xincdashspace*counter),
(int) (y1+yincdashspace*counter),
(int) (x1+xincdashspace*counter+xincdash),
(int) (y1+yincdashspace*counter+yincdash));
counter++;
}
if ((dashlength+spacelength)*counter<=linelength)
g.drawLine((int) (x1+xincdashspace*counter),
(int) (y1+yincdashspace*counter),
x2,y2);
}
double
double
ddx +=
ddy +=
int dx
int dy
=
=
=
=
x1
x1
x2
x2
dx;
dx;
dx;
dx;
yPoints[0]
yPoints[1]
yPoints[2]
yPoints[3]
=
=
=
=
y1
y1
y2
y2
dy;
dy;
dy;
dy;
Using JDK1.2
public void paint(Graphics g){
Graphics2D g2d = (Graphics2D)g;
int width = 10;
g2d.setStroke(new BasicStroke(width));
g2d.drawLine(x1, y1, x2, y2);
}
On a Component
int width = 10;
BasicStroke bs = new BasicStroke(width);
JLabel l = new JLabel();
l.getGraphics().setStroke(bs);
l.drawLine(0,0,100,100);
Using JDK1.3
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
public class TestLine extends JFrame{
private MyPanel panel;
public TestLine() {
setSize(200, 200);
panel = new MyPanel();
getContentPane().add( panel, "Center" );
}
public static void main( String [] args ){
TestLine tl = new TestLine();
tl.setVisible( true );
}
}
class MyPanel extends JPanel {
final static BasicStroke stroke = new BasicStroke(2.0f);
final static BasicStroke wideStroke = new BasicStroke(8.0f);
public MyPanel(){}
public void paintComponent( Graphics g ){
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint
(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
g2.setStroke( stroke );
g2.draw(new Line2D.Double(10.0, 10.0, 100.0, 10.0));
g2.setStroke( wideStroke );
g2.draw(new Line2D.Double(10.0, 50.0, 100.0, 50.0));
}
}
s = t.nextToken();
i = s.indexOf('');
value = Float.valueOf(s.substring(0, i)).floatValue();
c.addSlice(value, (Color)colors.get(s.substring(i + 1)));
}
resize(c.getMinimumSize().width, c.getMinimumSize().height);
add("Center", c);
}
}
class PieChartCanvas extends Canvas {
/*
** author
Ciaran Treanor ciaran@broadcom.ie
*/
final double aspectFudge = 2.5;
int radius, depth, called = 1, numSlices = 0;
float total = 0, value[] = new float[10];
Color color[] = new Color[10];
Graphics offGraphics;
Image gfxBuff;
public PieChartCanvas(int radius, int depth) {
this.value = value;
this.color = color;
this.radius = radius;
this.depth = depth;
}
public void paint(Graphics g) {
int startAngle;
float angle;
Dimension d = getSize();
if(gfxBuff == null) {
gfxBuff = createImage(d.width, d.height);
offGraphics = gfxBuff.getGraphics();
offGraphics.setColor(getBackground());
offGraphics.fillRect(0, 0, d.width, d.height);
}
// do the 3d effect
for(int x = depth; x >= 1; x) {
startAngle = 45;
for(int i = 0; i < numSlices; i++) {
offGraphics.setColor(color[i].darker());
angle = Math.round(360 * (value[i] / total));
offGraphics.fillArc(0, x, radius, (int)(radius / aspectFudge),
startAngle, (int)angle);
startAngle += angle;
}
}
// draw the pie slice
startAngle = 45;
for(int i = 0; i < numSlices; i++) {
offGraphics.setColor(color[i]);
angle = Math.round(360 * (value[i] / total));
offGraphics.fillArc(0, 0, radius, (int)(radius / aspectFudge),
startAngle, (int)angle);
startAngle += angle;
}
g.drawImage(gfxBuff, 0, 0, null);
}
public void addSlice(float value, Color color) {
this.value[numSlices] = value;
this.color[numSlices++] = color;
total += value;
}
public Dimension getPreferredSize() {
return getMinimumSize();
}
public Dimension getMinimumSize() {
return new Dimension(radius, (int)((radius / aspectFudge) + depth));
}
}
[JavaPie.hmtl]
<HTML>
<TABLE><TR><TD>
<APPLET CODE=Graph.class WIDTH=150 HEIGHT=150>
<PARAM NAME="depth" VALUE="30">
<PARAM NAME="width" VALUE="120">
<PARAM NAME="values" VALUE="1red,5green,7blue">
</APPLET>
<TD>
<TABLE>
<TR><TD>item 1<TD BGCOLOR="#FF0000">
<TR><TD>item 2<TD BGCOLOR="#008000">
<TR><TD>item 3<TD BGCOLOR="#0000FF">
</TABLE>
</TABLE>
</HMTL>
Try it here
It seems that drawRoundRect(.) 1,5 faster then drawRect(..) , because one of them is
completely native.
import java.awt.*;
import java.awt.event.*;
public class Class1 extends Frame implements ActionListener{
public void paint(Graphics g){
super.paint(g);
long t=System.currentTimeMillis();
for(int i=0;i<10000;i++){
g.drawRect(10,70,100,50);
}
t=System.currentTimeMillis()t;
g.drawString(String.valueOf(t),10,70);
t=System.currentTimeMillis();
for(int i=0;i<10000;i++){
g.drawRoundRect(10,130,100,50,0,0);
}
t=System.currentTimeMillis()t;
g.drawString(String.valueOf(t),10,130);
}
public void actionPerformed(ActionEvent p1){
repaint(0,10,200,300);
}
public static void main (String[] args){
Class1 c=new Class1();
c.setSize(300,300);
c.setLayout(new BorderLayout());
Button b=new Button("Refresh");
c.add(BorderLayout.SOUTH , b);
b.addActionListener(c);
c.show();
}
}
java.awt.AWTException;
java.awt.Robot;
java.awt.Rectangle;
java.awt.Toolkit;
java.awt.image.BufferedImage;
java.io.*;
javax.imageio.ImageIO;
class ScreenCapture {
public static void main(String args[]) throws
AWTException, IOException {
// capture the whole screen
BufferedImage screencapture = new Robot().createScreenCapture(
new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()) );
// Save as JPEG
File file = new File("screencapture.jpg");
ImageIO.write(screencapture, "jpg", file);
// Save as PNG
// File file = new File("screencapture.png");
// ImageIO.write(screencapture, "png", file);
}
}
[JDK11]
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class d extends Applet
implements MouseListener {
public void init() {
this.addMouseListener(this);
}
public void paint(Graphics g) {
g.drawString("Click here", 10,10);
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {
System.out.println
( "Click at (" + e.getX() + ":" + e.getY() + ")" );
if (e.getClickCount() == 2)
System.out.println( " and it's a double click!");
else
System.out.println( " and it's a simple click!");
}
}
}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mouseClicked(MouseEvent e) {
switch(e.getModifiers()) {
case InputEvent.BUTTON1_MASK: {
System.out.println("That's the LEFT button");
break;
}
case InputEvent.BUTTON2_MASK: {
System.out.println("That's the MIDDLE button");
break;
}
case InputEvent.BUTTON3_MASK: {
System.out.println("That's the RIGHT button");
break;
}
}
}
}
}
);
add(new Label
("You can quit by clicking on the 'X'"),"South");
add(new Label
("You can quit by clicking on the menu item 'Exit'"),"Center");
add(new Label
("You can quit with the MenuShortcut 'ctrlx'"),"North");
setSize(300, 300);
show();
}
public void actionPerformed(ActionEvent evt) {
String what = evt.getActionCommand();
if (what.equals("Exit"))
processEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
}
static public void main(String[] args) {
new ExitFromMenu();
}
}
The regular JDK can only deal with JPG, GIF, BMP or PNG file with the package ImageIO, see this
HowTo.
To deal with TIF file, you must use the JAI (Java Advanced Imaging) package.
This example will display a given TIF file. It will also display other types (JPG,...) by detecting the
type.
import
import
import
import
import
import
import
import
import
import
javax.media.jai.PlanarImage;
com.sun.media.jai.codec.ByteArraySeekableStream;
com.sun.media.jai.codec.ImageCodec;
com.sun.media.jai.codec.ImageDecoder;
com.sun.media.jai.codec.SeekableStream;
java.io.FileInputStream;
java.nio.ByteBuffer;
java.nio.channels.FileChannel;
java.awt.Image;
java.awt.image.RenderedImage;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.ImageIcon;
public class ImageViewer
com.sun.media.jai.codec.FileSeekableStream;
com.sun.media.jai.codec.ImageDecoder;
com.sun.media.jai.codec.ImageCodec;
com.sun.media.jai.codec.TIFFEncodeParam;
import
import
import
import
java.awt.image.RenderedImage;
javax.media.jai.RenderedOp;
javax.media.jai.JAI;
java.awt.image.renderable.ParameterBlock;
irfanview is an amazing software when it comes to transform a graphic format to another one. You
can use it from a command line or from a GUI.
See also : Convert many singlepage TIF into one multipage TIF
java.io.FileOutputStream;
java.io.OutputStream;
java.util.ArrayList;
java.util.List;
java.awt.image.BufferedImage;
import javax.media.jai.NullOpImage;
import javax.media.jai.OpImage;
3.72 Convert many singlepage TIF into one multipage TIF Tag(s): AWT
import javax.media.jai.PlanarImage;
import
import
import
import
import
import
com.sun.media.jai.codec.ImageEncoder;
com.sun.media.jai.codec.SeekableStream;
com.sun.media.jai.codec.FileSeekableStream;
com.sun.media.jai.codec.ImageDecoder;
com.sun.media.jai.codec.ImageCodec;
com.sun.media.jai.codec.TIFFEncodeParam;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;
public class ImageUtils {
public static BufferedImage imageToBufferedImage(Image im) {
BufferedImage bi = new BufferedImage
(im.getWidth(null),im.getHeight(null),BufferedImage.TYPE_INT_RGB);
Graphics bg = bi.getGraphics();
bg.drawImage(im, 0, 0, null);
bg.dispose();
return bi;
}
public static BufferedImage readImageFromFile(File file)
throws IOException
{
return ImageIO.read(file);
}
public static void writeImageToPNG
(File file,BufferedImage bufferedImage)
throws IOException
{
ImageIO.write(bufferedImage,"png",file);
}
public static void writeImageToJPG
(File file,BufferedImage bufferedImage)
throws IOException
{
ImageIO.write(bufferedImage,"jpg",file);
}
}
javax.media.jai.PlanarImage;
com.sun.media.jai.codec.ByteArraySeekableStream;
com.sun.media.jai.codec.ImageCodec;
com.sun.media.jai.codec.ImageDecoder;
com.sun.media.jai.codec.SeekableStream;
java.io.FileInputStream;
java.nio.ByteBuffer;
java.nio.channels.FileChannel;
java.awt.Color;
import
import
import
import
import
java.awt.Graphics;
java.awt.Image;
java.awt.image.PixelGrabber;
java.awt.image.BufferedImage;
java.awt.image.RenderedImage;
/**
* This utility loads a given TIF and try to detect if it's
* blank or not.
*
* We create inmemory image and then calculate the standard
* deviation of the color information. If a certain value is not
* reached then we assume that the image is mainly uniform and
* probably blank. The threshold value is an estimate. Depending
* the source of the TIF this value can be higher. For example,
* TIF from a FAX machine or a scanner can be dirty, with hair/dust presence,
* but with no content.
*
* jai_core.jar and jai_codec.jar are required.
* http://java.sun.com/products/javamedia/jai/index.jsp
*
* @author http://www.rgagnon.com/howto.html
*/
public class BlankDetection {
public static final int FAILURE = 2;
public static final int BLANK = 0;
public static final int NOTBLANK = 1;
// value where we can consider that this is a blank image
// can be much higher depending of the TIF source
// (ex. scanner or fax)
public static final int BLANK_THRESHOLD = 1000;
/**
* Creates an Image from a byte array
* @param data
* @return Image
* @throws Exception
*/
public static Image load(byte[] data) throws Exception {
Image image = null;
SeekableStream stream = new ByteArraySeekableStream(data);
String[] names = ImageCodec.getDecoderNames(stream);
ImageDecoder dec =
ImageCodec.createImageDecoder(names[0], stream, null);
RenderedImage im = dec.decodeAsRenderedImage();
image = PlanarImage.wrapRenderedImage(im).getAsBufferedImage();
// scaledown the image , maximum width : 500 px
// to preserve memory
Image imageScaled =
image.getScaledInstance(500, 1, Image.SCALE_SMOOTH);
return imageScaled;
}
/**
* Converts an Image to a BufferedImage
* @param im une Image
* @return BufferedImage
*/
public static BufferedImage imageToBufferedImage(Image im) {
BufferedImage bi = new BufferedImage
(im.getWidth(null),im.getHeight(null),BufferedImage.TYPE_INT_RGB);
Graphics bg = bi.getGraphics();
bg.drawImage(im, 0, 0, null);
bg.dispose();
return bi;
}
/**
* Check if an Image is blank or not
* Computes the standard deviation based on the color information
* @param bi bufferedimage
* @return true it's blank
*/
public static boolean isBlank(BufferedImage bi) throws Exception {
long count = 0;
long total = 0;
double totalVariance = 0;
double stdDev = 0;
int height = bi.getHeight();
int width = bi.getWidth();
int[] pixels = new int[width * height];
PixelGrabber pg = new PixelGrabber
(bi, 0, 0, width, height, pixels, 0, width);
pg.grabPixels();
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++) {
count++;
int pixel = pixels[j * width + i];
int red = (pixel >> 16) & 0xff;
int green = (pixel >> 8) & 0xff;
int blue = (pixel) & 0xff;
int pixelValue = new Color(red, green,blue,0).getRGB();
total += pixelValue;
double avg = total /count;
totalVariance += Math.pow(pixelValue avg, 2);
stdDev = Math.sqrt(totalVariance / count);
}
}
return (stdDev <BLANK_THRESHOLD);
}
/**
* Accept on the command line the path to a TIF file
*
* Returns an errorlevel based on the analysis
* 0 blank
* 1 not blank
* 2 IO error
*
* @param args path vers complet vers un PROPS
*/
public static void main(String[] args) {
try {
if (args.length==0) {
System.out.println("Missing parameter.");
System.exit(FAILURE);
}
String path = args[0];
FileInputStream in = new FileInputStream(path);
FileChannel channel = in.getChannel();
ByteBuffer buffer = ByteBuffer.allocate((int)channel.size());
channel.read(buffer);
com.lowagie.text.Document;
com.lowagie.text.Image;
com.lowagie.text.PageSize;
com.lowagie.text.Rectangle;
com.lowagie.text.pdf.PdfContentByte;
com.lowagie.text.pdf.PdfWriter;
com.lowagie.text.pdf.RandomAccessFileOrArray;
com.lowagie.text.pdf.codec.TiffImage;
PdfContentByte cb = writer.getDirectContent();
RandomAccessFileOrArray ra = null;
int comps = 0;
try {
ra = new RandomAccessFileOrArray(tiff);
comps = TiffImage.getNumberOfPages(ra);
}
catch (Throwable e) {
System.out.println("Exception in " + tiff + " "
+ e.getMessage());
continue;
}
System.out.println("Processing: " + tiff);
for (int c = 0; c < comps; ++c) {
try {
Image img = TiffImage.getTiffImage(ra, c + 1);
if (img != null) {
System.out.println("page " + (c + 1));
img.scalePercent
(7200f / img.getDpiX(), 7200f / img.getDpiY());
document.setPageSize
(new Rectangle(img.getScaledWidth(), img.getScaledHeight()));
img.setAbsolutePosition(0, 0);
cb.addImage(img);
document.newPage();
++pages;
}
}
catch (Throwable e) {
System.out.println("Exception " + tiff + " page "
+ (c + 1) + " " + e.getMessage());
}
}
ra.close();
document.close();
}
catch (Throwable e) {
e.printStackTrace();
}
System.out.println("done");
}
}
}
import
import
import
import
import
import
import
import
import
import
java.io.FileOutputStream;
java.io.IOException;
java.awt.image.RenderedImage;
com.sun.image.codec.jpeg.JPEGCodec;
com.sun.image.codec.jpeg.JPEGImageEncoder;
com.sun.media.jai.codec.SeekableStream;
com.sun.media.jai.codec.FileSeekableStream;
com.sun.media.jai.codec.TIFFDecodeParam;
com.sun.media.jai.codec.ImageDecoder;
com.sun.media.jai.codec.ImageCodec;
4 Environment
4.1 javaenv
then in myClass
String myvar = System.getProperty("myvar");
String myothervar = System.getProperty("myothervar");
If you don't know in advance, the name of the variable to be passed to the JVM, then there is no
100% Java way to retrieve them.
One approach (not the easiest one), is to use a JNI call to fetch the variables, see this HowTo.
A more lowtech way, is to launch the appropriate call to the operating system and capture the
output. The following snippet puts all environment variables in a Properties class and display the
value the TEMP variable.
import java.io.*;
import java.util.*;
public class ReadEnv {
public static Properties getEnvVars() throws Throwable {
Process p = null;
Properties envVars = new Properties();
Runtime r = Runtime.getRuntime();
String OS = System.getProperty("os.name").toLowerCase();
// System.out.println(OS);
if (OS.indexOf("windows 9") > 1) {
p = r.exec( "command.com /c set" );
}
else if ( (OS.indexOf("nt") > 1)
|| (OS.indexOf("windows 2000") > 1 )
|| (OS.indexOf("windows xp") > 1) ) {
// thanks to JuanFran for the xp fix!
p = r.exec( "cmd.exe /c set" );
}
4 Environment
else {
// our last hope, we assume Unix (thanks to H. Ware for the fix)
p = r.exec( "env" );
}
BufferedReader br = new BufferedReader
( new InputStreamReader( p.getInputStream() ) );
String line;
while( (line = br.readLine()) != null ) {
int idx = line.indexOf( '=' );
String key = line.substring( 0, idx );
String value = line.substring( idx+1 );
envVars.setProperty( key, value );
// System.out.println( key + " = " + value );
}
return envVars;
}
public static void main(String args[]) {
try {
Properties p = ReadEnv.getEnvVars();
System.out.println("the current value of TEMP is : " +
p.getProperty("TEMP"));
}
catch (Throwable e) {
e.printStackTrace();
}
}
}
thanks to w.rijnders for the w2k fix.
// ok
// but specific to 2003
// better,
// since no other OS would
// return "windows"
|| (OS.indexOf("windows xp") > 1) ) {
I started with "windows 200" but thought "what the hell" and made it "windows 20" to lengthen its
longivity. You could push it further and use "windows 2," I suppose. The only thing to watch out for
is to not overlap with "windows 9."
On Windows, preJDK 1.2 JVM has trouble reading the Output stream directly from the SET
command, it never returns. Here 2 ways to bypass this behaviour.
First, instead of calling directly the SET command, we use a BAT file, after the SET command we
print a known string. Then, in Java, when we read this known string, we exit from loop.
4 Environment
[env.bat]
@set
@echo **end
[java]
...
if (OS.indexOf("windows") > 1) {
p = r.exec( "env.bat" );
}
...
while( (line = br.readLine()) != null ) {
if (line.indexOf("**end")>1) break;
int idx = line.indexOf( '=' );
String key = line.substring( 0, idx );
String value = line.substring( idx+1 );
hash.put( key, value );
System.out.println( key + " = " + value );
}
The other solution is to send the result of the SET command to file and then read the file from Java.
...
if (OS.indexOf("windows 9") > 1) {
p = r.exec( "command.com /c set > envvar.txt" );
}
else if ( (OS.indexOf("nt") > 1)
|| (OS.indexOf("windows 2000") > 1
|| (OS.indexOf("windows xp") > 1) ) {
// thanks to JuanFran for the xp fix!
p = r.exec( "cmd.exe /c set > envvar.txt" );
}
...
// then read back the file as a Proprties
Properties p = new Properties();
p.load(new FileInputStream("envvar.txt"));
Thanks to JP Daviau
// UNIX
public Properties getEnvironment() throws java.io.IOException {
Properties env = new Properties();
env.load(Runtime.getRuntime().exec("env").getInputStream());
return env;
}
Properties env = getEnvironment();
String myEnvVar = env.get("MYENV_VAR");
4 Environment
Java's System properties contains some useful informations about the environment, for example,
the TEMP and PATH environment variables (on Windows).
public class ShowSome {
public static void main(String args[]){
System.out.println("TEMP : "
+ System.getProperty("java.io.tmpdir"));
System.out.println("PATH : "
+ System.getProperty("java.library.path"));
System.out.println("CLASSPATH : "
+ System.getProperty("java.class.path"));
System.out.println("SYSTEM DIR : " +
System.getProperty("user.home")); // ex. c:\windows on Win9x
System.out.println("CURRENT DIR: "
+ System.getProperty("user.dir"));
}
}
Here some tips from H. Ware about the PATH on different OS.
PATH is not quite the same as library path. In unixes, they are completely differentthe libraries
typically have their own directories.
System.out.println("the current value of PATH is:
p.getProperty("PATH")+"}");
{" +
System.out.println("LIBPATH: {" +
System.getProperty("java.library.path")+"}");
gives
the current value of PATH is:
{/home/hware/bin:/usr/local/bin:/usr/xpg4/bin:/opt/SUNWspro/bin:
/usr/ucb:/bin:/usr/bin:/home/hware/linuxbin:/usr/openwin/bin/:
/usr/local/games:/usr/ccs/lib/:/usr/new:/usr/sbin/:/sbin/:
/usr/openwin/lib:/usr/X11/bin:/usr/bin/X11/:/usr/local/bin/X11:
/usr/bin/pbmplus:/usr/etc/:/usr/dt/bin/:/usr/lib:
/usr/lib/nis:/usr/share/bin:/usr/share/bin/X11:
/home/hware/work/cdk/main/cdk/../bin:.}
LIBPATH:
{/usr/lib/j2re1.3/lib/i386:/usr/lib/j2re1.3/lib/i386/native_threads:
/usr/lib/j2re1.3/lib/i386/client:/usr/lib/j2sdk1.3/lib/i386:/usr/lib:/lib}
on my linux workstation. (java added all those except /lib and /usr/lib). But these two lines aren't the
same on window either:
This system is windows nt
the current value of PATH is:
{d:\OrbixWeb3.2\bin;D:\jdk1.3\bin;c:\depot\cdk\main\cdk\bin;c:\depot\
cdk\main\cdk\..\bin;d:\OrbixWeb3.2\bin;D:\Program
Files\IBM\GSK\lib;H:\pvcs65\VM\win32\bin;c:\cygnus
\cygwinb20\Hi586cygwin32\bin;d:\cfn\bin;D:\orant\bin;
C:\WINNT\system32;C:\WINNT;
d:\Program Files\Symantec\pcAnywhere;
C:\Program Files\Executive Software\DiskeeperServer\;}
LIBPATH:
{D:\jdk1.3\bin;.;C:\WINNT\System32;C:\WINNT;D:\jdk1.3\bin;
c:\depot\cdk\main\cdk\bin;c:\depot\cdk\main\cdk\..\bin;
4 Environment
d:\OrbixWeb3.2\bin;D:\Program Files\IBM\GSK\lib;
H:\pvcs65\VM\win32\bin;c:\cygnus\cygwinb20\Hi586cygwin32\bin;d:\cfn\bin;
D:\orant\bin;C:\WINNT\system32;
C:\WINNT;C:\Program Files\Dell\OpenManage\ResolutionAssistant\Common\bin;
d:\Program Files\Symantec\pcAnywhere;
C:\Program Files\Executive Software\DiskeeperServer\;}
Java is prepending itself! That confused me and broke my exec from ant.
Belorussian translation
For some odd reasons, the getenv() method was removed from the JDK. Rumors is that a
mechanism to retrieve an environment will be back in JDK1.5 (see this HowTo). But for now, you
can use D switch to retrieve named environment variable and pass them to the JVM (see this
HowTo) or use this JNI routine :
JNIEXPORT jstring JNICALL JavaHowTo_getenv
(JNIEnv *env, jclass c, jstring jname){
if ( jname == NULL ) {
return NULL ;
}
const char *name =
(*env)>GetStringUTFChars(env, jname, (jboolean *)NULL) ;
const char *value = getenv(name) ;
(*env)>ReleaseStringUTFChars(env, jname, name) ;
return value ? (*env)>NewStringUTF(env, value) : NULL ;
}
NOTE : This is fine if the environment variable contains only regular 7bit ASCII characters.
See also this HowTo.
= GetImage.class \
myCanvas.class
SOURCEFILES = GetImage.java \
myCanvas.java
$(CLASSFILES)
Name: myCanvas.class
JavaBean: True
<<
# end JAR support
all : $(JARFILE) $(CLASSFILES) doc
doc : $(CLASSFILES)
javadoc version author d $(DOC) $(SOURCEFILES)
install :
copy $CLASSESFILE $(DEST)
clean:
del $(CLASSFILES)
}
public static boolean isMicrosoft() {
try {
Class.forName("com.ms.applet.GenericAppletContext");
}
catch (ClassNotFoundException e) {
System.out.println("This browser is not a Microsoft Browser.");
return false;
}
return true;
}
}
For example, our MyApplet.class exists in three versions. One is using Microsoftspecific classes,
the other is a JDK1.1 applet and finally a version for JDK102only browser. The idea is to put all the
required classes in an ARCHIVE file. By using a javascript entities, we decide which archive to use.
During layout time, the javascript entity is remplaced by the right archive name.
<HTML></HTML><HEAD>
<SCRIPT>
function isBrowser(b,v) {
browserOk = false;
versionOk = false;
browserOk = (navigator.appName.indexOf(b) != 1);
versionOk = (v <= parseInt(navigator.appVersion));
return browserOk &versionOk;
}
archiveToBeUsed = "java102.jar";
if (isBrowser("Microsoft", 4)) {
archiveToBeUsed = "ie4.jar";
}
else {
if isBrowser("Netscape", 4) {
archiveToBeUsed = "n4.jar";
}
}
</SCRIPT></HEAD><BODY>
<APPLET CODE ="MyApplet.class"
HEIGHT=100
WIDTH=400
ARCHIVE=}; >
</APPLET>
</BODY></HTML>
NOTE: You may need to use the document.write() method to generate the right APPLET tag instead of a the Javascript entity to be compatible
with Netscape and IE.
4.10 Ant
For simple need, Ant can be used to do substitution in your sources.
We insert into the code a special tag to delimit code that need to be stripped by the Ant script. Let's
say we use //@STARTDEBUG@// and //@ENDDEBUG@//.
package com.rgagnon.howto;
import javax.swing.JFrame;
public class Example {
public static void main(String args[]){
JFrame f = new JFrame();
f.setSize(300,200);
f.setVisible(true);
f.setTitle("HowTo");
//@STARTDEBUG@//
f.setTitle(f.getTitle() + " DEBUG version");
//@ENDDEBUG@//
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
If you execute this code, the JFrame title will have the word "DEBUG" appended to it.
The Ant script to remove the debugging code is :
<project default="buildme">
<target name="compileprod">
<copy todir="../out" includeEmptyDirs="false">
<filterchain>
<tokenfilter>
<replacestring from="//@STARTDEBUG@//" to="/*" />
<replacestring from="//@ENDDEBUG@//" to="*/" />
</tokenfilter>
</filterchain>
<fileset dir=".">
<include name="**/*.java" />
</fileset>
</copy>
<javac srcdir="../out" />
</target>
<target name="compiledebug">
<javac srcdir="." />
</target>
After running this script, the source (in the ..\out directory)
package com.rgagnon.howto;
import javax.swing.JFrame;
public class Example {
public static void main(String args[]){
JFrame f = new JFrame();
f.setSize(300,200);
f.setVisible(true);
f.setTitle("HowTo");
/*
f.setTitle(f.getTitle() + " DEBUG version");
*/
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
NOTE: This can be useful if you want to trim a JAR to include only classes actually used.
The default value for the minimum is 2Mb, for the maximum it's 64Mb.
doclet.Packages=Packages
doclet.SerialData=Serial Data\:
doclet.Since=Since\:
doclet.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.
doclet.ClassUse_Subinterface=Subinterfaces of {0} in {1}
doclet.Frame_Version=Frame version
doclet.Generated_Docs_Untitled=Generated Documentation (Untitled)
[standard_fr.properties (extract)]
doclet.Window_Split_Index={0}\: {1}Index
doclet.Packages=Paquetages
doclet.SerialData=Donn\u00E9e s\u00E9rialis\u00E9e\:
doclet.Since=Depuis\:
doclet.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.
doclet.ClassUse_Subinterface=Sousinterfaces de {0} dans {1}
doclet.Frame_Version=Version avec cadres
doclet.Generated_Docs_Untitled=Documentation g\u00E9n\u00E9r\u00E9e
Once everything translated, put your standard_fr.properties into the tools.jar making sure that the
file is located in the right package (along standard.properties in
com.sun.tools.doclets.standard.resources).
To generate in french, use the locale switch on the command line
javadoc locale fr ....
java version
On Windows, if you have a "file not found" message, it's because the JVM can't be found
through the PATH. Do it again but with the complete path (if the path contains spaces, make
sure to use quotes!) :
"c:\program files\java\j2sdk1.5.0\bin\java" version
Compile it (again you may need to specify the complete path to the compiler if the PATH is
not set correctly):
"c:\program files\java\j2sdk1.5.0\bin\javac" source 1.5 Test15.java
Note the switch "source 1.5", if you don't specify it you won't be able to access the new
features (like System.out.printf()).
Run it
>"C:\Program Files\Java\j2sdk1.5.0\bin\java" Test15
Local time: 15:26:04
import java.io.*;
The RuntimeMXBean defines several convenient methods for accessing system properties about
the Java virtual machine.
[J2SE 1.5]
import java.util.Date;
import java.lang.management.RuntimeMXBean;
import java.lang.management.ManagementFactory;
class JMXTest {
public static void main(String args[]) {
JMXTest x = new JMXTest();
x.doit();
}
public void doit() {
try{
RuntimeMXBean mx = ManagementFactory.getRuntimeMXBean();
System.out.println("BOOTCLASSPATH:\n" + mx.getBootClassPath());
System.out.println("CLASSPATH:\n" + mx.getClassPath());
// the input arguments passed to the Java virtual machine
// which does not include the arguments to the main method.
System.out.println("COMMAND LINE ARGS:\n" + mx.getInputArguments());
// a map of names and values of all system properties.
System.out.println("SYSTEM PROPERTIES:\n" + mx.getSystemProperties());
System.out.println("VM start time : " + new Date(mx.getStartTime()));
System.out.println("VM up time : " + mx.getUptime() + " ms");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
System.getProperty("java.vm.name")
.toLowerCase().indexOf("64") >= 0;
}
// probably 32bit
return false;
}
}
you get
java version "1.5.0"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0b64)
Java HotSpot(TM) Client VM (build 1.5.0b64, mixed mode, sharing)
The default JVM with a JIT (JustInTime compiler) for a "client" mode is used. The other available
mode is "server".
From the Hot Spot FAQ at http://java.sun.com/docs/hotspot/HotSpotFAQ.html#compiler_types.
What's the difference between the client and server systems?
These two systems are different binaries. They are essentially two different compilers
(JITs)interfacing to the same runtime system. The client system is optimal for applications which
need fast startup times or small footprints, the server system is optimal for applications where the
overall performance is most important. In general the client system is better suited for interactive
applications such as GUIs. Some of the other differences include the compilation policy,heap
defaults, and inlining policy.
Where do I get the server and client systems?
Client and server systems are both downloaded with the 32bit Solaris and Linux downloads. For
32bit Windows, if you download the JRE, you get only the client, you'll need to download the SDK
to get both systems.
For 64bit, only the server system is included. On Solaris, the 64bit JRE is an overlay on top of the
32bit distribution. However, on Linux and Windows, it's a completely separate distribution. The
default setting is defined the file jvm.cfg.
On Debian GNU/Linux with Sun Java 1.5.0, the file is in /etc/java1.5.0sun.
4.19 Set the default JVM typeTag(s): Environment
It's probably the 1.6 JRE that will be used since it's the last installed.
If the bytecode is incompatible with the given JRE then .. it won't work, of course.
ref : Java 6 technotes
You can always give the complete path to use a specific installation. Launching the JVM this way
does not use the registry setting at all.
>"C:\Program Files\Java\j2re1.4.1_02\bin\java" version
java version "1.4.1_02"
The result is
In Linux:
export _JAVA_OPTIONS='Xms64m Xmx128m Dawt.useSystemAAFontSettings=lcd'
ref : http://java.sun.com/j2se/1.5.0/docs/guide/2d/flags.html
If the Java process is launch via javaw.exe (Applet) then the environment variable is called
_JPI_VM_OPTIONS.
For example :
_JPI_VM_OPTIONS = Dsome.property=true
For a Java Web Start process (javaws.exe), the environment variable is called
JAVAWS_VM_ARGS.
For example :
JAVAWS_VM_ARGS = Dsome.property=true
ref : http://docs.oracle.com/javase/7/docs/webnotes/tsg/TSGDesktop/html/plugin.html#gcexdd
4.23 Set default value for java property (system wide)Tag(s): Environment
[JDK 1.1]
to compile: java JC mySource.java
(use redirection to keep the output)
java JC mySource.java >output.txt
import java.io.*;
public class JC {
public static void main( String args[] )
throws IOException, InterruptedException {
String fn = "JC.java";
if( args.length > 0 ) fn = args[0];
System.out.println( "BEGIN (" + fn + ")" );
Process p =
Runtime.getRuntime().exec( "javac verbose " + fn );
String buf;
BufferedReader se = new BufferedReader
or you can always use a small text editor like Textpad where you can write with Java code (with
syntax coloring), compile, capture compiler output and launch your Applet or Application directly
from the editor.
and the JVIEW window won't close until you hit ENTER.
Or simply execute JVIEW directly in a DOS window with
jview <classname>
Check this Howto for a better way...
package JavaCom;
public class JavaBeanSays {
private String _hello = "Hello World!";
public String getHello() {
return _hello ;
}
public void setHello(String s) {
_hello = s;
}
}
NOTE: This is not really a Bean but let's keep it simple!
The next step is to build a manifest file to identify the bean in the jar. Here it is (manifest.txt):
Name: JavaCom/JavaBeanSays
JavaBean: true
NOTE: If no manifest is present all classes in the jar are treated as beans.
The JavaBeanSays class is in the directory JavaCom, the manifest.txt is the directory under it. From
the directory under (the one containing manifest.txt), we built the jar with :
jar cfm javacom.jar manifest.txt javacom\JavaBeanSays.class
NOTE: You can download my JavaCom.jar if you to proceed more rapidly.
The next step is to run the packager. You run it from the JDK installation directory. If the JDK is
installed in c:\dev\java\jdk1.2.1\ for example , you go there. And you start the packager with
bin\java.exe cp jre\lib\rt.jar;jre\lib\jaws.jar sun.beans.ole.Packager
A wizard is started, you follow the 5 steps to create the "JavaBeans bridge for ActiveX" for the
JavabeanSays component.
The first step is to specify where is located the JavaCom.jar file. When selected, the wizard should
list the JavaCom.JavaBeanSays bean, press Next. The "ActiveX" name under which the beans will
be seen is shown, press Next (in VbScript, the beans suffix must be added to this name).
An output directory is needed, be careful because this directory name will be hardcoded in the
generated files (REG and TLB), you need to specify a valid directory name. The packager assume
that a subdirectory bin is present with the file beans.ocx in it. You can create it and then copy
beans.ocx from the JRE\bin into it or edit the REG file to specify the original JRE\bin and update the
registry with the good location.
The Bean is now registered and ready to be used as a COM object.
NOTE: There is a commandline interface available in the packager if you want to bypass the wizard.
strFromJava = objJava.getHello
MsgBox strFromJava, _
0,
_
"JAVA BEAN OUTPUT"
objJava.setHello("Bonjour le monde!")
strFromJava = objJava.getHello
MsgBox strFromJava, _
0,
_
"JAVA BEAN OUTPUT"
NOTE: Check the JAVA PLUGIN SCRIPTING documentation (jdk1.2) or (jsdk1.4). document for more infos.
But applets are prevented from reading these system properties (for security reason):
java.home
java.class.path
user.name
user.home
user.dir
To read a system property from within an applet, simply invoke System.getProperty(key) on the
property you are interested in.
String s = System.getProperty("java.vendor");
You need a second script to launch a java class with a console (useful to see debugging traces or
textonly Java program). Called it CRunJava.vbs . Then you will have two choices from the
SendTo menu, one for consolebased program and one for GUIbased (Windows) program.
' [CRunJava.vbs] start a java class with a console
Dim WSHShell, FSO, javaclass, javacompletepath, cmdline
Set WSHShell = WScript.CreateObject("WScript.Shell")
Set FSO = WScript.CreateObject("Scripting.FileSystemObject")
If WScript.Arguments.Count = 0 Then
WScript.Echo "no argument on the command line."
Else
javaclass = WScript.Arguments(0)
If fso.GetExtensionName(javaclass) = "class" Then
javacompletepath = fso.GetAbsolutePathName(javaclass)
javapath = fso.GetParentFolderName(javacompletepath)
javaclass = fso.GetBaseName(javaclass)
' keep the console open
Note : A JAR can be made self executable (with double click), see this HowTo
to
javaw MyApp
In the properties tab panel, you also havethe possibility to assign an icon to the Shortcut. If you click
on the newly created icon, your Java application will start without opening a DOS box. If your
application is Text mode application use "java" instead of "javaw".
If the Microsoft JVM is used then use "wjview" (instead of "jview") to start a GUI Java application
from an icon.
In this example,we query the registry to extract the personal folder path ("My Documents") and the
processor ID and its name.
import java.io.*;
public class RegQuery {
private static final String REGQUERY_UTIL = "reg query ";
private static final String REGSTR_TOKEN = "REG_SZ";
private static final String REGDWORD_TOKEN = "REG_DWORD";
private static final String PERSONAL_FOLDER_CMD = REGQUERY_UTIL +
"\"HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\"
+ "Explorer\\Shell Folders\" /v Personal";
private static final String CPU_SPEED_CMD = REGQUERY_UTIL +
"\"HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\""
+ " /v ~MHz";
private static final String CPU_NAME_CMD = REGQUERY_UTIL +
"\"HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0\""
+ " /v ProcessorNameString";
}
catch (Exception e) {
return null;
}
}
static class StreamReader extends Thread {
private InputStream is;
private StringWriter sw;
StreamReader(InputStream is) {
this.is = is;
sw = new StringWriter();
}
public void run() {
try {
int c;
while ((c = is.read()) != 1)
sw.write(c);
}
catch (IOException e) { ; }
}
String getResult() {
return sw.toString();
}
}
public static void main(String s[]) {
System.out.println("Personal directory : "
+ getCurrentUserPersonalFolderPath());
System.out.println("CPU Name : " + getCPUName());
System.out.println("CPU Speed : " + getCPUSpeed() + " Mhz");
}
}
Remember : This code is a hack and may break anytime. A better alternative is to use JNA.
import
import
import
import
import
import
import
java.lang.reflect.InvocationTargetException;
java.lang.reflect.Method;
java.util.HashMap;
java.util.Map;
java.util.ArrayList;
java.util.List;
java.util.prefs.Preferences;
static
static
static
static
static
static
static
static
static
static
static
static
static
static
static
static {
try {
regOpenKey = userClass.getDeclaredMethod("WindowsRegOpenKey",
new Class[] { int.class, byte[].class, int.class });
regOpenKey.setAccessible(true);
regCloseKey = userClass.getDeclaredMethod("WindowsRegCloseKey",
new Class[] { int.class });
regCloseKey.setAccessible(true);
regQueryValueEx = userClass.getDeclaredMethod("WindowsRegQueryValueEx",
new Class[] { int.class, byte[].class });
regQueryValueEx.setAccessible(true);
regEnumValue = userClass.getDeclaredMethod("WindowsRegEnumValue",
new Class[] { int.class, int.class, int.class });
regEnumValue.setAccessible(true);
regQueryInfoKey = userClass.getDeclaredMethod("WindowsRegQueryInfoKey1",
new Class[] { int.class });
regQueryInfoKey.setAccessible(true);
regEnumKeyEx = userClass.getDeclaredMethod(
"WindowsRegEnumKeyEx", new Class[] { int.class, int.class,
int.class });
regEnumKeyEx.setAccessible(true);
regCreateKeyEx = userClass.getDeclaredMethod(
"WindowsRegCreateKeyEx", new Class[] { int.class,
byte[].class });
regCreateKeyEx.setAccessible(true);
regSetValueEx = userClass.getDeclaredMethod(
/**
* Read a value from key and value name
* @param hkey
HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @param valueName
* @return the value
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static String readString(int hkey, String key, String valueName)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
return readString(systemRoot, hkey, key, valueName);
}
else if (hkey == HKEY_CURRENT_USER) {
return readString(userRoot, hkey, key, valueName);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
/**
* Read value(s) and value name(s) form given key
* @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @return the value name(s) plus the value(s)
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static Map<String, String> readStringValues(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
return readStringValues(systemRoot, hkey, key);
}
else if (hkey == HKEY_CURRENT_USER) {
return readStringValues(userRoot, hkey, key);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
/**
* Read the value name(s) from a given key
* @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @return the value name(s)
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static List<String> readStringSubKeys(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
return readStringSubKeys(systemRoot, hkey, key);
}
else if (hkey == HKEY_CURRENT_USER) {
return readStringSubKeys(userRoot, hkey, key);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
/**
* Create a key
* @param hkey HKEY_CURRENT_USER/HKEY_LOCAL_MACHINE
* @param key
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void createKey(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int [] ret;
if (hkey == HKEY_LOCAL_MACHINE) {
ret = createKey(systemRoot, hkey, key);
regCloseKey.invoke(systemRoot, new Object[] { new Integer(ret[0]) });
}
else if (hkey == HKEY_CURRENT_USER) {
ret = createKey(userRoot, hkey, key);
regCloseKey.invoke(userRoot, new Object[] { new Integer(ret[0]) });
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
if (ret[1] != REG_SUCCESS) {
throw new IllegalArgumentException("rc=" + ret[1] + " key=" + key);
}
}
/**
* Write a value in a given key/value name
* @param hkey
* @param key
* @param valueName
* @param value
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void writeStringValue
(int hkey, String key, String valueName, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
if (hkey == HKEY_LOCAL_MACHINE) {
writeStringValue(systemRoot, hkey, key, valueName, value);
}
else if (hkey == HKEY_CURRENT_USER) {
writeStringValue(userRoot, hkey, key, valueName, value);
}
else {
throw new IllegalArgumentException("hkey=" + hkey);
}
}
/**
* Delete a given key
* @param hkey
* @param key
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void deleteKey(int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int rc = 1;
if (hkey == HKEY_LOCAL_MACHINE) {
rc = deleteKey(systemRoot, hkey, key);
}
else if (hkey == HKEY_CURRENT_USER) {
rc = deleteKey(userRoot, hkey, key);
}
if (rc != REG_SUCCESS) {
throw new IllegalArgumentException("rc=" + rc + " key=" + key);
}
}
/**
* delete a value from a given key/value name
* @param hkey
* @param key
* @param value
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
public static void deleteValue(int hkey, String key, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int rc = 1;
if (hkey == HKEY_LOCAL_MACHINE) {
rc = deleteValue(systemRoot, hkey, key, value);
}
else if (hkey == HKEY_CURRENT_USER) {
value=" + value);
}
// =====================
private static int deleteValue
(Preferences root, int hkey, String key, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
new Integer(hkey), toCstr(key), new Integer(KEY_ALL_ACCESS) });
if (handles[1] != REG_SUCCESS) {
return handles[1]; // can be REG_NOTFOUND, REG_ACCESSDENIED
}
int rc =((Integer) regDeleteValue.invoke(root,
new Object[] {
new Integer(handles[0]), toCstr(value)
})).intValue();
regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
return rc;
}
private static int deleteKey(Preferences root, int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int rc =((Integer) regDeleteKey.invoke(root,
new Object[] { new Integer(hkey), toCstr(key) })).intValue();
return rc; // can REG_NOTFOUND, REG_ACCESSDENIED, REG_SUCCESS
}
private static String readString(Preferences root, int hkey, String key, String value)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
new Integer(hkey), toCstr(key), new Integer(KEY_READ) });
if (handles[1] != REG_SUCCESS) {
return null;
}
byte[] valb = (byte[]) regQueryValueEx.invoke(root, new Object[] {
new Integer(handles[0]), toCstr(value) });
regCloseKey.invoke(root, new Object[] { new Integer(handles[0]) });
return (valb != null ? new String(valb).trim() : null);
}
private static Map<String,String> readStringValues
(Preferences root, int hkey, String key)
throws IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
HashMap<String, String> results = new HashMap<String,String>();
int[] handles = (int[]) regOpenKey.invoke(root, new Object[] {
new Integer(hkey), toCstr(key), new Integer(KEY_READ) });
if (handles[1] != REG_SUCCESS) {
return null;
}
int[] info = (int[]) regQueryInfoKey.invoke(root,
How to use it :
package com.rgagnon.howto;
public class WinRegistryTest {
public static void main(String args[]) throws Exception {
String value = "";
// IE Download directory (HKEY_CURRENT_USER)
value = WinRegistry.readString(
WinRegistry.HKEY_CURRENT_USER,
"Software\\Microsoft\\Internet Explorer",
"Download Directory");
System.out.println("IE Download directory = " + value);
// Query for Acrobat Reader installation path (HKEY_LOCAL_MACHINE)
value = WinRegistry.readString(
WinRegistry.HKEY_LOCAL_MACHINE,
"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\AcroRd32.exe",
"");
System.out.println("Acrobat Reader Path = " + value);
/*
this code is broken under win7 64 :(
20130112
"HowTo",
"java");
//
//
//
//
//
//
WinRegistry.deleteValue(
WinRegistry.HKEY_CURRENT_USER,
"SOFTWARE\\rgagnon.com", "HowTo");
WinRegistry.deleteKey(
WinRegistry.HKEY_CURRENT_USER,
"SOFTWARE\\rgagnon.com\\");
System.out.println("Done." );
}
The output :
IE Download directory = C:\Documents and Settings\Ral\Bureau
Acrobat Reader Path = C:\Program Files\Adobe\Acrobat 5.0\Reader\AcroRd32.exe
{SubVersionNumber=, CurrentBuild=1.511.1 () (snipped)...
[Accessibility, AeDebug, Asr, Classes, Compatibility, (snipped)...
Done.
"MicroVersion"="1"
"RuntimeLib"="C:\\Program Files\\Java\\j2re1.4.1_02\\bin\\client\\jvm.dll"
[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5]
"JavaHome"="C:\\Program Files\\Java\\jre1.5.0"
"RuntimeLib"="C:\\Program Files\\Java\\jre1.5.0\\bin\\client\\jvm.dll"
"MicroVersion"="0"
[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5.0]
"JavaHome"="C:\\Program Files\\Java\\jre1.5.0"
"MicroVersion"="0"
"RuntimeLib"="C:\\Program Files\\Java\\jre1.5.0\\bin\\client\\jvm.dll"
Output example :
C:\temp>findjava.cmd
Java Version = 1.6
Java home path (per registry) = C:\\applications\\dev\\jre6
Note :
The above script returns the default JVM if the PATH variable does not override it!
Oracle client installation is famous to force an outdated Java at the beginning of the PATH. This
oneliner displays the java.exe (if any) found in the PATH :
c:\> for %i in (java.exe) do @echo.
C:\WINDOWS\system32\java.exe
%~$PATH:i
The java.exe in the system32 relies on the CurrentVersion registry setting to determine which
registry key to use to look up the location of the Java RE.
java.io.BufferedReader;
java.io.File;
java.io.FileWriter;
java.io.InputStreamReader;
java.util.*;
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String line;
java.io.BufferedReader;
java.io.File;
java.io.FileWriter;
java.io.InputStreamReader;
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("cscript //NoLogo " + file.getPath());
BufferedReader input =
new BufferedReader
(new InputStreamReader(p.getInputStream()));
String line;
line = input.readLine();
if (line != null) {
if (line.equals(process)) {
found = true;
}
}
input.close();
}
catch(Exception e){
e.printStackTrace();
}
return found;
}
public static void main(String[] args){
boolean result = VBSUtils.isRunning("TextPad.exe");
msgBox("Is TextPad running ?
}
public static void msgBox(String msg) {
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
null, msg, "VBSUtils", javax.swing.JOptionPane.DEFAULT_OPTION);
}
}
java.io.BufferedReader;
java.io.IOException;
java.io.InputStream;
java.io.InputStreamReader;
java.util.ArrayList;
java.util.List;
4.42 Detect if a process is running using WMIC Tag(s): Misc Prog HowTo Java Environment
}
public static void main(String[] args) throws IOException {
System.out.println(WindowsUtils2.isProcessRunning("excel.exe"));
}
}
and then get the path of the JRE from the corresponding key
[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5\JavaHome]
Beware that some software (eg. Oracle) installs themself at the beginning of the PATH definition, so
it's their Java installation that will be found first.
You can run the absolute path to the java.exe file, as in
"C:\Program Files\Java\jre1.5.0\bin\java.exe" MyClass
It will not use the registry, and it will be guaranteed to use jre1.5.0.
So for a regular Java SE program, it is safe to specify the complete path to the JRE to launch it.
But for the Applet/Plugin or WebStartbased programs, the registry is always used to determine the
current JRE.
::
:: get the javahome
::
FOR /F "usebackq skip=4 tokens=3,4" %%A IN (`REG QUERY %JAVA_CURRENT% /v %JAVA_HOME% 2^>nul`) D
set JAVA_PATH=%%A %%B
)
echo the path of the current Java JVM according to the registry is
echo %JAVA_PATH%
echo.
echo now if we try it :
"%JAVA_PATH%\bin\java.exe" version
:end
>j.cmd
the current Java runtime is 1.6
the path of the current Java JVM according to the registry is
C:\Program Files\Java\jre1.6.0_06
now if we try it :
java version "1.6.0_06"
Java(TM) SE Runtime Environment (build 1.6.0_06b02)
4.44 Get the current Java version from a BAT fileTag(s): Environment
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Desktop directory : "
+ getCurrentUserDesktopPath());
}
static class StreamReader extends Thread {
private InputStream is;
private StringWriter sw;
StreamReader(InputStream is) {
this.is = is;
sw = new StringWriter();
}
public void run() {
try {
int c;
while ((c = is.read()) != 1)
sw.write(c);
}
catch (IOException e) { ; }
}
String getResult() {
return sw.toString();
}
}
}
java.io.BufferedReader;
java.io.File;
java.io.FileWriter;
java.io.InputStreamReader;
static
static
static
static
static
static
static
static
static
static
static
static
String
String
String
String
String
String
String
String
String
String
String
String
private VBSUtils() {
SF_ALLUSERSDESKTOP
SF_ALLUSERSSTARTMENU
SF_ALLUSERSPROGRAMS
SF_ALLUSERSSTARTUP
SF_DESKTOP
SF_FAVORITES
SF_MYDOCUMENT
SF_PROGRAMS
SF_RECENT
SF_SENDTO
SF_STARTMENU
SF_STARTUP
=
=
=
=
=
=
=
=
=
=
=
=
"AllUsersDesktop";
"AllUsersStartMenu";
"AllUsersPrograms";
"AllUsersStartup";
"Desktop";
"Favorites";
"MyDocuments";
"Programs";
"Recent";
"SendTo";
"StartMenu";
"Startup";
See also :
Get Windows Desktop path using the registry
Get Windows "My Documents" path using FileSystemView.getDefaultDirectory()
See also Get Windows Special Folders (JNA)
// see note
private static final String WINDOWS_DESKTOP = "Desktop";
/**
* the current user desktop path
* @return the current user desktop path
*/
public static String getWindowsCurrentUserDesktopPath() {
return System.getenv("userprofile") + "/" + WINDOWS_DESKTOP ;
}
/**
* Create an Internet shortcut on User's Desktop no icon specified
* @param name
name of the shortcut
* @param target URL
* @throws IOException
*/
public static void createInternetShortcutOnDesktop(String name, String target)
throws IOException
{
String path = getWindowsCurrentUserDesktopPath() + "/"+ name + ".URL";
createInternetShortcut(name, path, target, "");
}
/**
* Create an Internet shortcut on User's Desktop, icon specified
* @param name
name of the shortcut
* @param target URL
* @param icon
URL (ex. http://www.server.com/favicon.ico)
* @throws IOException
*/
public static void createInternetShortcutOnDesktop
(String name, String target, String icon)
throws IOException
{
String path = getWindowsCurrentUserDesktopPath() + "/"+ name + ".URL";
NOTE:
Prior Vista, the desktop path for a localized Windows can be different. With an english version, it's
Desktop while for a french version, it's called Bureau.
The only way to get the right name is to ask the Registry, see this HowTo.
// remote session
private WindowsUtils() {}
public static boolean isRemote() throws SecurityException, UnsatisfiedLinkError,
UnsupportedOperationException, IOException
{
NativeCall.init();
IntCall ic = null;
try {
ic = new IntCall("user32", "GetSystemMetrics");
int rc = ic.executeCall(new Integer(SM_REMOTESESSION));
return (rc gt; 0);
}
finally {
if (ic != null) ic.destroy();
}
}
public static void main(String ... args) throws Exception {
System.out.println(WindowsUtils.isRemote());
}
}
An easy way is to check the Windows environment variable sessionname. The value of this
environment variable will be 'Console' for a normal, local session. For an Remote Desktop session it
will contain the phrase 'RDP'.
public static boolean isRemoteDesktopSession() {
System.getenv("sessionname").toLowerCase().startsWith("rdp");
}
Note that environment varialbe values are read at the JVM startup. So if the JVM process was
started by a console session, but then accessed by an RDP session, further calls to
System.getenv("sessionname") still return 'Console'
See this HowTo to detect a Citrix session.
will be documented as
4.51.1 newMethod
public java.lang.String newMethod()
Returns:
value
Table(s):
firstname
lastname
city
country
4.51.1 newMethod
/**
* Will return true since <code>@todo</code>
* can be used in method documentation.
* @return true since <code>@todo</code>
* can be used in method documentation and false
* otherwise.
*/
public boolean inMethod() {
return true;
}
/**
* Will return true since <code>@todo</code>
* can be used in method documentation.
* @return true since <code>@todo</code>
* can be used in overview documentation and false
* otherwise.
*/
public boolean inOverview() {
return true;
}
/**
* Will return true since <code>@todo</code>
* can be used in package documentation.
* @return true since <code>@todo</code>
* can be used in package documentation and false
* otherwise.
*/
public boolean inPackage() {
return true;
}
/**
* Will return true since <code>@todo</code>
* can be used in type documentation (classes or interfaces).
* @return true since <code>@todo</code>
* can be used in type documentation and false
* otherwise.
*/
public boolean inType() {
return true;
}
/**
* Will return false since <code>@todo</code>
* is not an inline tag.
* @return false since <code>@todo</code>
* is not an inline tag.
*/
public boolean isInlineTag() {
return false;
}
/**
* Register this Taglet.
* @param tagletMap the map to register this tag to.
*/
public static void register(Map tagletMap) {
Table tag = new Table();
Taglet t = (Taglet) tagletMap.get(tag.getName());
if (t != null) {
4.51.1 newMethod
tagletMap.remove(tag.getName());
}
tagletMap.put(tag.getName(), tag);
}
/**
* Given the <code>Tag</code> representation of this custom
* tag, return its string representation.
* @param tag
the <code>Tag</code> representation of this custom tag.
*/
public String toString(Tag tag) {
String output = "";
String tables [] = tag.text().split(";");
int j = tables.length;
if (j > 0) {
output = "<DT><B>" + HEADER
+ "</B><DD><TABLE><TR>";
for (int i=0; i < j ; i++){
// deals with the current table and its fields
String current[] = tables[i].split(":");
output +=
"<TD><TABLE style=\"borderstyle:solid;"
+ " borderwidth:thin\">";
output +=
"<TH ALIGN=\"center\" STYLE=\"borderstyle:solid;"
+ " borderwidth:thin\">"
+ current[0] + "</TH>";
if (current.length > 1) {
String fields[] = current[1].split(",");
int k = fields.length;
for (int n=0; n < k ; n++) {
output += "<TR><TD ALIGN=\"center\">"
+ fields[n] + "</TD></TR>";
}
}
output += "</TABLE>";
}
output += "</TR></TABLE>";
}
return output;
}
/**
* Given an array of Tags representing this custom
* tag, return its string representation.
* @param tags the array of Tags representing of this custom tag.
*/
public String toString(Tag[] tags) {
if (tags.length == 0) {
return null;
}
String result = "";
for (int i = 0; i < tags.length; i++) {
result += toString(tags[i]);
}
return result ;
}
}
Compile your taglet. Use javac compiler version 1.4.0 (or later) in the Java 2 SDK. The required
class files are in the lib\tools.jar file in the SDK. Assuming the SDK is installed at C:\Program
Files\j2sdk1.4.1 :
4.51.1 newMethod
Run the javadoc tool using the taglet and tagletpath options. For example, if your taglet class file
is defined to be in package com.rgagnon.taglet and is stored in
C:\taglets\com\rgagnon\taglet\Table.class, then you should set tagletpath to C:\taglets. This
example calls javadoc on package com.package1, including Table taglet tags:
C:\dev\Work\java\taglet>javadoc taglet com.rgagnon.taglet.Table
tagletpath c:\dev\work\java\taglet com.package1
[standard_fr.properties (extract)]
doclet.Window_Split_Index={0}\: {1}Index
doclet.Packages=Paquetages
doclet.SerialData=Donn\u00E9e s\u00E9rialis\u00E9e\:
doclet.Since=Depuis\:
doclet.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.
doclet.ClassUse_Subinterface=Sousinterfaces de {0} dans {1}
doclet.Frame_Version=Version avec cadres
doclet.Generated_Docs_Untitled=Documentation g\u00E9n\u00E9r\u00E9e
Once everything translated, put your standard_fr.properties into the tools.jar making sure that the
file is located in the right package (along standard.properties in
com.sun.tools.doclets.standard.resources).
To generate in french, use the locale switch on the command line
javadoc locale fr ....
Now execute the javadoc utility located in [JDK]\bin directory from the root of the com.rgagnon
package.
4.53 Document a package using Javadoc Tag(s): Environment
You can represent any character with a numerical identity, the syntax is &#nnn; where nnn is the
Unicode code (decimal value) of the character.
The XML will not be visible since it will embedded in the HTML as tag and not as text.
With Javadoc 1.5, you can use the {@code ... } command. :
/**
* To use this class use this XML
* <pre>
* {@code
* <xml>
*
<parameter>foo</parameter>
*
<value>bar</value>
* </xml>
* }
* </pre>
*/
With the previous versions, one way was to add a space after the <.
/**
* To use this class use this XML
* <pre>
* < xml>
*
< parameter>foo< /parameter>
*
< value>bar< /value>
* < /xml>
* }
* </pre>
*/
buf.append(new java.util.Date());
buf.append(' ');
buf.append(rec.getLevel());
buf.append(' ');
buf.append(formatMessage(rec));
buf.append('\n');
return buf.toString();
}
});
logger = Logger.getLogger("TestLog");
logger.addHandler(fh);
}
catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
logger.severe("my severe message");
logger.warning("my warning message");
logger.info("my info message");
}
}
See this HowTo to format a duration in ms into a string as "Days , Hours , minutes and seconds".
While you can set the level in your code with something like
logger.setLevel(Level.WARN);
You put the properties file in the classpath and then from your code
URL url = ClassLoader.getSystemResource("log4j.props");
PropertyConfigurator.configure(url);
Logging activities have a cost. Even if you set the level at DEBUG level, the logger.debug(...) is
interpreted. Consider this line :
logger.setLevel(Level.DEBUG);
logger.debug("something wrong with the value of " + myValue.toString());
the toString() method will be called and the result concatened to a String even if the DEBUG level is
disabled.
The best practice is to check if the level is enabled or not.
logger.setLevel(Level.DEBUG);
if (logger.isDebugEnabled()) {
logger.debug("something wrong with the value of " + myValue.toString());
}
This way you will not incur the cost of parameter construction if debugging is disabled for logger.
You can even remove the unwanted logging operation from the bytecode! See this HowTo.
Finally it's a good idea to design a robust toString() method for your class like this one :
public String toString(){
StringBuffer sb = new StringBuffer();
sb.append(getClass().getName())
sb.append(" myValue=[").append(this.myValue).append("]");
sb.append(" anotherValue=[").append(this.anotherProperty).append("]");
return sb.toString();
}
even if myValue is null, this toString() method will display "null" as the value and not throw a
NullPointerExeception.
See also this HowTo and this one
It may be useful to change it onthefly for debugging purpose. You need to get the Log4J "root"
Logger and then change its "level".
...
setLogLevel("DEBUG");
...
setLogLevel("INFO");
...
private void setLogLevel(String level) {
Logger root = Logger.getRootLogger();
if ("DEBUG".equals(level)) {
root.setLevel(org.apache.log4j.Level.DEBUG);
}
else {
root.setLevel(org.apache.log4j.Level.INFO);
}
}
will launch the program and output to stdout the debugging information.
HTTPSender
HTTPSender
HTTPSender
HTTPSender
HTTPSender
...
4.62 Enable debug log level on OpenSource package(Apache Commons Logging)Tag(s): Environment
2009/08/21
2009/08/21
2009/08/21
2009/08/21
12:15:56:109
12:15:56:109
12:15:56:109
12:15:56:109
EDT
EDT
EDT
EDT
[DEBUG]
[DEBUG]
[DEBUG]
[DEBUG]
header
header
header
header
>>
>>
>>
>>
"Host: api.sandbox.ebay.com[\r][\n]"
"ContentLength: 1546[\r][\n]"
"ContentType: text/xml; charset=UTF8[\r][\n]"
"[\r][\n]"
In theory, you can specify many JARs in one ARCHIVE tag. But the current version of Netscape will
only load the first JAR and ignore the others.
Microsoft IEv4 can handle multiple JAR files.
In an application, simply include the JAR in the CLASSPATH :
4.63 Use a JAR/ZIP/CAB file with an AppletTag(s): Environment
To create a JAR file (compressed), use the JAR utility included with JDK1.1
jar cvf abc.jar a.class b.class c.class
According to some JAVA developers, JAR in CLASSPATH needs to be uncompressed (JDK1.1). To create uncompressed JAR:
[ZIP format]
JDK1.0.2 introduces the ZIP "uncompressed" format. To create an archive, simply use a ZIP tool
that supports the long filename format and specify the ZERO compression mode. You can use
Sun's JAR utility (included with JDK1.1) to create a JDK1.0.2 compatible ZIP file:
jar cvfO myArchive.zip *.class
[CAB format]
CAB (for CABINET) is used only by Microsoft Internet Explorer. It offers compression (like the JAR
but the ZIP format is uncompressed). To create a CAB file, use the CABARC utility from Microsoft :
CABARC n myArchive.cab *.*
to create myArchive.cab.
It is possible sign a CAB file using the Authenticode mechanism, check the Microsoft Web site for
more infos.
To associate a CAB file with an Applet, simply use the HTML :
<APPLET CODE="a.class"
WIDTH=100
HEIGHT=100>
<PARAM
NAME="cabbase"
VALUE="abc.cab">
</APPLET>
the cabbase parameter will be interpreted only by MSIE, nonMS browsers browser will simply
ignore it.
An Applet can support ZIP and CAB format by using the following HTML:
<APPLET
CODEBASE="."
ARCHIVE=abc.zip
CODE=a.class
width=610
height=600 >
<PARAM NAME="cabbase" VALUE="abc.cab">
</APPLET>
while Netscape will use the ZIP file and ignore de CAB parameter, MSIE will use CAB and ignore
the ZIP file.
Then create this manifest file (manifest.mft) with any text editor.
ManifestVersion: 1.0
MainClass: MyClass
Classpath: .
MainClass specifies the entry point with the main(String args[]) method.
The Classpath is used to specify the dependency of this jar (if any). You add the directories and
jars separated by a space. It is important because when running a jar , the CLASSPATH definition
(as defined by the environnement variable) is overridden.
Next, you include the manifest file in the JAR (MyJar.jar) with the MyClass class.
jar cvfm myjar.jar manifest.mft *.class
Then you are able to start the MyClass.class by doubleclicking on the MyJar.jar file (if the JRE is
correctly installed) or by typing
java jar myjar.jar
If you need to pass parameters, use the D switch before the jar switch and use the getProperty()
method to get the value.
The file association mechanism is made during the installation of the JRE.
You can verify that everything is ok with the following command from a DOS Shell
>assoc .jar
.jar=jarfile
>ftype jarfile
jarfile="C:\Program Files\Java\jre1.5.0_10\bin\javaw.exe" jar "%1" %*
If the association is broken or you need to change the JRE used then by using the assoc/ftype
utilities, you can modify the association easily (use /? to display the syntax of the assoc and ftype
utilities).
NOTE: On WinXp (or better), your user account needs to be at the Admin level.
On Windows (NT or better), you can also make JARs run from the commandline by setting the
PATHEXT environment variable, for example
SET PATHEXT=.EXE;.BAT;.CMD;.JAR
Then if you have the jar file MyJar.jar accessible via the PATH environment variable, typing "MyJar"
on the DOS command line will invoke "javaw jar MyJar.jar" .
The value of the ClassPath attribute specifies the relative URLs of the extensions or libraries that
this application or extension needs. URLs are separated by one or more spaces. The application or
extension class loader uses the value of this attribute to construct its internal search path.
You can use the i option to speed up your application's class loading time:
jar i main.jar
This will build an an INDEX.LIST file in the METAINF directory which will enable the application
class loader to download the right jar files when it is searching for classes or resources.
new File("C:/xtras/xercesImpl.jar").toURL();
URL urlB =
new File("C:/xtras/xmlParserAPIs.jar").toURL();
URL[] urls = { urlA,urlB };
URLClassLoader ulc = new URLClassLoader(urls);
//
Class c = Class.forName
("org.apache.xerces.dom.ChildNode", true, ulc);
//
System.out.println(c.getName());
}
catch(Exception e) {
e.printStackTrace();
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String args []){
new ExtractFromJAR().extractMyMDBFromJAR(".");
}
}
Run it ... and the mydb.mdb file should appear in the current directory.
java jar mydb.jar
I got a problem when the jar file was located in C:\Program Files\xyz due to the embedded space.
So I modified the code to
String home = getClass().getProtectionDomain()
.getCodeSource().getLocation()
.getPath().replaceAll("%20", " ");
The output
>jar cvfm Hello.jar manifest.mft com\rgagnon\HelloClass.class
added manifest
adding: com/rgagnon/HelloClass.class (in=1059) (out=601) (deflated 43%)
>java com.rgagnon.HelloClass
file:/C:/DEV/WORK/JAVA/com/rgagnon/HelloClass.class
>java jar Hello.jar
*** running from jar!
jar:file:/C:/DEV/WORK/JAVA/Hello.jar!/com/rgagnon/HelloClass.class
Here a variation on this subject, a method to return the name of the current running jar.
package com.rgagnon.howto;
public class RunningJar {
public static void main(String[] args) {
String runningJarName = new RunningJar().getRunningJarName();
if (runningJarName != null) {
System.out.println("Running from " + runningJarName);
}
else {
System.out.println("Not running from a jar");
}
}
public String getRunningJarName() {
String className = this.getClass().getName().replace('.', '/');
String classJar =
this.getClass().getResource("/" + className + ".class").toString();
if (classJar.startsWith("jar:")) {
String vals[] = classJar.split("/");
for (String val: vals) {
if (val.contains("!")) {
return val.substring(0, val.length() 1);
}
}
}
return null;
}
}
/*
output :
>java jar yop.jar
Running from yop.jar
>ren yop.jar yip.jar
*
*/
public static void main (String[] args){
List list = PackageUtils.getClasseNamesInPackage
("C:/j2sdk1.4.1_02/lib/mail.jar", "com.sun.mail.handlers");
System.out.println(list);
/*
output :
Jar C:/j2sdk1.4.1_02/lib/mail.jar looking for com/sun/mail/handlers
Found com.sun.mail.handlers.text_html.class
Found com.sun.mail.handlers.text_plain.class
Found com.sun.mail.handlers.text_xml.class
Found com.sun.mail.handlers.image_gif.class
Found com.sun.mail.handlers.image_jpeg.class
Found com.sun.mail.handlers.multipart_mixed.class
Found com.sun.mail.handlers.message_rfc822.class
[com.sun.mail.handlers.text_html.class,
com.sun.mail.handlers.text_xml.class, com
.sun.mail.handlers.image_jpeg.class,
, com.sun.mail.handlers.message_rfc822.class]
*/
}
}
Create a simple Hello class as shown below (you need have a package).
package howto;
public class Hello {
public static void main( String[] args ){
System.out.println( "Hello World" );
}
}
... and load it into your favorite editor. Type the following ant script and save it.
<project default="buildHello">
<target name="compile">
<javac srcdir="." />
</target>
<target name="buildHello" depends="compile" />
</project>
Go back to the editor and add the jar building command. The target compile is also executed
since the target jar depends on it.
<project default="buildHello">
<target name="compile">
<javac srcdir="." />
</target>
<target name="jar" depends="compile">
<jar destfile="hello.jar"
basedir="."
includes="**/*.class"
/>
</target>
<target name="buildHello" depends="compile,jar" />
</project>
EST
EST
EST
EST
2006
2006
2006
2006
METAINF/
METAINF/MANIFEST.MF
howto/
howto/Hello.class
Make your Jar autoexecutable by specifying the Main class into a MANIFEST.MF file to be
included in the Jar. Add the following lines to build.xml
<project default="buildHello">
<target name="compile">
<javac srcdir="." />
</target>
<target name="jar" depends="compile">
<delete file="hello.jar"/>
<delete file="MANIFEST.MF"/>
<manifest file="MANIFEST.MF">
<attribute name="BuiltBy" value="${user.name}"/>
<attribute name="MainClass" value="howto.Hello"/>
</manifest>
<jar destfile="hello.jar"
basedir="."
includes="**/*.class"
manifest="MANIFEST.MF"
/>
</target>
<target name="buildHello" depends="compile,jar" />
</project>
Add a build number with the Ant task buildnumber . Ant will create (if necessary) and increment a
property in a file called build.num (so you need to keep it!). Then a property, build.number, is
available in your Ant script. The version number is also a property. Here it is hardcoded in the
script but you can read it from a file.
<project default="buildHello">
<target name="compile">
<javac srcdir="." />
</target>
<target name="jar" depends="compile">
<delete file="hello.jar"/>
<delete file="MANIFEST.MF"/>
<property name="version.num" value="1.00"/>
<buildnumber file="build.num"/>
<manifest file="MANIFEST.MF">
<attribute name="BuiltBy" value="${user.name}"/>
<attribute name="MainClass" value="howto.Hello"/>
<attribute name="ImplementationVersion"
value="${version.num}b${build.number}"/>
</manifest>
<jar destfile="hello.jar"
basedir="."
includes="**/*.class"
manifest="MANIFEST.MF"
/>
</target>
<target name="buildHello" depends="compile,jar" />
</project>
Modify the Hello class to read the ImplementationVersion information and display it.
package howto;
public class Hello {
public static void main( String[] args ){
System.out.println( "Hello World ");
System.out.println("version : " +
Hello.class.getPackage().getImplementationVersion() );
}
}
Finally we add a target to cleanup and the main target to build everything to the build.xml file.
<project default="buildHello">
<target name="compile">
<javac srcdir="." />
</target>
<target name="jar">
<delete file="hello.jar"/>
<property name="version.num" value="1.00"/>
<buildnumber file="build.num"/>
<manifest file="MANIFEST.MF">
<attribute name="BuiltBy" value="${user.name}"/>
<attribute name="MainClass" value="howto.Hello"/>
<attribute name="ImplementationVersion"
value="${version.num}b${build.number}"/>
</manifest>
<jar destfile="hello.jar"
basedir="."
includes="**/*.class"
manifest="MANIFEST.MF"
/>
</target>
<target name="cleanup">
<delete>
<fileset dir="." includes="**/*.class"/>
<fileset file="MANIFEST.MF"/>
</delete>
</target>
<target name="buildHello" depends="compile,jar,cleanup" />
</project>
buildclasspath.cmd
set _CLASSPATH=%CLASSPATH%
set CLASSPATH=%1
for %%i in ( %1\*.jar ) do call buildclasspath_append.cmd %%~fsi
if "%_CLASSPATH%" == "" goto END
set CLASSPATH=%_CLASSPATH%;%CLASSPATH%
:END
buildclasspath_append.cmd
set CLASSPATH=%CLASSPATH%;%1
With XP (or better), it's simpler ... a single batch file can do the job.
@echo off
setlocal ENABLEDELAYEDEXPANSION
if defined CLASSPATH (set CLASSPATH=%CLASSPATH%;.) else (set CLASSPATH=.)
FOR /R .\lib %%G IN (*.jar) DO set CLASSPATH=!CLASSPATH!;%%G
Echo The Classpath definition is %CLASSPATH%
...
java MyClass
4.75 JDK6
According to http://java.sun.com/javase/6/docs/technotes/tools/windows/java.html, there is a new
way to include jars in a given directory without explicitly to specify each one of them.
As a special convenience, a class path element containing a
basename of * is considered equivalent to specifying a list
of all the files in the directory with the extension .jar
or .JAR (a java program cannot tell the difference between
the two invocations).
For example, if directory foo contains a.jar and b.JAR, then
the class path element foo/* is expanded to a A.jar:b.JAR,
except that the order of jar files is unspecified. All jar files
in the specified directory, even hidden ones, are included in
the list. A classpath entry consisting simply of * expands to a
list of all the jar files in the current directory. The CLASSPATH
environment variable, where defined, will be similarly expanded.
Note : There is a bug when using this feature with JAVAW, see
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6510337
Note : Use quote to avoid problem during the wildcard expansion, ex. javac cp "C:\mylib\*"
HelloWorld.java
The manifest file format restrictions mandated by the JDK requires the use of a space ' ' character
as the line continuation character, so ensure that your editor is not set up to trim trailing spaces
on saves and exits.
The line with the ClassPath: header must end with a space character and each of the lines
referencing the client jar's should start and end with a space ' ' character and the manifest file as
a whole must end with a blank line.
Remember that when you launch an application with
4.75 JDK6
the CLASSPATH definition (as defined by the environment variable) is overriden by the
"classpath" defined the jar's manifest.
See http://java.sun.com/docs/books/tutorial/deployment/jar/downman.html
Ant can be used to build your Jar and built the manifest classpath definition.
<target name="MyJar" depends="dist, compile" description="generate jar" >
<jar destfile="${dist}/${jar}">
<manifest>
<attribute name="MainClass" value="${Main_Class}"/>
<attribute name="ClassPath" value=". lib/utils.jar lib/client.jar" />
</manifest>
</jar>
</target>
It's possible (but not so simple) to do it automatically without specifying each jar one by one :
<path id="build.classpath">
<fileset dir="${basedir}"/>
<include name="lib/*.jar"/>
</fileset>
</path>
<pathconvert property="manifest.classpath" pathsep=" ">
<path refid="build.classpath"/>
<mapper>
<chainedmapper>
<flattenmapper/>
<globmapper from="*.jar" to="lib/*.jar"/>
</chainedmapper>
</mapper>
</pathconvert>
<target depends="compile" name="buildjar">
<jar jarfile="${basedir}/${test.jar}">
<fileset dir="${build}" />
<manifest>
<attribute name="MainClass" value="com.mycompany.TestMain"/>
<attribute name="ClassPath" value="${manifest.classpath}"/>
</manifest>
</jar>
</target>
Latest Ant version (1.7) includes a task called ManifestClassPath which converts a classpath into
a spaceseparated list of items used to set the Manifest ClassPath attribute. See
http://ant.apache.org/manual/CoreTasks/manifestclasspath.html
<path id="buildclasspath">
<fileset dir="${build.dir}">
<include name="*.jar"/>
</fileset>
</path>
<manifestclasspath property="lib.list" jarfile="${build.dir}/${jar.file}">
<classpath refid="buildclasspath" />
</manifestclasspath>
4.75 JDK6
<jar>
...
<manifest>
<attribute name="MainClass" value="com.mycompany.TestMain"/>
<attribute name="ClassPath" value=". ${lib.list}"/>
</manifest>
...
</jar>
java.applet.*;
java.awt.event.*;
java.awt.*;
netscape.javascript.*;
4.77 Detect browser type from an AppletTag(s): Applet Environment Javascript interaction
Don't forget the MAYSCRIPT parameter in the APPLET tag, it's required since the Applet is using
the JSObject to interact with the Javascript.
<html>
<head>
<script>
function getUserAgent() {
return navigator.userAgent;
}
</script>
</head><body>
<applet code="GetUserAgent.class" MAYSCRIPT height=100 width=500></Applet>
</body>
</html>
Try it here
You need to parse the returned value to detect browser type. Look at this utility,
http://code.google.com/p/useragentutils/ or at this code :
http://nerds.palmdrive.net/useragent/code.html to get the idea.
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="MyApplet.class"
NAME="myApplet"
HEIGHT=400 WIDTH=400 ALT="Oups! You don't have JAVA enabled">
<A HREF="nojava.html">Oups! You don't have JAVA enabled, click here.</A>
</APPLET>
</BODY></HTML>
4.81 See the Java Console Window Log (Java plugin)Tag(s): Applet Environment
5 Internationalization
5.1 javainter
javax.swing.*;
java.awt.*;
java.awt.event.*;
java.util.*;
java.text.*;
5 Internationalization
add(aButton);
// Number format output
double dn = 3.1416;
nf = (NumberFormat)
(MyResources.rb.getObject("aNumber"));
aTextField = new JTextField(6);
add(aTextField);
aTextField.setText(nf.format(dn));
// Number input validation
vButton =
(JButton)MyResources.rb.getObject("vButton");
add(vButton);
vButton.addActionListener(this);
vLabel = new JLabel("validation message ...");
add(vLabel);
setSize(400,400);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == vButton) {
try {
nf.parse(aTextField.getText());
vLabel.setText(MyResources.rb.getString("numOK"));
vLabel.invalidate();
this.validate();
}
catch (ParseException pe) {
pe.printStackTrace();
vLabel.setText(MyResources.rb.getString("numERR"));
vLabel.invalidate();
this.validate();
}
}
}
public static void main(String args[]) {
System.out.println("Current Local : " + Locale.getDefault());
Thread t = new Thread () {
public void run() {
International frame = new International();
frame.initGUI();
frame.setVisible(true);
}
};
SwingUtilities.invokeLater(t);
}
}
5 Internationalization
import java.util.*;
public class MyResources_en extends ListResourceBundle {
public Object [][] getContents() {
return contents;
}
static final Object[][] contents = {
{ "aLabel"
, "a Label (en)" }
};
}
5 Internationalization
This example uses ListResourceBundle classes to store the required resources. It is possible to
substitute them for Properties files without any change to the code. The properties files must have
the .properties extension.
See this Howto.
java.util.*;
java.text.*;
java.awt.*;
java.awt.event.*;
javax.swing.*;
}
public void initText() {
setTitle (rb.getString("title"));
r0.setText(rb.getString("r0"));
r1.setText(rb.getString("r1"));
r2.setText(rb.getString("r2"));
btnQuit.setText(rb.getString("btnQuit"));
Date d = new Date();
MessageFormat mf = new MessageFormat
(rb.getString("today"), localeCurrent);
today.setText(mf.format(new Object [] { d }));
}
public void initGUI(){
setLayout(new FlowLayout());
// RADIO buttons
bg = new ButtonGroup();
r0 = new JRadioButton();
r1 = new JRadioButton();
r2 = new JRadioButton();
bg.add(r0);
bg.add(r1);
bg.add(r2);
add(r0);
add(r1);
add(r2);
// default RADIO button
if (!defaultDone) {
String rDef = rb.getString("rDefault");
if (rDef.equals("r0"))
r0.setSelected(true);
else if (rDef.equals("r1"))
r1.setSelected(true);
else
r2.setSelected(true);
defaultDone = true;
}
else {
if (localeChoosen == 0)
r0.setSelected(true);
else if (localeChoosen == 1)
r1.setSelected(true);
else
r2.setSelected(true);
}
// QUIT button
btnQuit = new JButton();
add(btnQuit);
// today label
today = new JLabel();
add(today);
//
r0.addActionListener(this);
r1.addActionListener(this);
r2.addActionListener(this);
btnQuit.addActionListener(this);
setSize(400,100);
setVisible(true);
}
public void actionPerformed(ActionEvent ae){
if (ae.getSource() == btnQuit) {
System.exit(0);
}
else if (ae.getSource() == r0) localeChoosen = 0;
else if (ae.getSource() == r1) localeChoosen = 1;
else if (ae.getSource() == r2) localeChoosen = 2;
initLocale();
initText();
pack();
}
public static void main(String args[]) {
System.out.println("Current Locale : " + Locale.getDefault());
Thread t = new Thread () {
public void run() {
InternationalDynamic i = new InternationalDynamic();
i.initLocale();
i.initGUI();
i.initText();
i.pack();
}
};
SwingUtilities.invokeLater(t);
}
}
{
{
{
{
{
{
};
With the previous JAVA Howto, the resources were stored in classes. The drawback is when there
is a modification, we must recompile the class. With a resources file, we simply add or modify the
resource in a special file with a regular text editor. The JDK provides a class,
PropertyResourceBundle, to use properties file very easily. In fact, from the programmer's point of
view, there is no difference if the resources are stored in classes or properties files.
The ResourceBundle will look first for classes and if not found, it will look for properties files. We
don't have to specify filenames, the ResourceBundle will construct the filename using the same
mechanism used for classes. The file must have the extension .properties.
The ResourceBundle try to load the properties file from the current classpath.
If the properties are stored in subdirectory , use "." instead of "/".
For example, let's say that the properties file is in a subdirectory called "subdir" (from the current
directory). Then you can load the ResourcesDynamic resources file with
ResourceBundle.getBundle("subdir.ResourcesDynamic", localeCurrent);
[InternationalDynamic.java]
import
import
import
import
import
java.util.*;
java.text.*;
java.awt.*;
java.awt.event.*;
javax.swing.*;
// QUIT button
btnQuit = new JButton();
add(btnQuit);
// today label
today = new JLabel();
add(today);
//
r0.addActionListener(this);
r1.addActionListener(this);
r2.addActionListener(this);
btnQuit.addActionListener(this);
setSize(400,100);
setVisible(true);
}
public void actionPerformed(ActionEvent ae){
if (ae.getSource() == btnQuit) {
System.exit(0);
}
[RresourcesDynamic.properties]
title=Example
r0=United States
r1=France
r2=Germany
rDefault=r0
btnQuit=Quit
today=(def) {0,date,long}
[RresourcesDynamic_en.properties]
title=Example
r0=United States
r1=France
r2=Germany
rDefault=r0
btnQuit=Quit
today=(en) {0,date,long}
[ResourcesDynamic_fr.properties]
title=Exemple
r0=EtatsUnis
r1=France
r2=Allemagne
rDefault=r1
btnQuit=Quitte
today=(fr) {0,date, dd/MM/yyyy}
[ResourcesDynamic_de.properties]
title=Beispiel
r0=Vereinigte Staaten
r1=Frankreich
r2=Deutschland
rDefault=r2
btnQuit=Verlassen
today=(de) {0,date,dd.MM.yyyy}
For example :
import java.awt.*;
public class TestUnicode extends java.applet.Applet {
public static final String COPYRIGHT = "\u00a9";
public static final String REGISTERED = "\u00ae";
public static final String EURO = "\u20ac";
public void init () {
setLayout(new FlowLayout());
Label a = new Label(COPYRIGHT + " R\u00e9al Gagnon");
Label b = new Label(REGISTERED + " R\u00e9al's Software "
+ " price : 100 " + EURO);
add(a);
add(b);
}
}
Output :
Java not enabled!
A list of Unicode characters is available at the Unicode organization Web site.
Here a quick list for accented letters :
\u00e0 \u00c0
\u00e1 \u00c1
\u00e2
\u00e9
\u00e8
\u00ea
\u00ee
\u00e7
\u00c2
\u00c9
\u00c8
\u00ca
\u00ce
\u00c7
Then
import
import
import
import
javax.swing.*;
java.awt.event.*;
java.awt.*;
java.util.*;
System.out.println(result);
}
}
public Dimension getPreferredSize(){
return new Dimension(200, 200);
}
public static void main(String s[]) {
JFrame frame = new JFrame("");
MessageBoxExample panel = new MessageBoxExample();
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
}
}
{
// use the default locale
return convertStringAsStringNumberUnLocalized(Locale.getDefault(), value);
}
public static String convertStringAsStringNumberUnLocalized
(Locale loc, String value)
throws ParseException
{
double d = NumberUtils.getDoubleValue(loc, value);
return NumberFormat.getInstance(new Locale("us")).format(d);
}
[JFileChooser_fr.properties]
Title=JFileChooser de R\u00e9al
lookInLabelText=Courant
filesOfTypeLabelText=Type de fichier
upFolderToolTipText=Remonte
Then
[LocalizeJFileChooser.java]
import
import
import
import
javax.swing.*;
java.awt.event.*;
java.awt.*;
java.util.*;
locale = Locale.US;
}
public void setUILanguage() {
ResourceBundle rb;
rb = ResourceBundle.getBundle("JFileChooser", locale);
z_choosertitle = rb.getString("Title");
UIManager.put
("FileChooser.lookInLabelText",
rb.getString("lookInLabelText"));
UIManager.put
("FileChooser.filesOfTypeLabelText",
rb.getString("filesOfTypeLabelText"));
UIManager.put
("FileChooser.upFolderToolTipText",
rb.getString("upFolderToolTipText"));
/*
do the same with :
FileChooser.fileNameLabelText
FileChooser.homeFolderToolTipText
FileChooser.newFolderToolTipText
FileChooser.listViewButtonToolTipTextlist
FileChooser.detailsViewButtonToolTipText
FileChooser.saveButtonText=Save
FileChooser.openButtonText=Open
FileChooser.cancelButtonText=Cancel
FileChooser.updateButtonText=Update
FileChooser.helpButtonText=Help
FileChooser.saveButtonToolTipText=Save
FileChooser.openButtonToolTipText=Open
FileChooser.cancelButtonToolTipText=Cancel
FileChooser.updateButtonToolTipText=Update
FileChooser.helpButtonToolTipText=Help
Almost all Swing widgets can be customize this way. You can
examine the Swing sources to get these values or check
http://www.gargoylesoftware.com/papers/plafdiff.html for
a list of them.
*/
}
public void actionPerformed(ActionEvent e) {
int result;
if (e.getSource() instanceof JRadioButton) {
if (e.getActionCommand().equals("en"))
locale = Locale.US;
else
locale = Locale.FRANCE;
setUILanguage();
}
else {
z_chooser = new JFileChooser();
z_chooser.setCurrentDirectory(new java.io.File("."));
z_chooser.setDialogTitle(z_choosertitle);
if (z_chooser.showOpenDialog(this) !=
JFileChooser.APPROVE_OPTION)
return;
}
}
public Dimension getPreferredSize(){
return new Dimension(200, 200);
}
public static void main(String s[]) {
JFrame frame = new JFrame("");
LocalizeJFileChooser panel = new LocalizeJFileChooser();
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
}
}
[standard_fr.properties (extract)]
doclet.Window_Split_Index={0}\: {1}Index
doclet.Packages=Paquetages
doclet.SerialData=Donn\u00E9e s\u00E9rialis\u00E9e\:
doclet.Since=Depuis\:
doclet.Warn_inline_taglet=Inline tag {0} should only be used with a {1}.
doclet.ClassUse_Subinterface=Sousinterfaces de {0} dans {1}
doclet.Frame_Version=Version avec cadres
doclet.Generated_Docs_Untitled=Documentation g\u00E9n\u00E9r\u00E9e
Once everything translated, put your standard_fr.properties into the tools.jar making sure that the
file is located in the right package (along standard.properties in
com.sun.tools.doclets.standard.resources).
To generate in french, use the locale switch on the command line
javadoc locale fr ....
Case insensitive
java.util.Arrays.sort(myArray, String.CASE_INSENSITIVE_ORDER);
else {
return System.console().writer();
}
}
}
The output is :
Before :
Ral Real Raoul Rico
After :
Raoul Real Rico Ral
by
java.util.Arrays.sort(words, java.text.Collator.getInstance(java.util.Locale.FRENCH));
// or
// java.util.Arrays.sort(words, java.text.Collator.getInstance());
In this code, we have 2 strings, "tat" and "famille". We expect that "tat" is before "famille". But
String.compareTo() will return that "famille" is before "tat".
class Test {
public static void main(String args[]) {
String s1 = "tat";
String s2 = "famille";
// here we are expecting "" < "f"
if (s1.compareTo(s2) > 0) {
if (s1.compareTo(s2) > 0) {
// s1 lexicographically follows s2 which is not true!
Equality
To compare without taking into account the presence of accentued so that "" == "e", we use a
Collator.
import java.text.Collator;
// import java.util.Locale;
public class TextTest {
public static void main(String ... args) {
String a = "Real";
String b = "Ral";
System.out.println(a + " and " + b + " equals? " +
check(a,b));
/*
* output :
* Real and Ral equals? true
*/
}
}
}
=
=
=
=
=
s.replaceAll("[]","e");
s.replaceAll("[]","u");
s.replaceAll("[]","i");
s.replaceAll("[]","a");
s.replaceAll("","o");
s
s
s
s
s
=
=
=
=
=
s.replaceAll("[]","E");
s.replaceAll("[]","U");
s.replaceAll("[]","I");
s.replaceAll("[]","A");
s.replaceAll("","O");
System.out.println(s);
// output : E,E,E,E,U,U,I,I,A,A,O,e,e,e,e,u,u,i,i,a,a,o
}
}
As a bonus, here a method to convert a given string to uppercase with no accent. This can be
useful in a database field to simplify name searching with accent or not.
C:\temp>java Test
caractres franais :
caractres franais :
}
}
See also java encoding table for the encoding sets supported.
r.close();
System.exit(0);
}
}
java.nio.ByteBuffer;
java.nio.CharBuffer;
java.nio.charset.Charset;
java.nio.charset.CharsetDecoder;
java.nio.charset.CharacterCodingException;
A different (and simpler) approach is to take a given string and check if it's possible to encode it into
ASCII.
5.21 Detect nonASCII character in a StringTag(s): Internationalization String/Number
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
public class StringUtils {
static CharsetEncoder asciiEncoder =
Charset.forName("USASCII").newEncoder(); // or "ISO88591" for ISO Latin 1
public static boolean isPureAscii(String v) {
return asciiEncoder.canEncode(v);
}
public static void main (String args[])
throws Exception {
String test = "Ral";
System.out.println(test + " isPureAscii() : " + StringUtils.isPureAscii(test));
test = "Real";
System.out.println(test + " isPureAscii() : " + StringUtils.isPureAscii(test));
/*
* output :
*
Ral isPureAscii() : false
*
Real isPureAscii() : true
*/
}
}
Another way is to use a regular expression, see this Javascript HowTo for a hint!
To simply strip any nonascii characters form a string
public class Test {
public static void main(String args[]){
String input = "ea";
String output = input.replaceAll("[^\\p{ASCII}]", "");
System.out.println(output);
/*
* output : ea
*/
}
}
5.22 Get the month (or day) name (localized)Tag(s): Date and
Time Internationalization
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java0650.html
import java.text.DateFormatSymbols;
import java.util.Locale;
5.22 Get the month (or day) name (localized)Tag(s): Date and Time Internationalization
5.22 Get the month (or day) name (localized)Tag(s): Date and Time Internationalization
6 IO
6.1 javaio
6 IO
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return "\r\n" + sw.toString() + "\r\n";
}
catch(Exception e2) {
return "bad stack2string";
}
}
}
You may want to suppress output done with the regular System.out but maintain the ability to write
to the original streams directly when necessary.
// Keep a copy of the original out stream.
PrintStream original = new PrintStream(System.out);
// replace the System.out, here I redirect to NUL (for demonstration)
System.setOut(new PrintStream(new FileOutputStream("NUL:")));
System.out.println("bar"); // no output
// The original stream is still available
original.println("foo"); // output to stdout
java.io.ByteArrayInputStream;
java.io.IOException;
java.io.InputStream;
java.io.File;
java.io.FileInputStream;
import
import
import
import
import
import
import
javax.print.Doc;
javax.print.DocFlavor;
javax.print.DocPrintJob;
javax.print.PrintException;
javax.print.PrintService;
javax.print.PrintServiceLookup;
javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;
public class PrintTextFile {
public static void main(String[] args) throws PrintException, IOException {
String defaultPrinter =
PrintServiceLookup.lookupDefaultPrintService().getName();
System.out.println("Default printer: " + defaultPrinter);
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
FileInputStream in = new FileInputStream(new File("c:/temp/foo.txt"));
PrintRequestAttributeSet
pras.add(new Copies(1));
javax.print.Doc;
javax.print.DocFlavor;
javax.print.DocPrintJob;
javax.print.PrintException;
javax.print.PrintService;
javax.print.PrintServiceLookup;
javax.print.SimpleDoc;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.Copies;
import javax.print.event.PrintJobAdapter;
import javax.print.event.PrintJobEvent;
public class PrintText {
public static void main(String[] args) throws PrintException, IOException {
String defaultPrinter =
PrintServiceLookup.lookupDefaultPrintService().getName();
System.out.println("Default printer: " + defaultPrinter);
PrintService service = PrintServiceLookup.lookupDefaultPrintService();
// prints the famous hello world! plus a form feed
InputStream is = new ByteArrayInputStream("hello world!\f".getBytes("UTF8"));
PrintRequestAttributeSet
pras.add(new Copies(1));
allDone();
}
public void printJobNoMoreEvents(PrintJobEvent pje) {
allDone();
}
void allDone() {
synchronized (PrintJobWatcher.this) {
done = true;
System.out.println("Printing done ...");
PrintJobWatcher.this.notify();
}
}
});
}
public synchronized void waitForDone() {
try {
while (!done) {
wait();
}
} catch (InterruptedException e) {
}
}
}
try {
p = rt.exec( cmd );
if( p.waitFor() != 0 ) {
System.out.println("Error executing command: " + cmd );
System.exit( 1 );
}
byte data[] =
"Writing a byte stream out of a serial port.".getBytes();
FileOutputStream fos = new FileOutputStream( portname );
BufferedOutputStream bos = new BufferedOutputStream( fos );
fos.write( data, 0, data.length );
fos.close();
}
catch( Exception e ) {
e.printStackTrace();
}
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
public static void close(String drive) {
try {
File file = File.createTempFile("realhowto",".vbs");
file.deleteOnExit();
FileWriter fw = new FileWriter(file);
// to close a CD, we need eject two times!
String vbs = "Set wmp = CreateObject(\"WMPlayer.OCX\") \n"
+ "Set cd = wmp.cdromCollection.getByDriveSpecifier(\""
+ drive + "\") \n"
+ "cd.Eject \n "
+ "cd.Eject ";
fw.write(vbs);
fw.close();
Runtime.getRuntime().exec("wscript " + file.getPath()).waitFor();
// thanks to TrueJavaProgammer for the waitFor() tip!
// Runtime.getRuntime().exec("wscript "+ file.getPath());
// Thread.sleep(2000);
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args){
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
null, "Press OK to open CD", "CDUtils",
javax.swing.JOptionPane.DEFAULT_OPTION);
CDUtils.open("D:\\");
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
null, "Press OK to close CD", "CDUtils",
javax.swing.JOptionPane.DEFAULT_OPTION);
CDUtils.close("D:\\");
}
}
NOTE : Windows Media Player version 7 or later is required
private VolumeLabel() { }
public static void main(String[] args) {
System.out.println("\"" + get(args[0]) + "\"");
}
public static String get(String path) {
FileSystemView view = FileSystemView.getFileSystemView();
File dir = new File(path);
String name = view.getSystemDisplayName(dir);
if (name == null) { return null; }
name = name.trim();
if (name == null || name.length() < 1) {
return null;
}
int index = name.lastIndexOf(" (");
if (index > 0) {
name = name.substring(0, index);
}
return name;
}
}
The output
Running from c:\temp
>java VolumeLabel c:
"temp"
>java VolumeLabel c:\
"HARDDISK1"
java.io.File;
java.util.Arrays;
java.util.List;
javax.swing.filechooser.FileSystemView;
java.io.File;
java.util.Arrays;
java.util.List;
javax.swing.filechooser.FileSystemView;
java.io.BufferedWriter;
java.io.FileDescriptor;
java.io.FileOutputStream;
java.io.OutputStreamWriter;
The result is
>java Test >NUL
Loop time: 7000
Now, rewrite this program to use a 512bytes buffer and specify the ASCII as
characterencoding to be used.
6.14 Get faster console output (System.out.println() replacement)Tag(s): IO
import
import
import
import
java.io.BufferedWriter;
java.io.FileDescriptor;
java.io.FileOutputStream;
java.io.OutputStreamWriter;
The result is
>java Test >NUL
Loop time: 672
Note that your result will vary depending on your machine/java version but the performance gain
should in the same magnitude.
NOTE: JDK 1.5 provides the Scanner class to do this, see this HowTo.
6.20 Jansi
Jansi is a small java library that allows you to use ANSI escape sequences to format your console
output which works even on Windows.
import org.fusesource.jansi.AnsiConsole;
public class Test {
public static final
public static final
public static final
public static final
public static final
public static final
public static final
String
String
String
String
String
String
String
ANSI_CLS = "\u001b[2J";
ANSI_HOME = "\u001b[H";
ANSI_BOLD = "\u001b[1m";
ANSI_AT55 = "\u001b[10;10H";
ANSI_REVERSEON = "\u001b[7m";
ANSI_NORMAL = "\u001b[0m";
ANSI_WHITEONBLUE = "\u001b[37;44m";
}
}
NOTE: Check this "old" text file to have an overview of ANSI Escape Sequences.
The above example shows that it's possible to use ANSI codes directly but Jansi provides a neat
mechanism to help building the required ANSI sequence.
import static org.fusesource.jansi.Ansi.*;
import static org.fusesource.jansi.Ansi.Color.*;
...
System.out.println( ansi().eraseScreen().fg(RED).a("Hello").fg.(GREEN).a(" World").reset()
6.21 JCurses
The Java Curses Library (JCurses) is a library for developing text terminal based applications
using Java programming language. It is implemented as a Windowing toolkit similar to AWT, but
built upon the UNIX "curses" windowing system.
JCurses works on Unix and Windows (32 bit only, on a 64bit OS you need to use JCurses with a
32bit JVM).
This example will display a characterbased window with a label, a textfield and a button (don't
click with you mouse, use the keyboard!).
import
import
import
import
jcurses.system.*;
jcurses.widgets.*;
jcurses.util.*;
jcurses.event.*;
6.21 JCurses
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches
whitespace. The resulting tokens may then be converted into values of different types using the
various next methods.
6.22 Easy keyboard input (JDK1.5)Tag(s): IO
import java.util.Scanner;
class TestScanner {
public static void main(String args[]) {
// if input is
//
10,12
// then the output is
// 10
// 12
//
// we use a regex as delimiter to combine "," and
// whitespace (in this case the ENTER key)
Scanner sc = new Scanner(System.in).useDelimiter("[,\\s]");
while (sc.hasNextInt()) {
int i = sc.nextInt();
System.out.println(i);
}
System.out.println("Done");
}
}
Scanner can be used with String or Stream. For exemple, the above HowTo can be written like
this :
import java.util.Scanner;
class TestScanner {
public static void main(String args[]) {
String input = "10,12"
Scanner sc = new Scanner(System.in).useDelimiter(",");
while (sc.hasNextInt()) {
int i = sc.nextInt();
System.out.println(i);
}
System.out.println("Done");
}
}
NOTE : This technique changes the keyboard state so the effect is also seen outside the Java
program.
See also this related Howto.
super.println(s.toUpperCase());
}
});
System.out.println("hello world"); // output :
HELLO WORLD
}
}
Replace the regular output stream of System.out to do useful thing like implementing a Tee
mechanism to output to the console and to file.
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
public class TeeOutputStream extends OutputStream {
private OutputStream os1;
private OutputStream os2;
public TeeOutputStream(OutputStream os1, OutputStream os2) {
this.os1 = os1;
this.os2 = os2;
}
public void write(int i) throws IOException {
os1.write(i);
os2.write(i);
}
public void flush() throws IOException {
os1.flush();
os2.flush();
}
public void close() throws IOException {
os1.close();
os2.close();
}
public static void main(String[] args) throws IOException {
System.out.println("Starting...");
// keep the original
PrintStream originalOutStream = System.out;
System.setOut(
new PrintStream(
new TeeOutputStream(
System.out,
new PrintStream("C:/temp/howto.out"))));
// restore the original
System.out.println("*");
for (int i = 1; i<= 10; i++) {
System.out.println(i);
}
System.out.println("*");
System.setOut(originalOutStream);
System.out.println("Done. Check the log");
}
}
The next example, launch CMD.EXE, grab stdin/stdout and push to stdin command to be
interpreted by the shell.
String line;
OutputStream stdin = null;
InputStream stderr = null;
InputStream stdout = null;
// launch EXE and grab stdin/stdout and stderr
Process process = Runtime.getRuntime ().exec ("/folder/exec.exe");
stdin = process.getOutputStream ();
stderr = process.getErrorStream ();
stdout = process.getInputStream ();
6.27 Launch a Windows CMD (or BAT) file and retrieve the
errorlevel or exitcode
// win xp
import java.io.*;
public class CmdExec {
public static void main(String argv[]) {
try {
String line;
Process p = Runtime.getRuntime().exec("test.cmd");
p.waitFor();
System.out.println(p.exitValue());
}
catch (Exception err) {
err.printStackTrace();
}
}
}
6.27 Launch a Windows CMD (or BAT) file and retrieve the errorlevel or exitcode
See also this HowTo about the new Desktop API, the recommended solution (but you need
JDK1.6).
See also this one to open the default browser.
6.28 Launch a Unix script
If you need to pass arguments, it's safer to a String array especially if they contain spaces.
String[] cmd = { "myProgram.exe", "o=This is an option" };
Runtime.getRuntime().exec(cmd);
If using the start command and the path of the file to be started contains a space then you must
specified a title to the start command.
String fileName = "c:\\Applications\\My Documents\\test.doc";
String[] commands = {"cmd", "/c", "start", "\"DummyTitle\"",fileName};
Runtime.getRuntime().exec(commands);
6.34 VBSCRIPT
// Win9x
Runtime.getRuntime().exec("start myscript.vbs");
// WinNT
Runtime.getRuntime().exec("cmd /c start myscript.vbs");
or
// with a visible console
Runtime.getRuntime().exec("cscript myscript.vbs");
// with no visible console
Runtime.getRuntime().exec("wscript myscript.vbs");
To load a worksheet
import java.io.IOException;
class StartExcel {
public static void main(String args[])
throws IOException
{
String fileName = "c:\\temp\\xls\\test2.xls";
String[] commands = {"cmd", "/c", "start", "\"DummyTitle\"",fileName};
Runtime.getRuntime().exec(commands);
}
}
6.34 VBSCRIPT
It's important to pass a dummy title to the Windows start command where there is a possibility
that the filename contains a space. It's a feature.
/SaveCred option allows you to save a password for that account and then reuse it later. For
example, The command runas /savecred /user:administrator regedit.exe prompts
for the password, and then Regedit runs. Next time you use the same command, there is no
password prompt.
One potential problem is that when /SaveCred saves the credentials it saves it for whenever
RUNAS invokes that user account. This can be a huge security risk so be careful using it!
RUNAS capability can be disabled by editing the Registry or by disabling the RUNAS or
Secondary Logon Services. The appropriate registry key is
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer, create a
new DWORD value named HideRunAsVerb and assign it a value of 1 to disable Run as.
RUNAS doesn't work when used from a Windows service.
+ FILE_SEPARATOR + "textpad.exe"};
Runtime.getRuntime().exec(commands);
}
}
NOTE : Prior Vista, System folders were localized on disk like C:\Program Files > C:\Archivos de
programa on the Windows with the Spanish localization. Since Vista, System Folders always
exists with the english name BUT when viewed through Explorer, the localized name is shown.
See
http://msmvps.com/blogs/carlosq/archive/2007/02/12/windowsvistajunctionspointsmuiandlocalized
Launch many programs using Thread and use join() to wait for the completion.
[Program2.java]
public class Program2 {
public static void main(String arg[]) {
System.out.println("Hello from Program2");
System.out.println("Hello from Program2");
System.out.println("Hello from Program2");
System.out.println("Hello from Program2");
}
}
[Program1a.java]
public class Program1a {
public static void main(String arg[]) throws Exception{
System.out.println("Hello from Program1a");
Thread t1 = new Thread(){
public void run() {
Program2.main(new String[]{});}
};
t1.start();
t1.join();
System.out.println("Hello from Program1a");
}
}
The output :
C:\>java Program1a
Hello from Program1a
Hello from Program2
Hello from Program2
Hello from Program2
Hello from Program2
[StartBrowser.java]
Howto
Howto
Howto
Howto
Howto
import
import
import
import
import
java.applet.*;
java.awt.*;
java.awt.event.*;
java.net.*;
java.io.*;
1
2
3
4
5
);
setVisible(true);
}
public void actionPerformed (ActionEvent ae) {
String theUrl = url[lbx.getSelectedIndex()];
// start the default browser (Win95 platform)
// on listbox double click
String cmdLine = "start " + theUrl;
// on NT, you need to start cmd.exe because start is not
// an external command but internal, you need to start the
// command interpreter
// String cmdLine = "cmd.exe /c " + cmdLine;
try {
Process p = Runtime.getRuntime().exec(cmdLine);
}
catch (Exception e) {
e.printStackTrace();
}
}
public void initLbx() {
int i = 0;
try {
String aLine = "";
BufferedReader in
= new BufferedReader(new FileReader("urlList.txt"));
while(null != (aLine = in.readLine())) {
java.util.StringTokenizer st =
new java.util.StringTokenizer(aLine, "|");
url[i++] = st.nextToken();
lbx.addItem(st.nextToken());
// lbx.add(st.nextToken());
in JDK1.2
}
}
catch(Exception e) {
e.printStackTrace();
}
}
}
You may have difficulty to open a URL ending with .htm. All you need is to replace the last m with
%6D, like
rundll32 url.dll,FileProtocolHandler http://www.rgagnon.com/howto.htm
for
rundll32 url.dll,FileProtocolHandler http://www.rgagnon.com/howto.ht%6D
In this example, a file with the extension .xox will be defined and associated with a java program
(display the first 10 lines of selected .xox file).
First the java program to be associated with the .xox file type.
import java.io.*;
public class Head {
static final int MAX_LINES = 10;
public static void main(String args[]) throws Exception{
String line = null;
int i = 0 ;
FileInputStream fin = new FileInputStream(args[0]);
BufferedReader myInput = new BufferedReader
(new InputStreamReader(fin));
while ( (line = myInput.readLine()) != null) {
System.out.println(line);
i++;
if (i == MAX_LINES) break;
}
BufferedReader input =
new BufferedReader(new InputStreamReader(System.in));
System.out.print("*** Press any key...");
input.readLine();
}
}
With Windows, two commands are used to define a file association, assoc and ftype. You need
to execute these commands from an account with Administrator privilege.
To know more about these commands, type assoc /? or ftype /? .
Then we specify which program is used to handle the Xoxfile type of file.
The ftype command sets up an association between a file type name, and a string to be used to
execute it.
In this example, we specify the Java JVM to be used, the classpath to load the Head.class plus
the parameter (the selected .xox file).
>ftype Xoxfile=C:\Program Files\Java\jre1.5.0\bin\java cp c:\dev\work Head %1
Xoxfile=C:\Program Files\Java\jre1.5.0\bin\java cp c:\dev\work Head %1
Now, if you doubleclick on a file with .xox extension, a Dos shell is opened, the Head class is
launched with the clicked filename as a parameter and the first 10 line are displayed.
To make the file association works from a command line, you define the environment variable
PATHEXT to include the .xox extension.
>set pathext=.xox;%pathext%
PATHEXT=.XOX;.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
then you will be able, from a Dos shell, to type only the name of .xox file and the associated
program will be launched with that file as a parameter.
See also this HowTo.
java.io.BufferedReader;
java.io.File;
java.io.FileWriter;
java.io.InputStreamReader;
e.printStackTrace();
}
return result.trim();
}
fw.write(vbs);
fw.close();
Process p = Runtime.getRuntime().exec("wscript " + file.getPath());
p.waitFor();
return (p.exitValue() == 1);
}
catch(Exception e){
e.printStackTrace();
}
return false;
}
String line;
OutputStream stdin = null;
InputStream stderr = null;
InputStream stdout = null;
try {
// that our CMD file in our JAR
InputStream is =
getClass().getResource("/screensaver.cmd").openStream();
BufferedReader brCmdLine =
new BufferedReader(new InputStreamReader(is));
// launch CMD and grab stdin/stdout and stderr
Process process = Runtime.getRuntime ().exec ("cmd");
stdin = process.getOutputStream ();
stderr = process.getErrorStream ();
stdout = process.getInputStream ();
// "write" the CMD file into stdin
while ((line = brCmdLine.readLine()) != null) {
line += "\n";
stdin.write(line.getBytes() );
}
stdin.flush();
stdin.close();
// clean up if any output in stdout
BufferedReader brCleanUp =
new BufferedReader (new InputStreamReader (stdout));
while ((line = brCleanUp.readLine ()) != null) {
//System.out.println ("[Stdout] " + line);
}
brCleanUp.close();
// clean up if any output in stderr
brCleanUp =
new BufferedReader (new InputStreamReader (stderr));
while ((line = brCleanUp.readLine ()) != null) {
//System.out.println ("[Stderr] " + line);
}
brCleanUp.close();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
stdout.close();
stderr.close();
}
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
The following method read a data file and return the content as a String. We use a StringBuffer to
optimize string concatenation operations.
private static String readFile(String filename) throws IOException {
String lineSep = System.getProperty("line.separator");
BufferedReader br = new BufferedReader(new FileReader(filename));
String nextLine = "";
StringBuffer sb = new StringBuffer();
while ((nextLine = br.readLine()) != null) {
sb.append(nextLine);
//
// note:
//
BufferedReader strips the EOL character
//
so we add a new one!
//
sb.append(lineSep);
}
return sb.toString();
}
JDK1.5 provides the java.util.Scanner class which can be used to quickly read a file.
The delimeter "\Z" represents the endoffile marker.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class QuickFileRead {
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner =
new Scanner(new File("c:/temp/text.txt")).useDelimiter("\\Z");
String contents = scanner.next();
System.out.println(contents);
scanner.close();
}
}
import java.applet.*;
import java.net.*;
import java.io.*;
public class MyApplet extends Applet {
public void init() {
readFile("mydatafile.txt");
}
public void readFile(String f) {
try {
The next Applet reads a data file and inserts the data in a Choice component.
import
import
import
import
java.applet.*;
java.awt.*;
java.net.*;
java.io.*;
[dataforchoice.txt]
item
item
item
item
item
ITEM
1
2
3
4
5
6
Try it here.
Create 2 datafiles.
datafile1.txt in the same directory as FileUtils.class (in the root) and datafile2.txt in a subdirectory
called test
[datafile1.txt]
datafile1
datafile1
datafile1
datafile1
datafile1
line
line
line
line
line
1
2
3
4
5
[/test/datafile2.txt]
datafile2
datafile2
datafile2
datafile2
datafile2
line
line
line
line
line
1
2
3
4
5
Try it :
C> java cp MyJar.jar FileUtils
line
line
line
line
line
line
line
line
line
line
1
2
3
4
5
1
2
3
4
5
String thisLine;
try {
InputStream is = getClass().getResourceAsStream(s);
BufferedReader br = new BufferedReader
(new InputStreamReader(is));
while ((thisLine = br.readLine()) != null) {
System.out.println(thisLine);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
The html
<HTML><HEAD></HEAD><BODY>
<APPLET CODE=ReadFromJar.class width=1 height=1 archive=MyJarApplet.jar>
</APPLET>
See java console for output</BODY></HTML>
Try it here
ManifestVersion: 1.0
Classpath: .\mydb.jar
MainClass: ExtractFromJAR
Run it ... and the mydb.mdb file should appear in the current directory.
java jar mydb.jar
I got a problem when the jar file was located in C:\Program Files\xyz due to the embedded space.
So I modified the code to
String home = getClass().getProtectionDomain()
.getCodeSource().getLocation()
.getPath().replaceAll("%20", " ");
[floatwithdelimitercolon.dat]
1.2,1.3,1.6,1.78,1.2345
2.2,2.3,2.6,2.78,2.2345
[floatwithdelimiterspace.dat]
1.2 1.3 1.6 1.78 1.2345
2.2 2.3 2.6 2.78 2.2345
[JDK1.1]
FileOutputStream fos = new FileOutputStream("myfile", true);
Before writting to a file or in a database record it is necessary to change the default String
encoding. This done via the InputStreamReader class for input and OutputStreamWriter for
output.
InputStreamReader converts from the specified input encoding to Unicode while the
OutputStreamWriter converts from Unicode to the specified output encoding.
import java.io.*;
import java.awt.*;
public class DosString {
public static void main(String args[]){
String javaString = " \u00e9"; // Unicode for ""
try {
// output : Unicode to Cp850 (MSDOS Latin1)
FileOutputStream fos = new FileOutputStream("out.dat");
Writer w =
new BufferedWriter(new OutputStreamWriter(fos, "Cp850"));
w.write(JavaString);
w.flush();
w.close();
// input`: Cp850 to Unicode
FileInputStream fis = new FileInputStream("out.dat");
BufferedReader r =
new BufferedReader(new InputStreamReader(fis, "Cp850"));
String dosString = r.readLine();
r.close();
Frame f = new Frame();
f.setSize(100,100);
f.add(new Label(dosString));
f.setVisible(true);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
NOTE: When the character encoding is not specified, the default encoding is used. You can find out the current default encoding by looking
at file.encoding property with System.getProperty("file.encoding"); .
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Test {
public static void main(String[] args) throws IOException {
Path source = Paths.get("c:/temp/0multipage.tif");
Path target = Paths.get("c:/temp/1multipage.tif");
Files.copy(source, target, REPLACE_EXISTING); // Files.move(...) is also possible
// see http://docs.oracle.com/javase/tutorial/essential/io/copy.html
}
}
ref : http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4643189
On the Windows plateform, you can't copy a file bigger than 64Mb, an Exception in thread "main"
java.io.IOException: Insufficient system resources exist to complete the requested service is
thrown.
For a discussion about this see : http://forum.java.sun.com/thread.jspa?threadID=4396950
The workaround is to copy in a loop 64Mb each time until there is no more data.
Replace
6.57 Copy a fileTag(s): IO
...
try {
inChannel.transferTo(0, inChannel.size(),
outChannel);
}
...
by
...
try {
// magic number for Windows, 64Mb 32Kb)
int maxCount = (64 * 1024 * 1024) (32 * 1024);
long size = inChannel.size();
long position = 0;
while (position < size) {
position +=
inChannel.transferTo(position, maxCount, outChannel);
}
...
http://www.rgagnon.com/javadetails/../javadetails/java0063.html
/**
* Utilities log
*/
import java.io.*;
import java.text.*;
import java.util.*;
public class SimpleLog {
private static String logFile = "/msglog.txt";
private final static DateFormat df = new SimpleDateFormat ("yyyy.MM.dd
private SimpleLog() { }
public static void setLogFilename(String filename) {
logFile = filename;
new File(filename).delete();
try {
write("LOG file : " + filename);
}
catch (Exception e) {
System.out.println(stack2string(e));
}
}
public static void write(String msg) {
write(logFile, msg);
}
public static void write(Exception e) {
write(logFile, stack2string(e));
}
public static void write(String file, String msg) {
try {
Date now = new Date();
String currentTime = SimpleLog.df.format(now);
FileWriter aWriter = new FileWriter(file, true);
aWriter.write(currentTime + " " + msg
+ System.getProperty("line.separator"));
System.out.println(currentTime + " " + msg);
aWriter.flush();
aWriter.close();
}
catch (Exception e) {
System.out.println(stack2string(e));
}
}
private static String stack2string(Exception e) {
try {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return "\r\n" + sw.toString() + "\r\n";
}
catch(Exception e2) {
return "bad stack2string";
}
hh:mm:ss ");
}
}
and then
import java.io.*;
public class FileUtils{
public static void main(String args[]) throws Exception {
FileUtils.deleteFiles("c:/test/", ".gif");
}
public static void deleteFiles( String directory, String extension ) {
ExtensionFilter filter = new ExtensionFilter(extension);
File dir = new File(directory);
String[] list = dir.list(filter);
File file;
if (list.length == 0) return;
for (int i = 0; i < list.length; i++) {
//file = new File(directory + list[i]);
file = new File(directory, list[i]);
System.out.print(file + " deleted : " + file.delete());
}
}
}
}
will insert the string "HELLO WORLD" at line number 9 in the file "test.out".
of course you need more error checking...
[JDK1.1]
import java.io.*;
public class JInsert {
public static void main(String args[]){
try {
JInsert j = new JInsert();
j.insertStringInFile
(new File(args[0]),Integer.parseInt(args[1]), args[2]);
}
catch (Exception e) {
e.printStackTrace();
}
}
public void insertStringInFile
(File inFile, int lineno, String lineToBeInserted)
throws Exception {
// temp file
File outFile = new File("$$$$$$$$.tmp");
// input
FileInputStream fis = new FileInputStream(inFile);
BufferedReader in = new BufferedReader
(new InputStreamReader(fis));
// output
FileOutputStream fos = new FileOutputStream(outFile);
PrintWriter out = new PrintWriter(fos);
Suppose we have a class called Queue.class. We want to save the state of the Queue in a file.
Since our Queue extends the Vector class, the methods needed to serialize the object are
already done. All we need is an input or output stream.
First the Queue class
import java.util.Vector;
import java.io.*;
public class Queue extends Vector {
/*
** FIFO, first in first out
*/
Queue() {
super();
}
void put(Object o) {
addElement(o);
}
Object get() {
if (isEmpty()) return null;
Object o = firstElement();
removeElement(o);
return o;
}
Object peek() {
if (isEmpty()) return null;
return firstElement();
}
}
To display the value of lastModified(), you need to create a Date object and then use
SimpleDateFormat to get the String representation.
String
For a directory, a thread is launched where we keep the Files in a Map, we check the current
lastModifed value of a given file and compare it with the value stored in the Map. Also a special
check is made to detect if a File is deleted.
import java.util.*;
import java.io.*;
public abstract class DirWatcher extends TimerTask {
private String path;
private File filesArray [];
private HashMap dir = new HashMap();
private DirFilterWatcher dfw;
public DirWatcher(String path) {
this(path, "");
}
public DirWatcher(String path, String filter) {
this.path = path;
dfw = new DirFilterWatcher(filter);
filesArray = new File(path).listFiles(dfw);
// transfer to the hashmap be used a reference and keep the
// lastModfied value
for(int i = 0; i < filesArray.length; i++) {
dir.put(filesArray[i], new Long(filesArray[i].lastModified()));
}
}
public final void run() {
HashSet checkedFiles = new HashSet();
filesArray = new File(path).listFiles(dfw);
import java.io.*;
public class DirFilterWatcher implements FileFilter {
private String filter;
public DirFilterWatcher() {
this.filter = "";
}
public DirFilterWatcher(String filter) {
this.filter = filter;
}
public boolean accept(File file) {
if ("".equals(filter)) {
return true;
}
return (file.getName().endsWith(filter));
}
}
The example watches the c:/temp folder for any activities on any *.txt files.
import java.util.*;
import java.io.*;
public class DirWatcherTest {
public static void main(String args[]) {
See also this related howto, this one and finally this one too.
6.69 JNotify
http://jnotify.sourceforge.net/
JNotify is a java library that allow java application to listen to file system events. JNotify works on
both Windows (Windows 2000, XP, Vista) and Linux with INotify support (Kernel 2.6.14 and
above).
http://johannburkard.de/blog/programming/java/CallnativemethodsinaDLLfromJavawithoutJNI.
In this blog entry, the package NativeCall is used to call the Windows API to get notification about
modification in given folder.
6.72 Java 7
Java 7 provides a mechanism to get notificaton on file change without polling (JSR 203).
http://blogs.sun.com/thejavatutorials/entry/watching_a_directory_for_changes
java.io.File;
java.io.IOException;
java.net.URI;
java.net.URISyntaxException;
java.net.URL;
import java.io.FilenameFilter;
public class Filter implements FilenameFilter {
protected String pattern;
public Filter (String str) {
pattern = str;
}
public boolean accept (File dir, String name) {
return name.toLowerCase().endsWith(pattern.toLowerCase());
}
public static void main (String args[]) {
if (args.length != 1) {
System.err.println
("usage: java Filter <pattern list>
return;
}
java.io.File;
java.io.FilenameFilter;
java.util.Arrays;
java.util.Iterator;
java.util.TreeSet;
/**
* <CODE>
* GenericFileFilter xml = new GenericFileFilter ("xml");
* // GenericFileFilter xmlandpdf = new GenericFileFilter (new String [] { "xml", "pdf" });
* File dir = new File (".");
* String[] strs = dir.list(xml);
* for (int i = 0; i < strs.length; i++) {
* // strs[i]
* }
* </CODE>
*/
public class GenericFileFilter implements FilenameFilter {
private TreeSet<String> exts = new TreeSet<String>() ;
public GenericFileFilter(String ext) {
exts.add("." + ext.toLowerCase().trim());
}
}
public boolean accept(File dir, String name) {
final Iterator<String> extList = exts.iterator();
while (extList.hasNext()) {
if (name.toLowerCase().endsWith(extList.next())) {
return true;
}
}
return false;
}
}
If your need is simple then you don't need a complete class to implement a FilenameFilter. You
can declare an anonymous class with this simple onleliner.
import java.io.File;
import java.io.FilenameFilter;
...
files = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
}
);
File [] foldersToBeChecked =
new File("J:\\").listFiles
(new FileFilter() {
public boolean accept(File pathname) {
return (pathname.isDirectory());
}
}
);
for(File f : foldersToBeChecked) {
System.out.println(f);
}
}
}
else {
System.out.println("Usage :");
System.out.println(" java DirUtils c:\temp");
}
/*
output:
C:\Applications>java DirUtils c:\zip
recursive Dir from c:\zip
[c:\zip, c:\zip\AutoIt.exe, c:\zip\cc32d48.exe, c:\zip\CODE_UPLOAD
148812122001.zip, c:\zip\groups2.txt, c:\zip\httrack3.23.exe, c:\
zip\mass20.zip, c:\zip\mp3,c:\zip\mp3\BonkEnc1.0beta1.exe, c:\zi
p\mp3\cdex_150b10_enu.exe, c:\zip\mp3\hh_install.exe, c:\zip\mp3\T
PlayerSetup.exe, c:\zip\mp3\Tunchy1017full.zip, c:\zip\mp3\TWMP3en
coder.exe, c:\zip\ok, c:\zip\ok\CmdHerePowertoySetup.exe, c:\zip\o
k\htmldoc1.8.23winfree.exe, c:\zip\ok\j2sdk1_4_1_02windowsi58
6.exe, c:\zip\ok\jdk141hh.zip, c:\zip\ok\jsref13.zip, c:\zip\ok\T
weakUiPowertoySetup.exe, c:\zip\quickmail2_1.zip, c:\zip\RealOneP
layerV2GOLD.exe, c:\zip\RESTorefile2514.EXE,c:\zip\Shockwave_Insta
ller_Full.exe, c:\zip\Water.exe, c:\zip\winamp50_full.exe,c:\zip\w
olf, c:\zip\wolf\ok, c:\zip\wolf\ok\kf_box.zip, c:\zip\wolf\sp_off
lag_levels_14_final.zip, c:\zip\xpAntiSpy.zip]
*/
}
}
java.io.File;
java.io.IOException;
java.nio.file.DirectoryStream;
java.nio.file.FileSystems;
java.nio.file.Files;
import java.nio.file.Path;
public class TestDir {
public static void main( String[] args ) throws IOException {
int maxFiles = 10;
System.out.println( "TEST BIG DIR" );
nioRun( "\\\\server.local\\files\\20130220", maxFiles );
ioRun( "\\\\server.local\\files\\20130220", maxFiles );
}
// the classical way
private static void ioRun( String filePath, int maxFiles )
throws IOException {
int i = 1;
System.out.println( "IO run" );
long start = System.currentTimeMillis();
File folder = new File( filePath );
File[] listOfFiles = folder.listFiles();
// System.out.println("Total : " + listOfFiles.length);
for (File file : listOfFiles) {
System.out.println( "" + i + ": " + file.getName() );
if (++i > maxFiles) break;
}
long stop = System.currentTimeMillis();
System.out.println( "Elapsed: " + (stop start) + " ms" );
}
// the new way
private static void nioRun( String filePath, int maxFiles )
throws IOException {
int i = 1;
System.out.println( "NIO run" );
long start = System.currentTimeMillis();
Path dir = FileSystems.getDefault().getPath( filePath );
DirectoryStream stream = Files.newDirectoryStream( dir );
for (Path path : stream) {
System.out.println( "" + i + ": " + path.getFileName() );
if (++i > maxFiles) break;
}
stream.close();
long stop = System.currentTimeMillis();
System.out.println( "Elapsed: " + (stop start) + " ms" );
}
}
the result is :
TEST BIG DIR
NIO run
1: 1355970441334_000000_AA000000.PDF
2: 1355970441334_000000_AA000000.props
3: 1355970441335_530025_AA000000.PDF
4: 1355970441335_530025_AA000000.props
5: 1355970441336_832300_AA000000.PDF
6: 1355970441336_832300_AA000000.props
7: 1355970441337_877400_AA000000.PDF
8: 1355970441337_877400_AA000000.props
9: 1355970441338_879900_AA000000.PDF
10: 1355970441338_879900_AA000000.props
Elapsed: 158 ms
IO run
1: 1355970441334_000000_AA000000.PDF
2: 1355970441334_000000_AA000000.props
3: 1355970441335_530025_AA000000.PDF
4: 1355970441335_530025_AA000000.props
5: 1355970441336_832300_AA000000.PDF
6: 1355970441336_832300_AA000000.props
7: 1355970441337_877400_AA000000.PDF
8: 1355970441337_877400_AA000000.props
9: 1355970441338_879900_AA000000.PDF
10: 1355970441338_879900_AA000000.props
Elapsed: 73455 ms
Creates an empty file in the default temporaryfile directory, using the given prefix ("real") and
suffix (".howto"). Plus, the temporary file will be deleted when the virtual machine terminates.
6.81 Delete a nonempty directoryTag(s): IO
Deletion will be attempted only for normal termination of the virtual machine.
(Javadoc) The prefix argument must be at least three characters long. It is recommended that the prefix be a short, meaningful string such
as "hjb" or "mail". The suffix argument may be null, in which case the suffix ".tmp" will be used. To create the new file, the prefix and the
suffix may first be adjusted to fit the limitations of the underlying platform.
If the prefix is too long then it will be truncated, but its first three characters will always be
preserved. If the suffix is too long then it too will be truncated, but if it begins with a period
character ('.') then the period and the first three characters following it will always be preserved.
Once these adjustments have been made the name of the new file will be generated by
concatenating the prefix, five or more internallygenerated characters, and the suffix.
The location of the directory used to hold temporary files is defined by the property java.io.tmpdir.
The default value can be changed with the command line used to launch the JVM :
java Djava.io.tmpdir=C:\mydir
myClass
or , on Windows, you can set the environment variable TMP to a different value.
On some plateform, the temporary directory returned by java.io.tmpdir do not include a trailing
slash. That is,
Win NT
Win XP
Solaris
Linux
>
>
>
>
C:\TEMP\
C:\TEMP
/var/tmp/
/var/tmp
System.out.println(java.nio.charset.Charset.defaultCharset().name());
}
}
See also java encoding table for the encoding sets supported.
6.87 opencsv
A simple csv parser library for Java
http://opencsv.sourceforge.net/
6.88 ServingXML
Framework for flat/XML data transformations. Supported transformations : flatXML, XMLflat,
flatflat, and XMLXML
http://servingxml.sourceforge.net/
6.90 csvreader
Library for reading and writing CSV and plain delimited text files. All kinds of CSV files can be
handled, text qualified, Excel formatted, etc.
http://www.csvreader.com/java_csv.php
6.91 CSVFile
A simple set of Java classes used to handle CSV
http://sourceforge.net/projects/csvfile
6.92 FlatPack
Flat file parser that handles CSV, fixed length and custom delimiters. Export a DataSet to a fixed
length or delimited format. FlatPack provides a sorting mechanism for your flat files.
http://flatpack.sourceforge.net/
6.93 CSVJDBC
CsvJdbc is a simple readonly JDBC driver that uses Comma Separated Value (CSV) files as
database tables.
http://csvjdbc.sourceforge.net/
6.94 FFP
FFP Flat file parsing library, is used to parse text files where lines can be interpreted according
to positional patterns. The library can handle both multiline formats and files containing lines
have different known formats ("mixed format" files).
http://jffp.sourceforge.net/
6.93 CSVJDBC
w.write(oemString);
w.flush();
}
w.close();
r.close();
System.exit(0);
}
}
If the replacement extension contains any of the replacement meta characters then
at best one will get the wrong extension and it can cause an exception.
This is fixed by changing the replaceAll() line to
target = source.replaceFirst(Pattern.quote("." +
currentExtension) + "$", Matcher.quoteReplacement("." + newExtension));
A revised version
import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FileUtils {
public static boolean renameFileExtension
(String source, String newExtension)
{
String target;
String currentExtension = getFileExtension(source);
if (currentExtension.equals("")){
target = source + "." + newExtension;
}
else {
target = source.replaceFirst(Pattern.quote("." +
currentExtension) + "$", Matcher.quoteReplacement("." + newExtension));
}
return new File(source).renameTo(new File(target));
}
public static String getFileExtension(String f) {
String ext = "";
int i = f.lastIndexOf('.');
if (i > 0 && i < f.length() 1) {
ext = f.substring(i + 1);
}
return ext;
}
public static void main(String args[]) throws Exception {
System.out.println(
FileUtils.renameFileExtension("C:/temp/capture.pdf", "pdfa")
);
}
}
However if any Javascript is present, the script will be seen as text. Also you may need to add
some logic during the reading to take into account only what is inside the <BODY> tag.
java.io.IOException;
java.io.FileReader;
java.io.Reader;
java.util.List;
java.util.ArrayList;
import
import
import
import
javax.swing.text.html.parser.ParserDelegator;
javax.swing.text.html.HTMLEditorKit.ParserCallback;
javax.swing.text.html.HTML.Tag;
javax.swing.text.MutableAttributeSet;
Note that the HTMLEditorKit can be easily confused if the HTML to be parsed is not wellformed.
import java.io.Reader;
import java.io.BufferedReader;
import org.jsoup.Jsoup;
public class HTMLUtils {
private HTMLUtils() {}
public static String extractText(Reader reader) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(reader);
String line;
while ( (line=br.readLine()) != null) {
sb.append(line);
}
String textOnly = Jsoup.parse(sb.toString()).text();
return textOnly;
}
public final static void main(String[] args) throws Exception{
FileReader reader = new FileReader
("C:/RealHowTo/topics/javalanguage.html");
System.out.println(HTMLUtils.extractText(reader));
}
}
org.apache.tika.metadata.Metadata;
org.apache.tika.parser.AutoDetectParser;
org.apache.tika.parser.ParseContext;
org.apache.tika.parser.Parser;
org.apache.tika.sax.BodyContentHandler;
org.xml.sax.ContentHandler;
See Extract text from a PDF using Apache Tika, Get Mime Type from a file.
See also Extract links from an HTML page
java.io.IOException;
java.nio.file.Files;
java.nio.file.Path;
java.nio.file.Paths;
The default implementation is OSspecific and not very complete. It's possible to register a better
detector, like for example Apache Tika, see Transparently improve Java 7 mimetype recognition
with Apache Tika.
The builtin mimetype list is very limited but a mechanism is available to add very easily more
Mime Types/extensions.
The MimetypesFileTypeMap looks in various places in the user's system for MIME types file
entries. When requests are made to search for MIME types in the MimetypesFileTypeMap, it
searches MIME types files in the following order:
1. Programmatically added entries to the MimetypesFileTypeMap instance.
2. The file .mime.types in the user's home directory.
3. The file <java.home>/lib/mime.types.
4. The file or resources named METAINF/mime.types.
5. The file or resource named METAINF/mimetypes.default (usually found only in the
activation.jar file).
This method is interesting when you need to deal with incoming files with the filenames
normalized. The result is very fast because only the extension is used to guess the nature of a
given file.
org.apache.tika.metadata.Metadata;
org.apache.tika.parser.AutoDetectParser;
org.apache.tika.parser.Parser;
org.apache.tika.sax.BodyContentHandler;
org.xml.sax.ContentHandler;
finally {
if (is != null) is.close();
}
}
}
You can download here a ZIP containing the required jars if you want to check it out.
The nice thing about mimeutil is that it is very lightweight. Only 1 dependency with slf4j
http://droid.sourceforge.net/wiki/index.php/Introduction
java.io.*;
java.util.Arrays;
java.util.Comparator;
java.util.Date;
}
@SuppressWarnings("unchecked")
public static File[] dirListByAscendingDate(File folder) {
if (!folder.isDirectory()) {
return null;
}
File files[] = folder.listFiles();
Arrays.sort( files, new Comparator()
{
public int compare(final Object o1, final Object o2) {
return new Long(((File)o1).lastModified()).compareTo
(new Long(((File) o2).lastModified()));
}
});
return files;
}
@SuppressWarnings("unchecked")
public static File[] dirListByDescendingDate(File folder) {
if (!folder.isDirectory()) {
return null;
}
File files[] = folder.listFiles();
Arrays.sort( files, new Comparator()
{
public int compare(final Object o1, final Object o2) {
return new Long(((File)o2).lastModified()).compareTo
(new Long(((File) o1).lastModified()));
}
});
return files;
}
}
java.io.*;
java.util.Arrays;
java.util.ArrayList;
java.util.List;
java.util.Comparator;
* TEST
*/
public static void main(String args[]) throws Exception {
File files[] = FileUtils.dirListByExtension(new File("C:/temp"));
for (File file : files) {
System.out.println(file.getName());
}
// to reverse
//
List<File> temp = Arrays.asList(files);
//
java.util.Collections.reverse(temp);
//
files = temp.toArray(new File[]{});
//
for (File file : files) {
///
System.out.println(file.getName());
//
}
}
}
Then
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Test {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
FileFilterDateIntervalUtils filter =
new FileFilterDateIntervalUtils("20040101", "20041231");
File folder = new File("C:/temp");
File files[] = folder.listFiles(filter);
for (File f : files) {
System.out.println(f.getName() + " "
+ sdf.format(new Date(f.lastModified())));
}
}
}
false
true
false
true
false
false
*/
}
public static String wildcardToRegex(String wildcard){
StringBuffer s = new StringBuffer(wildcard.length());
s.append('^');
for (int i = 0, is = wildcard.length(); i < is; i++) {
char c = wildcard.charAt(i);
switch(c) {
case '*':
s.append(".*");
break;
case '?':
s.append(".");
break;
// escape special regexpcharacters
case '(': case ')': case '[': case ']': case '$':
case '^': case '.': case '{': case '}': case '|':
case '\\':
s.append("\\");
s.append(c);
break;
default:
s.append(c);
break;
}
}
s.append('$');
return(s.toString());
}
}
C:\1\2\3\4\5\test.txt == C:\1\2\3\4\...\test.txt
\\server\p1\p2\p3\p4\p5\p6 == \\server\p1\p2\p3\p4\...\p6
http://www.rgagnon.com/p1/p2/p3/p4/p5/pb.html == http://p1/p2/p3/p4/.../pb.html
The second accepts a limit corresponding to the total length of the path. If the limit is 20, the path
beginning will be truncated then ellipse and finally the filename. The result is similar to the Win32
API PathCompactPathExA.
ex :
C:\1\2\3\4\5\test.txt
== C:\1\2\3\...test.txt
\\server\p1\p2\p3\p4\p5\p6
== \\server\p1\p2...p6
http://www.rgagnon.com/p1/p2/p3/p4/p5/pb.html == http://www...pb.html
public class FileUtils {
public
public
public
public
public
public
static
static
static
static
static
static
final
final
final
final
final
final
int DEFAULT_SHORTENER_THRESHOLD = 4;
String SHORTENER_BACKSLASH_REGEX = "\\\\";
String SHORTENER_SLASH_REGEX = "/";
String SHORTENER_BACKSLASH = "\\";
String SHORTENER_SLASH = "/";
String SHORTENER_ELLIPSE = "...";
/**
* Return shorter path based on the limited threshold
* ex. C:/1/2/test.txt return C:/1/.../test.txt if threshold is 1
* @param path
* @param threshold
* @return
*/
public static String pathShortener(String path, int threshold) {
String regex = SHORTENER_BACKSLASH_REGEX;
String sep = SHORTENER_BACKSLASH;
if (path.indexOf("/") > 0) {
regex = SHORTENER_SLASH_REGEX;
sep = SHORTENER_SLASH;
}
String pathtemp[] = path.split(regex);
// remove empty elements
int elem = 0;
{
String newtemp [] = new String [pathtemp.length];
int j = 0;
for (int i=0; i < pathtemp.length; i++) {
if (!pathtemp[i].equals("")) {
newtemp [j++] = pathtemp[i];
elem++;
}
}
pathtemp = newtemp;
}
C:\Doc...SC Info.txt
C:\temp
C:\1\2\3\...test.txt
...testfile.txt
C:/1...test.txt
\\server\p1\p2\...p6
http://www...pb.html
*/
}
}
java.io.File;
java.io.FileInputStream;
java.io.InputStream;
java.io.IOException;
java.io.PrintStream;
43 41 54 49 4F 4E 20 44 41 54 41 5C 4D 4F 5A 49
4C 4C 41 5C 50 52 4F 46 49 4C 45 53 5C 44 45 46
41 55 4C 54 5C 43 42 50 4D 53 35 4E 38 2E 53 4C
CATION DATA\MOZI
LLA\PROFILES\DEF
AULT\CBPMS5N8.SL
34410
34420
34430
34440
...
54
48
6C
20
5C
0D
65
54
4D
0A
20
6F
41
20
69
20
49
20
73
61
4C
20
20
76
5C
20
61
6F
4D
20
20
69
41
20
6D
64
49
54
61
20
4C
68
69
69
5C
69
6C
6D
54
73
62
70
52
20
6F
61
41
66
78
63
53
69
2E
74
T\MAIL\MAIL\TRAS
H..
This fi
le is a mailbox.
To avoid impact
java.io.File;
java.io.IOException;
java.util.ArrayList;
java.util.Enumeration;
java.util.List;
java.util.jar.JarEntry;
java.util.jar.JarFile;
/**
* List the content of the given jar
* @param jarPath
* @return
* @throws IOException
*/
public static List<String> getJarContent(String jarPath) throws IOException{
List<String> content = new ArrayList<String>();
JarFile jarFile = new JarFile(jarPath);
Enumeration<JarEntry> e = jarFile.entries();
while (e.hasMoreElements()) {
JarEntry entry = (JarEntry)e.nextElement();
String name = entry.getName();
content.add(name);
}
return content;
}
Representation (hexadecimal)
EF BB BF
FE FF
FF FE
00 00 FE FF
FF FE 00 00
Representation (decimal)
239 187 191
254 255
255 254
0 0 254 255
255 254 0 0
UTF8 file are a special case because it is not recommended to add a BOM to them because it
can break other tools like Java. In fact, Java assumes the UTF8 don't have a BOM so if the BOM
is present it won't be discarded and it will be seen as data.
To create an UTF8 file with a BOM, open the Windows create a simple text file and save it as
utf8.txt with the encoding UTF8.
Now if you examine the file content as binary, you see the BOM at the beginning.
If we read it with Java.
import java.io.*;
public class x {
public static void main(String args[]) {
try {
FileInputStream fis = new FileInputStream("c:/temp/utf8.txt");
BufferedReader r = new BufferedReader(new InputStreamReader(fis,
"UTF8"));
for (String s = ""; (s = r.readLine()) != null;) {
System.out.println(s);
}
r.close();
System.exit(0);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
The output contains a strange character at the beginning because the BOM is not discarded :
?helloworld
This behaviour is documented in the Java bug database, here and here. There will be no fix for
now because it will break existing tools like javadoc ou xml parsers.
The Apache IO Commons provides some tools to handle this situation. The BOMInputStream
class detects the BOM and, if required, can automatically skip it and return the subsequent byte
as the first byte in the stream.
Or you can do it manually. The next example converts an UTF8 file to ANSI. We check the first
line for the presence of the BOM and if present, we simply discard it.
import java.io.*;
public class UTF8ToAnsiUtils {
// FEFF because this is the Unicode char represented by the UTF8 byte order mark (EF BB
public static final String UTF8_BOM = "\uFEFF";
public static void main(String args[]) {
try {
if (args.length != 2) {
System.out
.println("Usage : java UTF8ToAnsiUtils utf8file ansifile");
System.exit(1);
}
boolean firstLine = true;
FileInputStream fis = new FileInputStream(args[0]);
BufferedReader r = new BufferedReader(new InputStreamReader(fis,
"UTF8"));
FileOutputStream fos = new FileOutputStream(args[1]);
Writer w = new BufferedWriter(new OutputStreamWriter(fos, "Cp1252"));
for (String s = ""; (s = r.readLine()) != null;) {
if (firstLine) {
s = UTF8ToAnsiUtils.removeUTF8BOM(s);
firstLine = false;
}
w.write(s + System.getProperty("line.separator"));
w.flush();
}
w.close();
r.close();
System.exit(0);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
private static String removeUTF8BOM(String s) {
if (s.startsWith(UTF8_BOM)) {
s = s.substring(1);
}
return s;
}
}
Note that if the given file doesn't exist then it a new empty file is created.
For a Windows batch solution see this HowTo
6.118 JExcel
Java Excel API is a java API enabling developers to read, write, and modify Excel spreadsheets
dynamically. Any operating system which can run a Java virtual machine can both process and
deliver Excel spreadsheets. One nice thing about JExcelApi is that it has no dependencies on any
third party libraries.
Example : output an Excel file from a Servlet
import java.io.IOException;
import java.io.OutputStream;
import
import
import
import
javax.servlet.ServletException;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
import
import
import
import
jxl.Workbook;
jxl.write.Label;
jxl.write.WritableSheet;
jxl.write.WritableWorkbook;
See http://jexcelapi.sourceforge.net/
6.119 POI
The POI project consists of APIs for manipulating various file formats based upon Microsoft's OLE
2 Compound Document format using pure Java. POI is your Java Excel solution as well as your
Java Word solution.
HSSF is the POI Project's pure Java implementation of the Excel '97(2002) file format and it
provides a way to read spreadsheets create, modify, read and write XLS spreadsheets. Latest
POI version seems to support the .XLSX format.
Since it's Jakarta project, POI has a dependencies with other JARs (commons,log4j,etc...).
Example : create an Excel file
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = sheet.createRow((short)0);
row.createCell((short)0).setCellValue("HelloWorld");
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
The name was originally an acronym for "Poor Obfuscation Implementation" (ref: Wikipedia).
See http://jakarta.apache.org/poi/
6.120 JXLS
jXLS is a project that allows creation of extremely complex Excel reports just in several lines of
code. It is based on Jakarta POI.
With jXLS, all you need is to create XLS template file with all required formatting, formulas etc
using specific notation to indicate placement of data and then write a couple lines of code to
invoke jXLS engine passing XLS template and the exported data as parameters.
Example :
The XLS Template
Employees
Name
${employee.name}
Age
Payment
Bonus
${employee.age} ${employee.payment} ${employee.bonus}
$[SUM(@employee.payment@)]
6.119 POI
Payment Bonus
3000
30,00%
1500
15,00%
4500
Reading values from an XLS with jXLS is very simple. Suppose we have a worksheet with policy
numbers in the first column. We read and process them one by one.
import java.io.File;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
See http://jxls.sourceforge.net/
6.121 xlSQL
xlSQL is a JDBC Driver for Excel and CSV data sources. Documents can be read and written with
SQL as if they were tables in a database.
You can export XLS to XML or SQL INSERT statements. xlSQL includes its own "zeroadmin"
mySQL database. The documentation is minimal at this time.
See http://xlsql.sourceforge.net/
6.122 JCOM
JCOM is a Java to COM bridge library. With JCOM you can call a COM object from Java as if it
were a Java object without having to deal with the internals of JNI. The documentation is minimal
(in Japanese!).
Example :
import
import
import
import
jp.ne.so_net.ga2.no_ji.jcom.excel8.*;
jp.ne.so_net.ga2.no_ji.jcom.*;
java.io.File;
java.util.Date;
class TestExcel {
public static void main(String[] args) throws Exception {
ReleaseManager rm = new ReleaseManager();
6.121 xlSQL
try {
System.out.println("EXCEL startup...");
// if already started, open new window
ExcelApplication excel = new ExcelApplication(rm);
excel.Visible(true);
// display any information
System.out.println("Version="+excel.Version());
System.out.println("UserName="+excel.UserName());
System.out.println("Caption="+excel.Caption());
System.out.println("Value="+excel.Value());
ExcelWorkbooks xlBooks = excel.Workbooks();
ExcelWorkbook xlBook = xlBooks.Add();
// create new book
// enumurate all files
System.out.println
("set infomation of files in current directory to cell ...");
ExcelWorksheets xlSheets = xlBook.Worksheets();
ExcelWorksheet xlSheet = xlSheets.Item(1);
ExcelRange xlRange = xlSheet.Cells();
xlRange.Item(1,1).Value("filename" );
xlRange.Item(2,1).Value("size" );
xlRange.Item(3,1).Value("last modified time");
xlRange.Item(4,1).Value("is directory");
xlRange.Item(5,1).Value("is file");
xlRange.Item(6,1).Value("can read");
xlRange.Item(7,1).Value("can write");
File path = new File("./");
String[] filenames = path.list();
for(int i=0; i<filenames.length; i++) {
File file = new File(filenames[i]);
System.out.println(file);
xlRange.Item(1,i+2).Value( file.getName() );
xlRange.Item(2,i+2).Value( (int)file.length() );
xlRange.Item(3,i+2).Value( new Date(file.lastModified()) );
xlRange.Item(4,i+2).Value( file.isDirectory()?"Yes":"No" );
xlRange.Item(5,i+2).Value( file.isFile()?"Yes":"No" );
xlRange.Item(6,i+2).Value( file.canRead()?"Yes":"No" );
xlRange.Item(7,i+2).Value( file.canWrite()?"Yes":"No" );
}
String expression = "=Sum(B2:B"+(filenames.length+1)+")";
System.out.println
("embed equation, calculate sum of filesize: "+expression);
xlRange.Item(1,filenames.length+2).Value("sum");
xlRange.Item(2,filenames.length+2).Formula(expression);
xlRange.Columns().AutoFit();
// fit columns
// comment out, if print out.
// output default printer.
//
System.out.println("print out...");
//
xlSheet.PrintOut();
//
//
//
//
//
xlBook.Close(false,null,false);
excel.Quit();
6.121 xlSQL
See http://sourceforge.net/projects/jcom
See also this HowTo for an alternative package to access a COM package from Java.
See also this HowTo for a way to create a simple XLS without any additional library.
Now you can double click on the saved file to load it into Excel and the translation will be done.
This trick works with OpenOffice too.
From a server, remember to send the appropriate MIME TYPE : application/excel to the client.
See also this HowTo
Two test files : XLS with macro and XLS without macro
A nice OpenSource is http://www.lowagie.com/iText/ [ITEXT] . iText can deal with RTF and HTML
file too.
Nicely documented with many examples.
Create a PDF
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfWriter;
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World");
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("HelloWorld.pdf"));
document.open();
document.add(new Paragraph("Hello World"));
}
catch (DocumentException de) {
System.err.println(de.getMessage());
}
catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
document.close();
}
}
com.lowagie.text.Element;
com.lowagie.text.Image;
com.lowagie.text.PageSize;
com.lowagie.text.pdf.BaseFont;
com.lowagie.text.pdf.PdfContentByte;
com.lowagie.text.pdf.PdfReader;
com.lowagie.text.pdf.PdfStamper;
6.128 iText
http://www.lowagie.com/iText/
iText is a very simple to use package to create and manipulate PDF file.
6.127 Create a PDFTag(s): IO Open Source
For the simple need, only 1 jar is required (ex. itext2.1.3.jar, download at
http://www.lowagie.com/iText/download.html)
In this example, you pass on the command line a filename (plain text file args[0]) to convert to a
PDF file (args[1]).
import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
public class TextFileToPDF {
/*
ex. java TextFileToPDF c:\temp\text.txt c:\temp\text.pdf
*/
public static void main (String [] args){
BufferedReader input = null;
Document output = null;
System.out.println("Convert text file to pdf");
System.out.println("input : " + args[0]);
System.out.println("output : " + args[1]);
try {
// text file to convert to pdf as args[0]
input =
new BufferedReader (new FileReader(args[0]));
// letter 8.5x11
//
see com.lowagie.text.PageSize for a complete list of pagesize constants.
output = new Document(PageSize.LETTER, 40, 40, 40, 40);
// pdf file as args[1]
PdfWriter.getInstance(output, new FileOutputStream (args[1]));
output.open();
output.addAuthor("RealHowTo");
output.addSubject(args[0]);
output.addTitle(args[0]);
String line = "";
while(null != (line = input.readLine())) {
System.out.println(line);
Paragraph p = new Paragraph(line);
p.setAlignment(Element.ALIGN_JUSTIFIED);
output.add(p);
}
System.out.println("Done.");
output.close();
input.close();
System.exit(0);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
com.lowagie.text.Document;
com.lowagie.text.pdf.PdfCopy;
com.lowagie.text.pdf.PdfImportedPage;
com.lowagie.text.pdf.PdfReader;
}
/* example :
java SplitPDFFile d:\temp\x\tx.pdf
Reading d:\temp\x\tx.pdf
Number of pages : 3
Writing d:\temp\x\tx001.pdf
Writing d:\temp\x\tx002.pdf
Writing d:\temp\x\tx003.pdf
*/
}
}
com.lowagie.text.Document;
com.lowagie.text.pdf.PRAcroForm;
com.lowagie.text.pdf.PdfCopy;
com.lowagie.text.pdf.PdfImportedPage;
com.lowagie.text.pdf.PdfReader;
com.lowagie.text.pdf.SimpleBookmark;
This HowTo is based on the iText package. You need a recent version (ex. 2.*)
This a command line utility. You pass one or many tif files as argument and corresponding PDF
are produced. Multipage TIF are supported. TIF are resized to fit a letterpage dimension.
import java.io.FileOutputStream;
import
import
import
import
import
import
import
import
com.lowagie.text.Document;
com.lowagie.text.Image;
com.lowagie.text.PageSize;
com.lowagie.text.Rectangle;
com.lowagie.text.pdf.PdfContentByte;
com.lowagie.text.pdf.PdfWriter;
com.lowagie.text.pdf.RandomAccessFileOrArray;
com.lowagie.text.pdf.codec.TiffImage;
catch (Throwable e) {
System.out.println("Exception " + tiff + " page "
+ (c + 1) + " " + e.getMessage());
}
}
ra.close();
document.close();
}
catch (Throwable e) {
e.printStackTrace();
}
System.out.println("done");
}
}
}
import java.io.FileOutputStream;
import java.io.StringReader;
import
import
import
import
com.itextpdf.text.Document;
com.itextpdf.text.PageSize;
com.itextpdf.text.html.simpleparser.HTMLWorker; // deprecated
com.itextpdf.text.pdf.PdfWriter;
"<p>It DOES cost a lot to produce this site in ISP storage and transfer fees, " +
"in personal hardware and software costs to set up test environments, and above all,"
"the huge amounts of time it takes for one person to design and write the actual cont
"<p>If you feel that effort has been useful to you, perhaps you will consider giving
"<p>Donate using PayPal to real@rgagnon.com." +
"<p>Contributions via PayPal are accepted in any amount " +
"<P><br><table border='1'><tr><td>Java HowTo<tr>" +
"<td bgcolor='red'>Javascript HowTo<tr><td>Powerbuilder HowTo</table>" +
"</body></html>";
htmlWorker.parse(new StringReader(str));
document.close();
System.out.println("Done");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
As you can see, the validity of the parsed HTML (using HTMLWorker) is very relax. Closing tags
are not required : <BR> is ok (<BR/> is not mandatory).
HTMLWorker is ok with older iText version but the recommended approach with new iText
(HTMLWorker is now deprecated) is to use the XMLWorker. XMLWorker is stricter since you
must send XHTML document to it.
import java.io.FileOutputStream;
import java.io.StringReader;
import
import
import
import
public
com.itextpdf.text.Document;
com.itextpdf.text.PageSize;
com.itextpdf.text.pdf.PdfWriter;
com.itextpdf.tool.xml.XMLWorkerHelper;
class HtmlToPDF2 {
// itextpdf5.4.1.jar http://sourceforge.net/projects/itext/files/iText/
// xmlworker5.4.1.jar http://sourceforge.net/projects/xmlworker/files/
public static void main(String ... args ) {
try {
Document document = new Document(PageSize.LETTER);
PdfWriter pdfWriter = PdfWriter.getInstance
(document, new FileOutputStream("c://temp//testpdf.pdf"));
document.open();
document.addAuthor("Real Gagnon");
document.addCreator("Real's HowTo");
document.addSubject("Thanks for your support");
document.addCreationDate();
document.addTitle("Please read this");
XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
"<tr><td>Powerbuilder HowTo</td></tr></table></p>" +
"</body></html>";
worker.parseXHtml(pdfWriter, document, new StringReader(str));
document.close();
System.out.println("Done.");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Note : To get the color on a table cell, you need to use a style because the bgcolor attribute is not
supported. By default, FORM elements are not rendered. Review this document to see what is
supported : http://demo.itextsupport.com/xmlworker/doc.html
See also Convert HTML to PDF using YAHP
java.io.File;
java.io.FileOutputStream;
java.util.ArrayList;
java.util.HashMap;
java.util.List;
java.util.Map;
// http://www.allcolor.org/YaHPConverter/
import org.allcolor.yahp.converter.CYaHPConverter;
import org.allcolor.yahp.converter.IHtmlToPdfTransformer;
public class HtmlToPdf_yahp {
public static void main(String ... args ) throws Exception {
htmlToPdfFile();
}
public static void htmlToPdfFile() throws Exception {
CYaHPConverter converter = new CYaHPConverter();
File fout = new File("c:/temp/x.pdf");
properties.put(IHtmlToPdfTransformer.PDF_RENDERER_CLASS,
IHtmlToPdfTransformer.FLYINGSAUCER_PDF_RENDERER);
//properties.put(IHtmlToPdfTransformer.FOP_TTF_FONT_PATH, fontPath);
converter.convertToPdf(str,
IHtmlToPdfTransformer.A4P,
headerFooterList,
"file:///temp/", // root for relative external CSS and IMAGE
out,
properties);
out.flush();
out.close();
}
}
In the next example, we read an existing HTML file and convert it to a PDF file.
import
import
import
import
import
import
import
java.io.File;
java.io.FileOutputStream;
java.util.ArrayList;
java.util.HashMap;
java.util.List;
java.util.Map;
java.util.Scanner;
// http://www.allcolor.org/YaHPConverter/
import org.allcolor.yahp.converter.CYaHPConverter;
import org.allcolor.yahp.converter.IHtmlToPdfTransformer;
public class HtmlToPdf_yahp_2 {
public static void main(String ... args ) throws Exception {
String root = "c:/temp/html";
String input = "file_1659686.htm"; // need to be charset utf8
htmlToPdfFile(new File(root, input),
new File(root, input + ".pdf"));
System.out.println("Done");
}
public static void htmlToPdfFile(File htmlIn, File pdfOut) throws Exception {
Scanner scanner =
new Scanner(htmlIn).useDelimiter("\\Z");
String htmlContents = scanner.next();
CYaHPConverter converter = new CYaHPConverter();
FileOutputStream out = new FileOutputStream(pdfOut);
Map properties = new HashMap();
List headerFooterList = new ArrayList();
properties.put(IHtmlToPdfTransformer.PDF_RENDERER_CLASS,
IHtmlToPdfTransformer.FLYINGSAUCER_PDF_RENDERER);
//properties.put(IHtmlToPdfTransformer.FOP_TTF_FONT_PATH, fontPath);
converter.convertToPdf(htmlContents,
IHtmlToPdfTransformer.A4P,
headerFooterList,
"file:///temp/html/",
out,
properties);
out.flush();
out.close();
}
}
NOTE : After downloading YAHP (and its dependencies), you still need to build a YAHP.JAR, it's done easily with Eclipse... but you can get it
here.
import java.io.FileOutputStream;
//com.lowagie...
old version
//com.itextpdf... recent version
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.Image;
Unfortunately, Acrobat Reader stays opened (but minimized because of the /h switch) after the
printing operation :(
You can use a special wrapper to force the closing the Acrobat Reader after the print operation.
See http://www.biopdf.com/acrowrap/close_adobe_reader.php (acrowrap.exe).
org.apache.tika.parser.pdf.PDFParser;
org.apache.tika.metadata.Metadata;
org.apache.tika.parser.ParseContext;
org.apache.tika.sax.BodyContentHandler;
org.xml.sax.ContentHandler;
See also Extract text from HTML, Get Mime Type from a file.
6.136 Extract text from a PDF (with Apache Tika) Tag(s): IO OpenSource
/*
** a simple ZIP tool
**
** ex. java Zip file.1 file.2 > file.zip
**
*/
import java.io.*;
import java.util.zip.*;
class Zip {
public static void main(String args[]) throws IOException {
byte b[] = new byte[512];
ZipOutputStream zout = new ZipOutputStream(System.out);
for(int i = 0; i < args.length; i ++) {
InputStream in = new FileInputStream(args[i]);
ZipEntry e = new ZipEntry(args[i].replace(File.separatorChar,'/'));
zout.putNextEntry(e);
int len=0;
while((len=in.read(b)) != 1) {
zout.write(b,0,len);
}
zout.closeEntry();
print(e);
}
zout.close();
}
public static void print(ZipEntry e){
PrintStream err = System.err;
err.print("added " + e.getName());
if (e.getMethod() == ZipEntry.DEFLATED) {
long size = e.getSize();
if (size > 0) {
long csize = e.getCompressedSize();
long ratio = ((sizecsize)*100) / size;
err.println(" (deflated " + ratio + "%)");
}
else {
err.println(" (deflated 0%)");
}
}
else {
err.println(" (stored 0%)");
}
}
}
NOTE: There no way to directly add or modify an entry to a ZIP file after its creation. To do so, rename the old ZIP to a temporary filename.
Expand the contents of the old ZIP, create the new ZIP, add the original contents plus the new files and delete the old ZIP when done.
/*
** a simple viewZIP tool
**
** ex. java ViewZip file.zip
**
*/
import java.io.*;
import java.util.*;
import java.util.zip.*;
import java.text.*;
class ViewZip {
public static void main(String args[]) throws IOException {
InputStream in = new BufferedInputStream(new FileInputStream(args[0]));
ZipInputStream zin = new ZipInputStream(in);
ZipEntry e;
System.err.println("Size\t Date
Time
Method
Ratio
Name");
System.err.println("\t
");
while((e=zin.getNextEntry())!= null) {
zin.closeEntry();
print(e);
}
zin.close();
}
public static void print(ZipEntry e) {
PrintStream err = System.err;
err.print(e.getSize() + "\t");
DateFormat df = new SimpleDateFormat ("yyyy.mm.dd
Date d = new Date(e.getTime());
err.print(df.format(d) + " ");
if (e.getMethod() == ZipEntry.DEFLATED) {
err.print("deflated ");
long size = e.getSize();
if (size > 0) {
long csize = e.getCompressedSize();
long ratio = ((sizecsize)*100) / size;
if (ratio < 10) {
err.write(' ');
}
err.print(ratio + "%
");
}
else {
err.print(" 0%
");
}
}
else {
err.println(" (stored
0 %");
}
err.println(e.getName());
}
}
hh:mm:ss");
class UnZip {
public static void main(String args[]) throws IOException {
InputStream in =
new BufferedInputStream(new FileInputStream(args[0]));
ZipInputStream zin = new ZipInputStream(in);
ZipEntry e;
while((e=zin.getNextEntry())!= null) {
if (args.length > 1) {
if (e.getName().equals(args[1])) {
unzip(zin, args[1]);
break;
}
}
unzip(zin, e.getName());
}
zin.close();
}
public static void unzip(ZipInputStream zin, String s)
throws IOException {
System.out.println("unzipping " + s);
FileOutputStream out = new FileOutputStream(s);
byte [] b = new byte[512];
int len = 0;
while ( (len=zin.read(b))!= 1 ) {
out.write(b,0,len);
}
out.close();
}
}
(Windows) The sound used is determined from the setting found in Control Panel/Sounds and
Devices/Sounds/Sound Scheme/"Default Beep". If no sound file is selected then the beep() will
be a silence.
1,
// channels
true,
// signed
false);
// bigEndian
SourceDataLine sdl = AudioSystem.getSourceDataLine(af);
sdl.open(af);
sdl.start();
for (int i=0; i < msecs*8; i++) {
double angle = i / (SAMPLE_RATE / hz) * 2.0 * Math.PI;
buf[0] = (byte)(Math.sin(angle) * 127.0 * vol);
sdl.write(buf,0,1);
}
sdl.drain();
sdl.stop();
sdl.close();
}
public static void main(String[] args) throws Exception {
SoundUtils.tone(1000,100);
Thread.sleep(1000);
SoundUtils.tone(100,1000);
Thread.sleep(1000);
SoundUtils.tone(5000,100);
Thread.sleep(1000);
SoundUtils.tone(400,500);
Thread.sleep(1000);
SoundUtils.tone(400,500, 0.2);
}
}
java.io.File;
java.io.FileInputStream;
javax.sound.sampled.*;
javax.swing.*;
When a sound is playing, the action is stopped until the sound is finished. To play a sound and
keep the application responding to event, you need to play the sound in a Thread.
import
import
import
import
javax.sound.sampled.*;
javax.swing.*;
java.awt.*;
java.awt.event.*;
8, // sampleSizeInBits
1, // channels
true, // signed
false); // bigEndian
SourceDataLine sdl;
sdl = AudioSystem.getSourceDataLine(af);
sdl.open(af);
sdl.start();
byte[] buf = new byte[1];
int step;
for (int j = 0; j < repeat; j++) {
step = 10;
for (int i = 0; i < 2000; i++) {
buf[0] = ((i % step > 0) ? 32 : (byte) 0);
if (i % 250 == 0)
step += 2;
sdl.write(buf, 0, 1);
}
Thread.sleep(200);
}
sdl.drain();
sdl.stop();
sdl.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
http://freetts.sourceforge.net/javadoc/com/sun/speech/freetts/VoiceManager.html#getVoices(). In
this example, the available voice is setted with the system property "freetts.voices".
import java.beans.PropertyVetoException;
import java.util.Locale;
import
import
import
import
import
import
import
javax.speech.AudioException;
javax.speech.Central;
javax.speech.EngineException;
javax.speech.EngineStateError;
javax.speech.synthesis.Synthesizer;
javax.speech.synthesis.SynthesizerModeDesc;
javax.speech.synthesis.Voice;
Related links :
http://www.ryanh.com/uncategorized/javaspeechjsapifreetts/
http://java.sun.com/products/javamedia/speech/forDevelopers/jsapidoc/javax/speech/packagesummar
http://today.java.net/pub/a/today/2006/04/13/vocaljava.html
Sound 1
Sound 2
Supported windows property names:
win.sound.asterisk
win.sound.close
win.sound.default
win.sound.exclamation
win.sound.exit
win.sound.hand
win.sound.maximize
win.sound.menuCommand
win.sound.menuPopup
win.sound.minimize
win.sound.open
win.sound.question
win.sound.restoreDown
win.sound.restoreUp
win.sound.start
*/
Keep in mind that this technique is very specific to Windows and will not work on others OS.
7 JDBC
7.1 javajdbc
7 JDBC
Statement stmt;
String sql;
int rows;
sql =
+
+
+
+
+
stmt = theConn.createStatement();
rows = stmt.executeUpdate(sql);
theConn.dbConn.commit();
stmt.close();
You need to be aware to the snippet above contains a SQL Injection vulnerability. String concatentation of this form can only be used if you first
validate the fields to include only alphanumeric characters. Even, then it is generally considered bad practice when prepared statements solve
this problem more cleanly. This is especially when you in a Web application environnement.
The character "\" (backslash) can be difficult to use in an INSERT statement since "\" is considered
as an escape character in Java (and probably by the database too).
stmt.executeUpdate("INSERT INTO mytable VALUES('\\')");
may generate a SQL Exception even if the "\" is escaped for Java because you need to escape it
again for the database. At the end, you need to use "\\\\" to INSERT a simple "\".
stmt.executeUpdate("INSERT INTO mytable VALUES('\\\\')");
PreparedStatement prepstmt;
try {
prepstmt = theConn.prepareStatement
("UPDATE tCust SET custName = ? "+
" WHERE custId = ?");
prepstmt.setString(1,"Smith");
prepstmt.setString(2, cust_id.getText());
prepstmt.executeUpdate();
theConn.commit();
prepstmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
PreparedStatement prepstmt;
try {
prepstmt = theConn.prepareStatement
("DELETE FROM tCust "+
" WHERE custId = ?");
prepstmt.setString(1,cust_id.getText());
prepstmt.executeUpdate();
theConn.commit();
prepstmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
if (found)
System.out.println("Record found");
else
System.out.println("RECORD NOT FOUND");
JDBC 2.0 provides a way to retrieve a rowcount from a ResultSet without having to scan through all
the rows or issue a separate SELECT COUNT(*).
Statement s = conn.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet r = s.executeQuery
("SELECT * FROM employee WHERE id_emp LIKE '1%'");
r.last();
int count = r.getRow();
r.beforeFirst();
...
import java.sql.*;
import java.io.*;
class JDBCapp {
static MyConnection theConn;
public static void main (String args[]) {
JDBCapp j = new JDBCapp();
j.connectToDB();
j.insertIntoEmp();
j.selectFromEmp();
}
public void connectToDB() {
theConn = new MyConnection();
theConn.connect("your_db_profile", "username", "password");
}
public void insertIntoEmp() {
Employee employee = new Employee(42,"Real Gagnon", 98000);
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(employee);
// serialize the employee object into a byte array
byte[] employeeAsBytes = baos.toByteArray();
PreparedStatement pstmt =
theConn.dbConn.prepareStatement
("INSERT INTO EMPLOYEE (emp) VALUES(?)");
ByteArrayInputStream bais =
new ByteArrayInputStream(employeeAsBytes);
// bind our byte array to the emp column
pstmt.setBinaryStream(1,bais, employeeAsBytes.length);
pstmt.executeUpdate();
theConn.dbConn.commit();
pstmt.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
public void selectFromEmp() {
boolean found;
try {
Statement stmt = theConn.dbConn.createStatement();
ResultSet rs =
stmt.executeQuery("SELECT emp FROM Employe");
// loop through the result set
while (rs.next()) {
// fetch the serialized object to a byte array
byte[] st = (byte[])rs.getObject(1);
//
or byte[] st = rs.getBytes(1);
//
or Blob aBlob = rs.getBlob(1);
//
byte[] st = aBlob.getBytes(0, (int) aBlob.length());
ByteArrayInputStream baip =
new ByteArrayInputStream(st);
ObjectInputStream ois =
new ObjectInputStream(baip);
// recreate the object
Employee emp = (Employee)ois.readObject();
// display the result for demonstration
System.out.println(emp.name);
}
stmt.close();
rs.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
class Employee implements Serializable {
int ID;
String name;
double salary;
public Employee(int ID, String name, double salary) {
this.ID = ID;
this.name = name;
this.salary = salary;
}
}
class MyConnection {
Connection dbConn = null;
void connect(String db, String user, String passw) {
try {
Driver d =
(Driver)Class.forName
("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String URL = "jdbc:odbc:" + db;
dbConn =
DriverManager.getConnection(URL, user, passw);
}
catch (Exception e) {
e.printStackTrace();
}
}
void disconnect() {
try {
dbConn.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
then
String query = "begin thePackage.theProcedure(?,?,?); end;";
CallableStatement cs = conn.prepareCall(query);
cs.setString(1, "string parameter");
// #1 is INPUT
cs.setInt(2, 1);
cs.registerOutParameter(2, Types.INTEGER);
cs.registerOutParameter(3, Types.INTEGER);
cs.execute();
int output_parm2 = cs.getInt(2);
int output_parm3 = cs.getInt(3);
// #2 is INPUT
//
and OUTPUT
// #3 is OUTPUT
ResultSet rs =
statement.executeQuery("select col1,col2,col3 from mytable");
// Loop through the ResultSet and transfer in the Model
java.sql.ResultSetMetaData rsmd = rs.getMetaData();
int colNo = rsmd.getColumnCount();
while(rs.next()){
Object[] objects = new Object[colNo];
// tanks to umit ozkan for the bug fix!
for(int i=0;i<colNo;i++){
objects[i]=rs.getObject(i+1);
}
aModel.addRow(objects);
}
aTable.setModel(aModel);
01
002
01
003
01
004
01
005
01
006
01
007
The JDK API doc reveals that "The SQLWarning class provides information on a database access
warnings. Warnings are silently chained to the object whose method caused it to be reported". So
after DB operation, you ask the Connection object if there are any warnings. Depending on the
vendor driver, informations (not only Warnings) can be found in the SQLWarning object.
dbConn = DriverManager.getConnection
("jdbc:odbc:YourDatabaseName","username","password");
SQLWarning w = dbConn.getWarnings();
//
//
//
if
Error
When an error occurs, a SQLException is thrown. You can interrogate the SQLException object to
know more details about the actual error. Note that SQLException can be chained. The
SQLException object contains :
1. A string describing the error. This is used as the Java Exception message, available via the
getMessage method.
2. A "SQLState" string, which follows the XOPEN SQLState conventions.
3. An integer error code that is specific to each vendor.
try {
//
... some SQL operations
}
catch (SQLException ex) {
// SQLException occured.
// There could be multiple error objects chained together
System.out.out.println ("*** SQLException caught ***");
while (ex != null) {
System.out.println ("SQLState: " + ex.getSQLState () + "");
System.out.println ("Message: " + ex.getMessage() + "");
System.out.println ("Vendor ErrorCode: " + ex.getErrorCode() + "");
ex = ex.getNextException();
System.out.println("");
}
}
catch (java.lang.Exception ex) {
// Some other type of exception occurred
System.out.println("*** Exception caught ***");
System.out.println(ex.getMessage()+ "");
}
finally {
// Close the database connection.
try {
if (con != null) con.close();
}
catch (SQLException ignored) {
//do nothing
}
}
void disconnect() {
try {
dbConn.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
class MyConnection {
Connection dbConn = null;
void connect(String db, String user, String passw) {
try {
Driver d =
(Driver)Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
String URL = "jdbc:odbc:" + db;
dbConn = DriverManager.getConnection(URL, user, passw);
java.io.PrintWriter w =
new java.io.PrintWriter
(new java.io.OutputStreamWriter(System.out));
DriverManager.setLogWriter(w);
}
catch (Exception e) {
e.printStackTrace();
}
}
void disconnect() {
try {
dbConn.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
if (rs.next()) {
// Table exists
}
else {
// Table does not exist
}
java.sql.Connection;
java.sql.Statement;
java.sql.Driver;
java.sql.DriverManager;
java.sql.ResultSet;
java.sql.ResultSetMetaData;
import
import
import
import
import
import
import
javax.xml.parsers.DocumentBuilder;
javax.xml.parsers.DocumentBuilderFactory;
javax.xml.transform.*;
javax.xml.transform.stream.*;
javax.xml.transform.dom.*;
org.w3c.dom.Document;
org.w3c.dom.Element;
class JDBCapp
while (rs.next()) {
Element row = doc.createElement("Row");
results.appendChild(row);
for (int ii = 1; ii <= colCount; ii++) {
String columnName = rsmd.getColumnName(ii);
Object value = rs.getObject(ii);
Element node = doc.createElement(columnName);
node.appendChild(doc.createTextNode(value.toString()));
row.appendChild(node);
}
}
System.out.println(getDocumentAsXml(doc));
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (con != null) con.close();
if (stmt != null) stmt.close();
if (rs != null) rs.close();
}
catch (Exception e) {
}
}
}
public static String getDocumentAsXml(Document doc)
throws TransformerConfigurationException, TransformerException {
DOMSource domSource = new DOMSource(doc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
//transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING,"ISO88591");
// we want to pretty format the XML output
// note : this is broken in jdk1.5 beta!
transformer.setOutputProperty
("{http://xml.apache.org/xslt}indentamount", "4");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//
java.io.StringWriter sw = new java.io.StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);
return sw.toString();
}
}
class AccessCon {
public static Connection getConnection() throws Exception {
Driver d = (Driver)Class.forName
("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
Connection c = DriverManager.getConnection
("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=c:/tech97.mdb");
return c;
/*
To use an already defined ODBC Datasource :
String URL = "jdbc:odbc:myDSN";
Connection c = DriverManager.getConnection(URL, "user", "pwd");
*/
}
}
If you don't want to use JDBC escape sequence then it's possible to use native SQL based on the
target DBMS.
For Oracle, it will look like this :
SELECT value FROM vendors WHERE value LIKE '%=_%' ESCAPE '=';
ref : LaboOracle.com.
7.28 P6Spy
P6Spy is an open source framework for applications that intercept and optionally modify database
statements.
7.29 Proxool
Proxool is a Java connection pool.
It provides really nice logging facilities with the SQL statement and the running time.
Download at http://proxool.sourceforge.net/
7.31 Log4JDBC
Log4jdbc is a Java JDBC driver that can log SQL and/or JDBC calls (and optionally SQL timing
information) for other JDBC drivers
Download at http://code.google.com/p/log4jdbc/
7.29 Proxool
import
import
import
import
java.sql.Connection;
java.sql.DriverManager;
java.sql.PreparedStatement;
java.sql.SQLException;
When inserting many INSERTs (or DELETE/UPDATE), JDBC provides the addBatch() method to
cumulate the SQL statements. When ready, the whole batch is sent in one shot to minimize the
network traffic. A special attention to the error handling should made.
(Sun) Sending Batch Updates
The performance gain is good. For example, 100 individual INSERTS == 140ms 10 batched
INSERTS == 32ms
Using PreparedStatement in batch mode
import
import
import
import
import
java.io.IOException;
java.sql.Connection;
java.sql.DriverManager;
java.sql.PreparedStatement;
java.sql.SQLException;
7.29 Proxool
java.io.IOException;
java.sql.Connection;
java.sql.DriverManager;
java.sql.Statement;
java.sql.SQLException;
JDBC provides a way to give a hint about the size of the expected ResultSet.
Statement.setFetchSize() gives a hint about the number of rows that should be fetched from the
database each time new rows are needed. The goal is to reduce unnecessary network round trip.
With Oracle, the default value is 10 (i.e. the Oracle driver will retrieve ResultSets in 10row chunks)
A JDBC Compliant driver may choose to ignore the setFetchSize(). You should do some testing first
to check if the result is optimal.
See (Sun) 5.1.9 Providing Performance Hints
import
import
import
import
import
import
import
java.io.FileWriter;
java.io.IOException;
java.sql.Connection;
java.sql.DriverManager;
java.sql.ResultSet;
java.sql.SQLException;
java.sql.Statement;
(def == 10)
prefetch == 100
14859
14749
prefetch == 200
13343
13296
prefetch == 500
13891
13812
prefetch == 1000
13078
13078
*/
To use a Date, Time or Timestamp in a query, you can use JDBC escape codes.
Date
{d 'yyyymmdd'}
Time
{t {'hh:mm:ss'}
Timestamp {ts `yyyymmdd hh:mm:ss.f . . .'}
note: the .f .... is optional
With a PreparedStatement, you don't need JDBC escape codes, the JDBC driver will do the job for
you.
7.35 Handle datesTag(s): JDBC
java.util.Date today =
new java.util.Date();
java.sql.Date sqlToday =
new java.sql.Date(today.getTime());
PreparedStatement p = theConn.prepareStatement
("select * from cust where purchase_date <?");
p.setDate(1, sqlToday);
ResultSet rs = p.executeQuery();
To INSERT
PreparedStatement p = theConn.prepareStatement
("insert into TableWithADateColumn values(?)");
p.setDate(1, sqlToday);
p.executeUpdate();
or
p.executeUpdate
("insert into TableWithADateColumn values( { d '19991231' } )");
Example :
// for Oracle
String sql =
"select {fn dayname ({fn now()})}," +
"
"
"
"
{d '19970524'}, " +
{t '10:30:29' }, " +
{ts '19970524 10:30:29.123'}" +
from dual" ;
ResultSet rs = stmt.executeQuery(sql);
while (rs.next())
System.out.println("results:
"\n "
+ rs.getString(2)
"\n "
+ rs.getString(3)
"\n "
+ rs.getString(4)
" + rs.getString(1) +
+
+
);
FIRSTNAME
Beth
Dylan
Brian
ID
102
111
116
To access this data, we can use the JDBCODBC bridge. Microsoft provides an ODBC driver to
Excel worksheet.
Define an ODBC datasource (system DSN) named "employee_xls" that points to that worksheet.
example 1
import
import
import
import
java.io.*;
java.net.*;
java.sql.*;
java.util.*;
id : " + id);
}
finally {
if (con != null)
con.close();
}
}
}
example 2
import java.io.*;
import java.sql.*;
public class EmployeeReader{
public static void main(String[] args){
Connection connection = null;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection( "jdbc:odbc:employee_xls" );
Statement st = con.createStatement();
ResultSet rs = st.executeQuery( "Select * from [Sheet1$]" );
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
System.out.println ( "No of cols "+numberOfColumns
while (rs.next()) {
for (int i = 1; i <= numberOfColumns; i++) {
if (i > 1) System.out.print(", ");
String columnValue = rs.getString(i);
System.out.print(columnValue);
);
}
System.out.println("");
}
rs.close();
st.close();
}
catch(Exception ex) {
System.err.print("Exception: ");
System.err.println(ex.getMessage());
}
finally {
con.close();
}
}
}
7.41 JExcel
Java Excel API is a java API enabling developers to read, write, and modify Excel spreadsheets
dynamically. Any operating system which can run a Java virtual machine can both process and
deliver Excel spreadsheets. One nice thing about JExcelApi is that it has no dependencies on any
third party libraries.
Example : output an Excel file from a Servlet
import java.io.IOException;
import java.io.OutputStream;
import
import
import
import
javax.servlet.ServletException;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
import
import
import
import
jxl.Workbook;
jxl.write.Label;
jxl.write.WritableSheet;
jxl.write.WritableWorkbook;
See http://jexcelapi.sourceforge.net/
7.42 POI
The POI project consists of APIs for manipulating various file formats based upon Microsoft's OLE 2
Compound Document format using pure Java. POI is your Java Excel solution as well as your Java
Word solution.
HSSF is the POI Project's pure Java implementation of the Excel '97(2002) file format and it
provides a way to read spreadsheets create, modify, read and write XLS spreadsheets. Latest POI
version seems to support the .XLSX format.
Since it's Jakarta project, POI has a dependencies with other JARs (commons,log4j,etc...).
Example : create an Excel file
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = sheet.createRow((short)0);
row.createCell((short)0).setCellValue("HelloWorld");
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
The name was originally an acronym for "Poor Obfuscation Implementation" (ref: Wikipedia).
7.42 POI
See http://jakarta.apache.org/poi/
7.43 JXLS
jXLS is a project that allows creation of extremely complex Excel reports just in several lines of
code. It is based on Jakarta POI.
With jXLS, all you need is to create XLS template file with all required formatting, formulas etc using
specific notation to indicate placement of data and then write a couple lines of code to invoke jXLS
engine passing XLS template and the exported data as parameters.
Example :
The XLS Template
Employees
Name
${employee.name}
Age
Payment
Bonus
${employee.age} ${employee.payment} ${employee.bonus}
$[SUM(@employee.payment@)]
Payment Bonus
3000
30,00%
1500
15,00%
4500
Reading values from an XLS with jXLS is very simple. Suppose we have a worksheet with policy
numbers in the first column. We read and process them one by one.
import java.io.File;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
7.43 JXLS
See http://jxls.sourceforge.net/
7.44 xlSQL
xlSQL is a JDBC Driver for Excel and CSV data sources. Documents can be read and written with
SQL as if they were tables in a database.
You can export XLS to XML or SQL INSERT statements. xlSQL includes its own "zeroadmin"
mySQL database. The documentation is minimal at this time.
See http://xlsql.sourceforge.net/
7.45 JCOM
JCOM is a Java to COM bridge library. With JCOM you can call a COM object from Java as if it
were a Java object without having to deal with the internals of JNI. The documentation is minimal (in
Japanese!).
Example :
import
import
import
import
jp.ne.so_net.ga2.no_ji.jcom.excel8.*;
jp.ne.so_net.ga2.no_ji.jcom.*;
java.io.File;
java.util.Date;
class TestExcel {
public static void main(String[] args) throws Exception {
ReleaseManager rm = new ReleaseManager();
try {
System.out.println("EXCEL startup...");
// if already started, open new window
ExcelApplication excel = new ExcelApplication(rm);
excel.Visible(true);
// display any information
System.out.println("Version="+excel.Version());
System.out.println("UserName="+excel.UserName());
System.out.println("Caption="+excel.Caption());
System.out.println("Value="+excel.Value());
ExcelWorkbooks xlBooks = excel.Workbooks();
ExcelWorkbook xlBook = xlBooks.Add();
// create new book
// enumurate all files
System.out.println
("set infomation of files in current directory to cell ...");
ExcelWorksheets xlSheets = xlBook.Worksheets();
ExcelWorksheet xlSheet = xlSheets.Item(1);
ExcelRange xlRange = xlSheet.Cells();
xlRange.Item(1,1).Value("filename" );
xlRange.Item(2,1).Value("size" );
xlRange.Item(3,1).Value("last modified time");
xlRange.Item(4,1).Value("is directory");
xlRange.Item(5,1).Value("is file");
xlRange.Item(6,1).Value("can read");
xlRange.Item(7,1).Value("can write");
File path = new File("./");
7.44 xlSQL
xlBook.Close(false,null,false);
excel.Quit();
System.out.println("thank you .");
}
catch(Exception e) { e.printStackTrace(); }
finally { rm.release(); }
}
}
See http://sourceforge.net/projects/jcom
See also this HowTo for an alternative package to access a COM package from Java.
(workingdir + "testImagesOut.xls",0);
System.out.println("Successfully read: " + newbook);
}
public void testWrite(WorkBookHandle b, String fout){
try{
java.io.File f = new java.io.File(fout);
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bbout = new BufferedOutputStream(fos);
bbout.write(b.getBytes());
bbout.flush();
fos.close();
}
catch (java.io.IOException e){
System.err.println("IOException in Tester. "+e);
}
}
See also this HowTo for a way to create a simple XLS without any additional library.
Connection conn =
DriverManager.getConnection(url,"scott","tiger");
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
ResultSet rset =
stmt.executeQuery("select BANNER from SYS.V_$VERSION");
while (rset.next()) {
System.out.println (rset.getString(1));
}
stmt.close();
System.out.println ("Ok.");
}
}
While it is not to difficult to connect using the example above, it would be nice to connect without
having to specify a server and a port number. Since release 10.2.0.1.0, it's possible to give only a
TNSNAMES entry and the driver extract the required infos (server and port) for the defined
TNSNAMES.ORA file. In order for this to work you must have configured the file TNSNAMES.ORA
correctly and set a the java property oracle.net.tns_admin.
import
import
import
import
import
java.sql.Connection;
java.sql.DriverManager;
java.sql.ResultSet;
java.sql.SQLException;
java.sql.Statement;
import oracle.jdbc.OracleDriver;
public class TestOra {
public TestOra() {
System.setProperty("oracle.net.tns_admin","\\\\myserver\\TNSNAMES_DIR");
// or
// java.exe Doracle.net.tns_admin=\\myserver\TNSNAMES_DIR TestOra ...
//
}
public void doit
String usr =
String pwd =
String url =
() throws SQLException {
"scott";
"tiger";
"jdbc:oracle:thin:@MYORCL";
DriverManager.registerDriver(new OracleDriver());
Connection conn = DriverManager.getConnection(url,usr,pwd);
String sql = "select {fn now()} from dual" ;
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next())
System.out.println("results: " + rs.getString(1));
conn.close();
}
public static void main(String[] args){
TestOra test = new TestOra();
try {
test.doit();
System.out.println("Done..");
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
/*
\\myserver\TNSNAMES_DIR\tnsnames.ora
MYORCL =
(DESCRIPTION =
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = orcltest.local)(PORT = 1521))
)
(CONNECT_DATA = (SERVICE_NAME = orcl)(INSTANCE_ROLE=ANY))
)
*/
See also this HowTo to connect using the Oracle Connection Pool.
Thread.sleep(1000);
}
catch(Exception e) { }
}
}
}
}
Nice article on the subject : Oracle JDBC: Automatic key generation and retrieval
Thanks to F.Joyal for his help
Djava.util.logging.config.file=c:/myapp/oracledebug.propertie
#oracle.jdbc.adt.level = FINEST
#oracle.jdbc.conversion.level = FINEST
#oracle.jdbc.adt.level = FINEST
#oracle.jdbc.thin.level = FINEST
#oracle.jdbc.datum.level = FINEST
#oracle.jdbc.kprb.level = FINEST
#oracle.jdbc.pool.level = FINEST
#oracle.jdbc.xa.level = FINEST
#oracle.jdbc.sqlj.level = FINEST
#oracle.jdbc.oci.level = FINEST
#oracle.jdbc.jpub.level = FINEST
To turn tracing on and get the most amount of information, specify the following:
TRACE_LEVEL_CLIENT = SUPPORT
To turn tracing off, which you definitely want to do after your debugging session is complete, use
0 or OFF:
TRACE_LEVEL_CLIENT = OFF
java.sql.Connection;
java.sql.DriverManager;
java.sql.ResultSet;
java.sql.SQLException;
java.sql.Statement;
java.util.Properties;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.OracleDriver;
import oracle.net.ano.AnoServices;
public class TestOra3 {
public TestOra3() {
}
public void doit () throws SQLException {
Properties props = new Properties();
props.setProperty(
OracleConnection.CONNECTION_PROPERTY_THIN_NET_AUTHENTICATION_SERVICES,
"( " + AnoServices.AUTHENTICATION_KERBEROS5 + " )");
props.setProperty(
OracleConnection.CONNECTION_PROPERTY_THIN_NET_AUTHENTICATION_KRB5_MUTUAL,
"true");
System.setProperty("java.security.krb5.conf","c:/oracle/krb5.conf");
String url = "jdbc:oracle:thin:@//oracleserver.mydomain.com:5561/mydatabaseinstance";
DriverManager.registerDriver(new OracleDriver());
Connection conn = DriverManager.getConnection(url,props);
String sql = "select {fn user()} from dual" ;
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next())
System.out.println("results: " + rs.getString(1));
conn.close();
}
public static void main(String[] args){
TestOra3 test = new TestOra3();
try {
test.doit();
System.out.println("Done..");
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
When connecting with ODBC or OCI, the program column will contain the executable name used
to make the connection. If the connection is made with the Thin Driver,the program is "JDBC Thin
Client" (by default). The good news is that this information can be customized at the connect time
to provide a more interesting name (maximum length = 64 characters).
import
import
import
import
import
import
java.sql.Connection;
java.sql.DriverManager;
java.sql.ResultSet;
java.sql.SQLException;
java.sql.Statement;
java.util.Properties;
import oracle.jdbc.OracleConnection;
import oracle.jdbc.OracleDriver;
public class TestOra5 {
public TestOra5() {
Output :
7.52 Identify the connected program to an Oracle databaseTag(s): JDBC
|username
|bigadmin
|real
|scott
|osuser.
|real
|real
|real
|program
|JDBC Thin Client
|Winsql.exe
|My Java program : TestOra5
|machine
|Jupiter
|Saturn
|Mercury
The easy fix to define the field as a VARCHAR not a CHAR or replace the PreparedStatement
with a Statement.
Statement s;
s= conn.createStatement();
String val = "A10";
String sql ="SELECT desc_value from prod.DICT_VALUES WHERE code_value='" + val + "'" ;
ResultSet rs = s.executeQuery(sql);
while (rs.next())
System.out.println("results: " + rs.getString(1));
To keep a PreparedStatement, you need to add explicitly the trailing spaces or trim the value.
The first try is to trim the value with the rtrim() function.
7.53 Use a CHAR field in the WHERE clause in a PreparedStatementTag(s): JDBC
This is working fine but Oracle will not use the index and probably perform a table scan which is
not a good thing!
Oracle provides an API to make sure that the parameter received is handled as a CHAR value by
the database.
import oracle.jdbc.OraclePreparedStatement;
...
PreparedStatement ps;
ps = conn.prepareStatement("SELECT dewsc_value from prod.DICT_VALUES WHERE code_value= ?") ;
((OraclePreparedStatement)ps).setFixedCHAR(1, "A10");
rs = ps.executeQuery();
while (rs.next())
System.out.println("results: " + rs.getString(1));
The good thing is that we don't need to know the CHAR width of the field, the driver will figure it
out for us but using the special Oracle class can be problem.
A better solution is to instruct the database to add the missing trailing spaces with the rpad()
function.
This a better solution because ee are not using a special Oracle class and the database will use
the index.
8 JNI
8.1 javajni
Compile the Java program and use javah utility to generate the JavaHowTo.h header file.
javah jni JavaHowTo
8 JNI
then from C, we want to call the Java sayHello() method which returns a String :
JNIEXPORT void JNICALL Java_JavaHowTo_sayHello
(JNIEnv *env, jobject obj) {
const char *str;
jclass myclass_class =(jclass) env>NewGlobalRef
(env>FindClass ("MyClass"));
// we need the MyClass constructor
jmethodID constructorID = env>GetMethodID
(myclass_class, "", "()V");
// and the sayHello() method
jmethodID methodID = env>GetMethodID
(myclass_class, "sayHello", "()Ljava/lang/String;");
// instanciate a MyClass object
jobject myclass_object = env>NewObject
(myclass_class, constructorID);
// call the sayHello() method
jstring s = (jstring) env>CallObjectMethod
(myclass_object, methodID);
// convert the Java String to use it in C
str = env>GetStringUTFChars(s, 0);
printf("%s" , str);
env>ReleaseStringUTFChars(s, str);
}
8 JNI
There are two parts to the signature. The first part is enclosed within the parentheses and
represents the method's arguments. The second portion follows the closing parenthesis and
represents the return type. The mapping between the Java type and C type is
Type
boolean
byte
char
double
float
int
long
object
short
void
array
Chararacter
Z
B
C
D
F
I
J
L
S
V
[
Note that to specify an object, the "L" is followed by the object's class name and ends with a
semicolon, ';' .
The javap utility (included with the JDK) is very useful to show the signature to be used in JNI.
X:\>javap s java.awt.Label
Compiled from Label.java
public class java.awt.Label extends java.awt.Component {
public static final int LEFT;
/*
I
*/
public static final int CENTER;
/*
I
*/
public static final int RIGHT;
/*
I
*/
java.lang.String text;
/*
Ljava/lang/String;
*/
int alignment;
/*
I
*/
static {};
/*
()V
*/
public java.awt.Label();
/*
()V
*/
public java.awt.Label(java.lang.String);
/*
(Ljava/lang/String;)V
*/
public java.awt.Label(java.lang.String,int);
/*
(Ljava/lang/String;I)V
*/
public void addNotify();
/*
()V
*/
java.lang.String constructComponentName();
/*
()Ljava/lang/String;
*/
public int getAlignment();
/*
()I
*/
public java.lang.String getText();
/*
()Ljava/lang/String;
*/
protected java.lang.String paramString();
/*
()Ljava/lang/String;
*/
public synchronized void setAlignment(int);
/*
(I)V
*/
public void setText(java.lang.String);
/*
(Ljava/lang/String;)V
*/
The javap utility can be used on the java.* or your own classes.
The JNI code (tested on 64bit Windows / Java 6u24 64bit using mingw 64bit cross compiler
(x86_64w64mingw32gcc).
#include "JNIHowTo.h"
JNIEXPORT void JNICALL Java_JNIHowTo_printArray
(JNIEnv* env, jclass obj, jintArray arr) {
jsize len = (*env)>GetArrayLength(env, arr);
printf("int[] : [");
if (len > 0) {
jboolean iscopy;
jint* tab = (*env)>GetIntArrayElements(env, arr,
for (int i = 0; i < len ; i++) printf(" %d", (int)tab[i]);
if (iscopy == JNI_TRUE) (*env)>ReleaseIntArrayElements(env, arr, tab, JNI_ABORT);
}
printf(" ]\n"); fflush(stdout);
}
JNIEXPORT void JNICALL Java_JNIHowTo_printArrayR (JNIEnv* env, jclass obj) {
jclass
cls = (*env)>GetObjectClass(env, obj);
jfieldID fid = (*env)>GetFieldID(env, cls, "myArray", "[I");
if (fid) {
jobject arr = (*env)>GetObjectField(env, obj, fid);
jsize
len = (*env)>GetArrayLength(env, arr);
printf("via reflection:\nint[] : [");
if (len > 0) {
jboolean iscopy;
In JDK1.2 (or better), if the DLL is in the CLASSPATH then you don't need to specify a PATH. If the
DLL is not in the CLASSPATH then you need to specify the PATH.
Do something like this instead.
Runtime.getRuntime().load("d:/directoryX/subDirY/MyDll.dll");
or specify through the JVM command line the location where to find the JNI DLL to be loaded
java Djava.library.path=c:/temp JNIJavaHowTo
When you put the class into a package (say com.rgagnon), you need to include the package
information in the native function name like this:
JNIEXPORT void JNICALL Java_com_rgagnon_MyClass_myMethod(JNIEnv *, jobject);
To generated the proper header, compile the JNI class in the package then, using the javah utility
(from the root of the package) :
javah com.rgagnon.MyClass
#include <jni.h>
#include <stdio.h>
int main() {
JavaVM *vm;
JNIEnv *env;
JavaVMInitArgs vm_args;
JavaVMOption options[1];
options[0].optionString = "Djava.class.path=c:/myclasses";
vm_args.version = JNI_VERSION_1_2;
vm_args.options = options;
vm_args.nOptions = 1;
vm_args.ignoreUnrecognized = 1;
jstring jstr;
jobjectArray args;
jint res = JNI_CreateJavaVM((void **)
if (res < 0) {
printf("Can't create Java VM\n");
exit(1);
}
jclass cls = env>FindClass("HelloWorld"); // in c:/myclasses
if (cls == 0) {
printf("HelloWorld class not found\n");
exit(1);
}
jmethodID mid =
env>GetStaticMethodID(cls, "main", "([Ljava/lang/String;)V");
if (mid == 0) {
printf("main() method not found\n");
exit(1);
}
jstring argString = env>NewStringUTF(""); //empty arg list
jobjectArray args =
env>NewObjectArray(1, env>FindClass("java/lang/String"), jstr);
if (args == 0) {
printf("Out of memory\n");
exit(1);
}
env>CallStaticVoidMethod(cls, mid, args);
return 0;
}
NOTE : This is fine if the environment variable contains only regular 7bit ASCII characters.
See also this HowTo.
8.16 Clear the console, set color and cursor position (JNI)Tag(s):
JNI
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java0469.html
[Windows only]
First you need this Java stub (JavaHowTo.java) to provide an interface to the JNI DLL (jni3.dll).
class JavaHowTo {
public
public
public
public
public
public
static
static
static
static
static
static
final
final
final
final
final
final
short
short
short
short
short
short
FOREGROUND_BLACK = 0x0;
FOREGROUND_BLUE = 0x1;
FOREGROUND_GREEN = 0x2;
FOREGROUND_RED
= 0x4;
FOREGROUND_WHITE = 0x7;
FOREGROUND_INTENSITY = 0x8;
Compile and generate an header with javah JavaHowto, the result is a file called JavaHowTo.h.
8.16 Clear the console, set color and cursor position (JNI)Tag(s): JNI
Next we built a DLL, I'm using VisualStudio v6. Don't forget to include the folders
%JAVAHOME%\include and %JAVAHOME%\include\win32 to have access to the JNI header files.
// jni3.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#include <stdlib.h>
#include "JavaHowTo.h"
int originalColors;
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
return TRUE;
}
8.16 Clear the console, set color and cursor position (JNI)Tag(s): JNI
8.16 Clear the console, set color and cursor position (JNI)Tag(s): JNI
See http://johannburkard.de/software/nativecall/
// https://github.com/twall/jna#readme
//
you need 2 jars : jna3.5.1.jar and platform3.5.1.jar
public class IsRunning {
public static void main(String[] args) {
HWND hwnd = User32.INSTANCE.FindWindow
(null, "Microsoft Excel Classeur1"); // window title
if (hwnd == null) {
System.out.println("Excel is not running");
}
else{
User32.INSTANCE.ShowWindow(hwnd, 9 );
// SW_RESTORE
User32.INSTANCE.SetForegroundWindow(hwnd);
// bring to front
}
8.17 Call Windows API (Open source solution)Tag(s): JNI Open Source
}
}
This technique looks for the window title. Since my Excel installation is in French then the default
sheet name is Classeur1(in English it would be Sheet1).
Another way is to look for the window class name. For Excel, the class name is XLMAIN.
To search for the class name instead of the window title, change this line :
HWND hwnd = User32.INSTANCE.FindWindow("XLMAIN", null); // window class name
To determine the class name of a window for a specific program, you can use something like Spy++
(installed with Visual Studio).
It is also possible to search for the class name and the title to make the search more precise.
import com.sun.jna.platform.win32.Shell32;
import com.sun.jna.platform.win32.ShlObj;
import com.sun.jna.platform.win32.WinDef;
// https://github.com/twall/jna#readme
//
you need 2 jars : jna3.5.1.jar and platform3.5.1.jar
public class GetFolderPathDemo {
public static void main(String[] args) {
char[] pszPath = new char[WinDef.MAX_PATH];
Shell32.INSTANCE.SHGetFolderPath(null,
ShlObj.CSIDL_PROGRAM_FILES, null, ShlObj.SHGFP_TYPE_CURRENT,
pszPath);
System.out.println(Native.toString(pszPath));
Shell32.INSTANCE.SHGetFolderPath(null,
ShlObj.CSIDL_DESKTOPDIRECTORY, null, ShlObj.SHGFP_TYPE_CURRENT,
pszPath);
System.out.println(Native.toString(pszPath));
Shell32.INSTANCE.SHGetFolderPath(null,
ShlObj.CSIDL_COMMON_DOCUMENTS, null, ShlObj.SHGFP_TYPE_CURRENT,
pszPath);
System.out.println(Native.toString(pszPath));
/*
* output :
* C:\Program Files
* C:\Users\Real_User\Desktop
* C:\Users\Public\Documents
*/
}
}
9 Javascript interaction
9.1 javajs
The examples in these Howto's are tested with Netscape 7 (or better) on Windows.
Windows and Linux
The LiveConnect package is included with the Java plugin.
The official documentation for the various versions can be found at
http://java.sun.com/products/plugin/reference/docs/index.html. You need to add the plugin.jar to the
classpath (JRE_HOME\lib) for compilation.
Mac (old)
To use the LiveConnect packages on the Mac you will need to install the latest MRJ available from
the Apple website and then goto the Mozilla website and download the MRJ Plugin.
The only other thing then is to change the <applet> tags to <embed> tag (more info on this is on the
Mozilla site). Thanks to Neil English for the tip
Mac OSX
Java is preinstalled with Mac OSX.
The required jar is in /System/Library/Frameworks/JavaVM.framework/Versions/<your
version>/Home/lib
You need to add the plugin.jar to the classpath (JRE_HOME\lib) for compilation.
[JAVA APPLET]
import java.applet.*;
import java.awt.*;
public class JavaChrono extends Applet {
String previousTime = "0" ;
String currentTime = "0";
long j,k, l;
boolean okToChrono = false;
Color b, f;
public void init() {
b = getBackground();
f = getForeground();
MyThread tm = new MyThread(this);
tm.start();
}
public void startChrono() {
j = System.currentTimeMillis();
okToChrono = true;
}
public void stopChrono() {
okToChrono = false;
}
public void paint(Graphics g) {
if (okToChrono) {
g.setColor(b);
g.drawString(previousTime,10,30);
g.setColor(f);
k = System.currentTimeMillis();
l = kj;
currentTime = Long.toString(l/1000);
g.drawString(currentTime,10,30);
previousTime = currentTime;
}
}
}
class MyThread extends Thread {
JavaChrono theApplet;
public MyThread(JavaChrono a) {
theApplet = a;
}
public void run() {
while (true) {
try {
theApplet.repaint();
this.sleep(1000);
}
catch(InterruptedException e) { }
}
}
}
[HTML]
9 Javascript interaction
<HTML><HEAD></HEAD><BODY>
<APPLET CODE=JavaChrono.class
WIDTH=150
HEIGHT=150>
</APPLET>
<A HREF=""
onMouseOver="document.applets[0].startChrono()"
onMouseOut="document.applets[0].stopChrono()"
>
<IMG SRC="whatever.gif" WIDTH=100 HEIGHT=100>
</A>
/BODY/HTML
Try it here.
In the next example, when we click on a FORM's button, we tell the applet to open or close a frame.
[HTML]
<HTML>
<HEAD></HEAD>
<BODY>
<APPLET NAME="myApplet" CODE="MyApplet.class" HEIGHT=1 WIDTH=1></APPLET>
<FORM>
<INPUT TYPE="button"
VALUE="Start the Applet"
onClick=
"if (document.applets[0].isActive()) document.myApplet.showFrame()">
<INPUT TYPE="button"
VALUE="Stop the Applet"
onClick=
"if (document.applets[0].isActive()) document.myApplet.disposeFrame()">
/FORM/BODY/HTML
[JAVA APPLET]
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet {
Frame f = null;
public void init() { }
public void showFrame() {
if (f == null) {
f = new Frame();
f.setSize(100,100);
f.add(new Label("Hello World"));
f.setVisible(true);
}
}
public void disposeFrame() {
if (f != null) {
f.dispose();
f = null;
}
}
}
Try it here.
9 Javascript interaction
</APPLET>
/BODY/HTML
Try it here
import java.awt.*;
import java.applet.*;
// (IE and Netscape ok)
public class InJava2 extends Applet{
public int getScreenWidth() {
return Toolkit.getDefaultToolkit().getScreenSize().width;
}
public int getScreenHeight() {
return Toolkit.getDefaultToolkit().getScreenSize().height;
}
}
9.5 Calling Java applets methods using DOM and JavaScriptTag(s): Javascript interaction
...
<PARAM NAME="scriptable" value="true">
<PARAM NAME="mayscript" value="true">
...
</OBJECT>
[in your script]
document.all.myApplet.myMethod()
You use the scriptable parameter if you call Java method from Javascript.
You use the mayscript parameter if you call Javascript function from Java.
This Sun's document describes how Java to Javascript communication works when using the Java
Plugin.
</SCRIPT>
<FORM>
<INPUT type="button" value="Java says"
onClick = "JavaSays();">
</FORM>
<APPLET CODE="InJava3.class"
NAME="myApplet"
HEIGHT=0 WIDTH=0>
/APPLET/BODY/HTML
Try it here
Remember that IE4 can access only attributes and methods from a class derived from java.applet.Applet. If you want to call a method or use an
attribute in another class, you have to create a method in your applet class that calls the other class's method.
<APPLET CODE="InJava4.class"
NAME="myApplet" MAYSCRIPT
HEIGHT=10 WIDTH=10>
</APPLET>
</BODY>
/HTML
Try it here
java.applet.*;
java.awt.*;
java.awt.event.*;
netscape.javascript.*;
Another way is to use the Reflection API. That way you don't need to modify your CLASSPATH for
compilation or even import the netscape.jsobject package.
// posted by C Werner on the realhowto list
import java.lang.reflect.*;
...
import
import
import
import
java.applet.*;
java.awt.*;
java.awt.event.*;
netscape.javascript.*;
9.11 Have Applets on different frames communicates with each otherTag(s): Javascript interaction
java.applet.*;
java.awt.*;
java.awt.event.*;
java.net.URL;
netscape.javascript.*;
9.11 Have Applets on different frames communicates with each otherTag(s): Javascript interaction
target = getParameter("target");
setLayout(new BorderLayout());
tf = new TextField(20);
add("South", tf);
b = new Button("To other frame");
add("North",b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == b) {
String js =
"parent.f1.toOtherFrame(\"" +
tf.getText() +
"\",\"" + target + "\")";
System.out.println("to Javascript:" + js);
JSObject win = (JSObject) JSObject.getWindow(this);
win.eval(js);
}
}
public void fromOtherFrame(String s) {
tf.setText(s);
}
}
Try it here
For a JAVAonly solution check this Java Howto
FirstApplet.java
import java.applet.*;
9.12 Send a message from an Applet to another Applet on a different pageTag(s): Javascript interaction
import java.awt.*;
import java.awt.event.*;
import java.net.*;
public class FirstApplet extends Applet implements
ActionListener {
Button b;
TextField t;
public void init() {
add(new Label("Message to 2nd applet :"));
add(t= new TextField(20));
add(b = new Button("Load 2nd applet"));
b.addActionListener(this);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == b) {
try {
getAppletContext().showDocument
(new URL(getCodeBase(),
"SecondApplet.html?" + "message="
+ URLEncoder.encode(t.getText())));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
SecondApplet.html
<HTML><HEAD></HEAD><BODY>
<SCRIPT>
// from Javascript Howto general part 3,
//
replace all occurrence of token by another
//
in a string.
function replace(s, t, u) {
i = s.indexOf(t);
r = "";
if (i == 1) return s;
r += s.substring(0,i) + u;
if ( i + t.length <s.length)
r += replace(s.substring(i + t.length, s.length), t, u);
return r;
}
strlen = document.location.search.length
if (strlen > 0) {
theMessage = document.location.search
// strip the "message header"
theMessage = theMessage.substring(1 + 'message='.length,strlen)
// replace all '+" by space
theMessage = replace(theMessage, '+', ' ')
// replace encoded chars by decoded chars if any
theMessage = unescape(theMessage)
html = '<APPLET CODE="SecondApplet.class"'
html += ' HEIGHT=100'
html += ' WIDTH=400> '
html += '<PARAM NAME="Message" VALUE="' + theMessage + '"> '
html += '</APPLET>'
document.close()
document.open()
9.12 Send a message from an Applet to another Applet on a different pageTag(s): Javascript interaction
document.write(html)
document.close()
}
</SCRIPT>
/BODY/HTML
SecondApplet.java
import java.applet.*;
import java.awt.*;
public class SecondApplet extends Applet {
public void init() {
Label l = new Label("Message from 1st Applet");
add (l);
TextField tf = new TextField( 50 );
add(tf);
String s = getParameter("Message");
tf.setText(s);
}
}
You can try it here!
This method is useful when you need to pass the message to the SecondApplet via PARAM tag.
But if you don't need the PARAM tag, take a look at this Java Howto.
9.13 Retrieve values from a Java applet for HTML form (CGI)Tag(s): Javascript interaction
document.myForm.q.value = document.myApplet.getFirstName();
return true;
}
</SCRIPT>
<BODY>
<APPLET CODE="InitHTMLForm.class"
NAME="myApplet"
HEIGHT=0 WIDTH=0>
</APPLET>
<FORM ACTION="http://www.google.ca/search"
NAME="myForm"
onSubmit="return getValueFromApplet()">
<INPUT TYPE="hidden" VALUE="" NAME="q">
<INPUT TYPE="submit" VALUE="Submit" >
</FORM>
/BODY/HTML
Try it here
...
<BODY onLoad="waituntilok();">
....
/BODY
By calling the javascript function from the BODY onLoad handler, we can assume that the Applet is
loaded, initiated and started.
Here a "browser friendly" solution from N. Witteman to check if an Applet can be loaded (or found).
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
onError = errHandler;
// Without he parentheses, because we don't want IE
// to do this. Like this, only NS does.
function appLoaded() {
if (!document.applets[0].isActive)
// in IE: isActive returns an error if the applet IS loaded,
// false if not loaded
// in NS: isActive returns true if loaded, an error if not loaded,
// so never reaches the next statement
alert("IE: Applet could not be loaded");
}
function errHandler() {
alert("NS: Applet could not be loaded");
consume();
// stops further processing of the error
}
</SCRIPT>
</HEAD>
<BODY onLoad = appLoaded();>
<APPLET code=someClass.class
codeBase=someURL height=50 width=300><PARAM NAME="bgcolor" VALUE="FFFFFF">
</APPLET>
</BODY>
/HTML
java.applet.*;
java.awt.event.*;
java.awt.*;
netscape.javascript.*;
[JSjava.html]
<HTML><HEAD>
<SCRIPT>
function getHTMLInputText(){
return document.forms[0].elements[0].value;
}
function setHTMLInputText(s){
document.forms[0].elements[0].value = s;
}
</SCRIPT></HEAD><BODY>
<FORM>
<INPUT TYPE=text SZIE=20>
</FORM>
<APPLET NAME="JS" CODE=JSjava.class MAYSCRIPT WIDTH=200 HEIGTH=200>
/APPLET/BODY/HTML
For best result, never use LiveConnect JSObject in Applet's init() method.
else
return false;
}
because Unknown Java classes are reflected as JavaPackages, for reasons related to the fact that
there's no way to tell if something is a valid package.
netscape.javascript.*;
java.awt.*;
java.awt.event.*;
java.applet.*;
See this text file with some useful Javascript functions for cookies handling.
Check this Howto to detect if Cookies are enabled or not.
PARAM VALUE can't be changed ar runtime but during layout time, javascript "entities" can be
used to set calculated VALUES.
In this Howto, VALUES are coming from a javascript variable, a javascript function and a javascript
expression.
<HTML><HEAD></HEAD><BODY>
<SCRIPT>
var jsVar = "Hello World from jsVar";
function jsFnct() {
return "Hello World from jsFnct";
}
</SCRIPT></HEAD><BODY>
<<APPLET CODE ="MyApplet.class" HEIGHT=100 WIDTH=400>
<PARAM NAME="first" VALUE="&{jsVar};">
<param name="second" value="&{jsFnct()};">
<param name="third"
value="&{'hello world'.toUpperCase() + ' from js Expression'};">
</APPLET>
/BODY/HTML
A safe and simple way is to transform the Array as a big String with a known character used a
separator. From there, it's trivial to do some manipulations to retrieve the array.
In the following example, the first button is used to read directly the Java array. The second button
call a Java method which to transform the array as a string, then the Javascript function split() is
used to retrieve the array. The third button will modify the Java array. A Javascript array is
transformed with the function join() and on the Javaside, a StringTokenizer will do the rest.
[Java applet]
import java.awt.*;
import java.applet.*;
import java.util.*;
public class TestJavaArray extends Applet{
public String javaArray [] =
{ "array 1", "array 2" , "array 3" };
public String [] getJavaArray() {
return javaArray;
}
public String getJavaArrayAsAString() {
// you need more error checking here, of course...
int k;
String s = "";
k = javaArray.length;
s = javaArray[0];
for (int i= 1 ; i < k; i++) {
s += "|" + javaArray[i] ;
}
return s;
}
public void putJavaArray(String arrayAsAString) {
int i = 0;
String s;
StringTokenizer st =
new StringTokenizer(arrayAsAString, "|");
while(st.hasMoreTokens()){
javaArray[i++] = st.nextToken();
}
}
}
Try it here.
Here an interesting piece of code submitted by M. Caetano which does basically the same thing.
Note the use of regular expressions to keep the code short and compact. Since java classes are
called directly by javascript, these functions won't work with IE (only with Netscape).
/*
COPYJAVA
}
else {
return null;
}
}
else {
if ( /^\bobject\b$/i.test(typeof(arg_)) ) {
if ( this.length == 0 ) {
var len = java.lang.reflect.Array.getLength(arg_);
var i=0; while ( i < len ) { this[i] = ''+arg_[i++]; }
}
}
}
}
function makeJavaArray(type_,size_) {
if ( !/^\bnull\b$|^\bundefined\b$|^\s?$/i.test(type_) ) {
if (
/boolean|byte|int|long|short|double
|float|char|void|String|Object|Class|Thread/.test(type_)
) {
var type = type_.charCodeAt(0)<91 ? 'java.lang.' + type_: type_;
var size = !isNaN(Number(size_)) ? Number(size_) : 1;
return ( new
java.lang.reflect.Array.newInstance
(java.lang.Class.forName(type),size)
);
} // else invalid cast
} // else invalid args
}
visiblepage.html contains the Applet and a javascript function. The idea is to type something in a
TextField, press a Button to send a string to a javascript to do an alert() with the TextField content.
[visiblepage.html]
<HTML><HEAD>
<SCRIPT>
function showMessage(s) {
alert(s)
}
</SCRIPT>
</HEAD><BODY><H1>Simple Java to Javascript interaction</H1><P>
<APPLET CODE=SimpleApplet.class
WIDTH=150
HEIGHT=150>
</APPLET></BODY></HTML>
invisiblepage.html contains the function to extract the parameter and call the showMessage()
function in the visible frame.
<HTML><HEAD>
<SCRIPT>
function replace(s, t, u) {
i = s.indexOf(t);
r = "";
if (i == 1) return s;
r += s.substring(0,i) + u;
if ( i + t.length < s.length)
r += replace(s.substring(i + t.length, s.length), t, u);
return r;
}
function getAndSendMessage() {
theMessage = document.location.search.substring(1,255)
if (theMessage.length > 0) {
// replace all '+" by space
theMessage = replace(theMessage, '+', ' ')
window.parent.mainFrame.showMessage(unescape(theMessage))
}
}
</SCRIPT>
</HEAD><BODY onLoad="getAndSendMessage();">
</BODY></HTML>
and finally the Applet (a JDK102 style, since we want to be friendly to older browsers).
[SimpleApplet.java]
import java.applet.Applet;
import java.awt.*;
public class SimpleApplet extends Applet {
TextField aMessage;
Button
sendButton;
public void init() {
aMessage = new TextField(20);
add(aMessage);
sendButton = new Button("Send to Javascript");
add(sendButton);
}
public boolean action(Event e, Object o) {
if (e.target.equals(sendButton)) {
try {
getAppletContext().showDocument
(new java.net.URL
(getCodeBase(),
"invisiblepage.html?"+
java.net.URLEncoder.encode(aMessage.getText())),
"scriptFrame");
}
catch (Exception ex) {
ex.printStackTrace();
}
}
return true;
}
}
Try it here.
Javascript to Java
The idea here is to have an invisible Applet in an invisible frame that will receive a message (from
Javascript in the visible frame) through the search part of its URL. Then via a static pointer to the
visible Applet, the invisible Applet pass the message to the visible Applet by calling the appropriate
function.
The SimpleApplet2 is TextField which will be used to display the message type in the HTML FORM.
[SimpleApplet2.java]
import java.applet.Applet;
import java.awt.*;
The class to hold a static pointer to SimpleApplet2. This pointer will be used by the InvisibleApplet.
[SimpleAppletRegistered.java]
public class SimpleAppletRegistered {
static SimpleApplet2 sa;
}
[InvisibleApplet.java]
import java.applet.Applet;
public class InvisibleApplet extends Applet {
public void init() {
String completeURL = getDocumentBase().toString();
System.out.println("URL received : " + completeURL);
int i = completeURL.indexOf("?");
if (i > 1) {
String msg = completeURL.substring(completeURL.indexOf("?") + 1);
// call SimpleApplet via the static pointer
// you may to decode the string here with
//
java.net.URLDecoder.decode() method.
SimpleAppletRegistered.sa.setMessage(msg);
}
}
}
Try it here.
NOTE: A Static class can be shared between Applets only if the Applets are coming from the same server and the MAYSCRIPT is not used.
NOTE: To send a message containing spaces and other special characters like &or ?, you will need
to encode the message from Javascript (with the escape function) and decode the message in
Java.
NOTE : With IE, you need to run this sample through a Web server.
9.22 Directory listing on the Web server in a Java AppletTag(s): Javascript interaction
</SCRIPT></HEAD>
<FRAMESET ROWS="35%,65%,*" onLoad="reload_master()">
<FRAME SRC="blank.html" NAME="master">
<FRAME SRC="blank.html" NAME="detail">
<FRAME SRC="../images" NAME="contents" NORESIZE>
</FRAMESET>
/HTML
blank.html
<HTML<<HEAD><TITLE
</TITLE></HEAD><BODY>
</BODY></HTML>
When all pages are loaded, the selector.html page is loaded into the first visible frame. That page
contains the Applet. During layout time, Javascript extracts links to the an Array. Via the BODY
onLoad event handler, we trigger a Javascript function to transfer the Array to the Applet.
selector.html
<HTML><HEAD>
<SCRIPT>
var LinksLength =
parent.contents.window.document.links.length
var AllTheLinksAsArray = new Array()
// start at the second link because
// we dont want the root directory
for (var i = 1; i < LinksLength ; i++) {
s = parent.contents.window.document.links[i];
AllTheLinksAsArray[i] = s;
}
function putLinksIntoApplet() {
AllTheLinksAsString = AllTheLinksAsArray.join("|");
document.Selector.insertData(AllTheLinksAsString);
}
</SCRIPT></HEAD>
<BODY onLoad ="putLinksIntoApplet()">
<P ALIGN="center">Doubleclick to view
<APPLET
CODE=Selector.class
HEIGHT=100
WIDTH=400
NAME=Selector>
<PARAM NAME="targetFrame" VALUE="detail">
</APPLET>
</BODY>
/HTML
Selector.java
import
import
import
import
import
java.awt.*;
java.awt.event.*;
java.applet.*;
java.util.*;
java.net.*;
9.22 Directory listing on the Web server in a Java AppletTag(s): Javascript interaction
java.applet.*;
java.awt.*;
java.awt.event.*;
netscape.javascript.*;
9.23 Have a Java button close the browser windowTag(s): Javascript interaction
Try it here
[MyApplet.java]
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
}
}
9.25 Display a page after all applets are loadedTag(s): Javascript interaction
To compile, make sure that you have the plugin.jar in the classpath (or Eclipse Build Path). This jar
is usually located in [JRE]/lib folder. During runtime, it's already included by the Java plugin so you
don't have to worry about that.
The Java class
import
import
import
import
java.applet.*;
java.awt.event.*;
java.awt.*;
netscape.javascript.*;
Don't forget the MAYSCRIPT parameter in the APPLET tag, it's required since the Applet is using
the JSObject to interact with the Javascript.
<html>
<head>
<script>
function getUserAgent() {
return navigator.userAgent;
}
</script>
</head><body>
<applet code="GetUserAgent.class" MAYSCRIPT height=100 width=500></Applet>
</body>
</html>
Try it here
You need to parse the returned value to detect browser type. Look at this utility,
http://code.google.com/p/useragentutils/ or at this code :
http://nerds.palmdrive.net/useragent/code.html to get the idea.
9.25 Display a page after all applets are loadedTag(s): Javascript interaction
10 Servlet/JSP
10.1 javajsp
10 Servlet/JSP
Here we calling a script called aCGI.pl (a PERL script) passing the parameters name and site.
Parameters are encoded, spaces are changed to "+" and special character to hexadecimal using a
3letter escape sequence. Each parameter is delimited by the character "Habitually the encoding is
done through the static method encode of the java.net.URLencoder class.
String theCGI = "http://www.server.com/cgibin/aCGI.pl?";
String encoded = "name=" + URLencoder.encode("Real Gagnon");
URL cgiurl = new URL(thecgi + encoded);
Once the URL is constructed, you call the CGI using the showDocument method (Applet).
getAppletContext().showDocument(cgiurl);
The CGI will process the result and produce a page to be displayed.
The POST method allows the programmer to manipulate the data received from the CGI. First a
connection is made to the CGI, an OutputStream is open to send the parameters (if any). Then
InputStream is created to receive the result.
String theCGI = "http://www.server.com/cgibin/aCGI.pl";
String encoded = "name=" + URLencoder.encode("Real Gagnon");
URL CGIurl = new URL(theCGI);
URLConnection c = CGIurl.openConnection();
c.setDoOutput(true);
c.setUseCaches(false);
c.setRequestProperty("contenttype","application/xwwwformurlencoded");
DataOutputStream out = new DataOutputStream(c.getOutputStream());
out.writeBytes(encoded);
out.flush(); out.close();
BufferedReader in =
new BufferedReader(new InputStreamReader(c.getInputStream());
String aLine;
You can't do some output then some input and do again some output. You must do all the output
and then the input. There is no "dialog" between the client and the server. The client make a
request and the server send back the result and close the connection.
static
static
static
static
final
final
final
final
Cookie
String
String
String
http://www.rgagnon.com/javadetails/../javadetails/java0378.html
private int dumpData(java.sql.ResultSet rs, java.io.PrintWriter out)
throws Exception {
int rowCount = 0;
out.println("<P ALIGN='center'><TABLE BORDER=1>");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
// table header
out.println("<TR>");
for (int i = 0; i < columnCount; i++) {
out.println("<TH>" + rsmd.getColumnLabel(i + 1) + "</TH>");
}
out.println("</TR>");
// the data
while (rs.next()) {
rowCount++;
out.println("<TR>");
for (int i = 0; i < columnCount; i++) {
out.println("<TD>" + rs.getString(i + 1) + "</TD>");
}
out.println("</TR>");
}
out.println("</TABLE></P>");
return rowCount;
}
10.12 Specify the filename to be used for a file sent by a ServletTag(s): Servlet/JSP
A Bean
MyBean myBean = new MyBean();
myBean.setFooProperty("Real's HowTo");
request.setAttribute("foo", myBean);
In a Servlet
String path = getServletContext.getRealPath("/");
You may not get the real client IP if a the client is behind a proxy, you will get the IP of the proxy
and not the client. However, the proxy may include the requesting client IP in a special HTTP
header.
<%
out.print( request.getHeader("xforwardedfor") );
%>
There is a trimWhiteSpaces directive that should help to remove the whitespaces form the
generated JSP.
In your JSP code :
<%@ page trimDirectiveWhitespaces="true" %>
If you really have a required space in the generated JSP then you need use the HTML
nonbreaking space entity : .
Instead of hardcoding the cache name into your java component, make the name available
through a Property (of the Environment) of the Web application. This way your components are
more flexible and you are using the "J2EE way" to make a connection. In this example,
myconnection contains the cache name to be used.
javax.naming.InitialContext ctx = new javax.naming.InitialContext();
javax.sql.DataSource ds = (javax.sql.DataSource)
ctx.lookup("java:comp/env/jdbc/myconnection");
java.sql.Connection con = ds.getConnection();
java.sql.PreparedStatement stmt = con.prepareStatement(sql);
java.sql.ResultSet rs = stmt.executeQuery();
while (rs.next()) {
//do something
}
The JSP page will not be executed. If the container supports precompilation, the JSP page will be
compiled if necessary.
Here a JSP page that will scan the current directory (and subdirectories) to precompile all JSP
found.
<%@
<%@
<%@
<%@
page
page
page
page
Create a JAR file containing the .class file(s) and deploy the resulting JAR file via your webapp's
WEBINF/lib directory.
<%
Hello h = new Hello();
out.print(h.say());
%>
Create a tag library for it, deploy it via the webapp's WEBINF/tld directory.
TAG source code
TAG source code :
package test;
import java.io.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class HelloTag extends TagSupport {
public int doStartTag() throws JspException
{
try {
pageContext.getOut().println("Hello");
} catch (IOException e) {
}
return SKIP_BODY;
}
}
Create the desired method at the top of the page and copy it from page to page
<%!
public static String say() {
return "Hello";
}
%>
Create an "include file" (say hello.inc), place the method noted above in it, and include it at the
top of each JSP page
<%@ include file="hello.inc" %>
In a Servlet
String path = getServletContext.getRealPath("/");
NOTE: Pragma: nocache prevents caching only when used over a secure connection, Expires:
1 should do the job over unsecure conection.
See also this HowTo and this one.
10.30 Launch an external program, capture its output and display it in a JSPTag(s): Servlet/JSP
err.printStackTrace();
}
out.println("</pre>");
%>
The next example calls a VBSCRIPT to list the Windows groups for a specific user.
the VBS (listmembergroups.vbs)
Option Explicit
Dim objNetwork, strDomain, strUser, objUser, objGroup, strGroupMemberships
Set objUser = GetObject("WinNT://ssqvie/" &WScript.Arguments.item(0))
wscript.echo "<H2>" &objUser.Fullname &"</H2>"
For Each objGroup In objUser.Groups
wscript.echo objGroup.Name
Next
As always, special care must be taken if there is a risk that the called program can write
something into stderr (then the process will hang forever).
10.30 Launch an external program, capture its output and display it in a JSPTag(s): Servlet/JSP
ref :
http://download.oracle.com/docs/cd/E11035_01/wls100/programming/classloading.html#wp1097187
pagecheckseconds sets the interval, in seconds, at which WLS checks to see if JSP files have
changed and need recompiling. Dependencies are also checked and recursively reloaded if
changed.
If set to 0, pages are checked on every request. If set to 1, page checking and recompiling is
disabled.
java.sql.*;
java.util.Properties;
javax.naming.InitialContext;
javax.rmi.PortableRemoteObject;
javax.sql.DataSource;
The next example, make a remote call to an EJB host in a Weblogic server. You need wlclient
and the EJB client jars in the classpath.
import
import
import
import
java.util.Properties;
javax.naming.InitialContext;
javax.rmi.PortableRemoteObject;
com.company.common.myejb.*;
}
}
11 Language
11.1 javalanguage
Web
11 Language
The output
>java LoadingFromWhere
LoadingFromWhere is loaded from file:/C:/temp/
MyClass is loaded from file:/C:/temp/
The output
> java FromWhere
This class (FromWhere) is located at : file:/C:/temp/
11.6 JDK1.4
public class MyTest {
public static void main(String args[]) {
new MyTest().doit();
}
public void doit() {
System.out.println
(new Exception().getStackTrace()[0].getMethodName());
}
}
The output
doit
11.7 JDK1.5
While the above snippet is not bad, it is expensive since we need to create an Exception.
With JDK1.5, a new technique is available.
public class Test {
public static void main(String args[]) {
trace(Thread.currentThread().getStackTrace());
new Test().doit();
trace(Thread.currentThread().getStackTrace());
}
public void doit() {
trace(Thread.currentThread().getStackTrace());
doitagain();
}
public void doitagain() {
trace(Thread.currentThread().getStackTrace());
}
public static void trace(StackTraceElement e[]) {
boolean doNext = false;
for (StackTraceElement s : e) {
if (doNext) {
System.out.println(s.getMethodName());
return;
}
doNext = s.getMethodName().equals("getStackTrace");
}
}
}
main
doit
doitagain
main
/* Output examples:
Class : Class1
Method: class1Method2
### Class 1, Method2 ###
Class : java.util.Date
Method: toString
Sat Aug 11 13:18:39 EDT 2007
Class : java.util.Date
Method: getTime
1186852732140
*/
}
Another example, but this time we are passing a parameter to the constructor and calling a method
dynamically.
public class Test {
public static void main(String args[]) {
try {
String name = "java.lang.String";
String methodName = "toLowerCase";
// get String Class
Class cl = Class.forName(name);
// get the constructor with one parameter
java.lang.reflect.Constructor constructor =
cl.getConstructor
(new Class[] {String.class});
// create an instance
Object invoker =
constructor.newInstance
(new Object[]{"REAL'S HOWTO"});
// the method has no argument
Class arguments[] = new Class[] { };
// get the method
java.lang.reflect.Method objMethod =
cl.getMethod(methodName, arguments);
// convert "REAL'S HOWTO" to "real's howto"
Object result =
objMethod.invoke
(invoker, (Object[])arguments);
System.out.println(result);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
{
firstValue = 3.1416;
secondValue = 42;
thirdValue = "Hello world";
2
3
howto
*/
}
javax.tools.JavaCompiler;
javax.tools.StandardJavaFileManager;
javax.tools.StandardLocation;
javax.tools.ToolProvider;
null,
null,
null,
fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile)))
.call();
fileManager.close();
The tools.jar (located in the [JDK1.6]\lib) must be in the classpath during runtime, it is not included
with the JRE.
You can compile many sources in one shot.
The directory used to store the resulting class must be in the classpath if you want to use
compiled class. In Eclipse, you add the directory in the Build Path (as an External Class Folder).
try {
FileWriter aWriter = new FileWriter(todaySource, true);
aWriter.write("public class "+ todayClass + "{");
aWriter.write(" public void doit() {");
aWriter.write(" System.out.println(\""+todayMillis+"\");");
aWriter.write(" }}\n");
aWriter.flush();
aWriter.close();
}
catch(Exception e){
e.printStackTrace();
}
}
public boolean compileIt() {
String [] source = { new String(todaySource)};
ByteArrayOutputStream baos= new ByteArrayOutputStream();
new sun.tools.javac.Main(baos,source[0]).compile(source);
// if using JDK >= 1.3 then use
//
public static int com.sun.tools.javac.Main.compile(source);
return (baos.toString().indexOf("error")==1);
}
public void runIt() {
try {
Class params[] = {};
Object paramsObj[] = {};
Class thisClass = Class.forName(todayClass);
Object iClass = thisClass.newInstance();
Method thisMethod = thisClass.getDeclaredMethod("doit", params);
thisMethod.invoke(iClass, paramsObj);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
Launch many programs using Thread and use join() to wait for the completion.
[Program2.java]
public class Program2 {
public static void main(String arg[]) {
System.out.println("Hello from Program2");
System.out.println("Hello from Program2");
System.out.println("Hello from Program2");
System.out.println("Hello from Program2");
}
}
[Program1a.java]
public class Program1a {
public static void main(String arg[]) throws Exception{
System.out.println("Hello from Program1a");
Thread t1 = new Thread(){
public void run() {
Program2.main(new String[]{});}
};
t1.start();
t1.join();
System.out.println("Hello from Program1a");
}
}
The output :
C:\>java Program1a
Hello from Program1a
Hello from Program2
Hello from Program2
Hello from Program2
Hello from Program2
Hello from Program1a
class InnerClass {
public void sayHello() {
TestIt.this.enclosingClassMethod();
}
}
}
or
public class TestIt {
TestIt testItClass = this;
public static void main(String a[]){
new TestIt().doit();
/*
output :
Hello world!
*/
}
public void doit() {
new InnerClass().sayHello();
}
public void enclosingClassMethod(){
System.out.println("Hello world!");
}
class InnerClass {
public void sayHello() {
testItClass.enclosingClassMethod();
}
}
}
{
integer SUCCESS = 1;
integer FAILURE = 1;
integer NOTFOUND = 0;
Since the members of the class are defined as "static", there is no need to instantiate the class.
To use a constant, simply use CONSTANT.[constant name]
if (myMethod()==CONSTANT.SUCCESS) {
...;
}
else {
...;
}
Via an interface
This technique can be used if the constants are not really global but especially designed to be
used in a specific application for example. An applicationlevel class needs to implement the
interface to be able to see the constant definitions.
public interface APPCONSTANT
public static final String
public static final String
public static final String
}
{
APPNAME = "The Super APP";
APPVERSION = "version 1.0";
DBDRIVER = "oracle.jdbc.driver.OracleDriver";
NOTE : This is not considered as good practice (depending on who you are talking to!) to use an
interface this way.
NOTE: By convention, constant name are always in CAPITALS.
JDK1.5
JDK1.5 import statement can be used to import only static member from a class.
11.19 Use globally defined constantsTag(s): Language
Many standard Java objects already implements the Serializable interface so there is almost
nothing to do.
In the following snippet, we use a Vector to simulate a Queue.
First the Queue state is saved to a file.
Then rename main to main_serialize and main_reload to main and compile. Now the snippet read
the file to reload the Queue from the data previously saved.
import java.util.Vector;
import java.io.*;
public class Queue extends Vector {
/*
** FIFO
*/
Queue() {
super();
}
void put(Object o) {
addElement(o);
}
Object get() {
if (isEmpty()) return null;
Object o = firstElement();
removeElement(o);
return o;
}
Object peek() {
if (isEmpty()) return null;
return firstElement();
}
public static void main(String args[]) {
Queue theQueue;
theQueue = new Queue();
theQueue.put("element 1");
theQueue.put("element 2");
theQueue.put("element 3");
theQueue.put("element 4");
System.out.println(theQueue.toString());
// serialize the Queue
System.out.println("serializing theQueue");
try {
FileOutputStream fout = new FileOutputStream("thequeue.dat");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(theQueue);
oos.close();
}
catch (Exception e) { e.printStackTrace(); }
}
public static void main_load(String args[]) {
Queue theQueue;
theQueue = new Queue();
// unserialize the Queue
System.out.println("unserializing theQueue");
try {
FileInputStream fin = new FileInputStream("thequeue.dat");
ObjectInputStream ois = new ObjectInputStream(fin);
theQueue = (Queue) ois.readObject();
ois.close();
}
catch (Exception e) { e.printStackTrace(); }
System.out.println(theQueue.toString());
}
}
In your source, when you need some debugging codes, you included them in a if statement like
if (Debug.RELEASE) {
System.out.println("The value of i is " + i);
}
During compilation, since Debug.RELEASE is always true, the code will be present. In the
production environment, the Debug class looks like this:
11.21 Serialize an Object over a socketTag(s): Language
When compiling in that environment, the debugging code will be absent from the class file since
Debug.release is always false.
Another way is to simply close the out stream.
(System.out.println() will be present in your class but the output is disabled).
To use it
OnlyOne myOne = OnlyOne.getInstance();
To use it :
public class ClassUtilsTest {
String hello = "world";
int i = 42;
public static void main(String ... args) {
System.out.println(ClassUtils.toString(new ClassUtilsTest()));
// ClassUtilsTest[hello=world, i=42]
}
}
System.out.println(d);
d.setTime(1000);
System.out.println(d);
System.out.println(mydata.getDate());
// Sat Apr 19 23:17:43 EDT 2003
// Wed Dec 31 19:00:01 EST 1969
// Wed Dec 31 19:00:01 EST 1969
which is no good
}
}
Even if aDate is declared as private, it is possible to modify because a Date object is mutable and
we have a reference to it. The solution is to return a copy of aDate, so even if you have reference
to it, any modification will be done on the copy, not the original.
import java.util.Date;
class MyData {
private Date aDate;
MyData() {
aDate = new Date();
}
public Date getDate() {
return (Date)aDate.clone();
}
public void setdate(Date d) {
aDate = d;
}
}
public class DemoClone {
public static void main(String args[]) {
MyData mydata = new MyData();
Date d = mydata.getDate();
System.out.println(d);
d.setTime(1000);
System.out.println(d);
System.out.println(mydata.getDate());
// Sat Apr 19 23:17:43 EDT 2003
// Wed Dec 31 19:00:01 EST 1969
// Sat Apr 19 23:17:43 EDT 2003
which is good
}
}
j += 1;
}
}
System.out.println(j); // output 5
}
}
This can be useful if you want to format the StackTrace before showing it to the user.
java.lang.reflect.Field;
java.lang.reflect.Modifier;
java.util.HashMap;
java.util.Map;
*/
public static void sort(Object[] a, Comparer comparer) {
sort(a, null, 0, a.length 1, true, comparer);
}
/*
** Sort a and b, using a as the reference
*/
public static void sort(Object[] a, Object[] b,
int from, int to, boolean ascending, Comparer comparer) {
// No sort
if (a == null || a.length < 2) return;
// sort using Quicksort
int i = from, j = to;
Object center = a[ (from + to) / 2 ];
do {
if (ascending) {
while( (i < to) &(comparer.compare( center, a[i]) >
i++;
while( (j > from) &(comparer.compare(center, a[j]) <
j;
}
else {
// Decending sort
while( (i < to) &(comparer.compare( center, a[i]) <
i++;
while( (j > from) &(comparer.compare(center, a[j]) >
j;
}
if (i < j) {
// Swap elements
Object temp = a[i]; a[i] = a[j]; a[j] = temp;
// Swap in b array if needed
if (b != null) {
temp = b[i]; b[i] = b[j]; b[j] = temp;
}
}
if (i <= j) { i++; j; }
} while(i <= j);
// Sort the rest
if (from < j) sort(a, b, from, j, ascending, comparer);
if (i < to) sort(a, b, i, to, ascending, comparer);
}
0) )
0) )
0) )
0) )
[testArraySorter.java]
public class testArraySorter {
public static final ASCIIComparer asciiComparer = new ASCIIComparer();
public static void main(String args[]) {
if (args.length == 0)
JDK1.4 casesensitive
String[] myArray = new String[] {"foo","bar","baz"};
java.util.Arrays.sort(myArray);
caseinsensitive
String[] myArray = new String[] {"foo","Bar","baz"};
java.util.Arrays.sort(myArray, java.text.Collator.getInstance());
",")
",")
Arrays cannot be resized dynamically. If you want a dynamic data structure with random access,
you use a Collection (Map, ArrayList,...).
If you need to expand, you can use System.arraycopy() method to copy the content of an array to
another one.
import java.lang.reflect.Array;
public class ArrayUtils {
public static void main (String arg[]) {
String s[] = new String[20];
System.out.println("The s array length is " + s.length); // 20
s = (String[])ArrayUtils.expand(s);
System.out.println("The s array length is " + s.length); // 30
int i[] = {1 ,2 ,3, 4};
System.out.println("The i array length is " + i.length); // 4
i = (int[])ArrayUtils.expand(i);
System.out.println("The i array length is " + i.length); // 6
}
public static Object expand(Object a) {
Class cl = a.getClass();
if (!cl.isArray()) return null;
int length = Array.getLength(a);
int newLength = length + (length / 2); // 50% more
Class componentType = a.getClass().getComponentType();
Object newArray = Array.newInstance(componentType, newLength);
System.arraycopy(a, 0, newArray, 0, length);
return newArray;
}
}
But a better way is to use a Vector or an ArrayList. ArrayList is roughly equivalent to Vector,
except that it is unsynchronized.
import java.util.ArrayList;
public class ArrayListDemo {
public static void main (String arg[]) {
ArrayListDemo x = new ArrayListDemo();
x.doit1();
x.doit2();
}
public void doit1() {
// single dimension
ArrayList list = new ArrayList();
list.add("a");
list.add("b");
int size = list.size(); // 2
System.out.println("Array 1 " +list.get(0);
}
public void doit2() {
// multi dimensions
ArrayList list = new ArrayList();
ArrayList l1 = new ArrayList();
l1.add("a");
ArrayList l2 = new ArrayList();
// a
l2.add("b");
ArrayList l3 = new ArrayList();
l3.add("c");
list.add(l1);
list.add(l2);
list.add(l3);
int size1 = list.size(); // 3
int size2 = ((ArrayList)list.get(0)).size();
System.out.println("Array 2 "
+ ((ArrayList)list.get(1)).get(0));
// b
}
// 1
JDK1.5
java.utils.Arrays provides new ways to dump the content of an array. It's even possible to dump
mutidimensional arrays.
public class Test {
public static void main(String args[]) {
String s[] = {"a", "b", "c", "d"};
double d [][]= {
{0.50, 0.70, 0.40, 0.60},
{0.50, 1.10, 0.50, 0.80}
};
System.out.println(java.util.Arrays.toString(s));
System.out.println(java.util.Arrays.deepToString(d));
// output
// [a, b, c, d]
// [[0.5, 0.7, 0.4, 0.6], [0.5, 1.1, 0.5, 0.8]]
}
}
You can also use the new shorthand notation to iterate through an array :
public class Test {
public static void main(String args[]) {
String s[] = {"a", "b", "c", "d"};
for (String element : s)
System.out.println(element);
}
}
import java.util.*;
public class HashtableTest {
static String[] array1 = {"C","B","A"};
static String[] array2 = {"1","2","3"};
public static void main(String args[]) {
Hashtable h = new Hashtable();
h.put(array1[0], array2[0]);
h.put(array1[1], array2[1]);
h.put(array1[2], array2[2]);
// unsorted keys output
Iterator it = h.keySet().iterator();
while (it.hasNext()) {
String element = (String)it.next();
System.out.println(element + " " + (String)h.get(element));
}
System.out.println("============");
// sorted keys output thanks to T. GUIRADO for the tip!
Vector v = new Vector(h.keySet());
Collections.sort(v);
it = v.iterator();
while (it.hasNext()) {
String element = (String)it.next();
System.out.println( element + " " + (String)h.get(element));
}
/*
output :
A 3
C 1
B 2
============
A 3
B 2
C 1
*/
}
}
NOTE : When possible always use an HashMap instead of an Hashtable. Since Hashtable
methods are synchronized they are slower than those in HashMap.
See this Howto to sort an HashMap.
See this Howto to sort a Properties.
Iterator<String> it = data.iterator();
while (it.hasNext()) {
String s = it.next();
System.out.println(s);
}
}
}
When compiling the above class, the compiler (jdk1.5) emits the following warnings :
C:\ArrayListGeneric.java:21:
warning: [unchecked] unchecked call to add(E) as a member of the raw type
java.util.ArrayList
data.add("hello");
^
C:\ArrayListGeneric.java:22:
warning: [unchecked] unchecked call to add(E) as a member of the raw type
java.util.ArrayList
data.add("world");
^
C:\ArrayListGeneric.java:25: warning: [unchecked] unchecked conversion
found
: java.util.Iterator
required: java.util.Iterator
Iterator it = data.iterator();
^
3 WARNINGS
Since there are only warnings, your class is ready to run but ... it's not bad idea to eliminate the
warnings in production code.
Simply add the expected type (between < and >) after the class.
import java.util.*;
public class ArrayListGeneric {
public static void main(String[] args) {
ArrayList<String> data = new ArrayList<String>();
data.add("hello");
data.add("world");
Iterator<String> it = data.iterator();
while (it.hasNext()) {
String s = it.next();
11.44 Eliminate "[unchecked] unchecked call ..." compiler warning Tag(s): Language
System.out.println(s);
}
}
}
In JDK 1.6, it will be possible to insert a special annotation to suppress this kind of warning,
something like :
import java.util.*;
public class ArrayListGeneric {
@SuppressWarnings("unchecked")
public static void main(String[] args) {
ArrayList data = new ArrayList();
data.add("hello");
data.add("world");
Iterator it = data.iterator();
while (it.hasNext()) {
String s = it.next();
System.out.println(s);
}
}
}
11.44 Eliminate "[unchecked] unchecked call ..." compiler warning Tag(s): Language
12 ANT
When compiling with ANT, you see the following output :
[javac] Note: Some input files use unchecked or unsafe operations.
[javac] Note: Recompile with Xlint:unchecked for details.
but it's not easy to see the details of those unsafe operations. To add the Xlint, you need to use
the compilerarg tag in the javac task definition.
Something like
<target name="compile" description="Compile code">
<mkdir dir="${bin}"/>
<mkdir dir="${lib}"/>
<javac srcdir="${src}" destdir="${bin}"
includeAntRuntime="no"
classpathref="lib.path"
debug="${compile.debug}">
<compilerarg value="Xlint:unchecked"/>
</javac>
</target>
12 ANT
then we need a class to implement the Comparable interface. It's in there where we put the logic
behind the sorting.
import java.util.Comparator;
class PersonComparator implements Comparator{
public int compare(Object obj1, Object obj2) {
Person emp1 = (Person) obj1;
Person emp2 = (Person) obj2;
int nameComp = emp1.getLastName().compareTo(emp2.getLastName());
return ((nameComp == 0) ?
emp1.getFirstName().compareTo(emp2.getFirstName()) :
nameComp);
}
}
To test it :
import
import
import
import
import
java.util.ArrayList;
java.util.Arrays;
java.util.Collections;
java.util.List;
java.util.Iterator;
12 ANT
}
System.out.println("BEFORE:");
Iterator iter1 = names.iterator();
while (iter1.hasNext()) {
System.out.println(iter1.next());
}
// now sort everything
Collections.sort(names, new PersonComparator());
System.out.println("AFTER:");
Iterator iter2 = names.iterator();
while (iter2.hasNext()) {
System.out.println(iter2.next());
}
/*
output :
BEFORE:
[ firstname=Real,lastname=Smith]
[ firstname=Vincent,lastname=Smith]
[ firstname=Nathalie,lastname=Smith]
[ firstname=Christine,lastname=Smith]
[ firstname=Bart,lastname=Simpsons]
[ firstname=Lisa,lastname=Simpsons]
[ firstname=Marge,lastname=Simpsons]
[ firstname=Homer,lastname=Simpsons]
[ firstname=Maggie,lastname=Simpsons]
AFTER:
[ firstname=Bart,lastname=Simpsons]
[ firstname=Homer,lastname=Simpsons]
[ firstname=Lisa,lastname=Simpsons]
[ firstname=Maggie,lastname=Simpsons]
[ firstname=Marge,lastname=Simpsons]
[ firstname=Christine,lastname=Smith]
[ firstname=Nathalie,lastname=Smith]
[ firstname=Real,lastname=Smith]
[ firstname=Vincent,lastname=Smith]
*/
}
}
import java.util.*;
import java.io.*;
class TestCollectionPerformance {
private static String TEXT_BOOK_NAME = "warandpeace.txt";
public static void main(String[] args) {
try {
String text = readText();
// Read text into RAM
countDuplicateWords(text, new HashSet<String>());
countDuplicateWords(text, new TreeSet<String>());
countDuplicateWords(text, new ArrayList<String>());
countDuplicateWords(text, new LinkedList<String>());
}
catch (Throwable t) {
System.out.println(t.toString());
}
}
private static String readText() throws Throwable {
BufferedReader reader =
new BufferedReader(new FileReader(TEXT_BOOK_NAME));
String line = null;
StringBuffer text = new StringBuffer();
while ((line = reader.readLine()) != null) {
text.append(line + " ");
}
return text.toString();
}
private static void countDuplicateWords(String text,
Collection<String> listOfWords) {
int numDuplicatedWords = 0;
long startTime = System.currentTimeMillis();
for (StringTokenizer i = new StringTokenizer(text);
i.hasMoreElements();) {
String word = i.nextToken();
if (listOfWords.contains(word)) {
numDuplicatedWords++;
}
else {
listOfWords.add(word);
}
}
long endTime = System.currentTimeMillis();
System.out.println(numDuplicatedWords + " duplicated words. " +
"Using " + listOfWords.getClass().getName() +
", time = " + (endTime startTime) + "ms.");
}
}
Result :
522396
522396
522396
522396
duplicated
duplicated
duplicated
duplicated
words.
words.
words.
words.
Using
Using
Using
Using
The ArrayList provides a collection backed by an array. It provides quick indexed access to its
elements, and works best when elements are only added and removed at the end. To make this
happen, ArrayList performs an internal move operation when an element is added or removed.
The LinkedList is best when add and remove operations happen anywhere, not only at the end.
LinkList doesn't do an internal move operation for an element insert or remove, it just manipulates
reference pointers. But LinkedList's added flexibility comes at an added cost it results in much
slower indexed operations.
ref : Sun's Java tech Tips Feb2003
java.util.HashMap;
java.util.Iterator;
java.util.Map;
java.util.SortedSet;
java.util.TreeSet;
...
Map<String,java.io.File> theSimpsons = new HashMap<String,java.io.File>();
theSimpsons.put("Bart", new java.io.File("Bart.jpg"));
theSimpsons.put("Lisa", new java.io.File("Lisa.jpg"));
theSimpsons.put("Marge", new java.io.File("Marge.jpg"));
theSimpsons.put("Barney", new java.io.File("Barney.jpg"));
theSimpsons.put("Homer", new java.io.File("Homer.jpg"));
theSimpsons.put("Maggie", new java.io.File("Maggie.jpg"));
SortedSet<String> sortedset= new TreeSet<String>(theSimpsons.keySet());
Iterator<String> it = sortedset.iterator();
while (it.hasNext()) {
System.out.println (it.next());
}
...
java.util.ArrayList;
java.util.HashMap;
java.util.List;
java.util.Map;
}
return list;
}
[Java 1.4]
import
import
import
import
import
import
java.util.ArrayList;
java.util.HashMap;
java.util.Iterator;
java.util.List;
java.util.Map;
java.util.Set;
The trick is to use an Iterator and remove the item with Iterator.remove()
import java.util.ArrayList;
import java.util.Iterator;
public class Simple {
public static void main(String args[]) {
ArrayList<String> list = new ArrayList<String>();
list.add("Bart");
list.add("Lisa");
list.add("Marge");
list.add("Barney");
list.add("Homer");
list.add("Maggie");
for (Iterator<String> iter = list.iterator(); iter.hasNext();) {
String s = iter.next();
if (s.equals("Barney")) {
iter.remove();
}
else {
System.out.println(s);
}
}
for(String s: list)
{
System.out.println(s);
}
}
/*
output :
Bart
Lisa
Marge
Homer
Maggie
Bart
Lisa
Marge
Homer
Maggie
*/
}
Submitted by bdobby2000
protected static int countDistinctElements
( Vector source, int position, int count )
throws IllegalArgumentException , IndexOutOfBoundsException {
List list = source.subList(position, position+count);
Set set = new HashSet();
set.addAll(list);
return set.size();
}
12.7.1 List
public class DumpCollection {
public static void main(String[] args) {
java.util.ArrayList<String> theSimpsons = new
java.util.ArrayList<String>();
theSimpsons.add("Bart");
theSimpsons.add("Lisa");
theSimpsons.add("Marge");
theSimpsons.add("Barney");
theSimpsons.add("Homer");
theSimpsons.add("Maggie");
for (String character: theSimpsons) {
System.out.println(character);
}
}
}
12.7.2 Map
import java.util.*;
import java.io.*;
public class DumpCollection {
public static void main(String[] args) {
Map<String,File> theSimpsons = new HashMap<String,File>();
theSimpsons.put("Bart", new File("Bart.jpg"));
theSimpsons.put("Lisa", new File("Lisa.jpg"));
theSimpsons.put("Marge", new File("Marge.jpg"));
theSimpsons.put("Barney", new File("Barney.jpg"));
theSimpsons.put("Homer", new File("Homer.jpg"));
theSimpsons.put("Maggie", new File("Maggie.jpg"));
dump(theSimpsons);
}
public static void dump(Map<?,?> map) {
for (Map.Entry<?,?> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
}
/*
output :
Bart: Bart.jpg
Lisa: Lisa.jpg
Maggie: Maggie.jpg
Homer: Homer.jpg
Barney: Barney.jpg
Marge: Marge.jpg
*/
12.7.2 Map
import java.util.List;
import java.util.ArrayList;
public class InitCollections {
static ArrayList<String> list = new ArrayList<String>() {{
add("Bart");
add("Lisa");
add("Marge");
add("Barney");
12.7.2 Map
add("Homer");
add("Maggie");
}};
public static void main(String args[]) {
dump(list);
}
public static void dump(List<String> list) {
for (String s:list) {
System.out.println(s);
}
}
}
Use Arrays.asList()
import java.util.List;
import java.util.Arrays;
public class InitCollections {
public static void main(String args[]) {
List list = Arrays.asList("Bart", "Lisa", "Marge", "Homer", "Maggie");
dump(list);
}
public static void dump(List<String> list) {
for (String s:list) {
System.out.println(s);
}
}
}
then
package com.rgagnon.howto;
import static com.rgagnon.howto.CollectionUtils.List;
import java.util.List;
public class InitCollections {
public static void main(String args[]) {
List<String> list = List("Bart", "Lisa", "Marge", "Homer", "Maggie");
dump(list);
}
12.7.2 Map
From there a more versatile method is developped to accept a list of arrays to be merged into
one.
public class CollectionUtils {
public static String[] join(String [] ... parms) {
// calculate size of target array
int size = 0;
for (String[] array : parms) {
size += array.length;
}
String[] result = new String[size];
int j = 0;
for (String[] array : parms) {
for (String s : array) {
result[j++] = s;
}
}
return result;
}
We put in an array an instance of each implementation. Then we are able to run the desired
function by using the array index.
public class TestCommand {
public static void main(String[] args) {
Command[] commands = new Command[3];
commands[0] = new ACommandImpl();
commands[1] = new BCommandImpl();
commands[2] = new CCommandImpl();
// no error checking!
for (;;) {
String s = javax.swing.JOptionPane.showInputDialog
("Command no ? (0,1 or 2)", new Integer(0));
if (s == null) break;
commands[Integer.parseInt(s)].exec();
}
}
}
},
C() {
public void exec() {
System.out.println("This is Command type C");
}
}
}
then
public class TestCommand {
public static void main(String[] args) {
// no error checking!
for (;;) {
String s = javax.swing.JOptionPane.showInputDialog
("Command ID ? (A,B or C)", "A");
if (s == null) break;
Functions function = Functions.valueOf(s.toUpperCase());
function.exec();
}
}
}
NOTE : Using this technique, it's possible to simulate "switch ... case" based on a string value.
Order is preserved
import
import
import
import
import
java.util.HashSet;
java.util.ArrayList;
java.util.Iterator;
java.util.List;
java.util.Set;
Properties to Map
public static Map<String, String> propertiesToMap(Properties props) {
HashMap<String, String> hm = new HashMap<String,String>();
Enumeration<Object> e = props.keys();
while (e.hasMoreElements()) {
String s = (String)e.nextElement();
hm.put(s, props.getProperty(s));
}
return hm;
}
[JAVA code]
import java.util.*;
import java.io.*;
class ReadProps {
public static void main(String args[]) {
ReadProps props = new ReadProps();
props.doit();
}
public void doit() {
try{
Properties p = new Properties();
p.load(new FileInputStream("user.props"));
System.out.println("user = " + p.getProperty("DBuser"));
System.out.println("password = " + p.getProperty("DBpassword"));
System.out.println("location = " + p.getProperty("DBlocation"));
p.list(System.out);
}
catch (Exception e) {
System.out.println(e);
}
}
}
Since the Properties class extends the Hashtable, we can manipulate the Properties through the
get and put methods. The modified data can be saved back to a file with the save method. This
can be useful to store user preferences for example. Note that the order is not preserved.
import java.util.*;
import java.io.*;
class WriteProps {
public static void main(String args[]) {
WriteProps props = new WriteProps();
props.doit();
}
public void doit() {
try{
Properties p = new Properties();
p.load(new FileInputStream("user.props"));
p.list(System.out);
// new Property
p.put("today", new Date().toString());
// modify a Property
p.put("DBpassword","foo");
FileOutputStream out = new FileOutputStream("user.props");
p.save(out, "/* properties updated */");
}
catch (Exception e) {
System.out.println(e);
}
}
}
This ok with an application but you can't do it from an Applet since you can't write directly on the
server without some kind of a serverside process.
To read a Properties file via an Applet, load the Properties files this way :
12.14 Use an INI file (properties)Tag(s): Language
See also this HowTo, this one and finally this one too!
java.util.Properties;
java.io.File;
java.io.IOException;
java.io.FileInputStream;
java.net.URL;
Load from the startup directory of your application (ex. directory containing the jar)
[Hello.java]
public class Hello {
public static void main(String args[]) throws Exception{
Hello h = new Hello();
h.doit();
}
public void doit() throws Exception{
// properties in the classpath
java.util.Properties props = new java.util.Properties();
java.net.URL url = ClassLoader.getSystemResource("props.properties");
props.load(url.openStream());
System.out.println("prop1 :\n " + props.get("prop1"));
System.out.println("prop2 :\n " + props.get("prop2"));
}
}
The output
>java Hello
prop1 :
first line of prop1 second line of prop1third line of prop1
prop2 :
first line of prop2
second line of prop2
third line of prop2
p.list(System.out);
/*
output :
listing properties
today=Thu Aug 09 22:45:11 EDT 2007
user=Bob
*/
}
catch (Exception e) {
e.printStackTrace();
}
}
}
p.put(REALKEY, "barbar");
// read back from HKEY_LOCAL_MACHINE
System.out.println(p);
System.out.println(p.get(REALKEY, "HKLM houston we have a problem"));
}
}
import
import
import
import
java.util.Collections;
java.util.Enumeration;
java.util.Properties;
java.util.Vector;
13 Networking
13.1 javanet
JDK1.5 or less
One way, without using JNI, is to launch an external utility and interpret the output.
In Windows, "arp a" will return the MAC addresses of all adapters that have TCP/IP bound to them
and have recently (default < 5 mins) resolved an IP address. Otherwise, in NT/2K/XP, "ipconfig /all"
will return all relevant network info for IPbound adapters, including the MAC address (displayed as
"physical address").
In Linux, "ifconfig" does something similar.
Example for Windows
import
import
import
import
java.net.InetAddress;
java.io.InputStream;
java.io.BufferedInputStream;
java.io.IOException;
13 Networking
import java.text.ParseException;
import java.util.StringTokenizer;
//
// inspired by
//
http://forum.java.sun.com/thread.jspa?messageID=902023
//
public final class NetworkUtils {
private final static int MACADDR_LENGTH = 17;
private final static String WIN_OSNAME = "Windows";
private final static String WIN_MACADDR_REG_EXP =
"^[09AF]{2}[09AF]{2}[09AF]{2}[09AF]{2}[09AF]{2}[09AF]{2}$";
private final static String WIN_MACADDR_EXEC = "ipconfig /all";
13 Networking
13 Networking
The output
> java NetInfo
realone/209.142.72.112
realone
209.142.72.112
java.net.*;
java.util.*;
java.io.*;
java.nio.*;
ip.getInterfaces();
}
}
The output
> java IPAdress
Net interface: lo
IP address: /127.0.0.1
Net interface: eth0
IP address: /194.168.0.1
Net interface: eth1
IP address: /164.254.147.20
Net interface: ppp0
IP address: /64.68.115.69
Windows
A "lowtech" way to get the computer name (can be useful if there is no network card) is to use the
environment variable COMPUTERNAME (at least on modern Windows installation).
[JDK1.4 or less] Pass it to your JVM as java Dcomputername="%COMPUTERNAME%" ... and
then get the value with System.getProperty("computername")
[JDK1.5 or more] You can extract environment variable directly with
System.getenv("COMPUTERNAME")
To get the IP of a client from the server side, see this HowTo.
sun.net.inetaddr.negative.ttl
This is a sun private system property which corresponds to networkaddress.cache.negative.tt
It takes the same value and has the same meaning, but can be set as a commandline option.
However, the preferred way is to use the security property mentioned above.
So you can disable caching by adding Dsun.net.inetaddr.ttl=0 on the command line starting the
JVM. But you can't set the value of networkaddress.cache.ttl on the command line. You can set the
required value in the java.security file located in %JRE%\lib\security
networkaddress.cache.ttl=60
networkaddress.cache.negative.ttl=10
This change in the default behavior is also implemented by security updates and service packs that
were released after the 832894 security update.
By default, this new default behavior for handling user information in HTTP or HTTPS URLs applies
only to Windows Explorer and Internet Explorer. To use this new behavior in other programs that
host the Web browser control, create a DWORD value named SampleApp.exe, where
SampleApp.exe is the name of the executable file that runs the program. Set the DWORD value's
value data to 1 in one of the following registry keys.
For all users of the program, set the value in the following registry key:
HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer\
Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE
For the current user of the program only, set the value in the following registry key:
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\
Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE
To disable the new default behavior in Windows Explorer and Internet Explorer, create
iexplore.exe and explorer.exe DWORD values in one of the following registry keys and set their
value data to 0.
For all users of the program, set the value in the following registry key:
HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer\
Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE
For the current user of the program only, set the value in the following registry key:
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\
Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE
ref Microsoft Article ID : 834489
13.10 MiGBase64
java.util.Hashtable;
javax.naming.*;
javax.naming.directory.*;
The output is
>java MXLookup rgagnon.com realhowto.com
rgagnon.com has 1 mail servers
realhowto.com : DNS name not found [response code 3]
Now, imagine that you connect to isp.com and try to send a message. The mail server at isp.com
doesn't have the actual user list to know which addresses are valid, it just accepts everything and
relies on abc.com to sort out the bounces.
If these are not checked in the proper order, there will be no errors for invalid addresses.
Yahoo appears to use a store and forward mechanism to its own internal servers, thus
conclusively verifying a yahoo address is not possible. I suspect that hotmail is the same.
It is not possible to verify an address on a domain that uses a catchall account as the catch
account will receive the mail (it does, however, mean that someone will at least SEE the
message).
import
import
import
import
import
java.io.*;
java.net.*;
java.util.*;
javax.naming.*;
javax.naming.directory.*;
Now, do the SMTP validation, try each mail exchanger until we get
a positive acceptance. It *MAY* be possible for one MX to allow
a message [store and forwarder for example] and another [like
the actual mail server] to reject it. This is why we REALLY ought
to take the preference into account.
sender address
FROM: <tim@orbaker.com>" );
);
) throw new Exception( "Sender rejected" );
The "A" attribute returns only an address list, so f.length is always 1. I used something like:
boolean hasMX = "MX".equals(attr.getID());
and later
if (hasMX)
{
mailhost = f[1];
}
else
{
mailhost = f[0];
}
java.io.*;
java.net.*;
java.util.*;
javax.naming.*;
javax.naming.directory.*;
env.put("java.naming.factory.initial",
"com.sun.jndi.dns.DnsContextFactory");
DirContext ictx = new InitialDirContext( env );
Attributes attrs = ictx.getAttributes
( hostName, new String[] { "MX" });
Attribute attr = attrs.get( "MX" );
// if we don't have an MX record, try the machine itself
if (( attr == null ) || ( attr.size() == 0 )) {
attrs = ictx.getAttributes( hostName, new String[] { "A" });
attr = attrs.get( "A" );
if( attr == null )
throw new NamingException
( "No match for name '" + hostName + "'" );
}
// Huzzah! we have machines to try. Return them as an array list
// NOTE: We SHOULD take the preference into account to be absolutely
//
correct. This is left as an exercise for anyone who cares.
ArrayList res = new ArrayList();
NamingEnumeration en = attr.getAll();
while ( en.hasMore() ) {
String mailhost;
String x = (String) en.next();
String f[] = x.split( " " );
// THE fix *************
if (f.length == 1)
mailhost = f[0];
else if ( f[1].endsWith( "." ) )
mailhost = f[1].substring( 0, (f[1].length() 1));
else
mailhost = f[1];
// THE fix *************
res.add( mailhost );
}
return res;
}
public static boolean isAddressValid( String address ) {
// Find the separator for the domain name
int pos = address.indexOf( '@' );
// If the address does not contain an '@', it's not valid
if ( pos == 1 ) return false;
// Isolate the domain/machine name and get a list of mail exchangers
String domain = address.substring( ++pos );
ArrayList mxList = null;
try {
mxList = getMX( domain );
}
catch (NamingException ex) {
return false;
}
// Just because we can send mail to the domain, doesn't mean that the
// address is valid, but if we can't, it's a sure sign that it isn't
if ( mxList.size() == 0 ) return false;
//
//
//
//
Now, do the SMTP validation, try each mail exchanger until we get
a positive acceptance. It *MAY* be possible for one MX to allow
a message [store and forwarder for example] and another [like
the actual mail server] to reject it. This is why we REALLY ought
sender address
FROM: <tim@orbaker.com>" );
);
) throw new Exception( "Sender rejected" );
}
}
253
354
355
421
432
450
451
452
453
454
458
459
500
501
502
503
504
521
530
534
538
550
551
552
553
554
Description
System status, or system help reply.
Help message.
Domain service ready.
Ready to start TLS.
Domain service closing transmission channel.
OK, queuing for node node started.
Requested mail action okay, completed.
OK, no messages waiting for node node.
User not local, will forward to forwardpath.
OK, pending messages for node node started.
Cannot VRFY user (e.g., info is not local),
but will take message for this user and attempt delivery.
OK, messages pending messages for node node started.
Start mail input; end with ..
Octetoffset is the transaction offset.
Domain service not available, closing transmission channel.
A password transition is needed.
Requested mail action not taken: mailbox unavailable.
(ex. mailbox busy)
Requested action aborted: local error in processing.
Unable to process ATRN request now
Requested action not taken: insufficient system storage.
You have no mail.
TLS not available due to temporary reason.
Encryption required for requested authentication mechanism.
Unable to queue messages for node node.
Node node not allowed: reason.
Command not recognized: command.
Syntax error.
Syntax error, no parameters allowed.
Command not implemented.
Bad sequence of commands.
Command parameter not implemented.
Machine does not accept mail.
Must issue a STARTTLS command first.
Encryption required for requested authentication mechanism.
Authentication mechanism is too weak.
Encryption required for requested authentication mechanism.
Requested action not taken: mailbox unavailable.
User not local; please try forwardpath.
Requested mail action aborted: exceeded storage allocation.
Requested action not taken: mailbox name not allowed.
Transaction failed.
RFC0821
System.out.println
("There " + (i==1?"is " :"are ") + i +
" message" +(i==1?"":"s")+ " waiting.");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
private void send(BufferedWriter out, String s) throws IOException {
out.write(s+"\n");
out.flush();
}
private String receive(BufferedReader in) throws IOException {
return in.readLine();
}
private int checkMyMail
(String server, String user, String pass) throws IOException {
Socket s = new Socket(server, 110);
BufferedReader in = new BufferedReader(
new InputStreamReader(s.getInputStream()));
BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(s.getOutputStream()));
receive(in);
send(out, "USER " + user);
receive(in);
send(out, "PASS " + pass);
receive(in);
return getNumberOfMessages(in, out);
}
public int getNumberOfMessages
(BufferedReader in, BufferedWriter out) throws IOException {
int i = 0;
String s;
send(out, "LIST");
receive(in);
while((s = receive(in)) != null) {
if (!(s.equals("."))) {
i++;
}
else
return i;
}
return 0;
}
}
//
send(out, "DELE "+i);
//
receive(in);
//
return t;
}
import java.io.*;
import java.net.*;
public class TestMailMIME {
static int SMTPport = 25;
static Socket socket;
static DataInputStream in;
static DataOutputStream out;
static PrintStream prout;
/* Name of file to be sent. */
String FileName = "gumby.gif";
public static void main(String s[]) {
/*
** TestMailMIME [server] [recipient]
*/
TestMailMIME t = new TestMailMIME();
t.sendMail(s[0], s[1]);
}
public void sendMail(String mailServer, String recipient) {
System.out.println("Send mail with attached file ");
try {
Socket s = new Socket(mailServer, 25);
BufferedReader in = new BufferedReader
(new InputStreamReader(s.getInputStream(), "8859_1"));
BufferedWriter out = new BufferedWriter
(new OutputStreamWriter(s.getOutputStream(), "8859_1"));
String boundary = "DataSeparatorString";
// here you are supposed to send your username
sendln(in, out, "HELO theWorld");
// warning : some mail server validate the sender address
//
in the MAIL FROM command, put your real address here
sendln(in, out, "MAIL FROM: ");
sendln(in, out, "RCPT TO: <" + recipient + ">" );
//
to have more than one recipient, repeat
//
sendln(in, out, "RCPT TO: <" + recipient2 + ">" );
//
sendln(in, out, "RCPT TO: <" + recipient3 + ">" );
//
etc...
//
thanks to PY Colle for the tip!
sendln(in, out, "DATA");
body
"ContentType: text/plain; charset=\"usascii\"\r\n");
"I'm alive. Help me!\r\n\r\n");
"\r\n" + boundary );
01101101
01100101
01101110
encode "m"
01101101
011011 01
111111
011011 010000
b
Q
"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P",
"Q","R","S","T","U","V","W","X","Y","Z","a","b","c","d","e","f",
"g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v",
"w","x","y","z","0","1","2","3","4","5","6","7","8","9","+","/"
};
public static void encode(String filename, BufferedWriter out) {
try {
File f
= new File(filename);
FileInputStream fin = new FileInputStream(filename);
// read the entire file into the byte array
byte bytes[]
= new byte[(int)(f.length())];
int n
= fin.read(bytes);
if (n < 1) return;
// no bytes to encode!?!
int
int
int
int
int
n3byt
nrest
k
linelength
i
=
=
=
=
=
n / 3;
// how 3 bytes groups?
n % 3;
// the remaining bytes from the grouping
n3byt * 3; // we are doing 3 bytes at a time
0;
// current linelength
0;
// index
}
else if (nrest==1) {
// 1 byte left
buf[0] = (byte)((bytes[k] &0xFC) >> 2);
buf[1] = (byte)((bytes[k] &0x03) << 4);
}
if (nrest > 0) {
// send the padding
if ((linelength += 4) >= 76) send(out, "\r\n");
send(out, BaseTable[buf[0]]);
send(out, BaseTable[buf[1]]);
// Thanks to R. Claerman for the bug fix here!
if (nrest==2) {
send(out, BaseTable[buf[2]]);
}
else {
send(out, "=");
}
send(out, "=");
}
out.flush();
}
catch (Exception e) {
e.printStackTrace();
}
}
public static void send(BufferedWriter out, String s) {
try {
out.write(s);
System.out.print(s);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
If Elvis want to send a GIF and a text file about his Gumby old friend then he would change his
sendMail() for something like this
...
/* Name of files to be sent. */
String FileName1 = "gumby.gif";
String FileName2 = "gumby.txt";
...
public void sendMail(String mailServer, String recipient) {
System.out.println("Send mail with attached file");
try {
Socket s = new Socket(mailServer, 25);
BufferedReader in = new BufferedReader
(new InputStreamReader(s.getInputStream(), "8859_1"));
BufferedWriter out = new BufferedWriter
(new OutputStreamWriter(s.getOutputStream(), "8859_1"));
String boundary = "DataSeparatorString";
// here you are supposed to send your username
sendln(in, out, "HELO world");
HTML Email
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
class SimpleHTMLMail {
public static void main(String[] args) throws Exception{
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "mymail.server.org");
props.setProperty("mail.user", "emailuser");
props.setProperty("mail.password", "");
Session mailSession = Session.getDefaultInstance(props, null);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject("Testing javamail html");
message.setContent
("This is a test <b>HOWTO<b>", "text/html; charset=ISO88591");
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("elvis@presley.org"));
transport.connect();
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
}
}
javax.mail.*;
javax.mail.internet.*;
javax.activation.FileDataSource;
javax.activation.DataHandler;
import java.util.Properties;
class SimpleMailWithAttachment {
public static void main(String[] args) throws Exception{
boolean debug = false;
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "mymail.server.org");
props.setProperty("mail.user", "emailuser");
props.setProperty("mail.password", "");
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(debug);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject("Testing javamail with attachment");
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent("<h1>Check attachment</h1>", "text/html");
MimeBodyPart attachFilePart = new MimeBodyPart();
FileDataSource fds =
new FileDataSource("SimpleMailWithAttachment.java");
attachFilePart.setDataHandler(new DataHandler(fds));
attachFilePart.setFileName(fds.getName());
Multipart mp = new MimeMultipart();
mp.addBodyPart(textPart);
mp.addBodyPart(attachFilePart);
message.setContent(mp);
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("elvis@presley.org"));
transport.connect();
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
}
}
javax.mail.*;
javax.mail.internet.*;
javax.mail.Authenticator;
javax.mail.PasswordAuthentication;
import java.util.Properties;
One approach to include images in the mail body is to use the IMG tag and make the images
available on a server.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
class SimpleMail1 {
public static void main(String[] args) throws Exception{
System.out.println("Sending mail...");
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.mymailserver.com");
props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject("HTML mail with images");
message.setFrom(new InternetAddress("me@sender.com"));
message.setContent
("<h1>This is a test</h1>"
+ "<img src=\"http://www.rgagnon.com/images/jht.gif\">",
"text/html");
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("you@receiver.com"));
transport.connect();
transport.sendMessage(message,
message.getRecipients(Message.RecipientType.TO));
transport.close();
}
}
The browser accesses these images just as if it were displaying an image in a Web page.
Unfortunately, spammers have used this mechanism as a sneaky way to record who visits their
site (and mark your email as valid). To protect your privacy, many Webbased (and other) email
clients don't display images in HTML emails.
An alternative to placing absolute URLs to images in your HTML is to include the images as
attachments to the email. The HTML can reference the image in an attachment by using the
protocol prefix cid: plus the contentid of the attachment.
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import java.util.Properties;
class SimpleMail2 {
public static void main(String[] args) throws Exception{
System.out.println("Sending mail...");
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "smtp");
props.setProperty("mail.host", "smtp.mymailserver.com");
props.setProperty("mail.user", "myuser");
props.setProperty("mail.password", "mypwd");
Session mailSession = Session.getDefaultInstance(props, null);
mailSession.setDebug(true);
Transport transport = mailSession.getTransport();
MimeMessage message = new MimeMessage(mailSession);
message.setSubject("HTML mail with images");
message.setFrom(new InternetAddress("me@sender.com"));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress("you@receiver.com"));
//
// This HTML mail have to 2 part, the BODY and the embedded image
//
This setting puts the JavaMail classes in debug mode mode to System.out.
To redirect the JavaMail debugging output to a more appropriate log file you can
link a PrintStream to a ByteArrayOutputStream,
13.19 Debug a JavaMail ProgramTag(s): Networking
for example, you can detect if your firewall is blocking your connection.
Windows 7
By default, the telnet client is not installed on a Win7 workstation. To installed it, open command
shell and type :
pkgmgr /iu:"TelnetClient"
You can also install it through the Control Panel, see Microsoft Technet.
It's not uncommon that the outgoing mail needs to be encrypted using the SMTPS protocol.
It's the case for GMAIL for example.
You need Javamail 1.4 to use the SMTPS protocol.
import javax.mail.*;
import javax.mail.internet.*;
import java.util.Properties;
static
static
static
static
final
final
final
final
The property
props.put("mail.smtps.quitwait", "false");
ref : http://java.sun.com/products/javamail/javadocs/com/sun/mail/smtp/packagesummary.html
This setting, mail.smtps.quitwait, is not required anymore! (july2007)
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
java.io.ByteArrayInputStream;
java.io.File;
java.io.FileOutputStream;
java.io.IOException;
java.io.OutputStream;
java.io.PrintWriter;
java.util.Iterator;
java.util.Map;
import org.apache.poi.hsmf.MAPIMessage;
import org.apache.poi.hsmf.datatypes.AttachmentChunks;
import org.apache.poi.hsmf.exceptions.ChunkNotFoundException;
// You need poiscratchpad3.6
POI 3.7
import
import
import
import
import
import
import
import
java.io.ByteArrayInputStream;
java.io.File;
java.io.FileOutputStream;
java.io.IOException;
java.io.OutputStream;
java.io.PrintWriter;
java.util.Iterator;
java.util.Map;
import
import
import
import
import
org.apache.poi.hdgf.chunks.Chunk;
org.apache.poi.hsmf.MAPIMessage;
org.apache.poi.hsmf.datatypes.AttachmentChunks;
org.apache.poi.hsmf.datatypes.Chunks;
org.apache.poi.hsmf.exceptions.ChunkNotFoundException;
System.out.println(a.attachLongFileName);
// extract attachment
ByteArrayInputStream fileIn = new ByteArrayInputStream(a.attachData.getValue(
File f = new File("c:/temp", a.attachLongFileName.toString()); // output
OutputStream fileOut = null;
try {
fileOut = new FileOutputStream(f);
byte[] buffer = new byte[2048];
int bNum = fileIn.read(buffer);
while(bNum > 0) {
fileOut.write(buffer);
bNum = fileIn.read(buffer);
}
}
finally {
try {
if(fileIn != null) {
fileIn.close();
}
}
finally {
if(fileOut != null) {
fileOut.close();
}
}
}
}
}
else {
System.out.println("No attachment");
}
}
}
13.27 msgparser
http://auxilii.com/msgparser/
msgparser is a small open source Java library that parses Outlook .msg files and provides their
content using Java objects. msgparser uses the Apache POI POIFS library to parse the
message files which use the OLE 2 Compound Document format.
import java.util.List;
import com.auxilii.msgparser.*;
import com.auxilii.msgparser.attachment.*;
public class SimpleMsgParser {
public static void main(String[] args) throws Exception{
MsgParser msgp = new MsgParser();
Message msg = msgp.parseMsg("c:/temp/test2.msg");
String
String
String
String
fromEmail = msg.getFromEmail();
fromName = msg.getFromName();
subject = msg.getSubject();
body = msg.getBodyText();
13.27 msgparser
System.out.println("");
List atts = msg.getAttachments();
for (Attachment att : atts) {
if (att instanceof FileAttachment) {
FileAttachment file = (FileAttachment) att;
System.out.println("Attachment : " + file.getFilename());
// you get the actual attachment with
// byte date[] = file.getData();
}
}
}
}
13.28 jmbox
https://jmbox.dev.java.net/
The jmbox project (read jambox) is a Local Store Provider for JavaMail, enabling developers to
use JavaMail api to manage the mail stored in local repositories like Outlook Express, Mozilla,
Netscape etc.
At the moment are supported navigation and reading from Outlook Express 5/6 mail (dbx format).
java.util.*;
java.io.*;
javax.mail.*;
javax.mail.internet.*;
13.28 jmbox
Body :
This is an example for HowTo
...
}
...
Since the subject is used to set the filename, it's not a bad idea to sanitize it to remove illegal
characters.
private static String sanitizeFilename(String name) {
return name.replaceAll("[:\\\\/*?|<> \"]", "_");
}
java.io.*;
java.util.*;
javax.mail.*;
javax.mail.internet.*;
//
// inspired by :
// http://www.mikedesjardins.net/content/2008/03/usingjavamailtoreadandextract/
//
public static void doit() throws MessagingException, IOException {
Folder folder = null;
Store store = null;
try {
Properties props = System.getProperties();
props.setProperty("mail.store.protocol", "imaps");
Session session = Session.getDefaultInstance(props, null);
// session.setDebug(true);
store = session.getStore("imaps");
store.connect("imap.gmail.com","myemail@gmail.com", "******");
folder = store.getFolder("Inbox");
/* Others GMail folders :
* [Gmail]/All Mail
This folder contains all of your Gmail messages.
* [Gmail]/Drafts
Your drafts.
* [Gmail]/Sent Mail Messages you sent to other people.
* [Gmail]/Spam
Messages marked as spam.
* [Gmail]/Starred
Starred messages.
* [Gmail]/Trash
Messages deleted from Gmail.
*/
folder.open(Folder.READ_WRITE);
Message messages[] = folder.getMessages();
System.out.println("No of Messages : " + folder.getMessageCount());
System.out.println("No of Unread Messages : " + folder.getUnreadMessageCount());
for (int i=0; i < messages.length; ++i) {
System.out.println("MESSAGE #" + (i + 1) + ":");
Message msg = messages[i];
/*
if we don''t want to fetch messages already processed
if (!msg.isSet(Flags.Flag.SEEN)) {
String from = "unknown";
...
}
*/
String from = "unknown";
if (msg.getReplyTo().length >= 1) {
from = msg.getReplyTo()[0].toString();
}
else if (msg.getFrom().length >= 1) {
from = msg.getFrom()[0].toString();
}
String subject = msg.getSubject();
System.out.println("Saving ... " + subject +" " + from);
// you may want to replace the spaces with "_"
// the TEMP directory is used to store the files
String filename = "c:/temp/" + subject;
saveParts(msg.getContent(), filename);
msg.setFlag(Flags.Flag.SEEN,true);
// to delete the message
// msg.setFlag(Flags.Flag.DELETED, true);
}
}
finally {
if (folder != null) { folder.close(true); }
if (store != null) { store.close(); }
}
}
}
}
public static void saveParts(Object content, String filename)
throws IOException, MessagingException
{
OutputStream out = null;
InputStream in = null;
try {
if (content instanceof Multipart) {
Multipart multi = ((Multipart)content);
int parts = multi.getCount();
for (int j=0; j < parts; ++j) {
MimeBodyPart part = (MimeBodyPart)multi.getBodyPart(j);
if (part.getContent() instanceof Multipart) {
// partwithinapart, do some recursion...
saveParts(part.getContent(), filename);
}
else {
String extension = "";
if (part.isMimeType("text/html")) {
extension = "html";
}
else {
if (part.isMimeType("text/plain")) {
extension = "txt";
}
else {
// Try to get the name of the attachment
extension = part.getDataHandler().getName();
}
filename = filename + "." + extension;
System.out.println("... " + filename);
out = new FileOutputStream(new File(filename));
in = part.getInputStream();
int k;
while ((k = in.read()) != 1) {
out.write(k);
}
}
}
}
}
}
finally {
if (in != null) { in.close(); }
if (out != null) { out.flush(); out.close(); }
}
}
public static void main(String args[]) throws Exception {
ReceiveMailPOP3.doit();
}
}
//
HttpURLConnection.setInstanceFollowRedirects(false)
HttpURLConnection con =
(HttpURLConnection) new URL(URLName).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
Thanks to Steve B. for the bug fix!
The following is doing the same thing but this time we identify ourself to a proxy. See also this
HowTo.
import java.net.*;
import java.io.*;
import java.util.Properties;
public class URLUtils {
public static void main(String s[]) {
System.out.println(exists("http://www.rgagnon.com"));
System.out.println(exists("http://www.yahoo.com"));
}
NOTE: proxyHost, proxyPort are deprecated. you have to prefix them with "http.".
NOTE: Those properties are documented here :
http://java.sun.com/javase/6/docs/technotes/guides/net/properties.html.
You can set the required properties when starting the JVM for a JAVA application from the
command line:
java
Dhttp.proxyHost=myproxyserver.com
Dhttp.proxyPort=80 MyJavaApp
Or in your source :
System.setProperty("http.proxyHost", "myProxyServer.com");
System.setProperty("http.proxyPort", "80");
Since Java 1.5 you can also pass a java.net.Proxy instance to the openConnection() method:
//Proxy instance, proxy ip = 123.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("123.0.0.1", 8080));
URL url = new URL("http://www.yahoo.com");
HttpURLConnection uc = (HttpURLConnection)url.openConnection(proxy);
uc.connect();
String page;
StringBuffer tmp = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
while ((line = in.readLine()) != null){
page.append(line + "\n");
}
System.out.println(page);
}
catch (URISyntaxException e) {
e.printStackTrace();
}
if (l != null) {
for (Iterator iter = l.iterator(); iter.hasNext() {
java.net.Proxy proxy = (java.net.Proxy) iter.next();
System.out.println("proxy hostname : " + proxy.type());
InetSocketAddress addr = (InetSocketAddress) proxy.address();
if (addr == null) {
System.out.println("No Proxy");
}
else {
System.out.println("proxy hostname : " + addr.getHostName());
System.out.println("proxy port : " + addr.getPort());
}
}
}
The following example dumps the content of a URL but before we identify ourself to the proxy.
import java.net.*;
import java.io.*;
public class URLUtils {
public static void main(String s[]) {
URLUtils.dump("http://www.yahoo.com");
System.out.println("**************");
URLUtils.dump("https://www.paypal.com");
System.out.println("**************");
}
public static void dump(String URLName){
try {
DataInputStream di = null;
FileOutputStream fo = null;
byte [] b = new byte[1];
// PROXY
System.setProperty("http.proxyHost","proxy.mydomain.local") ;
System.setProperty("http.proxyPort", "80") ;
URL u = new URL(URLName);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
//
// it's not the greatest idea to use a sun.misc.* class
// Sun strongly advises not to use them since they can
// change or go away in a future release so beware.
//
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
String encodedUserPwd =
encoder.encode("mydomain\\MYUSER:MYPASSWORD".getBytes());
con.setRequestProperty
("ProxyAuthorization", "Basic " + encodedUserPwd);
// PROXY
di = new DataInputStream(con.getInputStream());
while(1 != di.read(b,0,1)) {
System.out.print(new String(b));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
With JDK1.2, the java.net.Authenticator can be used to send the credentials when needed.
public static void dump(String URLName){
try {
DataInputStream di = null;
FileOutputStream fo = null;
byte [] b = new byte[1];
// PROXY
System.setProperty("http.proxyHost","proxy.mydomain.local") ;
System.setProperty("http.proxyPort", "80") ;
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new
PasswordAuthentication("mydomain\\username","password".toCharArray());
}});
URL u = new URL(URLName);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
di = new DataInputStream(con.getInputStream());
while(1 != di.read(b,0,1)) {
System.out.print(new String(b));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
conn.setRequestProperty ("Authorization",
userNamePasswordBase64(uname,pword));
conn.connect ();
return conn.getInputStream();
}
public static String userNamePasswordBase64
(String username, String password)
{
return "Basic " + base64Encode (username + ":" + password);
}
private final
'A', 'B',
'I', 'J',
'Q', 'R',
'Y', 'Z',
'g', 'h',
'o', 'p',
'w', 'x',
'4', '5',
};
case 2:
encodedString += "==";
break;
}
}
return encodedString;
}
}
Use of the sun.* package is "discouraged" by sun and not formally supported. Those classes can
be missing in your JDK release.
Check this HowTo for a more official way to encode/decode to/from Base64.
Here we calling a script called aCGI.pl (a PERL script) passing the parameters name and site.
Parameters are encoded, spaces are changed to "+" and special character to hexadecimal using
a 3letter escape sequence. Each parameter is delimited by the character "Habitually the
encoding is done through the static method encode of the java.net.URLencoder class.
String theCGI = "http://www.server.com/cgibin/aCGI.pl?";
String encoded = "name=" + URLencoder.encode("Real Gagnon");
URL cgiurl = new URL(thecgi + encoded);
Once the URL is constructed, you call the CGI using the showDocument method (Applet).
getAppletContext().showDocument(cgiurl);
The CGI will process the result and produce a page to be displayed.
The POST method allows the programmer to manipulate the data received from the CGI. First a
connection is made to the CGI, an OutputStream is open to send the parameters (if any). Then
InputStream is created to receive the result.
String theCGI = "http://www.server.com/cgibin/aCGI.pl";
String encoded = "name=" + URLencoder.encode("Real Gagnon");
URL CGIurl = new URL(theCGI);
URLConnection c = CGIurl.openConnection();
c.setDoOutput(true);
c.setUseCaches(false);
c.setRequestProperty("contenttype","application/xwwwformurlencoded");
DataOutputStream out = new DataOutputStream(c.getOutputStream());
out.writeBytes(encoded);
out.flush(); out.close();
BufferedReader in =
new BufferedReader(new InputStreamReader(c.getInputStream());
String aLine;
while ((aLine = in.readLine()) != null) {
// data from the CGI
System.out.println(aLine);
}
You can't do some output then some input and do again some output. You must do all the output
and then the input. There is no "dialog" between the client and the server. The client make a
request and the server send back the result and close the connection.
import java.net.*;
import java.io.*;
import java.util.*;
class CookiesInJava {
static Hashtable theCookies = new Hashtable();
/**
* Send the Hashtable (theCookies) as cookies, and write them to
* the specified URLconnection
*
* @param
urlConn The connection to write the cookies to.
* @param
printCookies Print or not the action taken.
*
* @return The urlConn with the all the cookies in it.
*/
public URLConnection writeCookies
(URLConnection urlConn, boolean printCookies){
String cookieString = "";
Enumeration keys = theCookies.keys();
while (keys.hasMoreElements()) {
String key = (String)keys.nextElement();
cookieString += key + "=" + theCookies.get(key);
if (keys.hasMoreElements())
cookieString += "; ";
}
urlConn.setRequestProperty("Cookie", cookieString);
if (printCookies)
System.out.println("Wrote cookies:\n
" + cookieString);
return urlConn;
}
/**
* Read cookies from a specified URLConnection, and insert them
*
to the Hashtable
* The hashtable represents the Cookies.
*
* @param
urlConn the connection to read from
* @param
printCookies Print the cookies or not, for debugging
* @param
reset Clean the Hashtable or not
*/
public void readCookies(URLConnection urlConn, boolean printCookies,
boolean reset){
if (reset)
theCookies.clear();
int i=1;
String hdrKey;
String hdrString;
String aCookie;
while ((hdrKey = urlConn.getHeaderFieldKey(i)) != null) {
if (hdrKey.equals("SetCookie")) {
hdrString = urlConn.getHeaderField(i);
StringTokenizer st = new StringTokenizer(hdrString,",");
while (st.hasMoreTokens()) {
String s = st.nextToken();
aCookie = s.substring(0, s.indexOf(";"));
// aCookie = hdrString.substring(0, s.indexOf(";"));
int j = aCookie.indexOf("=");
if (j != 1) {
if (!theCookies.containsKey(aCookie.substring(0, j))){
// if the Cookie do not already exist then when keep it,
// you may want to add some logic to update
// the stored Cookie instead. thanks to rwhelan
theCookies.put
(aCookie.substring(0, j),aCookie.substring(j + 1));
if (printCookies){
System.out.println("Reading Key: "
+ aCookie.substring(0, j));
System.out.println("
Val: "
+ aCookie.substring(j + 1));
}
}
}
}
}
i++;
}
}
/**
* Display all the cookies currently in the HashTable
*
*/
public void viewAllCookies() {
System.out.println("All Cookies are:");
Enumeration keys = theCookies.keys();
String key;
while (keys.hasMoreElements()){
key = (String)keys.nextElement();
System.out.println("
" + key + "=" +
theCookies.get(key));
}
}
/**
* Display the current cookies in the URLConnection,
*
searching for the: "Cookie" header
*
* This is Valid only after a writeCookies operation.
*
* @param
urlConn The URL to print the associates cookies in.
*/
public void viewURLCookies(URLConnection urlConn) {
System.out.print("Cookies in this URLConnection are:\n
");
System.out.println(urlConn.getRequestProperty("Cookie"));
}
/**
* Add a specific cookie, by hand, to the HastTable of the Cookies
*
* @param
_key The Key/Name of the Cookie
* @param
_val The Calue of the Cookie
* @param
printCookies Print or not the result
*/
public void addCookie(String _key, String _val, boolean printCookies){
if (!theCookies.containsKey(_key)){
theCookies.put(_key,_val);
if (printCookies){
System.out.println("Adding Cookie: ");
System.out.println("
" + _key + " = " + _val);
}
}
}
}
Thanks to Saar Machtiner for the bug fix
import java.io.IOException;
import java.net.URL;
import java.util.Scanner;
public class NetUtils {
private NetUtils() {}
public static String getTextContent(URL url) throws IOException {
Scanner s = new Scanner(url.openStream()).useDelimiter("\\Z");;
String content = s.next();
return content;
}
public static void main(String[] args) throws IOException {
URL url = new URL("http://www.rgagnon.com/varia/copyrightnotice.txt");
System.out.println(NetUtils.getTextContent(url));
}
}
// input
URL url = new URL(aURL + aFile);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
di = new DataInputStream(urlConnection.getInputStream());
// output
fo = new FileOutputStream(aFile);
// copy the actual file
//
(it would better to use a buffer bigger than this)
while(1 != di.read(b,0,1))
fo.write(b,0,1);
di.close();
fo.close();
}
catch (Exception ex) {
System.out.println("Oups!!!");
ex.printStackTrace();
System.exit(1);
}
System.out.println("done.");
}
}
There is an issue with root certificate from Verisign (jdk142 or less, you have exception talking
about "untrusted server"), you may want to review this note :
http://sunsolve.sun.com/search/document.do?assetkey=126574361.
}
}
For application, take a look at the Sun's Secure Socket Extension (JSSE).
Before connecting with a secure URL, we must do this first :
java.security.Security.addProvider(new
com.sun.net.ssl.internal.ssl.Provider());
System.setProperty
("java.protocol.handler.pkgs",
"com.sun.net.ssl.internal.www.protocol");
A useful link for that is this JavaWorld's Tip
Since JDK 1.4, the JSSE package is included so you don't have to add anything special. However
you may need to import the certificate from the host (that is the server that you are connecting to
using the https: protocol). One easy way to do this is to open a secured page (say
https://mysecuredhost.com) with IE, click on the SSLsymbol (bottom right) and exported the key
into the file "c:\cacerts.ce". Go in "%java_home%\bin" and type this:
keytool import v alias meincert trustcacerts file c:\
import
import
import
import
java.io.InputStreamReader;
java.io.Reader;
java.net.URL;
java.net.URLConnection;
However, you can have a problem if the server certificate is selfsigned by a testing certification
authority (CA) which is not in trusted CAs of Java on the client side. An exception like
Exception in thread "main" javax.net.ssl.SSLHandshakeException:
sun.security.validator.ValidatorException:
PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException:
unable to find valid certification path to requested target
java.io.InputStreamReader;
java.io.Reader;
java.net.URL;
java.net.URLConnection;
import
import
import
import
import
import
import
javax.net.ssl.HostnameVerifier;
javax.net.ssl.HttpsURLConnection;
javax.net.ssl.SSLContext;
javax.net.ssl.SSLSession;
javax.net.ssl.TrustManager;
javax.net.ssl.X509TrustManager;
java.security.cert.X509Certificate;
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
};
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
// Create alltrusting host name verifier
HostnameVerifier allHostsValid = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) {
return true;
}
};
// Install the alltrusting host verifier
HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
/*
* end of the fix
*/
URL url = new URL("https://securewebsite.com");
URLConnection con = url.openConnection();
Reader reader = new InputStreamReader(con.getInputStream());
while (true) {
int ch = reader.read();
if (ch==1) {
break;
}
System.out.print((char)ch);
}
}
}
+ search + "e=UTF8";
Note : You may want to take a look at http://www.google.com/apis/ to learn how to interact with
Google via the official API's.
As seen above, you can directly override the HTTP header. Another way is to start the program
with a modified System.property http.agent.
>java
"Dhttp.agent=Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" MyClass
or in your program
System.setProperty
("http.agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
On the client side, a java application can use Jakarta Commons HTTP client to initiate a file
upload.
Postlet is a Java applet used to enable websites to allow their users to send multiple files to a
webserver with a few simple clicks. Postlet is useable with any server side scripting language that
is capable of handling file uploads.
However if any Javascript is present, the script will be seen as text. Also you may need to add
some logic during the reading to take into account only what is inside the <BODY> tag.
java.io.IOException;
java.io.FileReader;
java.io.Reader;
java.util.List;
java.util.ArrayList;
13.48 Remove HTML tags from a file to extract only the TEXTTag(s): IO String/Number Networking
import
import
import
import
javax.swing.text.html.parser.ParserDelegator;
javax.swing.text.html.HTMLEditorKit.ParserCallback;
javax.swing.text.html.HTML.Tag;
javax.swing.text.MutableAttributeSet;
Note that the HTMLEditorKit can be easily confused if the HTML to be parsed is not wellformed.
java.io.IOException;
java.io.FileReader;
java.io.Reader;
java.io.BufferedReader;
org.jsoup.Jsoup;
org.apache.tika.metadata.Metadata;
org.apache.tika.parser.AutoDetectParser;
org.apache.tika.parser.ParseContext;
org.apache.tika.parser.Parser;
org.apache.tika.sax.BodyContentHandler;
org.xml.sax.ContentHandler;
See Extract text from a PDF using Apache Tika, Get Mime Type from a file.
See also Extract links from an HTML page
java.io.IOException;
java.io.FileReader;
java.io.Reader;
java.util.List;
java.util.ArrayList;
import
import
import
import
import
javax.swing.text.html.parser.ParserDelegator;
javax.swing.text.html.HTMLEditorKit.ParserCallback;
javax.swing.text.html.HTML.Tag;
javax.swing.text.html.HTML.Attribute;
javax.swing.text.MutableAttributeSet;
import java.util.List;
import java.util.ArrayList;
import
import
import
import
org.jsoup.Jsoup;
org.jsoup.nodes.Document;
org.jsoup.nodes.Element;
org.jsoup.select.Elements;
http://www.rgagnon.com/javadetails/../javadetails/java0657.html
ServiceGen is an utility to generate a client module to access a web service hosted by BEA WLS.
This example use a generated client to call the function list of a Web Service.
import com.company.webservices.client.Commonwebservices;
import com.company.webservices.client.CommonwebservicesPort;
import com.company.webservices.client.Commonwebservices_Impl;
public class Test {
public static void main(String ... args) throws Exception{
System.setProperty("weblogic.webservice.verbose", "true");
String wsdlUri = "http://server.company.local/wsdl/commonWS.xml";
Commonwebservices ws = new Commonwebservices_Impl(wsdlUri);
CommonwebservicesPort wsp = ws.getcommonwebservicesPort("myusername", "mypassword");
String list = wsc.list();
System.out.println(list);
}
}
A typical output :
URL
http://server.company.local:80/commonWS/commonwebservices
Headers
:
ContentLength: [459]
SOAPAction: [""]
ContentType: [text/xml; charset=utf8]
<?xml version="1.0" encoding="utf8" standalone="yes"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<env:Header></env:Header>
<env:Body env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<m:list xmlns:m="http://company.local/common"></m:list>
</env:Body></env:Envelope>
<! END REQUEST FROM CLIENT >
<! RESPONSE TO CLIENT >
URL
: http://server.company.local:80/commonWS/commonwebservices
Response Code :200
Headers
:
Date=Mon, 17 Aug 2009 14:36:29 GMT
Server=MicrosoftIIS/6.0
XPoweredBy=Servlet/2.5 JSP/2.1
CacheControl=nocache="setcookie"
ContentLength=1211
ContentType=text/xml; charset=ISO88591
SetCookie=JSESSIONID=BJYXKJqfFC7nl9TMgYkJg9DpL5kZ1nTQy2M8v1BXJnT1R8n1DhfX!1553076658; pat
Envelope
:
<?xml version="1.0" encoding="ISO88591" standalone="yes"?>
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchemainstance"
xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<env:Header></env:Header>
<env:Body env:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<m:listResponse xmlns:m="http://company.local/common">
<result xsi:type="xsd:string">\\company.local\fonc_sas, \\company.local\unit_sas, \\company.l
</result></m:listResponse></env:Body></env:Envelope>
<! END RESPONSE TO CLIENT >
\\company.local\fonc_sas, \\company.local\unit_sas, \\company.local\prod_sas
If you need authentication to access the WSDL then it's possible to do something like this :
String wsdlUri =
"http://myusername:mypassword@server.company.local/commonWS/commonwebservices?WSDL";
((BindingProvider)engine).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "usernam
((BindingProvider)engine).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "passwor
logger.info(" result :" + mywsh.myFunction("42"));
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
/*
* a simple static http server
*/
public class SimpleHttpServer {
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/test", new MyHandler());
server.setExecutor(null); // creates a default executor
server.start();
}
static class MyHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
String response = "Welcome Real's HowTo test page";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
Compile and execute. To access the local server, open a browser at http://localhost:8000/test.
The next HttpServer provides 2 contexts :
http://localhost:8000/info to display an informative message.
http://localhost:8000/get to download a specific PDF to the browser.
import
import
import
import
import
import
java.io.BufferedInputStream;
java.io.File;
java.io.FileInputStream;
java.io.IOException;
java.io.OutputStream;
java.net.InetSocketAddress;
import
import
import
import
com.sun.net.httpserver.HttpExchange;
com.sun.net.httpserver.HttpHandler;
com.sun.net.httpserver.HttpServer;
com.sun.net.httpserver.Headers;
NOTE: proxyHost, proxyPort are deprecated. you have to prefix them with "http.".
NOTE: Those properties are documented here :
http://java.sun.com/javase/6/docs/technotes/guides/net/properties.html.
You can set the required properties when starting the JVM for a JAVA application from the
command line:
java
Dhttp.proxyHost=myproxyserver.com
Dhttp.proxyPort=80 MyJavaApp
Or in your source :
System.setProperty("http.proxyHost", "myProxyServer.com");
System.setProperty("http.proxyPort", "80");
Since Java 1.5 you can also pass a java.net.Proxy instance to the openConnection() method:
//Proxy instance, proxy ip = 123.0.0.1 with port 8080
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("123.0.0.1", 8080));
URL url = new URL("http://www.yahoo.com");
HttpURLConnection uc = (HttpURLConnection)url.openConnection(proxy);
uc.connect();
String page;
StringBuffer tmp = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
while ((line = in.readLine()) != null){
page.append(line + "\n");
}
System.out.println(page);
The following example dumps the content of a URL but before we identify ourself to the proxy.
import java.net.*;
import java.io.*;
public class URLUtils {
public static void main(String s[]) {
URLUtils.dump("http://www.yahoo.com");
System.out.println("**************");
URLUtils.dump("https://www.paypal.com");
System.out.println("**************");
}
public static void dump(String URLName){
try {
DataInputStream di = null;
FileOutputStream fo = null;
byte [] b = new byte[1];
// PROXY
System.setProperty("http.proxyHost","proxy.mydomain.local") ;
System.setProperty("http.proxyPort", "80") ;
URL u = new URL(URLName);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
//
// it's not the greatest idea to use a sun.misc.* class
// Sun strongly advises not to use them since they can
// change or go away in a future release so beware.
//
sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
String encodedUserPwd =
encoder.encode("mydomain\\MYUSER:MYPASSWORD".getBytes());
con.setRequestProperty
("ProxyAuthorization", "Basic " + encodedUserPwd);
// PROXY
di = new DataInputStream(con.getInputStream());
while(1 != di.read(b,0,1)) {
System.out.print(new String(b));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
With JDK1.2, the java.net.Authenticator can be used to send the credentials when needed.
public static void dump(String URLName){
try {
DataInputStream di = null;
FileOutputStream fo = null;
byte [] b = new byte[1];
// PROXY
System.setProperty("http.proxyHost","proxy.mydomain.local") ;
System.setProperty("http.proxyPort", "80") ;
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new
PasswordAuthentication("mydomain\\username","password".toCharArray());
}});
URL u = new URL(URLName);
HttpURLConnection con = (HttpURLConnection) u.openConnection();
di = new DataInputStream(con.getInputStream());
while(1 != di.read(b,0,1)) {
System.out.print(new String(b));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
http://www.rgagnon.com/javadetails/../javadetails/java0086.html
[JDK11]
ServerSocket server = new ServerSocket(port);
// timeout after 60 seconds
server.setSoTimeout(60000);
try {
Socket socket=server.accept();
}
catch ( java.io.InterruptedIOException e ) {
System.err.println( "Timed Out (60 sec)!" );
}
This is true for READ operation too. Since READ operation blocks as long necessary it may be
wise to use the setSoTimeout() method. Note that when the TIMEOUT expires, an
InterruptException is thrown. However, the socket is still connected even though the Exception
was raised.
NOTE: To make this a more "complete PING", you may want to check this Howto to display the response time.
isReachable() will use ICMP ECHO REQUESTs if the privilege can be obtained, otherwise it will
try to establish a TCP connection on port 7 (Echo) of the destination host. But most Internet sites
have disabled the service or blocked the requests (except some university web sites like the
example above) .
if (i==1) return;
System.out.print(new String(b,0,i));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
java.io.BufferedInputStream;
java.io.File;
java.io.FileInputStream;
java.io.IOException;
java.io.OutputStream;
java.net.ServerSocket;
java.net.Socket;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
try {
servsock = new ServerSocket(SOCKET_PORT);
while (true) {
System.out.println("Waiting...");
try {
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// send file
File myFile = new File (FILE_TO_SEND);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = sock.getOutputStream();
System.out.println("Sending " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)"
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Done.");
}
finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
}
}
finally {
if (servsock != null) servsock.close();
}
}
}
java.io.BufferedOutputStream;
java.io.FileOutputStream;
java.io.IOException;
java.io.InputStream;
java.net.Socket;
public final static int FILE_SIZE = 6022386; // file size temporary hard coded
// should bigger than the file to be downloade
public static void main (String [] args ) throws IOException {
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
try {
To try it, first you start the server. You make sure that the file to be sent (as specified in
SimpleFileServer) exists! Then you execute the client module.
To download a file, a simpler and better way is to use the builtin JDK HTTP server, see this
HowTo
14 Security
14.1 javasecurity
14 Security
The output is :
Input your secret password : howto
the computed hash (hex string) : 96A26200CBB466C1DD05CB6D9C7C13F1B90A82AC
Now try to enter a password : Howto
Wrong, try again...!
Now try to enter a password : HOWTO
Wrong, try again...!
Now try to enter a password : howto
You got it!
In this HowTo, a key file is created during the encryption process if the specified key file is not
found.
import
import
import
import
import
import
import
import
import
java.io.File;
java.io.FileWriter;
java.io.FileReader;
java.io.FileNotFoundException;
java.io.IOException;
java.security.GeneralSecurityException;
java.security.NoSuchAlgorithmException;
java.util.Properties;
java.util.Scanner;
import
import
import
import
javax.crypto.Cipher;
javax.crypto.KeyGenerator;
javax.crypto.SecretKey;
javax.crypto.spec.SecretKeySpec;
return complete.digest();
}
// see this Howto for a faster way to convert
// a byte array to a HEX string
public static String getMD5Checksum(String filename) throws Exception {
byte[] b = createChecksum(filename);
String result = "";
for (int i=0; i < b.length; i++) {
result +=
Integer.toString( ( b[i] & 0xff ) + 0x100, 16).substring( 1 );
}
return result;
}
public static void main(String args[]) {
try {
System.out.println(getMD5Checksum("apachetomcat5.5.17.exe"));
// output :
// 0bb2827c5eacf570b6064e24e0e6653b
// ref :
// http://www.apache.org/dist/
//
tomcat/tomcat5/v5.5.17/bin
//
/apachetomcat5.5.17.exe.MD5
// 0bb2827c5eacf570b6064e24e0e6653b *apachetomcat5.5.17.exe
}
catch (Exception e) {
e.printStackTrace();
}
}
}
The next example is used to create a .chk file which contains a MD5 checksum of a given file. The
same program is used to check if a file has been altered by looking at previously generated .chk file
and compared with current checksum of the given file.
import java.security.*;
import java.io.*;
public class Checksum {
//
// returns 0 error
//
1 ok (create)
//
1 same (check)
//
2 different (check)
//
public static void main(String args[]) {
if (args.length == 2) {
if (args[0].equals("create")) {
System.exit(new Checksum().create(args[1]));
}
else if (args[0].equals("check")) {
System.exit(new Checksum().check(args[1]));
}
}
else {
System.out.println("Usage : java Checksum create [filename]\n"+
"
java Checksum check [filename]");
}
}
The java.util.zip package can be used to create a checksum. However the CRC32 is not a very
strong way to make sure that a file is not altered.
14.5 Create a checksumTag(s): Security
import java.io.*;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
public class ComputeCRC32 {
public static long getChecksumValue(Checksum checksum, String fname) {
try {
BufferedInputStream is = new BufferedInputStream(
new FileInputStream(fname));
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) >= 0) {
checksum.update(bytes, 0, len);
}
is.close();
}
catch (IOException e) {
e.printStackTrace();
}
return checksum.getValue();
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java ComputeCRC32 <file>");
System.exit(1);
}
long cs = getChecksumValue(new CRC32(), args[0]);
System.out.println("crc32 " + args[0] + " : " + cs);
}
}
However, MD5 is not secure anymore because researchers have proven that it is possible to
manipulate the original data to get the same MD5 as the original. The alternative is to use SHA1
which is on 160bits (MD5 is 128bits). It's still not perfect but it is better than MD5.
import java.io.*;
import java.security.MessageDigest;
public class ChecksumSHA1 {
public static byte[] createChecksum(String filename) throws
Exception
{
InputStream fis = new FileInputStream(filename);
byte[] buffer = new byte[1024];
MessageDigest complete = MessageDigest.getInstance("SHA1");
int numRead;
do {
numRead = fis.read(buffer);
if (numRead > 0) {
complete.update(buffer, 0, numRead);
}
} while (numRead != 1);
fis.close();
return complete.digest();
}
// see this Howto for a faster way to convert
// a byte array to a HEX string
public static String getSHA1Checksum(String filename) throws Exception {
byte[] b = createChecksum(filename);
String result = "";
for (int i=0; i < b.length; i++) {
result +=
Integer.toString( ( b[i] &0xff ) + 0x100, 16).substring( 1 );
}
return result;
}
public static void main(String args[]) {
try {
System.out.println(getSHA1Checksum("c:/temp/isapi_redirect1.2.30.dll"));
// output :
// cca9176f72ff56beb1f76c21b1d7daa6be192890
// ref :
//
http://tomcat.apache.org/
//
dev/dist/tomcatconnectors/
//
jk/binaries/win32/jk1.2.30/
//
isapi_redirect1.2.30.dll.sha1
//
// cca9176f72ff56beb1f76c21b1d7daa6be192890 *isapi_redirect1.2.30.dll
}
catch (Exception e) {
e.printStackTrace();
}
}
}
MD5 or SHA1 checksum can be used to validate a password without passing the actual password.
1. The server sends a random string to the client.
2. The client appends his password to the random string, and returns an MD5/SHA1 sum of the
result to the server.
3. On the server, do the same and compare the MD5/SHA1 sums.
4. If both MD5/SHA1 are identicals then the password is good.
will print the current user. You can't use this technique to secure your application since it is very to
spoof.
14.6 Get the user nameTag(s): Applet Security
In Applet there is no way unless you ask for it or use a signed applet. If you have access to a
serverside, something like an ASP page can be used to detect the current NT user name if the
client and the server are configured correcty (SSO).
See this related HowTo for a JSP hack!
String s;
if (msg[8] == 1) {
off = 18;
byte z = 0;
byte[] msg1 =
{(byte)'N', (byte)'T', (byte)'L', (byte)'M', (byte)'S',
(byte)'S', (byte)'P', z,
(byte)2, z, z, z, z, z, z, z,
(byte)40, z, z, z, (byte)1, (byte)130, z, z,
z, (byte)2, (byte)2, (byte)2, z, z, z, z, //
z, z, z, z, z, z, z, z};
//
response.setStatus(response.SC_UNAUTHORIZED);
response.setHeader("WWWAuthenticate", "NTLM "
+ new sun.misc.BASE64Encoder().encodeBuffer(msg1).trim());
return;
}
else if (msg[8] == 3) {
off = 30;
length = msg[off+17]*256 + msg[off+16];
offset = msg[off+19]*256 + msg[off+18];
s = new String(msg, offset, length);
//out.println(s + " ");
}
else
return;
length = msg[off+1]*256 + msg[off];
offset = msg[off+3]*256 + msg[off+2];
s = new String(msg, offset, length);
//out.println(s + " ");
length = msg[off+9]*256 + msg[off+8];
offset = msg[off+11]*256 + msg[off+10];
s = new String(msg, offset, length);
out.println("Hello <span style='position:relative; width:190;"
+ " height:10;filter:glow(Color=#009966,Strength=1)'>");
out.println(s + "</SPAN>");
}
%></BODY>
NOTES:
A comment from Weijun Ji : This technique only works if a user has its IE browser security setting set at middle/low (or if the server is trusted
like in an intranet environment). With this setting, browser will grab login username automatically. If the security setting is at high, then a window
will prompt user for input. At that time, whatever username the user put in will be passed to the "NTLM program". Since the user is not
authenticated, you have no way to know if this user is a true user or not. In this way, any user can pretend to be anybody else as long as he has
his security level set as high.
A comment from A. Santana : It didn't work for Firefox, so I did a silly workaround in the midtime. I
removed everything is not a word or space... look: s.replaceAll("[^azAZ\s]","");
You want to deeper into this subject, take a look at these sites :
http://www.innovation.ch/java/ntlm.html
http://free.tagish.net/jaas/index.jsp
http://www.luigidragone.com/networking/ntlm.html
Starting from jdk1.4.2, Sun provides support for NTLM, see
http://java.sun.com/j2se/1.4.2/changes.html#networking
For a complete solution see JCIFS (for Tomcat and others) at http://jcifs.samba.org
14.7 Get username using NT Challenge (NTLM)Tag(s): Security
NULL
This change in the default behavior is also implemented by security updates and service packs that
were released after the 832894 security update.
By default, this new default behavior for handling user information in HTTP or HTTPS URLs applies
only to Windows Explorer and Internet Explorer. To use this new behavior in other programs that
host the Web browser control, create a DWORD value named SampleApp.exe, where
SampleApp.exe is the name of the executable file that runs the program. Set the DWORD value's
value data to 1 in one of the following registry keys.
14.8 Check if the current user belongs a specific Windows group/roleTag(s): Security Powerscript
For all users of the program, set the value in the following registry key:
HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer\
Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE
For the current user of the program only, set the value in the following registry key:
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\
Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE
To disable the new default behavior in Windows Explorer and Internet Explorer, create
iexplore.exe and explorer.exe DWORD values in one of the following registry keys and set their
value data to 0.
For all users of the program, set the value in the following registry key:
HKEY_LOCAL_MACHINE\Software\Microsoft\Internet Explorer\
Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE
For the current user of the program only, set the value in the following registry key:
HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\
Main\FeatureControl\FEATURE_HTTP_USERNAME_PASSWORD_DISABLE
ref Microsoft Article ID : 834489
Java SE6 provides a buiiltin mechanism to input a password from the console.
java.io.Console cons;
char[] passwd;
if ((cons = System.console()) != null &
(passwd = cons.readPassword("[%s]", "Password:")) != null) {
...
}
This JSP will not display the script code and the browser execute it.
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<c:set var="test" scope="session">
<script>
alert("hello")
</script>
</c:set>
<h1>out with escapeXml=false</h1>
<c:out value="${test}" escapeXml="false" /><br>
<br />
With JSF, the tag <h:outputtext ... > provides the same protection.
Also see Java Edition of the OWASP ESAPI Toolkit
[MyLogin.java]
import java.awt.*;
import java.awt.event.*;
public class MyLogin extends Dialog implements ActionListener {
boolean id = false;
Button ok,can;
TextField username;
TextField password;
MyLogin(Frame frame){
super(frame, "Welcome", true);
setLayout(new FlowLayout());
username = new TextField(15);
password = new TextField(15);
password.setEchoChar('*');
add(new Label("User :"));
add(username);
add(new Label("Password :"));
add(password);
addOKCancelPanel();
createFrame();
pack();
setVisible(true);
}
void addOKCancelPanel() {
Panel p = new Panel();
p.setLayout(new FlowLayout());
createButtons( p );
add( p );
}
void createButtons(Panel p) {
p.add(ok = new Button("OK"));
ok.addActionListener(this);
p.add(can = new Button("Cancel"));
can.addActionListener(this);
}
void createFrame() {
Dimension d = getToolkit().getScreenSize();
setLocation(d.width/4,d.height/3);
}
public void actionPerformed(ActionEvent ae){
if(ae.getSource() == ok) {
id = true;
setVisible(false);
}
else if(ae.getSource() == can) {
id = false;
setVisible(false);
}
}
}
15 Swing
15.1 javaswing
instead of
import com.sun.java.swing.*;
IE or Netscape don't support directly Swing Applet. You must use the Java plugins. Then you will
need to use the <OBJECT> (IE) or <EMBED> (Netscape) HTML tag instead of the regular
<APPLET> tag.
15 Swing
Swing UI default
Even with the new naming mecanism in JDK1.2, some LookAndFeel packages are keeping the
oldname.
Windows
Motif
Mac
Metal
Basic
Multi
It's not bad idea to set the look and feel to a known good value and then try the notsosure value.
try {
// sure look and feel
UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
// notsosure look and feel
System.setProperty("os.name", "Windows");
System.setProperty("os.version", "5.1");
UIManager.setLookAndFeel(
"com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
}
catch (Exception ex) {
ex.printStackTrace();
}
}
private void createMenu(){
JMenuBar mb = new JMenuBar();
JMenu file = new JMenu("File");
mb.add(file);
file.add(openAction);
file.add(saveAction);
file.add(quitAction);
setJMenuBar(mb);
}
private void createToolBar() {
JToolBar bar = new JToolBar();
bar.add(openAction);
bar.add(saveAction);
bar.add(quitAction);
getContentPane().add(bar, "North");
}
private void createButtons() {
JPanel j = new JPanel();
JButton b1 = new JButton("Open");
JButton b2 = new JButton("Save");
JButton b3 = new JButton("Quit");
b1.addActionListener(openAction);
b2.addActionListener(saveAction);
b3.addActionListener(quitAction);
j.add(b1);
j.add(b2);
j.add(b3);
getContentPane().add(j, "East");
}
}
class OpenAction extends AbstractAction {
public OpenAction() {
super("Open", new ImageIcon("open.gif"));
}
public void actionPerformed(ActionEvent e) {
System.out.println("Open action");
}
}
class SaveAction extends AbstractAction {
public SaveAction() {
super("Save", new ImageIcon("save.gif"));
}
public void actionPerformed(ActionEvent e) {
System.out.println("Save action");
}
}
class QuitAction extends AbstractAction {
public QuitAction() {
super("Quit", new ImageIcon("quit.gif"));
}
public void actionPerformed(ActionEvent e) {
System.out.println("Quit action");
System.out.println("Bye.");
System.exit(0);
}
}
java.util.Comparator;
java.util.Iterator;
java.util.Map;
java.util.Set;
java.util.TreeSet;
import javax.swing.UIManager;
public class UIDefaults {
public static void main(String[] args) {
try {
Set defaults = UIManager.getLookAndFeelDefaults().entrySet();
// this TreeSet will hold the sorted properties
TreeSet ts = new TreeSet(new Comparator() {
public int compare(Object a, Object b) {
Map.Entry ea = (Map.Entry) a;
Map.Entry eb = (Map.Entry) b;
return
((String) ea.getKey()).compareTo(((String)eb.getKey()));
}
});
ts.addAll(defaults);
for (Iterator i = ts.iterator(); i.hasNext();) {
Map.Entry entry = (Map.Entry) i.next();
System.out.print(entry.getKey() + " = " );
System.out.println(entry.getValue());
}
you can click on it to trigger an action or use this area to display notification.
java.awt.*;
java.awt.image.*;
java.awt.event.*;
javax.swing.*;
}
try {
SystemTray sysTray = SystemTray.getSystemTray();
trayIcon = createTrayIconFromFile();
//trayIcon = createTrayIconFromResource();
//trayIcon = createTrayIconFromBuiltInIcon();
sysTray.add(trayIcon);
trayIcon.displayMessage("Ready",
"Tray icon started and tready", TrayIcon.MessageType.INFO);
}
catch (AWTException e) {
System.out.println("Unable to add icon to the system tray");
System.exit(1);
}
}
}
This code can load the icon from a file, a file in the classpath (resource) or use a builtin icon in
the JDK.
}
}
} );
pack();
setVisible( true );
}
public static void main(String args[]) {
new CloseOrNot();
}
}
import javax.swing.*;
import java.io.*;
/**
* http://tanksoftware.com/juk/developer/src/com/
*
tanksoftware/util/RedirectedFrame.java
* A Java Swing class that captures output to the command line
** (eg, System.out.println)
* RedirectedFrame
* <p>
* This class was downloaded from:
* Java CodeGuru (http://codeguru.earthweb.com/java/articles/382.shtml) <br>
* The origional author was Real Gagnon (real.gagnon@tactika.com);
* William Denniss has edited the code, improving its customizability
*
* In breif, this class captures all output to the system and prints it in
* a frame. You can choose weither or not you want to catch errors, log
* them to a file and more.
* For more details, read the constructor method description
*/
private
private
private
private
private
private
boolean catchErrors;
boolean logFile;
String fileName;
int width;
int height;
int closeOperation;
* @param logFile set this to true if you want the output logged
* @param fileName the name of the file it is to be logged to
* @param width the width of the frame
* @param height the height of the frame
* @param closeOperation the default close operation
*
(this must be one of the WindowConstants)
*/
public RedirectedFrame
(boolean catchErrors, boolean logFile, String fileName, int width,
int height, int closeOperation) {
this.catchErrors = catchErrors;
this.logFile = logFile;
this.fileName = fileName;
this.width = width;
this.height = height;
this.closeOperation = closeOperation;
Container c = getContentPane();
setTitle("Output Frame");
setSize(width,height);
c.setLayout(new BorderLayout());
c.add("Center" , aTextArea);
displayLog();
this.logFile = logFile;
System.setOut(aPrintStream); // catches System.out messages
if (catchErrors)
System.setErr(aPrintStream); // catches error messages
// set the default closing operation to the one given
setDefaultCloseOperation(closeOperation);
Toolkit tk = Toolkit.getDefaultToolkit();
Image im = tk.getImage("myicon.gif");
setIconImage(im);
}
javax.swing.*;
javax.swing.border.*;
java.awt.event.*;
java.awt.*;
win.setSize(200,200);
win.setVisible(true);
}
}
javax.swing.*;
java.awt.*;
java.awt.event.*;
java.net.*;
to set an anchor, you get the URL then add the "#anchor".
...
URL url = getClass().getResource("contents.html");
tp.setPage(new URL(url.toExternalForm() + "#section42"));
...
System.out.println("ret : " + i );
i = MessageBox.okcancel("Are your sure ?");
System.out.println("ret : " + i );
i = MessageBox.ok("Done.");
System.out.println("ret : " + i );
}
}
Then
import
import
import
import
javax.swing.*;
java.awt.event.*;
java.awt.*;
java.util.*;
button.setActionCommand("en");
button.addActionListener(this);
group.add(button);
add(button);
button = new JRadioButton("Francais");
button.setActionCommand("fr");
button.addActionListener(this);
group.add(button);
add(button);
go = new JButton("Do it");
go.addActionListener(this);
add(go);
locale = Locale.US;
}
public void setUILanguage() {
ResourceBundle rb;
rb = ResourceBundle.getBundle("JOptionPane", locale);
UIManager.put("OptionPane.yesButtonText", rb.getString("Yes"));
UIManager.put("OptionPane.noButtonText", rb.getString("No"));
UIManager.put("OptionPane.cancelButtonText", rb.getString("Cancel"));
msg = rb.getString("SaveMsg");
}
public void actionPerformed(ActionEvent e) {
int result;
if (e.getSource() instanceof JRadioButton) {
if (e.getActionCommand().equals("en"))
locale = Locale.US;
else
locale = Locale.FRANCE;
setUILanguage();
}
else {
// the button action
result = JOptionPane.showConfirmDialog(this,msg);
System.out.println(result);
}
}
public Dimension getPreferredSize(){
return new Dimension(200, 200);
}
public static void main(String s[]) {
JFrame frame = new JFrame("");
MessageBoxExample panel = new MessageBoxExample();
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
}
This example will show 2 radio buttons, one for english, one for french. Press the button to
display a localized JFileChooser according to the radio button selected.
Create 2 properties files, one for english , one for french (these files are incomplete but should be
enough to get you started).
[JFileChooser_en.properties]
Title=Real's JFileChooser
lookInLabelText=Current
filesOfTypeLabelText=File type
upFolderToolTipText=go up
[JFileChooser_fr.properties]
Title=JFileChooser de R\u00e9al
lookInLabelText=Courant
filesOfTypeLabelText=Type de fichier
upFolderToolTipText=Remonte
Then
[LocalizeJFileChooser.java]
import
import
import
import
javax.swing.*;
java.awt.event.*;
java.awt.*;
java.util.*;
locale = Locale.US;
}
public void setUILanguage() {
ResourceBundle rb;
rb = ResourceBundle.getBundle("JFileChooser", locale);
z_choosertitle = rb.getString("Title");
UIManager.put
("FileChooser.lookInLabelText",
rb.getString("lookInLabelText"));
UIManager.put
("FileChooser.filesOfTypeLabelText",
rb.getString("filesOfTypeLabelText"));
UIManager.put
("FileChooser.upFolderToolTipText",
rb.getString("upFolderToolTipText"));
/*
do the same with :
FileChooser.fileNameLabelText
FileChooser.homeFolderToolTipText
FileChooser.newFolderToolTipText
FileChooser.listViewButtonToolTipTextlist
FileChooser.detailsViewButtonToolTipText
FileChooser.saveButtonText=Save
FileChooser.openButtonText=Open
FileChooser.cancelButtonText=Cancel
FileChooser.updateButtonText=Update
FileChooser.helpButtonText=Help
FileChooser.saveButtonToolTipText=Save
FileChooser.openButtonToolTipText=Open
FileChooser.cancelButtonToolTipText=Cancel
FileChooser.updateButtonToolTipText=Update
FileChooser.helpButtonToolTipText=Help
Almost all Swing widgets can be customize this way. You can
examine the Swing sources to get these values or check
http://www.gargoylesoftware.com/papers/plafdiff.html for
a list of them.
*/
}
public void actionPerformed(ActionEvent e) {
int result;
if (e.getSource() instanceof JRadioButton) {
if (e.getActionCommand().equals("en"))
locale = Locale.US;
else
locale = Locale.FRANCE;
setUILanguage();
}
else {
z_chooser = new JFileChooser();
z_chooser.setCurrentDirectory(new java.io.File("."));
z_chooser.setDialogTitle(z_choosertitle);
if (z_chooser.showOpenDialog(this) !=
JFileChooser.APPROVE_OPTION)
return;
}
}
public Dimension getPreferredSize(){
return new Dimension(200, 200);
}
public static void main(String s[]) {
JFrame frame = new JFrame("");
LocalizeJFileChooser panel = new LocalizeJFileChooser();
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
}
}
javax.swing.*;
java.awt.event.*;
java.awt.*;
java.util.*;
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//
// disable the "All files" option.
//
chooser.setAcceptAllFileFilterUsed(false);
//
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
System.out.println("getCurrentDirectory(): "
+ chooser.getCurrentDirectory());
System.out.println("getSelectedFile() : "
+ chooser.getSelectedFile());
}
else {
System.out.println("No Selection ");
}
}
public Dimension getPreferredSize(){
return new Dimension(200, 200);
}
public static void main(String s[]) {
JFrame frame = new JFrame("");
DemoJFileChooser panel = new DemoJFileChooser();
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
}
}
javax.swing.*;
java.awt.event.*;
java.awt.*;
java.util.*;
implements ActionListener {
JButton go;
JFileChooser chooser;
String choosertitle;
public DemoJFileChooser() {
go = new JButton("Do it");
go.addActionListener(this);
add(go);
}
public void actionPerformed(ActionEvent e) {
int result;
chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle(choosertitle);
disableNewFolderButton(chooser);
//
int rc = chooser.showOpenDialog(this);
if (rc == JFileChooser.APPROVE_OPTION) {
System.out.println("getCurrentDirectory(): "
+ chooser.getCurrentDirectory());
System.out.println("getSelectedFile() : "
+ chooser.getSelectedFile());
}
else {
System.out.println("No Selection!");
}
}
}
}
);
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
}
}
javax.swing.*;
java.awt.event.*;
java.awt.*;
java.util.*;
if (rc == JFileChooser.APPROVE_OPTION) {
System.out.println("getCurrentDirectory(): "
+ chooser.getCurrentDirectory());
System.out.println("getSelectedFile() : "
+ chooser.getSelectedFile());
}
else {
System.out.println("No Selection!");
}
}
public Dimension getPreferredSize(){
return new Dimension(200, 200);
}
public static void main(String s[]) {
JFrame frame = new JFrame("");
DemoJFileChooser panel = new DemoJFileChooser();
frame.addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent e) {
System.exit(0);
}
}
);
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
}
}
java.awt.Dimension;
java.awt.event.WindowAdapter;
java.awt.event.WindowEvent;
java.awt.event.ActionListener;
import
import
import
import
import
javax.swing.JFrame;
javax.swing.JLabel;
javax.swing.JButton;
javax.swing.JRootPane;
javax.swing.SwingUtilities;
public JFrameWithNoMinMax() {
createAndShowUI();
}
private void createAndShowUI(){
setTitle("This JFRAME looks like JDialog");
setSize(new Dimension(500,100));
setUndecorated(true);
setResizable(false);
getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
//addWindowListener(new WindowAdapter(){
// public void windowClosing(WindowEvent e) {
//
System.out.println("Window Closing");
//
System.exit(0);
// }
//});
}
public static void main(String[] args){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
new JFrameWithNoMinMax().setVisible(true);
}
});
}
}
15.26 Show a JFrame on a specific screen in a dual monitor configuration Tag(s): Swing
java.awt.*;
javax.swing.*;
javax.swing.text.*;
javax.swing.event.*;
acceptedChars = acceptedchars;
}
public void setNegativeAccepted(boolean negativeaccepted) {
if (acceptedChars.equals(NUMERIC) ||
acceptedChars.equals(FLOAT) ||
acceptedChars.equals(ALPHA_NUMERIC)){
negativeAccepted = negativeaccepted;
acceptedChars += "";
}
}
public void insertString
(int offset, String str, AttributeSet attr)
throws BadLocationException {
if (str == null) return;
if (acceptedChars.equals(UPPERCASE))
str = str.toUpperCase();
else if (acceptedChars.equals(LOWERCASE))
str = str.toLowerCase();
for (int i=0; i <str.length(); i++) {
if (acceptedChars.indexOf(str.valueOf(str.charAt(i))) == 1)
return;
}
if (acceptedChars.equals(FLOAT) ||
(acceptedChars.equals(FLOAT + "") &negativeAccepted)) {
if (str.indexOf(".") != 1) {
if (getText(0, getLength()).indexOf(".") != 1) {
return;
}
}
}
if (negativeAccepted &str.indexOf("") != 1) {
if (str.indexOf("") != 0 || offset != 0 ) {
return;
}
}
super.insertString(offset, str, attr);
}
}
import java.awt.*;
import javax.swing.*;
public class TESTJTextFieldFilter extends JApplet{
JTextField tf1,tf1b,tf1c,tf2,tf3;
JLabel l1,l1b,l1c,l2,l3;
public void init() {
getContentPane().setLayout(new FlowLayout());
//
l1 = new JLabel("only numerics");
tf1 = new JTextField(10);
getContentPane().add(l1);
getContentPane().add(tf1);
tf1.setDocument
(new JTextFieldFilter(JTextFieldFilter.NUMERIC));
//
l1b = new JLabel("only float");
tf1b = new JTextField(10);
getContentPane().add(l1b);
getContentPane().add(tf1b);
tf1b.setDocument
(new JTextFieldFilter(JTextFieldFilter.FLOAT));
//
l1c = new JLabel("only float(can be negative)");
tf1c = new JTextField(10);
getContentPane().add(l1c);
getContentPane().add(tf1c);
JTextFieldFilter jtff = new JTextFieldFilter(JTextFieldFilter.FLOAT);
jtff.setNegativeAccepted(true);
tf1c.setDocument(jtff);
//
l2 = new JLabel("only uppercase");
tf2 = new JTextField(10);
getContentPane().add(l2);
getContentPane().add(tf2);
tf2.setDocument
(new JTextFieldFilter(JTextFieldFilter.UPPERCASE));
//
l3 = new JLabel("only 'abc123%$'");
tf3 = new JTextField(10);
getContentPane().add(l3);
getContentPane().add(tf3);
tf3.setDocument
(new JTextFieldFilter("abc123%$"));
}
}
With JDK.14, you have the JFormattedTextField class. You can provide an input mask like (###)
####### for a telephone number, and it will not accept any input that doesn't follow that format.
import
import
import
import
java.awt.Container;
javax.swing.*;
javax.swing.text.*;
java.text.ParseException;
It's also possible to provide simple validation. For example, specify a field to accept only numeric
with a minimum and a maximum value. If the input is not valid then a warning beep is produced.
import
import
import
import
java.awt.Container;
javax.swing.*;
javax.swing.text.*;
java.text.ParseException;
java.awt.*;
java.util.*;
java.awt.event.*;
javax.swing.*;
f.pack();
f.show();
}
}
class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent e) {
Window win = e.getWindow();
win.setVisible(false);
System.exit(0);
}
}
It's not a bad idea to give a visual cue that the textfield is not validated. Here a bad textfield will
show a red border, a good one will be black.
import javax.swing.border.*;
...
class HowtoVerifier extends InputVerifier {
public boolean verify(final JComponent input) {
JTextField tf = (JTextField) input;
String pass = tf.getText();
if (!pass.equals("howto")) {
SwingUtilities.invokeLater(new Runnable(){
public void run(){
input.setBorder( new LineBorder(Color.RED) );
}
});
return false;
}
SwingUtilities.invokeLater(new Runnable(){
public void run(){
input.setBorder( LineBorder.createBlackLineBorder() );
}
});
return true;
}
}
...
To try it :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class MyFrameApplet extends JApplet {
public void init() {
MyFrame myFrame = new MyFrame();
}
}
15.32 Make sure that my jTextfield has the focus when a JFrame is createdTag(s): Swing
java.awt.*;
java.util.*;
java.awt.event.*;
javax.swing.*;
java.awt.event.KeyEvent;
java.awt.event.InputEvent;
java.awt.event.WindowAdapter;
java.awt.event.WindowEvent;
import
import
import
import
import
import
javax.swing.JFrame;
javax.swing.JTextField;
javax.swing.KeyStroke;
javax.swing.text.DefaultEditorKit;
javax.swing.text.JTextComponent;
javax.swing.text.Keymap;
myFrame.setVisible(true);
}
public static void main(String args[]) {
new Test().doit();
}
}
First, we define the class representing a node. This node contains a title (the label), a URL, 2
icons (open and close).
import javax.swing.*;
public class RealSwingNode extends Object {
private String _title;
private String _link;
private ImageIcon _openedIcon;
private ImageIcon _closedIcon;
RealSwingNode
(String title, String link, ImageIcon closed, ImageIcon opened) {
_title = title;
_link = link;
_openedIcon = opened;
_closedIcon = closed;
}
String getTitle() { return _title; }
String getLink()
{ return _link; }
ImageIcon getOpenedIcon() { return _openedIcon; }
ImageIcon getClosedIcon() { return _closedIcon; }
public String toString() { return _title; }
}
Then we define how the node would be shown in the Tree. This is done by implementing a
Renderer class.
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
public class RealSwingTreeIconRenderer extends Object
implements TreeCellRenderer {
JLabel _label;
RealSwingTreeIconRenderer() {
_label = new JLabel();
_label.setOpaque(true);
}
public Component getTreeCellRendererComponent
(JTree tree, Object value, boolean selected,
boolean expanded, boolean leaf, int row, boolean hasFocus) {
RealSwingNode _userObject = null;
_label.setFont(tree.getFont());
if (selected){
_label.setForeground(tree.getBackground());
_label.setBackground(tree.getForeground());
}
else {
_label.setBackground(tree.getBackground());
_label.setForeground(tree.getForeground());
}
if (value instanceof RealSwingNode) {
_userObject = (RealSwingNode) value;
}
else if(value instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode node;
node = (DefaultMutableTreeNode) value;
if (node.getUserObject() instanceof RealSwingNode) {
_userObject = (RealSwingNode) node.getUserObject();
}
}
if(_userObject != null) {
if (expanded)
_label.setIcon(_userObject.getOpenedIcon());
else
_label.setIcon(_userObject.getClosedIcon());
_label.setText(_userObject.getTitle());
}
else {
_label.setIcon(null);
_label.setText(value.toString());
}
return _label;
}
}
The next step is building the JTree in a JPanel. We use a datafile to define the Tree nodes. Since
this Tree is designed to be used in Applet, we must pass a JApplet reference to be able to read
some parameters passed via the HTML PARAM tags.
import
import
import
import
import
import
javax.swing.*;
javax.swing.tree.*;
javax.swing.event.*;
java.awt.event.*;
java.awt.*;
java.util.*;
import java.net.*;
import java.io.*;
public class RealSwingTree extends JPanel
implements TreeSelectionListener {
private JApplet parentApplet;
private JTree tree;
private Font f;
private ImageIcon treeIcons[];
private String targetFrame;
public RealSwingTree() {
System.out.println(System.getProperty("os.name"));
try {
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
}
catch (Exception ex_ignored) {
ex_ignored.printStackTrace();
}
}
public void setParentApplet(JApplet j) {
parentApplet = j;
}
public void initTree() {
// build the tree from the datafile
DefaultMutableTreeNode rootNode = null;
DefaultMutableTreeNode currentNode = null;
DefaultMutableTreeNode node = null;
RealSwingNode rsn = null;
RealSwingTreeIconRenderer rstir;
TreeSelectionModel tsm;
int token, value=0, oldvalue=0, rootvalue=0, image1idx=0, image2idx=0;
String strValue, lnkValue, imageValue;
boolean rootDone=false;
boolean itemDone=true;
System.out.println("[RealSwingTree] Begin populateTree() " );
try {
initTreeIcons();
targetFrame = parentApplet.getParameter("targetframe");
URL urlFile =
new URL(parentApplet.getCodeBase(),
parentApplet.getParameter("datafile"));
Reader r = new BufferedReader
(new InputStreamReader(urlFile.openStream()));
StreamTokenizer st = new StreamTokenizer(r);
st.quoteChar('"');
st.eolIsSignificant(false);
st.parseNumbers();
//
// datafile structure <level> <label> <link> <image1> <image2>
//
while ((token = st.nextToken()) != StreamTokenizer.TT_EOF ) {
// get level
value = new Double(st.nval).intValue();
if (!rootDone) {
setFont(f);
setLayout(new BorderLayout());
tree.setRootVisible(true);
tree.setShowsRootHandles(true);
tree.addTreeSelectionListener(this);
tsm = tree.getSelectionModel();
tsm.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
rstir = new RealSwingTreeIconRenderer();
tree.setCellRenderer(rstir);
tree.setRowHeight(0);
add(new JScrollPane(tree),"Center");
}
catch (Exception e) {e.printStackTrace(); }
System.out.println("[RealSwingTree] End populatetree()");
}
rsn = (RealSwingNode)dmtn.getUserObject();
System.out.println("Click! link: " + rsn.getLink());
if (!rsn.getLink().equals("")) {
try {
URL newURL = new URL
(parentApplet.getCodeBase() + rsn.getLink());
System.out.println("
url: " + newURL.toString()
+ " target:" +targetFrame);
parentApplet.getAppletContext().showDocument
(newURL,targetFrame);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
public Dimension getPreferredSize() {
return new Dimension(250, 400);
}
}
Here a sample datafile. The structure is "[level] [label] [link] [image1] [image2]". The image
number is the index of the image passed via the PARAM leaveimageslist.
[treedata.txt]
0 "Welcome | Bienvenue" "welcome.html"
0 "Java Howto" "" "0" "1"
1 "What's new" "javanew.html" "2" "2"
1 "General" "" "0" "1"
2 "part 1" "javag1.html" "2" "2"
Here the HTML used to test the Tree. Since there is almost no error checking, all PARAM tags
are required.
<HTML><BODY>
<APPLET CODE="RealSwingTreeApplet.class"
NAME="RealTree"
HEIGHT=2000 WIDTH=196>
<PARAM NAME="datafile" VALUE="treedata.txt">
<PARAM NAME="bgcolor" VALUE="FFFFFF">
<PARAM NAME="font" VALUE="Courier">
The <APPLET> tag and Swing applet are ok with Appletviewer, but in most browser, you need to
execute the Applet under the Java plugin. Therefore, you need to use the <EMBED> tag with
Netscape or <OBJECT> tag with IE. So for example, with Netscape, the HTML will be like this :
<HTML><BODY>
<EMBED type="application/xjavaapplet;version=1.2.2" width="200"
height="2000" code="RealSwingTreeApplet.class"
datafile="treedata.txt"
bgcolor="FFFFFF"
... other params here ...
pluginspage="http://java.sun.com/products/plugin/1.2/plugininstall.html">
<NOEMBED>
No JDK 1.2 support for APPLET!!
</NOEMBED>
</EMBED>
</BODY></HTML>
Finally, you may want to grab these images used in this Howto .
root.gif
fclose.jpg
fopen.jpg
fpage.jpg
javax.swing.*;
javax.swing.tree.*;
java.awt.event.*;
java.awt.*;
java.util.*;
root.add(node1);
node1.add(node2);
root.add(node3);
node3.add(node4);
setLayout(new BorderLayout());
tree = new JTree(root);
add(new JScrollPane((JTree)tree),"Center");
}
public Dimension getPreferredSize(){
return new Dimension(200, 120);
}
public static void main(String s[]){
MyJFrame frame = new MyJFrame("Tree Collapse Expand");
}
}
class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent e) {
Window win = e.getWindow();
win.setVisible(false);
System.exit(0);
}
}
class MyJFrame extends JFrame implements ActionListener {
JButton b1, b2, b3;
SimpleTree panel;
MyJFrame(String s) {
super(s);
setForeground(Color.black);
setBackground(Color.lightGray);
panel = new SimpleTree();
expandAll(panel.tree);
getContentPane().add(panel,"Center");
b1 = new JButton("Expand");
b3 = new JButton("Expand to last");
b2 = new JButton("Collapse");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
getContentPane().add(b1,"West");
getContentPane().add(b3,"North");
getContentPane().add(b2,"East");
setSize(300,300);
setVisible(true);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowCloser());
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == b1) expandAll(panel.tree);
if (ae.getSource() == b3) expandToLast(panel.tree);
if (ae.getSource() == b2) collapseAll(panel.tree);
}
tree.expandRow(row);
row++;
}
}
/*
// alternate version, suggested by C.Kaufhold
public void expandToLast(JTree tree) {
TreeModel data = tree.getModel();
Object node = data.getRoot();
if (node == null) return;
TreePath p = new TreePath(node);
while (true) {
int count = data.getChildCount(node);
if (count == 0) break;
node = data.getChild(node, count 1);
p = p.pathByAddingChild(node);
}
tree.scrollPathToVisible(p);
}
*/
java.awt.event.ActionEvent;
java.awt.event.ActionListener;
java.awt.event.MouseAdapter;
java.awt.event.MouseEvent;
import javax.swing.JComponent;
import
import
import
import
import
import
import
javax.swing.JMenuItem;
javax.swing.JPopupMenu;
javax.swing.JTree;
javax.swing.tree.DefaultMutableTreeNode;
javax.swing.tree.DefaultTreeModel;
javax.swing.tree.TreeNode;
javax.swing.tree.TreePath;
}
}
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.*;
import javax.swing.tree.*;
public class TreeWithPopup extends JPanel{
DefaultMutableTreeNode root, node1, node2, node3;
public TreeWithPopup() {
MyJTree tree;
root = new DefaultMutableTreeNode("root", true);
node1 = new DefaultMutableTreeNode("node 1", true);
node2 = new DefaultMutableTreeNode("node 2" , true);
node3 = new DefaultMutableTreeNode("node 3", true);
root.add(node1);
node1.add(node2);
root.add(node3);
setLayout(new BorderLayout());
tree = new MyJTree(root);
add(new JScrollPane((JTree)tree),"Center");
}
public Dimension getPreferredSize(){
return new Dimension(300, 300);
}
public static void main(String s[]){
JFrame frame = new JFrame("Tree With Popup");
TreeWithPopup panel = new TreeWithPopup();
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setForeground(Color.black);
frame.setBackground(Color.lightGray);
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Window win = e.getWindow();
win.setVisible(false);
System.exit(0);
}
});
}
}
import
import
import
import
javax.swing.*;
javax.swing.tree.*;
java.awt.event.*;
java.awt.*;
MyApp
See also List of undocumented properties to change the behavior of Swing in Suns JVM.
javax.swing.*;
javax.swing.tree.*;
java.awt.event.*;
java.awt.*;
java.util.*;
java.io.*;
}
}
class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent e) {
Window win = e.getWindow();
win.setVisible(false);
System.exit(0);
}
}
class MyJFrame extends JFrame {
JButton b1, b2, b3;
SimpleTree panel;
MyJFrame(String s) {
super(s);
panel = new SimpleTree();
getContentPane().add(panel,"Center");
setSize(300,300);
setVisible(true);
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(new WindowCloser());
}
}
myJTree.getSelectionModel().
setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
Also you may want to disable the CTRLA key which select the entire tree.
[JDK1.2]
KeyStroke ks = KeyStroke.getKeyStroke("ctrl A");
tree.unregisterKeyboardAction(ks);
[JDK1.3+]
KeyStroke ks = KeyStroke.getKeyStroke("ctrl A");
tree.getInputMap().put(ks, "none");
If you want to use the more regular and + sign to collapse or expand a tree node.
javax.swing.*;
javax.swing.tree.*;
java.awt.event.*;
java.awt.*;
java.util.*;
JFrame {
private JPanel
topPanel;
private JTable
table;
private JScrollPane scrollPane;
SimpleJTable() {
setTitle( "Simple Table Application" );
setSize( 300, 200 );
topPanel = new JPanel();
topPanel.setLayout( new BorderLayout() );
getContentPane().add( topPanel );
Object[][] cellData = {
{"row1col1", "row1col2"},
{"row2col1", "row2col2"},
{"row3col1", "row3col2"},
{"row4col1", "row4col2"},
{"row5col1", "row5col2"}};
String[] columnNames = {"col1", "col2"};
table = new JTable(cellData, columnNames);
}
public static void main(String ... arg) {
SimpleJTable mainFrame = new SimpleJTable();
mainFrame.setVisible( true );
}
}
}
public void setValueAt(Object aValue, int row, int column) {
data[row][column] = aValue;
}
};
aTable = new JTable(dataModel);
ListSelectionModel listMod = aTable.getSelectionModel();
listMod.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
listMod.addListSelectionListener(this);
JScrollPane scrollpane = new JScrollPane(aTable);
scrollpane.setPreferredSize(new Dimension(300, 300));
frame.getContentPane().add(scrollpane);
frame.pack();
frame.setVisible(true);
aTable.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
if (e.getClickCount() == 2){
System.out.println(" double click" );
}
}
} );
}
public void valueChanged(ListSelectionEvent e) {
int maxRows;
int[] selRows;
Object value;
if (!e.getValueIsAdjusting()) {
selRows = aTable.getSelectedRows();
if (selRows.length > 0) {
for (int i= 0; i <3 ; i++) {
// get Table data
TableModel tm = aTable.getModel();
value = tm.getValueAt(selRows[0],i);
System.out.println("Selection : " + value );
}
System.out.println();
}
}
}
public static void main(String[] args) {
new SimpleTable();
}
}
First we need a TableModel to define the data structure to used by the JTable.
[DataFileTableModel.java]
import
import
import
import
import
javax.swing.*;
javax.swing.table.*;
javax.swing.event.*;
java.io.*;
java.util.*;
}
public int getRowCount() {
return data.size() / getColumnCount();
}
public int getColumnCount(){
return columnNames.size();
}
public String getColumnName(int columnIndex) {
String colName = "";
if (columnIndex <= getColumnCount())
colName = (String)columnNames.elementAt(columnIndex);
return colName;
}
public Class getColumnClass(int columnIndex){
return String.class;
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
public Object getValueAt(int rowIndex, int columnIndex) {
return (String)data.elementAt
( (rowIndex * getColumnCount()) + columnIndex);
}
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
return;
}
}
[DataFileTable.java]
import
import
import
import
import
javax.swing.*;
java.awt.event.*;
java.awt.*;
java.io.*;
java.util.*;
}
public Dimension getPreferredSize(){
return new Dimension(400, 300);
}
public static void main(String s[]) {
JFrame frame = new JFrame("Data File Table");
DataFileTable panel;
panel = new DataFileTable("customers.dat");
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setForeground(Color.black);
frame.setBackground(Color.lightGray);
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
frame.addWindowListener(new WindowCloser());
}
}
class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent e) {
Window win = e.getWindow();
win.setVisible(false);
System.exit(0);
}
}
15.52 Read a data file into a JTable and reload if data file have
changedTag(s): Swing
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java0214.html
15.51 Disable row selection in a JTableTag(s): Swing
We use the Observer/Observable mechanism to detect if the data file have been modifed since
the last time.
We use the same data file and DataFileTableModel as the previous Howto. Some minor
modifications are needed for the DataFileTable class. This class now implements the Observer
interface (see the update() method which will be called when the Observable object send a
notification).
[DataFileTable.java]
import
import
import
import
import
javax.swing.*;
java.awt.event.*;
java.awt.*;
java.io.*;
java.util.*;
frame.setBackground(Color.lightGray);
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
frame.addWindowListener(new WindowCloser());
}
}
class WindowCloser extends WindowAdapter {
public void windowClosing(WindowEvent e) {
Window win = e.getWindow();
win.setVisible(false);
System.exit(0);
}
}
The DataFileWatchdog, an Observable object, is simple. We use a Swing Timer to check every
second if a given file have changed. If the timestamp is different then the last one, then all
registered Observers are notified about it.
[DataFileWatchdog.java]
import
import
import
import
javax.swing.Timer;
java.awt.event.*;
java.io.*;
java.util.*;
This technique is not the best one since a exception is generated when Swing tries to display an
"hidden column".
For a better way check out these links :
http://www.codeguru.com/java/articles/660.shtml
http://www.expertsexchange.com/Programming/Programming_Languages/Java/Q_20394392.html
setRowSelectionInterval(row, row);
getModel().fireTableDataChanged(); // notify the model
}
15.57 Make a JList select an item on doubleclick or the ENTER keyTag(s): Swing
this.al = al;
}
}
To try it:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TestActionJList {
public static void main(String args[]) {
JFrame jf = new JFrame();
jf.getContentPane().add(new PanelWithActionJList());
jf.pack();
jf.setVisible(true);
}
}
class PanelWithActionJList extends JPanel {
public PanelWithActionJList() {
setLayout(new GridLayout(1,1));
String[] items =
{ "item 0", "item 1", "item 2", "item 3" , "item 4",
"item 5", "item 6", "item 7", "item 8" , "item 9" };
final ActionJList ajl = new ActionJList(items);
ajl.setVisibleRowCount(5);
ajl.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.out.println("action in Panel " + ajl.getSelectedValue());
}
});
JScrollPane jsp = new JScrollPane();
jsp.getViewport().add(ajl);
add(jsp);
}
}
javax.swing.*;
java.awt.event.*;
java.awt.*;
java.util.*;
import java.util.*;
public class JListWithImages extends JList {
public JListWithImages() {
setCellRenderer(new CustomCellRenderer());
}
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
Vector vector = new Vector();
panel.setForeground(Color.black);
panel.setBackground(Color.white);
// first line
JPanel jp1 = new JPanel();
jp1.add(new JLabel(new ImageIcon("gumby.gif")));
jp1.add(new JLabel("A line for Gumby"));
jp1.add(new JLabel(new ImageIcon("gumby2.gif")));
// second line
JPanel jp2 = new JPanel();
jp2.add(new JLabel(new ImageIcon("gumby.gif")));
jp2.add(new JLabel("Another line for Gumby"));
jp2.add(new JLabel(new ImageIcon("gumby2.gif")));
vector.addElement(jp1);
vector.addElement(jp2);
JListWithImages jlwi = new JListWithImages();
jlwi.setListData(vector);
panel.add(jlwi);
frame.getContentPane().add(panel);
frame.setSize(300,300);
frame.setVisible(true);
}
class CustomCellRenderer implements ListCellRenderer {
public Component getListCellRendererComponent
(JList list, Object value, int index,
boolean isSelected,boolean cellHasFocus) {
Component component = (Component)value;
component.setBackground
(isSelected ? Color.black : Color.white);
component.setForeground
(isSelected ? Color.white : Color.black);
return component;
}
}
}
The above Howto use the default layout, so each line line in the JList are centered. The version
below is showing each line left justified instead.
import
import
import
import
javax.swing.*;
javax.swing.border.*;
java.awt.*;
java.util.*;
public JListWithImages() {
setCellRenderer(new CustomCellRenderer());
}
public static void main(String[] args) {
JFrame frame = new JFrame();
JPanel panel = new JPanel();
Vector vector = new Vector();
panel.setForeground(Color.black);
panel.setBackground(Color.white);
// first line
JPanel jp1 = new JPanel(new FlowLayout(FlowLayout.LEFT));
jp1.add(new JLabel(new ImageIcon("gumby.gif")));
jp1.add(new JLabel("A line for Gumby"));
jp1.add(new JLabel(new ImageIcon("gumby2.gif")));
// second line
JPanel jp2 = new JPanel(new FlowLayout(FlowLayout.LEFT));
jp2.add(new JLabel(new ImageIcon("gumby.gif")));
jp2.add(new JLabel("Another line for Gumby"));
jp2.add(new JLabel(new ImageIcon("gumby2.gif")));
// NEW
// NEW
vector.addElement(jp1);
vector.addElement(jp2);
JListWithImages jlwi = new JListWithImages();
jlwi.setListData(vector);
jlwi.setBorder(new LineBorder(Color.black));
panel.add(jlwi);
frame.getContentPane().add(panel);
frame.setSize(300,300);
frame.setVisible(true);
}
class CustomCellRenderer implements ListCellRenderer {
public Component getListCellRendererComponent
(JList list, Object value, int index,
boolean isSelected,boolean cellHasFocus) {
Component component = (Component)value;
component.setBackground
(isSelected ? Color.black : Color.white);
component.setForeground
(isSelected ? Color.white : Color.black);
return component;
}
}
}
import
import
import
import
javax.swing.*;
java.awt.event.*;
java.awt.*;
java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;
import java.text.Collator;
// import java.util.Locale;
public class SortJList extends JPanel
implements ActionListener{
JButton jb1, jb2;
JTextField tf;
JList list;
int i = 1;
public SortJList(){
Vector data;
setLayout(new BorderLayout());
list = new JList();
list.setModel(new DefaultListModel());
add(new JScrollPane(list),"Center");
add(jb1 = new JButton("Add"), "West");
add(jb2 = new JButton("Sort"), "East");
add(tf = new JTextField(), "North");
jb1.addActionListener(this);
jb2.addActionListener(this);
}
public Dimension getPreferredSize(){
return new Dimension(50, 50);
}
public void actionPerformed(ActionEvent ae) {
DefaultListModel dlm;
if (ae.getSource() == jb1) {
// add
dlm = (DefaultListModel)list.getModel();
dlm.addElement
((Object) tf.getText());
}
else {
// sort
dlm = (DefaultListModel) list.getModel();
int numItems = dlm.getSize();
String[] a = new String[numItems];
for (int i=0;i<numItems;i++){
a[i] = (String)dlm.getElementAt(i);
}
sortArray(Collator.getInstance(),a);
// Locale loc = Locale.FRENCH;
// sortArray(Collator.getInstance(loc), (String[])a);
for (int i=0;i<numItems;i++) {
dlm.setElementAt(a[i], i);
}
}
}
public static void sortArray(Collator collator, String[] strArray) {
String tmp;
if (strArray.length == 1) return;
for (int i = 0; i < strArray.length; i++) {
for (int j = i + 1; j < strArray.length; j++) {
if( collator.compare(strArray[i], strArray[j] ) > 0 ) {
tmp = strArray[i];
strArray[i] = strArray[j];
strArray[j] = tmp;
}
}
}
}
public static void main(String s[]) {
JFrame frame = new JFrame("Sort JList");
SortJList panel = new SortJList();
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.getContentPane().add(panel,"Center");
frame.setSize(200,200);
frame.setVisible(true);
}
}
javax.swing.*;
java.awt.event.*;
java.awt.*;
java.util.*;
}
}
class ActionJList extends MouseAdapter{
protected JList list;
public ActionJList(JList l){
list = l;
}
public void mouseClicked(MouseEvent e){
if(e.getClickCount() == 2){
int index = list.locationToIndex(e.getPoint());
ListModel dlm = list.getModel();
Object item = dlm.getElementAt(index);;
list.ensureIndexIsVisible(index);
System.out.println("Double clicked on " + item);
}
}
}
javax.swing.*;
java.awt.event.*;
java.awt.*;
java.util.*;
list.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent me) {
// if right mouse button clicked (or me.isPopupTrigger())
if (SwingUtilities.isRightMouseButton(me)
&!list.isSelectionEmpty()
&list.locationToIndex(me.getPoint())
== list.getSelectedIndex()) {
popupMenu.show(list, me.getX(), me.getY());
}
}
}
);
jmi1.addActionListener(this);
jmi2.addActionListener(this);
}
public Dimension getPreferredSize(){
return new Dimension(50, 50);
}
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == jb1 || ae.getSource() == jmi1) {
// add
DefaultListModel dlm =
(DefaultListModel) list.getModel();
dlm.addElement
((Object) Integer.toString(i++));
}
else {
// clear
list.setModel(new DefaultListModel());
}
}
public static void main(String s[]) {
JFrame frame = new JFrame("PopUp JList");
PopUpJList panel = new PopUpJList();
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.getContentPane().add(panel,"Center");
frame.setSize(200,200);
frame.setVisible(true);
}
}
import javax.swing.*;
import java.awt.*;
public class SelectableJLabel extends JPanel {
public SelectableJLabel() {
// a regular JLabel
add(new JLabel("You can't select me"));
// a lookalike JLabel
JTextField f = new JTextField("You can select me");
f.setEditable(false);
f.setBorder(null);
f.setForeground(UIManager.getColor("Label.foreground"));
f.setFont(UIManager.getFont("Label.font"));
add(f);
}
public Dimension getPreferredSize() {
return new Dimension(100, 100);
}
public static void main(String s[]){
JFrame frame = new JFrame("SelectableJLabel");
SelectableJLabel panel = new SelectableJLabel();
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize());
frame.setVisible(true);
}
}
java.awt.Color;
java.awt.event.*;
javax.swing.*;
javax.swing.Timer;
}
}
// for testing
private static void createAndShowUI() {
JFrame frame = new JFrame("BlinkLabel");
final BlinkLabel bl = new BlinkLabel("I'm blinking!");
frame.getContentPane().setLayout(new java.awt.FlowLayout());
frame.getContentPane().add(bl);
JButton b = new JButton("toogle blink");
b.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent ae) {
bl.blinkingOn = !bl.blinkingOn;
}
});
frame.getContentPane().add(b);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
public static void main(String[] args) {
java.awt.EventQueue.invokeLater(new Runnable(){
public void run(){
createAndShowUI();
}
});
}
//
}
To the end
myJTextArea.setCaretPosition(myJTextArea.getDocument().getLength());
javax.swing.*;
javax.swing.plaf.*;
java.awt.event.*;
java.awt.*;
setSize(400, 300);
getContentPane().setLayout(new FlowLayout());
// globally
UIManager.put("ToolTip.font",
new FontUIResource("SansSerif", Font.BOLD, 18));
JButton b1 = new JButton("tooltip 1");
b1.setToolTipText("tool tip sansserif bold");
getContentPane().add(b1);
// only one
String html =
"<html><p><font color=\"#800080\" " +
"size=\"4\" face=\"Verdana\">tool tip verdana" +
"</font></p></html>";
JButton b2 = new JButton("tooltip 2");
b2.setToolTipText(html);
getContentPane().add(b2);
WindowListener wndCloser = new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(wndCloser);
setVisible(true);
}
public static void main(String args[]){
new TooltipInSwing();
}
}
ToolTipManager.sharedInstance().setDismissDelay(Integer.MAX_VALUE);
getContentPane().add(b1);
WindowListener wndCloser = new WindowAdapter(){
public void windowClosing(WindowEvent e) {
System.exit(0);
}
};
addWindowListener(wndCloser);
setVisible(true);
}
public static void main(String args[]){
new TooltipInSwing();
}
}
output :
Second technique
import
import
import
import
java.io.*;
javax.swing.*;
java.awt.*;
javax.swing.filechooser.FileSystemView;
output:
If you need more generic image, you use a JFileChooser and extract the image for a file or
directory.
import
import
import
import
java.io.*;
javax.swing.*;
java.awt.*;
javax.swing.filechooser.*;
import javax.swing.*;
import java.awt.event.*;
class RightJMenuBar {
public static void main(String args[]) {
new RightJMenuBar().doit();
}
public void doit() {
JFrame frame = new JFrame("Real's HowTo");
JMenuBar menuBar = new JMenuBar();
// Create a menu
JMenu menu = new JMenu("Menu Label");
JMenuItem item = new JMenuItem("item");
menu.add(item);
menuBar.add(menu);
// shift to the right
menuBar.add(Box.createGlue());
// this button will be shifted right on the menubar
Action actionQuit = new AbstractAction("Quit") {
public void actionPerformed(ActionEvent evt) {
System.exit(0);
}
};
menuBar.add(new JButton(actionQuit));
frame.setJMenuBar(menuBar);
frame.setSize(300,300);
frame.setVisible(true);
}
}
How it looks :
16 Thread
16.1 javathread
++
| thread B |
++
(CONSUME)
>
[ProduceData.java]
import java.io.*;
public abstract class ProduceData implements Runnable {
OutputStream os;
public ProduceData(OutputStream os) {
this.os = os;
Thread t = new Thread(this);
t.start();
}
public abstract boolean dataProduction();
public void run() {
while(dataProduction()) ;
}
}
[ConsumeData.java]
import java.io.*;
public abstract class ConsumeData implements Runnable {
InputStream is;
public ConsumeData(InputStream is) {
this.is = is;
Thread t = new Thread(this);
t.start();
}
16 Thread
16 Thread
}
catch (Exception e) {
e.printStackTrace();
}
return true;
}
}
[TestThread.java]
import java.io.*;
public class TestThread {
public static void main(String a[]){
try {
PipedOutputStream os = new PipedOutputStream();
PipedInputStream is = new PipedInputStream();
os.connect(is);
new SendProduction(os);
new ReceiveProduction(is);
}
catch (Exception e) {}
}
}
++
> | thread B |
|
++
|
(consume)
|
|
|
++
+ > | thread C |
++
(CONSUME)
The ProduceData.class and ConsumeData.class are the same as the previous JAVA Howto.
[AtomicInputStream.java]
import java.io.*;
16.3 Pipe the output of a thread to the input of other threadsTag(s): Thread
[SendProduction.java]
import java.io.*;
public class SendProduction extends ProduceData {
OutputStream os;
SendProduction(OutputStream os) {
super(os);
this.os = os;
}
public boolean dataProduction() {
byte[] j = new byte[3];
boolean done = false;
j[0] = 0 ; j[1] = 1; j[2] = 2;
while(!done) {
try {
os.write(j, 0, 3);
}
catch (Exception e) {
e.printStackTrace();
return true;
}
}
return done;
}
}
[ReceiveProduction.java]
import java.io.*;
public class ReceiveProduction extends ConsumeData {
AtomicInputStream as;
ReceiveProduction(AtomicInputStream as) {
super(as);
this.as = as;
}
16.3 Pipe the output of a thread to the input of other threadsTag(s): Thread
[TestThread.java]
import java.io.*;
public class TestThread {
public static void main(String a[]){
try {
PipedOutputStream os = new PipedOutputStream();
AtomicInputStream as = new AtomicInputStream(3);
os.connect(as);
new SendProduction(os);
new ReceiveProduction(as);
new ReceiveProduction(as);
new ReceiveProduction(as);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
testThread(int i) {
super();
this.i = i;
}
public void run() {
for (int j=0; j < i; j++) {
System.out.println
(Thread.currentThread().getName() + " " + j);
}
System.out.println
(Thread.currentThread().getName() + " FINISHED");
}
public static void main(String a[]) {
try {
testThread tt1 = new testThread(50);
testThread tt2 = new testThread(75);
Thread t1 = new Thread(tt1,"Test thread 1");
Thread t2 = new Thread(tt2,"Test thread 2");
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println("Main FINISHED");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
if (state == STOP)
return false;
return true;
}
public void run() {
while true {
doSomething();
if (!checkState())
break;
}
}
) , seconds*1000 ) ;
Swing also provide a Timer class. A Timer object will send an ActionEvent to the registered
ActionListener.
import javax.swing.Timer;
import java.awt.event.*;
import java.util.*;
public class TimerDemo implements ActionListener {
Timer t = new Timer(1000,this);
TimerDemo() {
t.start();
}
public static void main(String args[]) {
TimerDemo td = new TimerDemo();
// create a dummy frame to keep the JVM running
// (for demonstation purpose)
java.awt.Frame dummy = new java.awt.Frame();
dummy.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == t) {
System.out.println
("\007Being ticked " + Calendar.getInstance().getTime());
}
}
}
Wait.manySec(5);
System.out.println("Done");
}
}
java.applet.*;
java.awt.*;
java.awt.event.*;
java.net.*;
(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
e.getWindow().dispose();
}
}
);
}
}
class DelayedMethod extends Thread {
AnnoyingPopUps myObj = null; // customize for your need
boolean oktorun = false;
int delay;
DelayedMethod(AnnoyingPopUps myObj) {
this.myObj = myObj;
this.delay = 2000;
}
DelayedMethod(AnnoyingPopUps myObj, int delay) {
this.myObj = myObj;
this.delay = delay;
}
public void run() {
while (true) {
try {
sleep(delay);
if (oktorun)
myObj.displayPopup(); // customize this too!
}
catch (InterruptedException ignored) {}
}
}
}
}
import java.util.concurrent.TimeUnit;
public class DemoScheduledTask {
public static void main(String args[]) {
// pool size == 5
ScheduledThreadPoolExecutor stpe = new ScheduledThreadPoolExecutor(5);
SimpleTask01 st01 = new SimpleTask01();
// start right now and after every 5 sec.
stpe.scheduleAtFixedRate(st01, 0, 5, TimeUnit.SECONDS);
SimpleTask02 st02 = new SimpleTask02();
// start in 1 sec and after every 2 sec.
stpe.scheduleAtFixedRate(st02, 1, 2, TimeUnit.SECONDS);
}
}
class SimpleTask01 implements Runnable {
public void run() {
System.out.println("Real's HowTo");
}
}
class SimpleTask02 implements Runnable {
int current = 10;
public void run() {
if (current > 0) {
System.out.println(current);
if (current == 0) {
System.out.println("end.");
}
}
}
}
Consumer(){
super("Consumer");
}
public void run(){
for(;;){
try {
Thread.sleep(1);
}
catch (Exception e){
e.printStackTrace();
}
Iterator it = data.iterator();
while (it.hasNext()) it.next();
}
}
}
static class Producer extends Thread {
Producer(){
super("Producer");
}
public void run(){
for(;;){
try {
Thread.sleep(1);
}
catch (Exception e){
e.printStackTrace();
}
data.addElement(new Object());
if (data.size() > 1000) data.removeAllElements();
}
}
}
}
The following Exception is generated very quickly because the Producer is trying to modify the data
(a Vector) while the Consumer is using it.
java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(Unknown Source)
at java.util.AbstractList$Itr.next(Unknown Source)
at RW$Consumer.run(RW.java:26)
The solution is to use the keyword synchronized to put a lock on the data while we are using it.
import java.util.*;
public class RW {
private static Vector data = new Vector();
public static void main(String[] args) throws Exception {
new Producer().start();
new Consumer().start();
}
static class Consumer extends Thread {
Consumer(){
super("Consumer");
}
public void run(){
for(;;){
try {
Thread.sleep(1);
}
catch (Exception e){
e.printStackTrace();
}
synchronized(data){
Iterator it = data.iterator();
while (it.hasNext()) it.next();
}
}
}
}
static class Producer extends Thread {
Producer(){
super("Producer");
}
public void run(){
for(;;){
try {
Thread.sleep(1);
}
catch (Exception e){
e.printStackTrace();
}
data.addElement(new Object());
if (data.size() > 1000) data.removeAllElements();
}
}
}
}
PrepareProduction(BlockingQueue<String> q) { queue = q; }
public void run() {
String thisLine;
System.out.println("Start PrepareProduction");
try {
FileInputStream fin = new FileInputStream("d:/input_data.dat");
BufferedReader input = new BufferedReader
(new InputStreamReader(fin));
while ((thisLine = input.readLine()) != null) {
queue.put(thisLine);
}
fin.close();
input.close();
// special marker for the consumer threads
// to mark the EOF
queue.put("*");
queue.put("*");
queue.put("*");
queue.put("*");
queue.put("*");
queue.put("*");
queue.put("*");
queue.put("*");
queue.put("*");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
A Consumer extract a value from the Queue and execute an operation. If there is no data in the
Queue, the BlockingQueue will wait. The endofdata is marked by the presence of a special
marker (the "*" in this example).
import java.util.concurrent.BlockingQueue;
public class DoProduction implements Runnable {
private final BlockingQueue<String> queue;
DoProduction(BlockingQueue<String> q) { queue = q; }
public void run() {
try {
System.out.println
("Start " + Thread.currentThread().getName());
String value = queue.take();
while (!value.equals("*")) {
//System.out.println
// (Thread.currentThread().getName()+": " + value );
/*
do something with value
*/
value = queue.take();
}
}
catch (Exception e) {
System.out.println
(Thread.currentThread().getName() + " " + e.getMessage());
}
}
}
A test class
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class Test {
public static void main(String[] args) throws Exception {
BlockingQueue<String> q =
new LinkedBlockingQueue<String>();
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
p1
c1
c2
c3
c4
c5
c6
c7
c8
c9
=
=
=
=
=
=
=
=
=
=
new
new
new
new
new
new
new
new
new
new
Thread(new
Thread(new
Thread(new
Thread(new
Thread(new
Thread(new
Thread(new
Thread(new
Thread(new
Thread(new
PrepareProduction(q));
DoProduction(q));
DoProduction(q));
DoProduction(q));
DoProduction(q));
DoProduction(q));
DoProduction(q));
DoProduction(q));
DoProduction(q));
DoProduction(q));
p1.start();
c1.start();
c2.start();
c3.start();
c4.start();
c5.start();
c6.start();
c7.start();
c8.start();
c9.start();
p1.join();
c1.join();
c2.join();
c3.join();
c4.join();
c5.join();
c6.join();
c7.join();
c8.join();
c9.join();
System.out.println("Done.");
}
}
Using a LinkedList
If you need don't need all the benefits of BlockingQueue then a simple LinkedList can be more
appropriate, especially if you need to process large amount of data in a batch process. Since you
are in a multithreaded world, it's safer to use the synchronized version of the LinkedList
implementation. Keep in mind that theses examples are minimal and need more error checking!
First the Producer
import java.io.*;
import java.util.*;
public class PrepareProduction implements Runnable{
private final List<String> queue;
PrepareProduction(List<String> q) { queue = q; }
public void run() {
String thisLine;
System.out.println("Start PrepareProduction");
try {
FileInputStream fin = new FileInputStream("d:/input_data.dat");
BufferedReader input = new BufferedReader
(new InputStreamReader(fin));
while ((thisLine = input.readLine()) != null) {
queue.add(thisLine);
}
fin.close();
input.close();
// special marker for EOF
queue.add("*");
queue.add("*");
queue.add("*");
queue.add("*");
queue.add("*");
queue.add("*");
queue.add("*");
queue.add("*");
queue.add("*");
}
catch (Exception e) {
e.printStackTrace();
}
}
}
The Consumer
import java.util.*;
public class DoProduction implements Runnable {
private final List<String> queue;
DoProduction(List<String> q) { queue = q; }
public void run() {
try {
System.out.println("Start "
+ Thread.currentThread().getName());
// you may need to wait for the first data available
// with a BlockingQueue it's done for you.
String value = queue.remove(0);
while (!value.equals("*")) {
System.out.println(Thread.currentThread().getName()
+": " + value );
/*
do something with value
*/
value = queue.remove(0);
}
}
catch (Exception e) {
System.out.println(Thread.currentThread().getName()
The test
import java.util.*;
public class Test {
public static void main(String[] args) throws Exception {
List q = Collections.synchronizedList
(new LinkedList<String>());
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
Thread
p1
c1
c2
c3
c4
c5
c6
c7
c8
c9
=
=
=
=
=
=
=
=
=
=
new
new
new
new
new
new
new
new
new
new
Thread(new
Thread(new
Thread(new
Thread(new
Thread(new
Thread(new
Thread(new
Thread(new
Thread(new
Thread(new
PrepareProduction(q));
DoProduction(q));
DoProduction(q));
DoProduction(q));
DoProduction(q));
DoProduction(q));
DoProduction(q));
DoProduction(q));
DoProduction(q));
DoProduction(q));
p1.start();
c1.start();
c2.start();
c3.start();
c4.start();
c5.start();
c6.start();
c7.start();
c8.start();
c9.start();
p1.join();
c1.join();
c2.join();
c3.join();
c4.join();
c5.join();
c6.join();
c7.join();
c8.join();
c9.join();
System.out.println("Done.");
}
}
Code :
public class TestVMID {
public static void main(String arg[]) {
System.out.println(new java.rmi.dgc.VMID().toString());
System.out.println(new java.rmi.dgc.VMID().toString());
System.out.println(new java.rmi.dgc.VMID().toString());
}
}
Output :
d578271282b42fce:2955b56e:107df3fbc96:8000
d578271282b42fce:2955b56e:107df3fbc96:7fff
d578271282b42fce:2955b56e:107df3fbc96:7ffe
See also this HowTo for unique numerical id based on the system time.
17 Varia
17.1 javavaria
17 Varia
The format is :
[2 chars for each byte in 4 byte ip address]:
[8 char unique string]:
[16 char from time in hex]:
[8 char from count]
Code :
public class TestVMID {
public static void main(String arg[]) {
System.out.println(new java.rmi.dgc.VMID().toString());
System.out.println(new java.rmi.dgc.VMID().toString());
System.out.println(new java.rmi.dgc.VMID().toString());
}
}
Output :
d578271282b42fce:2955b56e:107df3fbc96:8000
d578271282b42fce:2955b56e:107df3fbc96:7fff
d578271282b42fce:2955b56e:107df3fbc96:7ffe
See also this HowTo for unique numerical id based on the system time.
java.io.File;
java.io.FileWriter;
java.io.BufferedReader;
java.io.InputStreamReader;
17.8 Get the hard disk serial number or Motherboard serial numberTag(s): Varia
java.io.File;
java.io.FileWriter;
java.io.BufferedReader;
java.io.InputStreamReader;
}
input.close();
}
catch(Exception e){
e.printStackTrace();
}
return result.trim();
}
public static void main(String[] args){
String sn = DiskUtils.getSerialNumber("C");
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
null, sn, "Serial Number of C:",
javax.swing.JOptionPane.DEFAULT_OPTION);
}
}
[testArraySorter.java]
public class testArraySorter {
public static final ASCIIComparer asciiComparer = new ASCIIComparer();
public static void main(String args[]) {
if (args.length == 0)
System.out.println("give me some args to sort");
else {
ArraySorter.sort(args, asciiComparer);
for (int i = 0; i < args.length; i++) {
System.out.println(args[i]);
}
}
}
public static class ASCIIComparer implements ArraySorter.Comparer {
public int compare(Object a, Object b) {
return ((String)a).compareTo((String)b);
}
}
}
JDK1.4 casesensitive
String[] myArray = new String[] {"foo","bar","baz"};
java.util.Arrays.sort(myArray);
caseinsensitive
Case insensitive
java.util.Arrays.sort(myArray, String.CASE_INSENSITIVE_ORDER);
The output is :
Before :
Ral Real Raoul Rico
After :
Raoul Real Rico Ral
by
java.util.Arrays.sort(words, java.text.Collator.getInstance(java.util.Locale.FRENCH));
// or
// java.util.Arrays.sort(words, java.text.Collator.getInstance());
strArray[j] = tmp;
}
}
}
}
double d = Double.valueOf(n).doubleValue();
return true;
}
catch (NumberFormatException e) {
e.printStackTrace();
return false;
}
}
/*
** For testing purpose
**
**
java SSNUtils or java SSNUtils
**
*/
public static void main(String args[]) throws Exception {
String aSSN = "";
if (args.length > 0)
aSSN = args[0];
else {
BufferedReader input =
new BufferedReader(new InputStreamReader(System.in));
System.out.print("SSN number : ");
aSSN = input.readLine();
}
System.out.println
("The SSN " + aSSN + " is " +(validSSN(aSSN)?" good.":" bad."));
}
}
INVALID
VISA
MASTERCARD
AMERICAN_EXPRESS
EN_ROUTE
DINERS_CLUB
=
=
=
=
=
=
1;
0;
1;
2;
3;
4;
/**
* Valid a Credit Card number
*/
public static boolean validCC(String number)
throws Exception {
int CardID;
if ( (CardID = getCardID(number)) != 1)
return validCCNumber(number);
return false;
}
/**
* Get the Card type
* returns the credit card type
*
INVALID
= 1;
*
VISA
= 0;
*
MASTERCARD
= 1;
*
AMERICAN_EXPRESS = 2;
*
EN_ROUTE
= 3;
*
DINERS_CLUB
= 4;
*/
public static int getCardID(String number) {
int valid = INVALID;
String
String
String
String
digit1
digit2
digit3
digit4
=
=
=
=
number.substring(0,1);
number.substring(0,2);
number.substring(0,3);
number.substring(0,4);
if (isNumber(number)) {
/*
** VISA prefix=4
** length=13 or 16 (can be 15 too!?! maybe)
*/
if (digit1.equals("4")) {
if (number.length() == 13 || number.length() == 16)
valid = VISA;
}
/*
** MASTERCARD prefix= 51 ... 55
** length= 16
*/
else if (digit2.compareTo("51")>=0 &digit2.compareTo("55")<=0) {
if (number.length() == 16)
valid = MASTERCARD;
}
/*
** AMEX prefix=34 or 37
** length=15
*/
else if (digit2.equals("34") || digit2.equals("37")) {
if (number.length() == 15)
valid = AMERICAN_EXPRESS;
}
/*
** ENROU prefix=2014 or 2149
** length=15
*/
else if (digit4.equals("2014") || digit4.equals("2149")) {
if (number.length() == 15)
valid = EN_ROUTE;
}
/*
** DCLUB prefix=300 ... 305 or 36 or 38
** length=14
*/
else if (digit2.equals("36") || digit2.equals("38") ||
(digit3.compareTo("300")>=0 &digit3.compareTo("305")<=0)) {
if (number.length() == 14)
valid = DINERS_CLUB;
}
}
return valid;
/*
** DISCOVER card prefix = 60
**
lenght = 16
**
left as an exercise ...
*/
}
public static boolean isNumber(String n) {
try {
double d = Double.valueOf(n).doubleValue();
return true;
}
catch (NumberFormatException e) {
e.printStackTrace();
return false;
}
}
public static String getCardName(int id) {
return (id > 1 &id < cardNames.length ? cardNames[id] : "");
}
public static boolean validCCNumber(String n) {
try {
/*
** known as the LUHN Formula (mod10)
*/
int j = n.length();
String [] s1 = new String[j];
for (int i=0; i < n.length(); i++) s1[i] = "" + n.charAt(i);
int checksum = 0;
for (int i=s1.length1; i >= 0; i= 2) {
int k = 0;
if (i > 0) {
k = Integer.valueOf(s1[i1]).intValue() * 2;
if (k > 9) {
String s = "" + k;
k = Integer.valueOf(s.substring(0,1)).intValue() +
Integer.valueOf(s.substring(1)).intValue();
}
checksum += Integer.valueOf(s1[i]).intValue() + k;
}
else
checksum += Integer.valueOf(s1[0]).intValue();
}
return ((checksum % 10) == 0);
}
catch (Exception e) {
e.printStackTrace();
return false;
}
}
/*
** For testing purpose
**
**
java CCUtils [credit card number] or java CCUtils
**
*/
public static void main(String args[]) throws Exception {
String aCard = "";
if (args.length > 0)
aCard = args[0];
else {
BufferedReader input =
new BufferedReader(new InputStreamReader(System.in));
System.out.print("Card number : ");
aCard = input.readLine();
}
if (getCardID(aCard) > 1) {
System.out.println("This card is supported.");
System.out.println("This a " + getCardName(getCardID(aCard)));
System.out.println
("The card number " + aCard + " is "
+ (validCC(aCard)?" good.":" bad."));
}
else
System.out.println("This card is invalid or unsupported!");
}
}
}
class MyClass {
MyClass() {
System.out.println
(this.getClass().getName() + " is loaded from " +
this.getClass().getProtectionDomain().getCodeSource().getLocation());
}
}
The output
>java LoadingFromWhere
LoadingFromWhere is loaded from file:/C:/temp/
MyClass is loaded from file:/C:/temp/
The output
> java FromWhere
This class (FromWhere) is located at : file:/C:/temp/
17.17 Get the class name with or without the packageTag(s): Varia
The output
Frame
java.awt.Frame
java.awt
ClassUtils
ClassUtils
GregorianCalendar
java.util.GregorianCalendar
java.util
Thanks to L. Janovszki for the idea
Alternate way to get only the package name (null if there is no package) :
Class cls = java.lang.String.class;
Package pkg = cls.getPackage();
String name = pkg.getName();
// java.lang
17.17 Get the class name with or without the packageTag(s): Varia
Compile the source code and then disassemble the bytecode with
javap c Test1
// to redirect the output to a file
javap c Test1 >test1.out
The Result is
Compiled from "Test1.java"
class Test1 extends java.lang.Object{
Test1();
Code:
0:
aload_0
1:
invokespecial
#1; //Method java/lang/Object."":()V
4:
return
public static void main(java.lang.String[]);
Code:
0:
new #2; //class java/lang/Integer
3:
dup
4:
iconst_1
5:
invokespecial
#3; //Method java/lang/Integer."":(I)V
8:
pop
9:
new #2; //class java/lang/Integer
12: dup
13: iconst_2
14: invokespecial
#3; //Method java/lang/Integer."":(I)V
17: pop
18: new #2; //class java/lang/Integer
21: dup
22: iconst_3
23: invokespecial
#3; //Method java/lang/Integer."":(I)V
26: pop
27: return
}
and compile the following class and dissassemble the Test2 class.
class Test2 {
public static void main(String args[]) {
int
new
new
new
i = 1;
Integer(i++);
Integer(i++);
Integer(i++);
}
}
Compiled from "Test2.java"
class Test2 extends java.lang.Object{
Test2();
Code:
0:
aload_0
1:
invokespecial
#1; //Method java/lang/Object."":()V
4:
return
public static void main(java.lang.String[]);
Code:
0:
iconst_1
1:
istore_1
2:
new #2; //class java/lang/Integer
5:
dup
6:
iload_1
7:
iinc
1, 1
10: invokespecial
#3; //Method java/lang/Integer."":(I)V
13: pop
14: new #2; //class java/lang/Integer
17: dup
18: iload_1
19: iinc
1, 1
22: invokespecial
#3; //Method java/lang/Integer."":(I)V
25: pop
26: new #2; //class java/lang/Integer
29: dup
30: iload_1
31: iinc
1, 1
34: invokespecial
#3; //Method java/lang/Integer."":(I)V
37: pop
38: return
}
Second example
17.19 Self replicating programsTag(s): Varia
Third example
author Daniel Pitts
[Q.java]
enum Q {a("enum Q{a(%c%s%c);Q(String t){System.out.printf(t,34,t,34);System.exit(0);}}");
Q(String t){System.out.printf(t,34,t,34);System.exit(0);}}
The URL in the middle does not generate any compiler warning because http: is considered as a
label and the //www.rgagnon... is seen as a comment.
The next one is strange. From the main(), we create a Foo instance, then we call getFoo() which
returns a null and from "null" , we can access the value of fubar!
public class Foo {
static int fubar = 42;
Foo getFoo() {
return null;
}
42
(from Usenet)
>
>
>
>
>
>
>
>
>
I am new to java, and I really havent had time to do much work in it.
However, I have a small project that is due next week for my class. Can
anyone help me by providing some code? It should do the following;
The program is simple. It should allow a user to input a string of digits,
and then output the sum of those digits.
For example; the user inputs 3563
the program would then output 17 (3+5+6+3)
Signature programs are short programs that people have been using as part of their signature in
Usenet message or email. They are small programs, that are often rather cryptic because they have
to save space as much as possible.
Here collection of classic signature programs, my own signature when I was a the Universite de
Montreal (a long time ago...) is there!
+
Real Gagnon,
|
Universite de Montreal
|
xxxxxxx@xxx.xxxxxxxxx.xx |
#include
/* BC ok , Apollo NFG */
int main(void) { int i=0;
while(putchar(i++["\13Dl~fxym789\26xd"]i));
while(putchar((i)["\0\t+*)('}
A signature program in Java is not an easy task because Java is lot more verbose than C. Here an
attempt, try it to see the output!
The above code is shown as an image to make sure that special characters are rendered correctly.
To see the actual code, download the source : Howto.java.
See also this HowTo
2:
int i = 0;
if (i = 0){
System.out.println("Won't print, why ?");
}
3:
public class WontCompile {
public static void main(String[] args) {
getInt(09);
}
private static void getInt(int i) {
System.out.println(i);
}
}
4:
// this don't do what it is supposed to do
void setIsDirtyData(boolean isdirtyData) {this.isDirtyData = isDirtyData;}
java.util.List;
javax.script.ScriptEngineManager;
javax.script.ScriptEngine;
javax.script.ScriptEngineFactory;
javax.script.ScriptException;
java.util.Arrays;
java.util.List;
javax.script.ScriptEngineManager;
javax.script.ScriptEngine;
javax.script.ScriptException;
+ " println(values[index]);"
+ "}";
try {
engine.eval(jsCode);
}
catch (ScriptException se) {
se.printStackTrace();
}
// pass a collection from javascript to java
jsCode =
"importPackage(java.util);"
+ "var list2 = Arrays.asList(['Moe', 'Barney', 'Ned']); ";
try {
engine.eval(jsCode);
}
catch (ScriptException se) {
se.printStackTrace();
}
List <String> list2 = (List<String>) engine.get("list2");
System.out.println("*** Javascript object to Java");
for (String val : list2) {
System.out.println(val);
}
}
}
/*
output :
*** Java object to Javascript
Homer
Bart
Marge
Maggie
Lisa
*** Javascript object to Java
Moe
Barney
Ned
*/
The next example uses an external file containing the javascript code. The .JS file is loaded from
the classpath.
[scripting02.js]
importPackage(java.util);
var list1 = Arrays.asList
(['Homer', 'Bart', 'Marge', 'Maggie', 'Lisa']);
var listObject = {
list2 : Arrays.asList
(['Moe', 'Barney', 'Ned']),
getList2 : function() {
return listObject.list2;
}
};
import java.io.InputStreamReader;
import java.util.List;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
public class Scripting02 {
public static void main(String[] args) throws Exception{
ScriptEngineManager mgr = new ScriptEngineManager();
// we are using the rhino javascript engine
ScriptEngine engine = mgr.getEngineByName("javascript");
// the .js is in the classpath
engine.eval(new InputStreamReader
(Scripting02.class.getResourceAsStream("scripting02.js")));
// retreive a javascript object directly
List <String> list1 = (List <String>)engine.get("list1");
if (list1 != null) {
for (String s : (List<String>) list1) {
System.out.println(s);
}
}
System.out.println("***");
// call a javascript function to retrieve an object
if (engine instanceof Invocable){
Invocable engineInv = (Invocable)engine;
Object obj = engine.get("listObject");
Object list2 = engineInv.invokeMethod(obj, "getList2");
if (list2 != null) {
for (String s : (List<String>) list2) {
System.out.println(s);
}
}
}
}
}
/*
output :
Homer
Bart
Marge
Maggie
Lisa
***
Moe
Barney
Ned
*/
Because each application is running in it's own JVM, there is no obvious way to detect if a particuliar
application is already running.
The socket technique
One way to detect to prevent multiple application execution is to use a simple socket server. The
application will try a connection to that Server, if it's a success then the application is already
running (and the application is stopped), if no connection is made then the application create the
Server.
In this example, the simple server is running on the same machine as the application so the
machine name is "localhost", the port 80 is used, you may want to customize the port number for
your machine.
[JustOneServer.java]
import java.io.*;
import java.net.*;
public class JustOneServer extends Thread {
// you may need to customize this for your machine
public static final int PORT = 80 ;
ServerSocket serverSocket = null;
Socket clientSocket = null;
public void run() {
try {
// Create the server socket
serverSocket = new ServerSocket(port, 1);
while (true) {
// Wait for a connection
clientSocket = serverSocket.accept();
// System.out.println("*** Got a connection! ");
clientSocket.close();
}
}
catch (IOException ioe) {
System.out.println("Error in JustOneServer: " + ioe);
}
}
}
[JustOne.java]
import java.io.*;
import java.net.*;
public class JustOne {
SimpleDummyServer sds = null;
public static void main(String args[]){
new JustOne().doit();
}
public void doit() {
try {
Socket clientSocket = new Socket("localhost", JustOneServer.PORT);
System.out.println("*** Already running!");
System.exit(1);
}
catch (Exception e) {
sds = new JustOneServer();
sds.start();
}
while(true) {
try { System.out.print("."); Thread.sleep(5 * 60); }
catch(Exception e) { e.printStackTrace(); }
}
}
}
}
}
}
}
[JustOneTest.java]
public class JustOneTest {
public static void main(String[] args) {
new JustOneTest().test();
}
void test() {
JustOneLock ua = new JustOneLock("JustOneId");
if (ua.isAppActive()) {
System.out.println("Already active.");
System.exit(1);
}
else {
System.out.println("NOT already active.");
try {
while(true) {
try { System.out.print("."); Thread.sleep(5 * 60); }
catch(Exception e) { e.printStackTrace(); }
}
}
catch (Exception e) { }
}
}
}
Runtime.getRuntime().exec
(new String[] {
"cmd.exe",
"/c",
"\"" + System.getenv("APPDATA") +
"\\Microsoft\\Internet Explorer\\Quick Launch\\Show Desktop.scf" + "\""});
}
}
.scf is a special file that contains a command for the Windows Explorer.
This command file can be localized for Windows in a different language, for the french Windows, it's
"Bureau.scf". It may be a good to make a copy of it under a different (and known) name and
location.
18 XML
18.1 javaxml
18 XML
XPath is a language that describes a way to locate and process items in XML documents by using
an addressing syntax based on a path through the document's logical structure or hierarchy.
Xalan is a specification for transforming XML documents into HTML or other XML document types.
Xerces is a set of parsers compatible with XML.
XHTML (Extensible Hypertext Markup Language) is a reformulation of HTML 4.0 as an application
of the XML.
Useful links:
JAXP overview
<TD><SPAN datafld="url"></SPAN></TD>
</TR>
</TABLE>
</BODY>
</HTML>
[howto.xsl]
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="1.0">
<xsl:template match="/">
<html>
<head><title>Real's HowTo</title></head>
<body>
<table border="1">
<tr>
<th>Title</th>
<th>URL</th>
</tr>
<xsl:foreach select="howto/topic">
<tr>
<td><xsl:valueof select="title"/></td>
<td><xsl:valueof select="url"/></td>
</tr>
</xsl:foreach>
</table>
</body></html>
</xsl:template>
</xsl:stylesheet>
[HowToXSLT.java]
// jdk1.4.1
import javax.xml.transform.*;
import java.net.*;
import java.io.*;
public class HowToXSLT {
public static void main(String[] args) {
try {
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer =
tFactory.newTransformer
(new javax.xml.transform.stream.StreamSource
("howto.xsl"));
transformer.transform
(new javax.xml.transform.stream.StreamSource
("howto.xml"),
new javax.xml.transform.stream.StreamResult
( new FileOutputStream("howto.html")));
}
catch (Exception e) {
e.printStackTrace( );
}
}
}
<howto>
<topic>
<title>Java</title>
<url>http://www.rgagnon/javahowto.htm</url>
</topic>
<topic>
<title>PowerBuilder</title>
<url>http://www.rgagnon/pbhowto.htm</url>
</topic>
<topic>
<title>Javascript</title>
<url>http://www.rgagnon/jshowto.htm</url>
</topic>
<topic>
<title>VBScript</title>
<url>http://www.rgagnon/vbshowto.htm</url>
</topic>
</howto>
[HowToListerSAX.java]
// jdk1.4.1
import java.io.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
// using SAX
public class HowToListerSAX {
class HowToHandler extends DefaultHandler {
boolean title = false;
boolean url
= false;
public void startElement(String nsURI, String strippedName,
String tagName, Attributes attributes)
throws SAXException {
if (tagName.equalsIgnoreCase("title"))
title = true;
if (tagName.equalsIgnoreCase("url"))
url = true;
}
public void characters(char[] ch, int start, int length) {
if (title) {
System.out.println("Title: " + new String(ch, start, length));
title = false;
}
else if (url) {
System.out.println("Url: " + new String(ch, start,length));
url = false;
}
}
}
[HowToListerDOM.java]
// jdk1.4.1
import java.io.File;
import javax.xml.parsers.*;
import org.w3c.dom.*;
// using DOM
public class HowtoListerDOM {
public static void main(String[] args) {
File file = new File("howto.xml");
try {
DocumentBuilder builder =
DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = builder.parse(file);
NodeList nodes = doc.getElementsByTagName("topic");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
NodeList title = element.getElementsByTagName("title");
Element line = (Element) title.item(0);
System.out.println("Title: " + getCharacterDataFromElement(line));
NodeList url = element.getElementsByTagName("url");
line = (Element) url.item(0);
System.out.println("Url: " + getCharacterDataFromElement(line));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}
}
javax.xml.parsers.*;
org.xml.sax.InputSource;
org.w3c.dom.*;
java.io.*;
Name: Sara
Title: Clerk
*/
}
public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;
return cd.getData();
}
return "?";
}
}
org.w3c.dom.*;
javax.xml.parsers.*;
javax.xml.transform.*;
javax.xml.transform.stream.*;
javax.xml.transform.dom.*;
(OutputKeys.OMIT_XML_DECLARATION, "yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING,"ISO88591");
transformer.setOutputProperty
("{http://xml.apache.org/xslt}indentamount", "4");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
java.io.StringWriter sw = new java.io.StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);
String xml = sw.toString();
return xml;
}
public static void main(String args[])
throws javax.xml.parsers.ParserConfigurationException,
javax.xml.transform.TransformerException,
javax.xml.transform.TransformerConfigurationException{
System.out.println(new TestDOM().doit());
/*
output :
<?xml version="1.0" encoding="ISO88591"?>
<howto>
<java url="http://www.ragagnon.com/howto.html"/>
</howto>
/*
}
}
</data>
bruce.xsl
<?xml version="1.0" encoding="ISO88591"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<table>
<xsl:foreach select="data/guynamedbruce">
<tr>
<td>
<xsl:valueof select="FirstName"/>
</td>
<td>
<xsl:valueof select="LastName"/>
</td>
</tr>
</xsl:foreach>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
Try it here
org.w3c.dom.*;
javax.xml.parsers.*;
javax.xml.transform.*;
javax.xml.transform.stream.*;
javax.xml.transform.dom.*;
The result is
<?xml version="1.0" encoding="ISO88591"?>
<HOWTOS>
<TOPIC>
<TITLE>Java</TITLE>
<URL>http://www.rgagnon/topics/javaxml.html</URL>
</TOPIC>
</HOWTOS>
import java.io.*;
import
import
import
import
import
org.w3c.dom.*;
javax.xml.parsers.*;
javax.xml.transform.*;
javax.xml.transform.stream.*;
javax.xml.transform.dom.*;
(OutputKeys.OMIT_XML_DECLARATION, "no");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING,"ISO88591");
// we want to pretty format the XML output
transformer.setOutputProperty
("{http://xml.apache.org/xslt}indentamount", "4");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//
transformer.transform(domSource, out);
}
}
The result is
<?xml version="1.0" encoding="ISO88591"?>
<?xmlstylesheet type="text/xsl" href="howto.xsl"?>
<HOWTOS>
<TOPIC>
<TITLE>Java</TITLE>
<URL>http://www.rgagnon/topics/javaxml.html</URL>
</TOPIC>
</HOWTOS>
The java.beans package provides useful methods to save an object state into an XML file and easily
read it back.
Here an Helper class for our Foo class.
import java.beans.XMLEncoder;
import java.beans.XMLDecoder;
import java.io.*;
public class FooHelper {
public static void write(Foo f, String filename) throws Exception{
XMLEncoder encoder =
new XMLEncoder(
new BufferedOutputStream(
new FileOutputStream(filename)));
encoder.writeObject(f);
encoder.close();
}
public static Foo read(String filename) throws Exception {
XMLDecoder decoder =
new XMLDecoder(new BufferedInputStream(
new FileInputStream(filename)));
Foo o = (Foo)decoder.readObject();
decoder.close();
return o;
}
}
}
}
Just for fun, here the resulting XML file (with my installation)
<?xml version="1.0" encoding="UTF8"?>
<java version="1.5.0beta" class="java.beans.XMLDecoder">
<object class="Foo">
<void property="foo">
<string>bar</string>
</void>
</object>
/JAVA
// SAX classes.
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import
import
import
import
javax.xml.parsers.*;
javax.xml.transform.*;
javax.xml.transform.stream.*;
javax.xml.transform.sax.*;
BufferedReader in;
StreamResult out;
TransformerHandler th;
AttributesImpl atts;
public static void main (String args[]) {
new ToXML().doit();
}
public void doit () {
try{
in = new BufferedReader(new FileReader("data.txt"));
out = new StreamResult("data.xml");
initXML();
String str;
while ((str = in.readLine()) != null) {
process(str);
}
in.close();
closeXML();
}
catch (Exception e) { e.printStackTrace(); }
}
th.endElement("","","TITLE");
th.startElement("","","URL",atts);
th.characters(elements[1].toCharArray(),0,elements[1].length());
th.endElement("","","URL");
th.endElement("","","TOPIC");
}
public void closeXML() throws SAXException {
th.endElement("","","HOWTOS");
th.endDocument(); }
}
import java.io.*;
import
import
import
import
import
org.w3c.dom.*;
javax.xml.parsers.*;
javax.xml.transform.*;
javax.xml.transform.stream.*;
javax.xml.transform.dom.*;
BufferedReader in;
StreamResult out;
Document xmldoc;
Element root;
public static void main (String args[]) {
new ToXML().doit();
}
public void doit () {
try{
in = new BufferedReader(new FileReader("data.txt"));
out = new StreamResult("data.xml");
initXML();
String str;
while ((str = in.readLine()) != null) {
process(str);
}
in.close();
writeXML();
}
catch (Exception e) { e.printStackTrace(); }
}
java.sql.Connection;
java.sql.Statement;
java.sql.Driver;
java.sql.DriverManager;
java.sql.ResultSet;
java.sql.ResultSetMetaData;
import
import
import
import
import
import
import
javax.xml.parsers.DocumentBuilder;
javax.xml.parsers.DocumentBuilderFactory;
javax.xml.transform.*;
javax.xml.transform.stream.*;
javax.xml.transform.dom.*;
org.w3c.dom.Document;
org.w3c.dom.Element;
class JDBCapp
String sql;
try {
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder =factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element results = doc.createElement("Results");
doc.appendChild(results);
// connection to an ACCESS MDB
con = AccessCon.getConnection();
sql = "select objet from Email";
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount();
while (rs.next()) {
Element row = doc.createElement("Row");
results.appendChild(row);
for (int ii = 1; ii <= colCount; ii++) {
String columnName = rsmd.getColumnName(ii);
Object value = rs.getObject(ii);
Element node = doc.createElement(columnName);
node.appendChild(doc.createTextNode(value.toString()));
row.appendChild(node);
}
}
System.out.println(getDocumentAsXml(doc));
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (con != null) con.close();
if (stmt != null) stmt.close();
if (rs != null) rs.close();
}
catch (Exception e) {
}
}
}
public static String getDocumentAsXml(Document doc)
throws TransformerConfigurationException, TransformerException {
DOMSource domSource = new DOMSource(doc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
//transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
transformer.setOutputProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperty(OutputKeys.ENCODING,"ISO88591");
// we want to pretty format the XML output
// note : this is broken in jdk1.5 beta!
transformer.setOutputProperty
("{http://xml.apache.org/xslt}indentamount", "4");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
//
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.*;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class SimpleXPath {
public static void main(String[] args) throws Exception {
XPath xpath = XPathFactory.newInstance().newXPath();
String xpathExpression = "/howto/topic/@name";
InputSource inputSource = new InputSource("howto.xml");
NodeList nodes = (NodeList) xpath.evaluate
(xpathExpression, inputSource, XPathConstants.NODESET);
int j = nodes.getLength();
for (int i = 0; i < j; i++) {
System.out.println(nodes.item(i).getTextContent());
}
/*
output :
Java
PowerBuilder
Javascript
VBScript
*/
}
}
int j = urls.getLength();
for (int i = 0; i < j ; i++) {
if (urls.item(i).getNodeName().equals("url")) {
System.out.println("url :" + urls.item(i).getTextContent());
}
}
/*
output :
url :http://www.rgagnon.com/topics/pbcommon.html
url :http://www.rgagnon.com/topics/pbpfc.html
*/
}
}
If your XML is in a String (not in a File) then you need to get an InputStream from it.
import java.io.ByteArrayInputStream;
import java.io.InputStream;
...
String xml = "<?xml version="1.0"?>"
+ " <howto>"
+ "
<topic name="Java">"
...
+ "</howto>";
You may need to pass the required encoding to the String.getBytes() method. See this HowTo
Consider this XML :
<?xml version="1.0" encoding="UTF8"?>
<UDSObjectList>
<UDSObject>
<Handle>chg_tpl:400004</Handle>
<Attributes>
<Attribute DataType="2001">
<AttrName>id</AttrName>
<AttrValue>400004</AttrValue>
</Attribute>
<Attribute DataType="2002">
<AttrName>persistent_id</AttrName>
<AttrValue>chg_tpl:400004</AttrValue>
</Attribute>
</Attributes>
</UDSObject>
</UDSObjectList>
If we want the Handle text value then we don't need to retrieve the NODESET, only the TEXT.
import
import
import
import
java.io.ByteArrayInputStream;
java.io.InputStream;
javax.xml.xpath.XPath;
javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
...
String xml = "<?xml version="1.0" encoding="UTF8"?>"
+ "<UDSObjectList>"
...
+ "</UDSObjectList>";
...
InputStream is = new ByteArrayInputStream(xml.getBytes("UTF8"));
XPath xpath = XPathFactory.newInstance().newXPath();
String xpathExpression = "/UDSObjectList/UDSObject/Handle";
InputSource inputSource = new InputSource(is);
String handle = xpath.evaluate(xpathExpression, inputSource);
System.out.println(handle);
/*
output :
chg_tpl:400004
*/
One last example. Suppose we have an XML file containing SQL Statements.
<queries>
<query id="getUserByName">select * from users where name=?</query>
<query id="getUserByEmail">select * from users where email=?</query>
</queries>
To retrieve a SELECT
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;
import org.xml.sax.InputSource;
public class Test {
public static void main(String[] args) throws Exception {
System.out.println(getQuery("getUserByName"));
System.out.println(getQuery("getUserByEmail"));
}
public static String getQuery (String id) throws Exception {
XPath xpath = XPathFactory.newInstance().newXPath();
// in this example, sql.xml is loaded from the classpath
InputSource is = new InputSource(Test.class.getResourceAsStream("/sql.xml"));
return xpath.evaluate("/queries/query[@id='" + id +"']", is);
}
}
/* output :
select * from users where name=?
select * from users where email=?
*/
org.w3c.dom.*;
javax.xml.parsers.*;
javax.xml.transform.*;
javax.xml.transform.stream.*;
javax.xml.transform.dom.*;
The result is
<?xml version="1.0" encoding="ISO88591"?>
<HOWTOS>
<TOPIC>
<TITLE>Java</TITLE>
<URL>http://www.rgagnon/topics/javaxml.html</URL>
</TOPIC>
</HOWTOS>
org.w3c.dom.*;
javax.xml.parsers.*;
javax.xml.transform.*;
javax.xml.transform.stream.*;
javax.xml.transform.dom.*;
The result is
<?xml version="1.0" encoding="ISO88591"?>
<?xmlstylesheet type="text/xsl" href="howto.xsl"?>
<HOWTOS>
<TOPIC>
<TITLE>Java</TITLE>
<URL>http://www.rgagnon/topics/javaxml.html</URL>
</TOPIC>
</HOWTOS>
p.loadFromXML(in);
p.list(System.out);
/*
output :
listing properties
today=Thu Aug 09 22:45:11 EDT 2007
user=Bob
*/
}
catch (Exception e) {
e.printStackTrace();
}
}
}
import
import
import
import
import
import
import
javax.xml.transform.Transformer;
javax.xml.transform.TransformerFactory;
javax.xml.transform.dom.DOMSource;
javax.xml.transform.stream.StreamResult;
javax.xml.xpath.XPath;
javax.xml.xpath.XPathConstants;
javax.xml.xpath.XPathFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
public class XMLReplaceDemo {
static String inputFile = "C:/temp/data.xml";
static String outputFile = "C:/temp/data_new.xml";
public static void main(String[] args) throws Exception {
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(new InputSource(inputFile));
// locate the node(s)
XPath xpath = XPathFactory.newInstance().newXPath();
NodeList nodes = (NodeList)xpath.evaluate
("//employee/name[text()='John']", doc, XPathConstants.NODESET);
// make the change
for (int idx = 0; idx < nodes.getLength(); idx++) {
nodes.item(idx).setTextContent("John Paul");
}
// save the result
Transformer xformer = TransformerFactory.newInstance().newTransformer();
xformer.transform
(new DOMSource(doc), new StreamResult(new File(outputFile)));
}
}
The result
<?xml version="1.0" encoding="UTF8" standalone="no"?><data>
<employee>
<name>John Paul</name>
<title>Manager</title>
</employee>
<employee>
<name>Sara</name>
<title>Clerk</title>
</employee>
</data>
howto (topic*)>
topic (title,url)>
title (#PCDATA)>
url (#PCDATA)>
java.io.IOException;
javax.xml.parsers.DocumentBuilder;
javax.xml.parsers.DocumentBuilderFactory;
javax.xml.parsers.SAXParser;
javax.xml.parsers.SAXParserFactory;
org.xml.sax.XMLReader;
import javax.xml.parsers.ParserConfigurationException;
import
import
import
import
org.xml.sax.ErrorHandler;
org.xml.sax.SAXException;
org.xml.sax.SAXParseException;
org.xml.sax.InputSource;
NOTES :
The DOM is faster than SAX but DOM reads the entire structure in memory so the memory
consumption is bigger.
DTD is the old way to validate an XML structure. The preferred way is to use an XML schema
(XSD) which provides a more complete validation process.
To validate using an XML Schema (XSD), see this HowTo
The code (using SAX parser) to validate an XML file using a given external XSD.
import java.io.IOException;
// SAX
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.XMLReader;
//SAX and external XSD
import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.SchemaFactory;
import
import
import
import
import
javax.xml.parsers.ParserConfigurationException;
org.xml.sax.ErrorHandler;
org.xml.sax.SAXException;
org.xml.sax.SAXParseException;
org.xml.sax.InputSource;
The code (using DOM parser) to validate an XML file using the referenced XSD :
import java.io.IOException;
// DOM
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import
import
import
import
import
javax.xml.parsers.ParserConfigurationException;
org.xml.sax.ErrorHandler;
org.xml.sax.SAXException;
org.xml.sax.SAXParseException;
org.xml.sax.InputSource;
The code (using SAX parser) to validate an XML file using the referenced XSD :
import
// SAX
import
import
import
java.io.IOException;
import
import
import
import
import
javax.xml.parsers.ParserConfigurationException;
org.xml.sax.ErrorHandler;
org.xml.sax.SAXException;
org.xml.sax.SAXParseException;
org.xml.sax.InputSource;
javax.xml.parsers.SAXParser;
javax.xml.parsers.SAXParserFactory;
org.xml.sax.XMLReader;
factory.setNamespaceAware(true);
SAXParser parser = factory.newSAXParser();
parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage",
"http://www.w3.org/2001/XMLSchema");
XMLReader reader = parser.getXMLReader();
reader.setErrorHandler(
new ErrorHandler() {
public void warning(SAXParseException e) throws SAXException {
System.out.println("WARNING: " + e.getMessage()); // do nothing
}
public void error(SAXParseException e) throws SAXException {
System.out.println("ERROR: " + e.getMessage());
throw e;
}
public void fatalError(SAXParseException e) throws SAXException {
System.out.println("FATAL: " + e.getMessage());
throw e;
}
}
);
reader.parse(new InputSource(xml));
return true;
}
catch (ParserConfigurationException pce) {
throw pce;
}
catch (IOException io) {
throw io;
}
catch (SAXException se){
return false;
}
}
public static void main (String args[]) throws Exception{
System.out.println(XMLUtils.validateWithIntXSDWithSAX("c:/temp/howto.xml"));
}
}
This HowTo uses the builtin XML parser, you can switch JAXP in debug mode by passing a
special switch on the JVM commandline.
java Djaxp.debug=1 ...
or
java Djaxp.debug ...
NOTES :
The DOM is faster than SAX but DOM reads the entire structure in memory so the memory
consumption is bigger.
See http://en.wikibooks.org/wiki/XML_Schema for more infos about XSD.
To validate using an DTD, see this HowTo.
Decimal
#9
#10
#13
#32#55295
#57344#65533
#10000#1114111
any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.
ref : http://www.w3.org/TR/RECxml/#charsets.
The exception to this rule is that CDATA sections may contain any character, including ones not in the above range.
For example, if data is coming from a Cut&Paste operation from a Microsoft Word document, you
may end up with 0x1a characters. Later, when the XML data is parsed, an Exception
"hexadecimal value 0x1A, is an invalid character" will be thrown.
The following methods will remove all invalid XML characters from a given string (the special
handling of a CDATA section is not supported).
Using Regex
public static String sanitizeXmlChars(String xml) {
if (xml == null || ("".equals(xml))) return "";
// ref : http://www.w3.org/TR/RECxml/#charsets
// jdk 7
Pattern xmlInvalidChars =
Pattern.compile(
"[^\\u0009\\u000A\\u000D\\u0020\\uD7FF\\uE000\\uFFFD\\x{10000}\\x{10FFFF}]"
);
return xmlInvalidChars.matcher(xml).replaceAll("");
}
will produce
Read the article.
RSS is a method to syndicate content on the web. This is done by creating an XML document
which summarizes specific content such as news, blog posts or comments or any informations.
There are many versions but the 2 most used are RSS 2.0 and ATOM.
18.24.2 Atom
Atom was an answer to the incompatibilites between all the RSS versions. Adopted by the IETF,
the official specification is RFC4287, http://www.ietf.org/rfc/rfc4287.
18.24.2 Atom
java.io.File;
java.io.FileInputStream;
java.io.FileOutputStream;
java.io.IOException;
import
import
import
import
java.util.ArrayList;
java.util.Collection;
java.util.Date;
java.text.SimpleDateFormat;
class CreateRSSFeedUsingCommons {
public static void main(String args[]) {
SimpleDateFormat formatter=
new SimpleDateFormat("dd MMM yyyy HH:mm:ss Z");
String today = formatter.format(new Date());
Channel newChannel = new Channel();
newChannel.setCopyright("(c)Real Gagnon 2007");
newChannel.setDescription("Useful Java code examples");
newChannel.setLink("http://www.rgagnon.com/howto.html");
newChannel.setLanguage("en");
newChannel.setPubDate(today);
The result is :
<?xml version="1.0"?>
<!DOCTYPE rss PUBLIC
"//Netscape Communications//DTD RSS 0.91//EN"
"http://my.netscape.com/publish/formats/rss0.91.dtd">
<rss version="0.91">
<channel>
<title>null</title>
<description>Useful Java code examples</description>
<link>http://www.rgagnon.com/howto.html</link>
<language>en</language>
<copyright>(c)Real Gagnon 2007</copyright>
<pubDate>29 mai 2007 23:48:42 0400</pubDate>
<item>
<title>Real's HowTo</title>
<link>http://www.rgagnon.com/javadetails/</link>
<description>Cool java snippet!</description>
</item>
</channel>
</rss>
The RSS created is at version 0.91 level. To support RSS v2 file then you need to modify the
source files yourself ... that's what OpenSource is all about!
import com.sun.syndication.feed.synd.*;
import com.sun.syndication.io.SyndFeedOutput;
import
import
import
import
import
import
java.io.FileWriter;
java.io.Writer;
java.text.DateFormat;
java.text.SimpleDateFormat;
java.util.ArrayList;
java.util.List;
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
public String getPubDate() {
return pubdate;
}
public void setPubDate(String pubdate) {
this.pubdate = pubdate;
}
}
}
public String getLanguage() {
return language;
}
public void setLanguage(String language) {
this.language = language;
}
public String getCopyright() {
return copyright;
}
public void setCopyright(String copyright) {
this.copyright = copyright;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
public String getGuid() {
return guid;
}
public void setGuid(String guid) {
this.guid = guid;
}
}
java.text.SimpleDateFormat;
java.util.Calendar;
java.util.List;
java.util.Locale;
javax.xml.stream.XMLEventFactory;
javax.xml.stream.XMLEventWriter;
javax.xml.stream.XMLOutputFactory;
javax.xml.stream.XMLStreamException;
javax.xml.stream.events.Characters;
javax.xml.stream.events.EndElement;
javax.xml.stream.events.StartDocument;
javax.xml.stream.events.StartElement;
javax.xml.stream.events.XMLEvent;
entry.setGuid("http://www.rgagnon.com/javadetails/java0605.html");
entry.setLink("http://www.rgagnon.com/javadetails/java0605.html");
entry.setPubDate(RSSFeed.formatDate(Calendar.getInstance()));
entries.add(entry);
feed.setEntries(entries);
try {
RSSWriter.write(feed, TestRSSWriter.RSSFEED);
}
catch (Exception e) {
e.printStackTrace();
}
System.out.println("Done.");
}
}
The result is
<?xml version="1.0"?>
<rss version="2.0">
<channel>
<title>Real's HowTo</title>
<link>http://www.rgagnon.com</link>
<description>Useful code snippets for Java</description>
<language>en</language>
<copyright>Copyright by Real Gagnon</copyright>
<pubDate>Mon, 23 Jun 2008 11:15:31 0400</pubDate>
<item>
<title>The PDF are updated</title>
<description>Java (756 pages), Powerbuilder (197), Javascript (99) and VBS (32)</descript
<link>http://64.18.163.122/rgagnon/download/index.htm</link>
<guid>http://64.18.163.122/rgagnon/download/index.htm</guid>
<pubDate>Mon, 23 Jun 2008 11:15:31 0400</pubDate>
</item>
<item>
<title>Java : Display a TIF</title>
<description>Using JAI, how to display a TIF file</description>
<link>http://www.rgagnon.com/javadetails/java0605.html</link>
<guid>http://www.rgagnon.com/javadetails/java0605.html</guid>
<pubDate>Mon, 23 Jun 2008 11:15:31 0400</pubDate>
</item>
</channel>
</rss>
In a previous HowTo, we saw how to create a RSS feed using commons.digester or ROME
packages. In this HowTo, we are parsing a given feed using the packages.
import org.apache.commons.digester.rss.Channel;
import org.apache.commons.digester.rss.Item;
import org.apache.commons.digester.rss.RSSDigester;
import java.net.HttpURLConnection;
import java.net.URL;
public class ParseRSSFeedUsingCommons {
public static void main(String args[]) throws Exception {
RSSDigester digester=new RSSDigester();
String feed = "http://www.rgagnon.com/feed.xml";
URL url=new URL(feed);
HttpURLConnection httpSource=
(HttpURLConnection)url.openConnection();
Channel channel=
(Channel)digester.parse(httpSource.getInputStream());
if (channel==null) {
throw new Exception("can't communicate with " + url);
}
Item rssItems[]=channel.findItems();
for (int i=0;i<rssItems.length;i++) {
System.out.println(rssItems[i].getTitle());
System.out.println(rssItems[i].getLink());
System.out.println(rssItems[i].getDescription());
System.out.println();
}
/*
to parse from a file instead of a URL
import java.io.FileInputStream;
...
String feed = "feed.xml"
FileInputStream fis = new FileInputStream(feed);
Channel channel=(Channel)digester.parse(fis);
...
*/
}
}
the output
JS: Resize an IFRAME based on its content
http://www.rgagnon.com/jsdetails/js0129.html
Using the onLoad event, resize the IFRAME according to its content
Java: Communicate between threads using a Queue
http://www.rgagnon.com/javadetails/java0555.html
BlockingQueue (Java 5) is designed to work in a multithreaded world
JDBC: Escape special character in a LIKE clause
http://www.rgagnon.com/javadetails/java0554.html
How to use LIKE clause wildcards as literals
...
import
import
import
import
com.sun.syndication.feed.synd.*;
com.sun.syndication.feed.synd.SyndFeed;
com.sun.syndication.io.SyndFeedInput;
com.sun.syndication.io.XmlReader;
import java.net.URL;
import java.util.List;
import java.util.Iterator;
public class ParseRSSFeedUsingRome {
public static void main(String args[]) throws Exception {
String feed = "http://www.rgagnon.com/feed.xml";
URL feedUrl = new URL(feed);
SyndFeedInput input = new SyndFeedInput();
SyndFeed sf = input.build(new XmlReader(feedUrl));
List entries = sf.getEntries();
Iterator it = entries.iterator();
while (it.hasNext()) {
SyndEntry entry = (SyndEntry)it.next();
System.out.println(entry.getTitle());
System.out.println(entry.getLink());
SyndContent description = entry.getDescription();
System.out.println(description.getValue());
System.out.println();
}
/*
to parse from a file instead of a URL
import java.io.FileInputStream;
...
String feed = "feed.xml"
FileInputStream fis = new FileInputStream(feed);
SyndFeedInput input = new SyndFeedInput();
SyndFeed sf = input.build(new XmlReader(fis));
*/
}
}
18.26.3 RSSUTIL.TLD
A Sun article about a JSP Tag Library to parse a RSS feed.
http://java.sun.com/developer/technicalArticles/javaserverpages/rss_utilities/
</xsl:template>
</xsl:stylesheet>
19 DEPRECATED
19.1 javadeprecated
For example
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world.");
IO.PressAnyKey();
}
19 DEPRECATED
See also this Howto for a solution using the Sun's JVM and the REG utility.
If an error is returned by the Win32 API called, you can't get the actual error code by calling the
standard getLastError() Win32 API. You must use the special keyword setLastError in the
@dll.import directive to instruct the JVM to keep the error code. Then you retrieve the error code by
calling the getLastWin32Error() method from the DllLib class.
import com.ms.dll.DllLib;
public class TestChangeDirectory {
public static void main (String[] args) {
boolean rc;
// for demonstration
// we specify a nonexistent directory, to get an error code...
StringBuffer newdir = new StringBuffer("Unknown directory");
rc = SetCurrentDirectoryA(newdir);
if (!rc) {
int err = DllLib.getLastWin32Error();
// should be rc : 2 "ERROR_FILE_NOT_FOUND"
System.out.println("rc : " + err);
To be able to do the same in Applet, you need to sign the Applet then make the following call before
making API calls:
import com.ms.security.*;
...
PolicyEngine.assertPermission(PermissionID.SYSTEM);
Thanks to H. Parvillers for the tip.
The javareg utility is part of the Microsoft Java SDK which can be freely downloaded from the
Microsoft Web site.
First a simple Java class.
[JavaSays.java]
package JavaCom;
public class JavaSays {
public String Hello() {
return "Hello world" ;
}
public String Say(String what) {
return what ;
}
}
That's it. The system now has a COM object called JavaCom.JavaSays installed.
VbScript and JScript are useful scripting tools. They are now part of a regular Windows installation
(or IE). If your Windows installation is too old, you can download the Windows Scripting Host from
the Microsoft Web site.
[VbScript TestJavaCom.vbs]
' VBSCRIPT connect to a Java COM object
Dim objJava
Set objJava = WScript.CreateObject("JavaCom.JavaSays")
strFromJava = objJava.Hello
MsgBox strFromJava, _
0,
_
"JAVA COM OUTPUT"
19.11 Wrap a Java class in a COM object (this howto is deprecated)Tag(s): DEPRECATED
http://www.rgagnon.com/javadetails/../javadetails/java0122.html
This howto is deprecated (old stuff)
You need to obtain a certificate from a trusted source.
A Certificate for developer can be purchased for about $200 (with $100/year to renew it), see
Thawte certification for example. For non US citizen, it can be difficult to obtain a certificate from US
based trusted source, because of the exportation limitation imposed on encryption technique.
Certificates used to sign email are not secured enough to sign applets, they are CLASS 1
certificate, you need something like CLASS 3 to be able to sign an applet.
Signing an Applet means signing the JAR containing the Applet. To sign a JAR, you need tools
provided by Netscape. Zigbert is a commandline utility. Also a GUI JAR packager can be used to
sign JARS. You may look at this JAVA Howto for infos about JAR file.
Sun's JAVAKEY utility can't be used to produce/sign certificate/JAR compatible for the Netscape
security manager. Read the Netscape's security FAQ or Netscape OBJECT SIGNING
RESOURCES for more informations.
Once the Applet signed, we must use the netscape.security (also called Capabilities) package to
grant/remove privileges. This package is included with Netscape v4 or can be downloaded from the
Netscape Web site.
When compiling a JAVA source containing references to the Capabilities class, we must adjust to
CLASSPATH to include the JAR java40.jar (with v4).
set CLASSPATH=
.;c:\windev\jdk1.1.3\lib\classes.zip;
c:\program files\netscape\communicator\program\java\classes\java40.jar;
WILL ENABLEJAR file without a certificate to request privileges on your machine. If you agree, it
will be possible for an Applet to lauch a program, write a file on your hard disk or print on the printer.
You will still have to ask for privileges in your program using the Netscape capabilites classes.
19.13 Bypass the need for a certificate (this howto is deprecated)Tag(s): DEPRECATED
Another way is to lower general security setting to more allow more freedom when running applets
locally. Add or modify the following entries in the prefs.js:
user_pref("unsigned.applets.low_security_for_local_classes", true);
user_pref("signed.applets.local_classes_have_30_powers", true);
user_pref("signed.applets.low_security_for_local_classes", true);
user_pref("signed.applets.verbose_security_exception", true);
Then you don't need to asked for privileges for local classes.
NOTE: When adding or modifying the file prefs.js, Netscape must not be running because your modification will be overwritten. So shut down
Netscape, edit the prefs.js and then restart Netscape.
With IE, you can achieve the same thing through the Internet option menu.
Internet Options
Security Tab
Internet Custom level
Java permissions
Custom radio buttons
Java Custom settings
select the permissions given to unsigned content.
import
import
import
import
java.applet.*;
java.awt.*;
java.awt.event.*;
netscape.security.*;
lauchButton.addActionListener(this);
filename = new TextField(20);
add(filename);
browserName = System.getProperty("java.vendor");
if (browserName.indexOf("Netscape") > 1)
securitySupported = true;
setSize(200, 200);
}
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() == lauchButton) {
if (securitySupported) {
PrivilegeManager.enablePrivilege("UniversalExecAccess");
try {
Runtime.getRuntime().exec("notepad.exe " + filename.getText());
}
catch(Exception e) {
e.printStackTrace();
}
}
else {
getAppletContext().showStatus("security not installed");
}
}
}
}
19.15 Get rid of the message "Warning unsigned applet window" (this howto is deprecated)Tag(s): DEPRE
import
import
import
import
import
java.applet.*;
java.awt.*;
java.awt.event.*;
java.io.*;
netscape.security.*;
19.15 Get rid of the message "Warning unsigned applet window" (this howto is deprecated)Tag(s): DEPRE
else {
getAppletContext().showStatus("security not installed");
}
}
}
}
19.17 Write "otherbrowserfriendly" code when using the Netscape Capabilities package (this howto is dep
In application, with the Sun JVM, you have the following options:
java Djava.compiler=NONE myapp
or
SET JAVA_COMPILER=NONE (Set the environment variable JAVA_COMPILER)
java myapp
or
JAVA NOJIT MYAPP
With the MS JVM, you set the environment variable MSJAVA_ENABLE_JIT to 0 to disable the
Microsoft JIT, or use the Registry key
HKEY_CURRENT_USER\Software\Microsoft\Java VM\EnableJIT
START_JAVA
and then
START MYPAGE.HTML
19.21 Avoid the Netscape "Couldn't connect to '' with origin from 'localclasspathclasses'" message. (this h
The only reliable way is to get this information from the serverside.
import java.net.*;
import java.io.*;
import java.applet.*;
public class GetClientIP extends Applet {
public void init() {
try {
InetAddress thisIp =
InetAddress.getLocalHost();
System.out.println("IP:"+thisIp.getHostAddress());
}
catch(Exception e) {
e.printStackTrace();
}
}
}
<HTML><HEAD></HEAD><BODY>
<APPLET CODE="GetClientIP.class"
HEIGHT=10 WIDTH=10>
</APPLET>
Check JAVA console for output
/BODY
Try it here
NOTE: Netscape returns the IP address with the default security settings so it's not problem. With IE5, you must go to the security TAB,
Internet, Java Custom, Edit and select "Allow access to all IP address".
For example, our MyApplet.class exists in three versions. One is using Microsoftspecific classes,
the other is a JDK1.1 applet and finally a version for JDK102only browser. The idea is to put all the
required classes in an ARCHIVE file. By using a javascript entities, we decide which archive to use.
During layout time, the javascript entity is remplaced by the right archive name.
<HTML></HTML><HEAD>
<SCRIPT>
function isBrowser(b,v) {
browserOk = false;
versionOk = false;
browserOk = (navigator.appName.indexOf(b) != 1);
versionOk = (v <= parseInt(navigator.appVersion));
return browserOk &versionOk;
}
archiveToBeUsed = "java102.jar";
if (isBrowser("Microsoft", 4)) {
archiveToBeUsed = "ie4.jar";
}
else {
if isBrowser("Netscape", 4) {
archiveToBeUsed = "n4.jar";
}
}
</SCRIPT></HEAD><BODY>
<APPLET CODE ="MyApplet.class"
HEIGHT=100
WIDTH=400
ARCHIVE=}; >
</APPLET>
</BODY></HTML>
NOTE: You may need to use the document.write() method to generate the right APPLET tag instead of a the Javascript entity to be compatible
with Netscape and IE.
import sun.net.nntp.*;
import java.io.*;
public class NntpPost {
public static void main(String[] args) throws IOException {
/*
** pass your news server as parameter
19.24 Post a message on a newsserver using NNTP protocol (this howto is deprecated)Tag(s): DEPRECAT
**
eg. java NttpPost news.server.com
*/
NntpClient c = new NntpClient(args[0]);
NewsgroupInfo ni = c.getGroup("alt.test");
PrintStream p = c.startPost();
System.out.println("Starting post at " + args[0] + "...");
p.println("From: epresley@jailhouse.rock (Elvis Presley)");
p.println("Newsgroups: alt.test");
p.println("Subject: I'm alive");
p.println("");
p.println("Hi");
p.println("Don't be cruel, please help me");
p.println(" ");
p.println("Thanks in advance");
if (c.finishPost())
System.out.println("Ending post... success");
else
System.out.println("Ending post... failed");
c.closeServer();
}
}
Here some java code to illustrate NTTP protocol without using the undocumented classes,
Communicating with an NNTP server.
Sun's JavaMail APi can be used to interact with a NTTP server, check out the Knife Plugin.
import sun.net.nntp.*;
import java.io.*;
public class NntpGetGroup {
public static void main(String[] args)
throws IOException {
/*
** pass your news server, newsgroup as parameter
**
eg. java NttpPost news.server.com alt.test
*/
NntpClient c = new NntpClient(args[0]);
c.setGroup(args[1]);
NewsgroupInfo ni = c.getGroup(args[1]);
int first = ni.firstArticle;
int last = ni.lastArticle;
for (int i = first; i <= last; i++) {
String aLine;
BufferedReader br = null;
import sun.net.nntp.*;
import java.io.*;
public class NntpHeader {
public static void main(String[] args)
throws IOException {
/*
** pass your news server as parameter
**
eg. java NttpPost news.server.com
*/
NntpClient c = new NntpClient(args[0]);
String newsgroup = "alt.test";
c.setGroup(newsgroup);
NewsgroupInfo ni = c.getGroup(newsgroup);
int first = ni.firstArticle;
int last = ni.lastArticle;
for (int i = first; i <= last; i++) {
try {
InputStream theHeader = c.getHeader(i);
BufferedReader br = new BufferedReader(new
InputStreamReader(theHeader));
String theLine;
System.out.println("\nHeader " + i + "/" + last);
while ((theLine = br.readLine()) != null)
System.out.println(theLine);
}
catch (NntpProtocolException ne) {
/*
19.26 Get a list of headers from a newsgroup (this howto is deprecated)Tag(s): DEPRECATED
import
import
import
import
sun.net.nntp.*;
sun.net.*;
java.io.*;
java.util.*;
19.27 Get a list of all available newsgroup from a newsserver (this howto is deprecated)Tag(s): DEPRECAT
20 String/Number
20.1 javastringnumber
Web
20 String/Number
double to String :
String str = Double.toString(i);
long to String :
String str = Long.toString(l);
float to String :
String str = Float.toString(f);
String to integer :
str = "25";
int i = Integer.valueOf(str).intValue();
or
int i = Integer.parseInt(str);
String to double :
20.3 Convert from type X to type YTag(s): String/Number String/Number
Double d = Double.valueOf(str).doubleValue();
String to long :
long l = Long.valueOf(str).longValue();
or
Long l = Long.parseLong(str);
String to float :
Float f = Float.valueOf(str).floatValue();
decimal to binary :
int i = 42;
String bin = Integer.toBinaryString(i);
decimal to hexadecimal :
int i = 42;
String hexstr = Integer.toString(i, 16);
or
String hexstr = Integer.toHexString(i);
or (with leading zeroes and uppercase)
public class Hex {
public static void main(String args[]){
int i = 42;
System.out.print
(Integer.toHexString( 0x10000 | i).substring(1).toUpperCase());
}
}
char to String
String s = String.valueOf('c');
65 DECIMAL
System.out.println(j);
}
integer to boolean
b = (i != 0);
// ex : 42 != 0 > true
boolean to integer
i = (b)?1:0;
// true > 1
Note :To catch illegal number conversion, use the try/catch mechanism :
try{
i = Integer.parseInt(aString);
}
catch(NumberFormatException e) {
...
}
}
NOTE: You may want to look at Howto optimize string operations
The following snippet will strip or keep from a given string the specified characters.
Thanks to T. GUIRADO for the idea
String
The String class offers the replaceAll() method that can be used with String or char (JDK1.4+).
replaceAll() accepts a regex as argument so it can be very powerful.
To delete all nondigit in a String
System.out.println(
"@*1#^2$@!34#5ajs67>?<{8_(9SKJDH".replaceAll("\\D", ""));
// output : 123456789
If your project already depends on Apache Commons then StringUtils provides many methods to
manipulate String objects, no need to reinvent the wheel!
import org.apache.commons.lang.StringUtils;
...
foo = StringUtils.replace(foo, "bar", "baz");
// replace in foo the occurrence of bar" by "baz"
To remove a character :
public static String removeChar(String s, char c) {
StringBuffer r = new StringBuffer( s.length() );
r.setLength( s.length() );
int current = 0;
for (int i = 0; i < s.length(); i ++) {
char cur = s.charAt(i);
if (cur != c) r.setCharAt( current++, cur );
}
return r.toString();
}
Keep in mind, that you need to escape characters like $ or | since they have special meaning when
used in a regular expression. It can be quite an adventure to deal with the "\" since it is considered
as an escape character in Java. You always need to "\\" a "\" in a String. But the fun begins when
you want to use a "\" in regex expression, because the "\" is an escape character in regex too. So
for a single "\" you need to use "\\\\" in a regex expression.
public class Test {
public static void main(String[] args){
String text = "\\\\server\\apps\\file.txt";
System.out.println("original : " + text);
System.out.println("converted : " + text.replaceAll("\\\\","\\\\\\\\"));
/*
output :
original : \\server\apps\file.txt
converted : \\\\server\\apps\\file.txt
*/
}
}
Since replaceAll() is based on a regex expression, it is very easy to make the substituion case
insensitive.
20.6 Replace every occurences of a string within a stringTag(s): String/Number
[ < JDK1.4]
String,replaceAll() is not available with Java version older than 1.4, you need to code the
substitution. This snippet provides a simple replacesAll() equivalent.
public static String replaceAll(String target, String from, String to) {
//
target is the original string
//
from
is the string to be replaced
//
to
is the string which will used to replace
// returns a new String!
int start = target.indexOf(from);
if (start == 1) return target;
int lf = from.length();
char [] targetChars = target.toCharArray();
StringBuffer buffer = new StringBuffer();
int copyFrom = 0;
while (start != 1) {
buffer.append (targetChars, copyFrom, start copyFrom);
buffer.append (to);
copyFrom = start + lf;
start = target.indexOf (from, copyFrom);
}
buffer.append (targetChars, copyFrom, targetChars.length copyFrom);
return buffer.toString();
}
output is :
This
is
the
string
to
be
tokenized
*/
StringTokenizer does not react correctly if you have two separators consecutively.
Here an enhanced StringTokenizer (thanks to jsanza) to deal with that :
import java.util.*;
/**
* This class wraps a standard java.util.StringTokenizer, but provides
* an additional mode of operation (NO_CONSECUTIVE_DELIMS).
*
*/
public class EnhancedStringTokenizer implements Enumeration {
public static final int NO_RETURN_DELIMS = 0;
public static final int RETURN_DELIMS = 1;
public static final int NO_CONSECUTIVE_DELIMS = 2;
protected int Mode = NO_CONSECUTIVE_DELIMS;
void setMode(int mode) {
Mode = mode;
}
public int getMode() {
return Mode;
}
// default delimiter in the StringTokenizer
protected String Delimiter = " \t\n\r\f";
protected void setDelimiter(String delim){
Delimiter = delim;
}
public String getDelimiter() {
return Delimiter;
}
protected String Remainder = "";
protected void setRemainder(String str) {
Remainder = str;
}
public String getRemainder() {
return Remainder;
}
/**
* Same as the StringTokenizer constructor. No added functionality.
*/
public EnhancedStringTokenizer(String str, String delim){
setMode(this.NO_RETURN_DELIMS);
setDelimiter(delim);
st = new StringTokenizer(str, delim);
}
/**
* Same as the StringTokenizer constructor. No added functionality.
*/
public EnhancedStringTokenizer
(String str, String delim, boolean returnDelims) {
if (returnDelims) {
setMode(RETURN_DELIMS);
}
else {
setMode(NO_RETURN_DELIMS);
}
setDelimiter(delim);
st = new StringTokenizer(str, delim, returnDelims);
}
/**
* Using this constructor allows use of the NO_CONSECUTIVE_DELIMS mode
* of operation.
*/
public EnhancedStringTokenizer(String str, String delim, int mode) {
setMode(mode);
setDelimiter(delim);
switch (getMode()) {
case NO_RETURN_DELIMS :
st = new StringTokenizer(str, delim, false);
break;
case RETURN_DELIMS :
st = new StringTokenizer(str, delim, true);
break;
case NO_CONSECUTIVE_DELIMS :
default :
init(str);
break;
}
}
void init(String str) {
setRemainder(str);
}
public int countTokens() {
switch (getMode()) {
{
case NO_CONSECUTIVE_DELIMS :
{
String oldRem = getRemainder();
int count = 0;
try {
String temp;
while (true) {
temp = nextToken();
count++;
}
}
catch (NoSuchElementException nsee) {
setRemainder(oldRem);
return count;
}
}
default :
return st.countTokens();
}
}
public boolean hasMoreElements() {
switch (getMode()) {
case NO_CONSECUTIVE_DELIMS :
int intIndex = 0;
intIndex =
getRemainder().indexOf(getDelimiter(), intIndex);
if (intIndex != 1) {
return true;
}
else {
if (getRemainder().length() > 0) {
return true;
}
else {
return false;
}
}
default :
return st.hasMoreElements();
}
}
public Object nextElement() throws NoSuchElementException {
switch (getMode()) {
case NO_CONSECUTIVE_DELIMS :
int intIndex = 0;
intIndex =
getRemainder().indexOf(getDelimiter(), intIndex);
if (intIndex != 1) {
String retValue =
getRemainder().substring(0, intIndex);
setRemainder(getRemainder().substring(intIndex + 1));
return retValue;
}
else {
if (getRemainder().length() > 0) {
String retValue = getRemainder();
setRemainder("");
return retValue;
}
else {
throw new NoSuchElementException();
}
}
default :
return st.nextElement();
}
}
public boolean hasMoreTokens() {
switch (getMode()) {
case NO_CONSECUTIVE_DELIMS :
int intIndex = 0;
intIndex =
getRemainder().indexOf(getDelimiter(), intIndex);
if (intIndex != 1) {
return true;
}
else {
if (getRemainder().length() > 0) {
return true;
}
else {
return false;
}
}
default :
return st.hasMoreElements();
}
}
public String nextToken() throws NoSuchElementException {
switch (getMode()) {
case NO_CONSECUTIVE_DELIMS :
int intIndex = 0;
intIndex =
getRemainder().indexOf(getDelimiter(), intIndex);
if (intIndex != 1) {
String retValue =
getRemainder().substring(0, intIndex);
setRemainder(getRemainder().substring(intIndex + 1));
return retValue;
}
else {
if (getRemainder().length() > 0) {
String retValue = getRemainder();
setRemainder("");
return retValue;
}
else {
throw new NoSuchElementException();
}
}
default :
return st.nextToken();
}
}
public String nextToken(String delim) throws NoSuchElementException {
switch (getMode()) {
case NO_CONSECUTIVE_DELIMS :
setDelimiter(delim);
return nextToken();
default :
return st.nextToken(delim);
}
}
new EnhancedStringTokenizer(
testStr,
"|",
EnhancedStringTokenizer.NO_CONSECUTIVE_DELIMS);
while (st.hasMoreTokens()) {
String aux = st.nextToken();
System.out.print(aux.length());
System.out.println(">"+aux+"<");
}
}
}
See also this HowTo to split a given String into an array based on a specific separator.
For JDK1.4+, you may want to look at the String.split() method. See this HowTo.
split() is based on regex expression, a special attention is needed with some characters which have
a special meaning in a regex expression.
For example :
public class StringSplit {
public static void main(String args[]) throws Exception{
String testString = "Real.How.To";
// bad
System.out.println(java.util.Arrays.toString(
testString.split(".")
));
// output : []
// good
System.out.println(java.util.Arrays.toString(
testString.split("\\.")
));
// output : [Real, How, To]
}
}
And
public class StringSplit {
public static void main(String args[]) throws Exception{
String testString = "Real|How|To";
// bad
System.out.println(java.util.Arrays.toString(
testString.split("|")
));
// output : [, R, e, a, l, |, H, o, w, |, T, o]
// good
System.out.println(java.util.Arrays.toString(
testString.split("\\|")
));
// output : [Real, How, To]
}
}
The special character needs to be escaped with a "\" but since "\" is also a special character in
Java, you need to escape it again with another "\" !
Consider this example
public class StringSplit {
public static void main(String args[]) throws Exception{
String testString = "Real|How|To|||";
System.out.println(
java.util.Arrays.toString(
testString.split("\\|")
));
// output : [Real, How, To]
}
}
The result does not include the empty strings between the "|" separator. To keep the empty strings :
public class StringSplit {
public static void main(String args[]) throws Exception{
String testString = "Real|How|To|||";
System.out.println(
java.util.Arrays.toString(
testString.split("\\|", 1)
));
// output : [Real, How, To, , , ]
}
}
See split(String.int).
String.split() is only available since JDK 1.4.
We have an extra element. The fix is to specify a regular expression to match one or more spaces.
public class StringSplit {
public static void main(String args[]) throws Exception{
String testString = "Real How To";
System.out.println(
java.util.Arrays.toString(
testString.split("\\s+")
));
// output : [Real, How, To]
}
}
Since String.split() is based on regular expression, you can make some complex operations with a
simple call!
String testString = "{RealHowto}{java0438.html}{usage of String.split()}";
System.out.println(java.util.Arrays.toString(
testString.split("[{}]")
));
// output : [, RealHowto, , java0438.html, , usage of String.split()]
// note : extra empty elements :(
To split a long string into into fixedlength parts. In this example, we split in groups of 3 characters :
String testString = "012345678901234567890";
System.out.println(java.util.Arrays.toString(
testString.split("(?<=\\G.{3})")
));
// output : [012, 345, 678, 901, 234, 567, 890]
String concatenation via the "+" operator is one of the most convenient things to do in Java. It is
also one of the most expensive, in terms of memory and performance.
20.9 Optimize String operationsTag(s): String/Number
or any other concatenation, it **ACTUALLY** generates (for runtime use) the code sequence that
follows (or, at least, the bytecode equivalent of it):
StringBuffer temp = new StringBuffer( );
temp.append( String.valueOf( "abc" ) );
temp.append( String.valueOf( someInt ) );
temp.append( String.valueOf( someArray[index] );
String s = temp.toString( );
The weak spot in all this is the construction of the StringBuffer object: the size of the buffer is
ALWAYS 16 characters. Then, as data is appended to the buffer, if more space is needed the size
of the buffer is doubled and the old data is copied to the new buffer.
So to optimize we have to bypass the automatic StringBuffer when possible. In this JAVA Howto, a
snippet is given to replace a character at a specific position. An optimized version, using the
StringBuffer would be:
public static String replaceCharAt(String s, int pos, char c) {
StringBuffer buf = new StringBuffer( s );
buf.setCharAt( pos, c );
return buf.toString( );
}
Only one buffer created, exactly the right size. Converting a StringBuffer to a String costs almost
nothing, as the actual buffer is shared between the two.
In the same Howto, a snippet about removing a character in a String can be optimized like:
public static String removeChar(String s, char c) {
StringBuffer r = new StringBuffer( s.length() );
r.setLength( s.length() );
int current = 0;
for (int i = 0; i < s.length(); i ++) {
char cur = s.charAt(i);
if (cur != c) r.setCharAt( current++, cur );
}
return r.toString();
}
In the original version, a new String object was created and discarded immediately!
The weak spot of the original method to remove a character is when the parameter s passed havee
than 17 characters, the temporary StringBuffer created by the compiler will have to be extended. To
optimize, simply rewrite the method using a StringBuffer with the correct size:
public static String removeCharAt(String s, int pos) {
StringBuffer buf = new StringBuffer( s.length() 1 );
buf.append( s.substring(0,pos) ).append( s.substring(pos+1) );
return buf.toString();
}
[JDK1.5]
The String trim() method returns a copy of the string, with leading and trailing whitespace omitted.
ref : http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#trim()
[JDK1.4]
Here a complete solution to remove leading or trailing spaces in a String using regular expressions.
public class BlankRemover {
private BlankRemover () {}
/* remove leading whitespace */
public static String ltrim(String source) {
return source.replaceAll("^\\s+", "");
}
boolean startsWithDigitOrUpper(String s) {
return Pattern.compile("^[AZ09]").matcher(s).find();
}
Howto
*
Howto*
*/
}
These oneliners are useful to pad to a fix length with a given character.
public class Test {
public static void main(String args[]) throws Exception {
System.out.println(String.format("%10s", "howto").replace(' ', '*'));
System.out.println(String.format("%10s", "howto").replace(' ', '*'));
}
/*
output
*****howto
howto*****
*/
}
[JDK1.4 or less]
/**
* Pads a String <code>s</code> to take up <code>n</code>
* characters, padding with char <code>c</code> on the
* left (<code>true</code>) or on the right (<code>false</code>).
* Returns <code>null</code> if passed a <code>null</code>
* String.
**/
public static String paddingString(String s, int n, char c,
boolean paddingLeft) {
if (s == null) {
return s;
}
int add = n s.length(); // may overflow int size... should not be a problem in real life
if(add <= 0){
return s;
}
StringBuffer str = new StringBuffer(s);
or use the String.replaceAll(regex,replacement) method which is doing basically the same thing.
newString = myString.replaceAll("(\r\n|\r|\n|\n\r)", "<br>");
The following snippets remove from a String accented letters and replace them by their regular
ASCII equivalent.
These can be useful before inserting data into a database to made sorting easier.
=
=
=
=
=
s.replaceAll("[]","e");
s.replaceAll("[]","u");
s.replaceAll("[]","i");
s.replaceAll("[]","a");
s.replaceAll("","o");
s
s
s
s
s
=
=
=
=
=
s.replaceAll("[]","E");
s.replaceAll("[]","U");
s.replaceAll("[]","I");
s.replaceAll("[]","A");
s.replaceAll("","O");
System.out.println(s);
// output : E,E,E,E,U,U,I,I,A,A,O,e,e,e,e,u,u,i,i,a,a,o
}
}
As a bonus, here a method to convert a given string to uppercase with no accent. This can be
useful in a database field to simplify name searching with accent or not.
Description
Any valid number, uses Character.isDigit .
Escape character, used to escape any of
the special formatting characters.
Any character ( Character.isLetter ).
All lowercase letters are mapped to upper case.
Any character ( Character.isLetter ).
All upper case letters are mapped to lower case.
Any character or number
( Character.isLetter or Character.isDigit )
Any character ( Character.isLetter ).
Anything.
Any hex character (09, af or AF).
As you can see, it is now possible to call a method with a variable number of parameters. But it is
also possible to use an array (with the new String.format()).
You can use this new feature to quickly format strings into table :
public class Divers {
public static void main(String args[]){
String format = "|%1$10s|%2$10s|%3$20s|\n";
System.out.format(format, "FirstName", "Init.", "LastName");
System.out.format(format, "Real", "", "Gagnon");
System.out.format(format, "John", "D", "Doe");
String ex[] = { "John", "F.", "Kennedy" };
System.out.format(String.format(format, (Object[])ex));
}
}
Output:
|FirstName
|Real
|John
|John
|Init.
|
|D
|F.
|LastName
|Gagnon
|Doe
|Kennedy
|
|
|
|
To align numbers :
String format = "%10.2f\n"; // width == 10 and 2 digits after the dot
float [] floats = {123.45f, 99.0f, 23.2f, 45.0f};
for(int i=0; i<floats.length; i++) {
float value = floats[i];
System.out.format(format, value);
}
Output :
123.45
99.00
23.20
45.00
java.text.MessageFormat is a very powerful API, you should study the javadoc to see all the
possibilities.
In this code, we have 2 strings, "tat" and "famille". We expect that "tat" is before "famille". But
String.compareTo() will return that "famille" is before "tat".
class Test {
public static void main(String args[]) {
String s1 = "tat";
String s2 = "famille";
// here we are expecting "" < "f"
if (s1.compareTo(s2) > 0) {
if (s1.compareTo(s2) > 0) {
// s1 lexicographically follows s2 which is not true!
System.out.println("not ok " + s1 + " > " + s2 );
}
}
/*
output :
not ok tat > famille
*/
}
Equality
To compare without taking into account the presence of accentued so that "" == "e", we use a
Collator.
import java.text.Collator;
// import java.util.Locale;
public class TextTest {
public static void main(String ... args) {
String a = "Real";
String b = "Ral";
System.out.println(a + " and " + b + " equals? " +
check(a,b));
/*
* output :
* Real and Ral equals? true
*/
}
// Collator c = Collator.getInstance(Locale.US);
//
// accent and upper/lowercase not taken into account
Collator c = Collator.getInstance();
c.setStrength(Collator.PRIMARY);
return (c.compare(a,b) == 0 );
}
}
20.21 Create a String with fixed length and filled with a specific
characterTag(s): String/Number
Current version of this HowTo :
http://www.rgagnon.com/javadetails/../javadetails/java0512.html
public class StringFixedAndFilled {
public static void main(String argv[])
{
String s = ">" + fillString('X', 25) + "<";
System.out.println(s);
s = ">" + fillString(' ', 25) + "<";
System.out.println(s);
/*
output : >XXXXXXXXXXXXXXXXXXXXXXXXX<
>
<
*/
}
public static String fillString(char fillChar, int count){
// creates a string of 'x' repeating characters
char[] chars = new char[count];
while (count>0) chars[count] = fillChar;
return new String(chars);
}
}
String.
Maybe not the best way but it is certainly very easy!
import java.io.*;
import java.util.*;
public class Unquote {
public static void main(String[] args) {
String a = "Visit Real\\'s at http://www.rgagnon.com";
String b = unquote(a);
System.out.println(a);
System.out.println(b);
/*
output :
Visit Real\'s at http://www.rgagnon.com
Visit Real's at http://www.rgagnon.com
*/
}
public static String unquote(String a) {
Properties prop = new Properties();
try {
prop.load(new ByteArrayInputStream(("x=" + a).getBytes()));
}
catch (IOException ignore) {}
return prop.getProperty("x");
}
}
sb.append(c); break;
}
}
return sb.toString();
}
Here another snippet to convert a String to HTML. This one is little bit better because it deals with
space versus nonbreaking space ( ) and Unicode characters.
Submitted by S. Bayer. (PS. Thanks to ablage_p for the fix!)
public static String stringToHTMLString(String string) {
StringBuffer sb = new StringBuffer(string.length());
// true if last char was blank
boolean lastWasBlankChar = false;
int len = string.length();
char c;
for (int i = 0; i < len; i++)
{
c = string.charAt(i);
if (c == ' ') {
// blank gets extra work,
// this solves the problem you get if you replace all
// blanks with , if you do that you loss
// word breaking
if (lastWasBlankChar) {
lastWasBlankChar = false;
sb.append(" ");
}
else {
lastWasBlankChar = true;
sb.append(' ');
}
}
else {
lastWasBlankChar = false;
//
// HTML Special Chars
if (c == '"')
sb.append(""");
else if (c == '&')
sb.append("&");
else if (c == '<')
sb.append("<");
else if (c == '>')
sb.append(">");
else if (c == '\n')
// Handle Newline
sb.append("<br/>");
else {
int ci = 0xffff & c;
if (ci < 160 )
// nothing special only 7 Bit
sb.append(c);
else {
// Not 7 Bit use the unicode system
sb.append("&#");
sb.append(new Integer(ci).toString());
sb.append(';');
}
}
}
}
return sb.toString();
}
do {
continueLoop = false;
i = source.indexOf("&", skip);
if (i > 1) {
j = source.indexOf(";", i);
if (j > i) {
String entityToLookFor = source.substring(i, j + 1);
String value = (String) htmlEntities.get(entityToLookFor);
if (value != null) {
source = source.substring(0, i)
+ value + source.substring(j + 1);
continueLoop = true;
}
else if (value == null){
skip = i+1;
continueLoop = true;
}
}
}
} while (continueLoop);
return source;
}
public static void main(String args[]) throws Exception {
// to see accented character to the console (Windows DOS Shell)
java.io.PrintStream ps = new java.io.PrintStream(System.out, true, "Cp850");
String test = "© 2007 Réal Gagnon <www.rgagnon.com>";
ps.println(test + "\n>\n" +unescapeHTML(test));
/*
output ((Windows DOS Shell):
© 2007 Réal Gagnon <www.rgagnon.com>
>
2007 Ral Gagnon <www.rgagnon.com>
*/
}
}
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
,
">" } ,
"\"" } ,
"" } ,
"" } ,
"" } ,
"" } ,
"" } ,
"" } ,
"" } ,
"" } ,
"" } ,
"" } ,
"" } ,
"" } ,
"" } ,
"" } ,
"" } ,
{
{
{
{
{
{
};
"Ù"
"Û"
"Ü"
"©"
"®"
"€"
,
,
,
,
,
,
"" } ,
"" } ,
"" } ,
"\u00a9"
"\u00ae"
"\u20a0"
{ "û"
{ "ü"
{ " "
} ,
} ,
}
, "" } ,
, "" } ,
, " " } ,
This HowTo deals only with a small subset of the available HTML entities. See this Wikipedia article
for a complete list :
http://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Character_entities_in_HT
java.nio.ByteBuffer;
java.nio.CharBuffer;
java.nio.charset.Charset;
java.nio.charset.CharsetDecoder;
java.nio.charset.CharacterCodingException;
A different (and simpler) approach is to take a given string and check if it's possible to encode it into
ASCII.
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
public class StringUtils {
static CharsetEncoder asciiEncoder =
Charset.forName("USASCII").newEncoder(); // or "ISO88591" for ISO Latin 1
Another way is to use a regular expression, see this Javascript HowTo for a hint!
To simply strip any nonascii characters form a string
public class Test {
public static void main(String args[]){
String input = "ea";
String output = input.replaceAll("[^\\p{ASCII}]", "");
System.out.println(output);
/*
* output : ea
*/
}
}
20.28 Remove HTML tags from a file to extract only the TEXTTag(s): IO String/Number Networking
However if any Javascript is present, the script will be seen as text. Also you may need to add some
logic during the reading to take into account only what is inside the <BODY> tag.
java.io.IOException;
java.io.FileReader;
java.io.Reader;
java.util.List;
java.util.ArrayList;
import
import
import
import
javax.swing.text.html.parser.ParserDelegator;
javax.swing.text.html.HTMLEditorKit.ParserCallback;
javax.swing.text.html.HTML.Tag;
javax.swing.text.MutableAttributeSet;
}
}
Note that the HTMLEditorKit can be easily confused if the HTML to be parsed is not wellformed.
java.io.IOException;
java.io.FileReader;
java.io.Reader;
java.io.BufferedReader;
org.jsoup.Jsoup;
org.apache.tika.metadata.Metadata;
org.apache.tika.parser.AutoDetectParser;
org.apache.tika.parser.ParseContext;
org.apache.tika.parser.Parser;
org.apache.tika.sax.BodyContentHandler;
org.xml.sax.ContentHandler;
try {
is = new FileInputStream("C:/Temp/javax.html");
ContentHandler contenthandler = new BodyContentHandler();
Metadata metadata = new Metadata();
Parser parser = new AutoDetectParser();
parser.parse(is, contenthandler, metadata, new ParseContext());
System.out.println(contenthandler.toString());
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (is != null) is.close();
}
}
}
See Extract text from a PDF using Apache Tika, Get Mime Type from a file.
See also Extract links from an HTML page
java.io.IOException;
java.io.FileReader;
java.io.Reader;
java.util.List;
java.util.ArrayList;
import
import
import
import
import
javax.swing.text.html.parser.ParserDelegator;
javax.swing.text.html.HTMLEditorKit.ParserCallback;
javax.swing.text.html.HTML.Tag;
javax.swing.text.html.HTML.Attribute;
javax.swing.text.MutableAttributeSet;
if (tag == Tag.A) {
String address = (String) attribute.getAttribute(Attribute.HREF);
list.add(address);
}
}
public
public
public
public
void
void
void
void
};
parserDelegator.parse(reader, parserCallback, false);
return list;
}
public final static void main(String[] args) throws Exception{
FileReader reader = new FileReader("javanew.html");
List<String> links = HTMLUtils.extractLinks(reader);
for (String link : links) {
System.out.println(link);
}
}
}
org.jsoup.Jsoup;
org.jsoup.nodes.Document;
org.jsoup.nodes.Element;
org.jsoup.select.Elements;
return result;
}
A faster way
import java.io.UnsupportedEncodingException;
public class StringUtils {
static final
(byte)'0',
(byte)'4',
(byte)'8',
(byte)'c',
};
byte[] HEX_CHAR_TABLE
(byte)'1', (byte)'2',
(byte)'5', (byte)'6',
(byte)'9', (byte)'a',
(byte)'d', (byte)'e',
= {
(byte)'3',
(byte)'7',
(byte)'b',
(byte)'f'
+ m.group(2).toLowerCase()) ;
}
str = m.appendTail(sb).toString();
return str;
}
public static void main(String [] args) {
System.out.println(StringUtils.upperCaseWordFirst(" #600howto"));
System.out.println(StringUtils.upperCaseWordFirst("ELVis preSLEY"));
System.out.println(StringUtils.upperCaseWordFirst("john o'connor &steeve mcmillan"));
/*
output :
#600HowTo
Elvis Presley
John O'Connor &Steeve Mcmillan
for the "mcmillan", well this may be not enough and you will need
to process it as a special case if needed...
*/
}
}
int n = b64is.read(tmp);
byte[] res = new byte[n];
System.arraycopy(tmp, 0, res, 0, n);
return res;
}
public static void main(String[] args) throws Exception {
String test = "realhowto";
byte res1[] = Base64Utils.encode(test.getBytes());
System.out.println(test + " base64 > " + java.util.Arrays.toString(res1));
System.out.println(new String(res1));
byte res2[] = Base64Utils.decode(res1);
System.out.println("");
System.out.println( java.util.Arrays.toString(res1) + " string > "
+ new String(res2));
/*
* output
* realhowto base64 >
*
[99, 109, 86, 104, 98, 71, 104, 118, 100, 51, 82, 118]
*
cmVhbGhvd3Rv
* [99, 109, 86, 104, 98, 71, 104, 118, 100, 51, 82, 118]
*
string > realhowto
*/
}
}
20.41 MiGBase64
MiGBase64 is a very fast Base64 Codec written in Java. http://migbase64.sourceforge.net/.
4565789 ";
formatted_string = FormatLine.justifyLeft(25,original_string);
System.out.println("");
System.out.println(original_string);
System.out.println("");
System.out.println(formatted_string);
20.41 MiGBase64
/*
output :
01234567890123456789
01234567890123456789
01234567890 0123
4565789
01234567890 0123
4565789
*/
}
}
The second accepts a limit corresponding to the total length of the path. If the limit is 20, the path
beginning will be truncated then ellipse and finally the filename. The result is similar to the Win32
API PathCompactPathExA.
ex :
C:\1\2\3\4\5\test.txt
== C:\1\2\3\...test.txt
\\server\p1\p2\p3\p4\p5\p6
== \\server\p1\p2...p6
http://www.rgagnon.com/p1/p2/p3/p4/p5/pb.html == http://www...pb.html
public class FileUtils {
public
public
public
public
public
public
static
static
static
static
static
static
final
final
final
final
final
final
int DEFAULT_SHORTENER_THRESHOLD = 4;
String SHORTENER_BACKSLASH_REGEX = "\\\\";
String SHORTENER_SLASH_REGEX = "/";
String SHORTENER_BACKSLASH = "\\";
String SHORTENER_SLASH = "/";
String SHORTENER_ELLIPSE = "...";
/**
* Return shorter path based on the limited threshold
* ex. C:/1/2/test.txt return C:/1/.../test.txt if threshold is 1
* @param path
* @param threshold
* @return
*/
public static String pathShortener(String path, int threshold) {
String regex = SHORTENER_BACKSLASH_REGEX;
String sep = SHORTENER_BACKSLASH;
if (path.indexOf("/") > 0) {
regex = SHORTENER_SLASH_REGEX;
sep = SHORTENER_SLASH;
}
String pathtemp[] = path.split(regex);
// remove empty elements
int elem = 0;
{
String newtemp [] = new String [pathtemp.length];
int j = 0;
for (int i=0; i < pathtemp.length; i++) {
if (!pathtemp[i].equals("")) {
newtemp [j++] = pathtemp[i];
elem++;
}
}
pathtemp = newtemp;
}
}
}
return new String(shortPathArray);
}
output :
C:\Documents and Settings\All Users\Application Data\Apple Computer\iTunes\...\SC Info.
C:\temp
C:\1\2\3\4\...\test.txt
C:/1/2/test.txt
C:/1/2/3/4/.../test.txt
\\server\p1\p2\p3\p4\...\p6
\\server\p1\p2\p3
http://www.rgagnon.com/p1/p2/p3/.../pb.html
C:\Doc...SC Info.txt
C:\temp
C:\1\2\3\...test.txt
...testfile.txt
C:/1...test.txt
\\server\p1\p2\...p6
http://www...pb.html
*/
}
}
Unicode has a special character to show an ellipsis (to use one character instead of 3) :
public static final String ELLIPSE = "\u2026";
java.awt.Font;
java.awt.Graphics;
java.awt.Graphics2D;
java.awt.RenderingHints;
java.awt.image.BufferedImage;
java.io.File;
java.io.IOException;
import javax.imageio.ImageIO;
public class AsciiBanner {
Output is :
######***
#########*
##
**#*
##
*#*
##
*#*
##
**#*
########**
######***
## ****
##
*#**
##
*#*
##
*##*
##
*#*
##
**#*
##
*#*
*******
*#####**
*#** **#*
*#*
*#*
*#######*
*#######*
*#*
*#*
*#** **#*
**#####**
*******
*******
*######*
*#****#*
#*
****##
**######
*#****##
*#* *##
*#* **##*
*#######*
*******#*
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
##
**
**
**
******
*######*
*#****#*
*#*
*##****
***###**
****#*
*#*
*#****#*
*######*
******
##
##
##
##
##
##
##
##
##
##
##
##
###########
###########
##
##
##
##
##
##
##
##
##
##
##
##
##
##
******* *#*
**#####** ***
*#** **#* *#*
*#*
*#* *#*
*#*
*#* *#
*#
#* *#
*#*
*#* **
*#*
*#*
*
*#** **#*
*
**#####**
*******
double to String :
String str = Double.toString(i);
long to String :
String str = Long.toString(l);
float to String :
String str = Float.toString(f);
String to integer :
str = "25";
int i = Integer.valueOf(str).intValue();
or
int i = Integer.parseInt(str);
String to double :
Double d = Double.valueOf(str).doubleValue();
String to long :
long l = Long.valueOf(str).longValue();
or
Long l = Long.parseLong(str);
String to float :
Float f = Float.valueOf(str).floatValue();
decimal to binary :
int i = 42;
String bin = Integer.toBinaryString(i);
decimal to hexadecimal :
int i = 42;
String hexstr = Integer.toString(i, 16);
or
String hexstr = Integer.toHexString(i);
or (with leading zeroes and uppercase)
public class Hex {
public static void main(String args[]){
int i = 42;
System.out.print
(Integer.toHexString( 0x10000 | i).substring(1).toUpperCase());
}
}
char to String
String s = String.valueOf('c');
65 DECIMAL
integer to boolean
b = (i != 0);
// ex : 42 != 0 > true
boolean to integer
i = (b)?1:0;
// true > 1
Note :To catch illegal number conversion, use the try/catch mechanism :
20.46 Convert from type X to type YTag(s): String/Number String/Number
try{
i = Integer.parseInt(aString);
}
catch(NumberFormatException e) {
...
}
// output :
// 1
// 4
}
}
In the next example, a boolean is being stored and then retrieved from an ArrayList. The 1.5
version leaves the conversion required to transition to an Boolean and back to the compiler.
import java.util.Collection.*;
import java.util.*;
public class Test15 {
public static void main(String ... args) {
ArrayList<Boolean> list = new ArrayList<Boolean>();
list.add(0, true);
boolean flag = list.get(0);
System.out.println(flag);
}
}
Note : To be able to compile that code with the JDK1.5, you need to specify the switch source
1.4 on the javac command line.
JDK1.0.2
public class TestRound102 {
public static void main(String
double d = 3.1537;
// output is 3.2
System.out.println(d + " : "
// output is 3.15
System.out.println(d + " : "
// output is 3.154
System.out.println(d + " : "
d= 9.155;
// output is 9.2
System.out.println(d + " : "
// output is 9.16
System.out.println(d + " : "
args[]){
+ round(d, 1));
+ round(d, 2));
+ round(d, 3));
+ round(d, 1));
+ round(d, 2));
// output is 3.155
System.out.println(d +
d= 1234.156789;
// output is 1234.2
System.out.println(d +
// output is 1234.16
System.out.println(d +
// output is 1234.157
System.out.println(d +
// output is 1234.1568
System.out.println(d +
d= 1.5;
// output is 2
System.out.println(d +
}
// positive value only.
public static double round(double value, int decimalPlace)
{
double power_of_ten = 1;
// floating point arithmetic can be very tricky.
// that's why I introduce a "fudge factor"
double fudge_factor = 0.05;
while (decimalPlace > 0) {
power_of_ten *= 10.0d;
fudge_factor /= 10.0d;
}
return Math.round((value + fudge_factor)* power_of_ten) / power_of_ten;
}
}
On Windows, the regional settings (Control Panel) are used for decimal point and hundred
separator.
If the decimal separator is set to "," in your Regional Settings and you really want a "." then
import java.text.*;
JDK1.5
System.out.println() directly supports formatting so it's possible to give a known Locale (with the
right decimal separator) to bypass the current Locale.
System.out.printf(Locale.UK, "%6.2f%n", 123456.78) ;
*/
String format = String.format("%%0%dd", digits);
return String.format(format, n);
}
public static void main(String[] args) throws Exception{
System.out.println(NumberUtils.formatLong(123456L, 10));
/* output : 0000123456
*/
}
}
jdk1.2
Using DecimalFormat.format()
import java.util.Arrays;
import java.text.DecimalFormat;
public class NumberUtils {
public static String formatLong(long n, int digits) {
char[] zeros = new char[digits];
Arrays.fill(zeros, '0');
DecimalFormat df = new DecimalFormat(String.valueOf(zeros));
return df.format(n);
}
public static void main(String[] args) throws Exception{
System.out.println(NumberUtils.formatLong(123456L, 10));
/* output : 0000123456
*/
}
}
prejdk1.1
public class DemoNumber {
public static void main(String args[]) {
long n = 123456;
String mask = "00000000000";
String ds = Long.toString(n); // double to string
String z = mask.substring(0 , mask.length() ds.length()) + ds;
System.out.println(z);
/* output : 0000123456
*/
}
}
128
255
*/
}
public static int unsignedByteToInt(byte b) {
return (int) b & 0xFF;
}
}
<<
<<
<<
<<
24;
16;
8;
0;
returns "Incompatible type for constructor. Explicit cast needed to convert double to int." even if
the constructor Color (float r, float g, float b) is valid. That's because the compiler interprets
numbers like 0.1 as double not float. You must use the suffixe "f" to indicate that the number is a
float.
Color c = new Color(0.1f,0.2f,0.4f);
The output
4
0
0
10
10
4
10
10
6
10
8.13013058393518
0.6631286078928067
4.382003543427801
7.2768144451559795
7.312852816962123
8.69257797289748
2.4967782036871657
4.451145854389913
1.82517092998838
import java.text.DecimalFormat;
public class EnglishNumberToWords {
private static final String[] tensNames = {
"",
" ten",
" twenty",
" thirty",
" forty",
" fifty",
" sixty",
" seventy",
" eighty",
" ninety"
};
private static final String[] numNames = {
"",
" one",
" two",
" three",
" four",
" five",
" six",
" seven",
" eight",
" nine",
" ten",
" eleven",
" twelve",
" thirteen",
" fourteen",
" fifteen",
" sixteen",
" seventeen",
" eighteen",
" nineteen"
};
private static String convertLessThanOneThousand(int number) {
String soFar;
if (number % 100 <20){
soFar = numNames[number % 100];
number /= 100;
}
else {
soFar = numNames[number % 10];
number /= 10;
soFar = tensNames[number % 10] + soFar;
number /= 10;
}
if (number == 0) return soFar;
return numNames[number] + " hundred" + soFar;
}
zero
one
sixteen
one hundred
one hundred eighteen
two hundred
two hundred nineteen
eight hundred
eight hundred one
one thousand three hundred sixteen
one million
two millions
three millions two hundred
seven hundred thousand
nine millions
nine millions one thousand
one hundred twenty three millions four hundred
fifty six thousand seven hundred eighty nine
two billion one hundred forty seven millions
four hundred eighty three thousand six hundred forty seven
three billion ten
}
}
Franais
Quite different than the english version but french is a lot more difficult!
package com.rgagnon.howto;
import java.text.*;
class FrenchNumberToWords {
private static final String[] dizaineNames = {
"",
"",
"vingt",
"trente",
"quarante",
"cinquante",
"soixante",
"soixante",
"quatrevingt",
"quatrevingt"
};
private static final String[] uniteNames1 = {
"",
"un",
"deux",
"trois",
"quatre",
"cinq",
"six",
"sept",
"huit",
"neuf",
"dix",
"onze",
"douze",
"treize",
"quatorze",
"quinze",
"seize",
"dixsept",
"dixhuit",
"dixneuf"
};
private static final String[] uniteNames2 = {
"",
"",
"deux",
"trois",
"quatre",
"cinq",
"six",
"sept",
"huit",
"neuf",
"dix"
};
private static String convertZeroToHundred(int number) {
int laDizaine = number / 10;
int lUnite = number % 10;
String resultat = "";
switch
case 1
case 7
case 9
(laDizaine) {
:
:
:
case 1 :
if (leReste > 0) {
resultat = "cent " + sReste;
}
else {
resultat = "cent";
}
break;
default :
if (leReste > 0) {
resultat = uniteNames2[lesCentaines] + " cent " + sReste;
}
else {
resultat = uniteNames2[lesCentaines] + " cents";
}
}
return resultat;
}
public static String convert(long number) {
// 0 999 999 999 999
if (number == 0) { return "zro"; }
String snumber = Long.toString(number);
// pad des "0"
String mask = "000000000000";
DecimalFormat df = new DecimalFormat(mask);
snumber = df.format(number);
// XXXnnnnnnnnn
int lesMilliards = Integer.parseInt(snumber.substring(0,3));
// nnnXXXnnnnnn
int lesMillions = Integer.parseInt(snumber.substring(3,6));
// nnnnnnXXXnnn
int lesCentMille = Integer.parseInt(snumber.substring(6,9));
// nnnnnnnnnXXX
int lesMille = Integer.parseInt(snumber.substring(9,12));
String tradMilliards;
switch (lesMilliards) {
case 0:
tradMilliards = "";
break;
case 1 :
tradMilliards = convertLessThanOneThousand(lesMilliards)
+ " milliard ";
break;
default :
tradMilliards = convertLessThanOneThousand(lesMilliards)
+ " milliards ";
}
String resultat = tradMilliards;
String tradMillions;
switch (lesMillions) {
case 0:
tradMillions = "";
break;
case 1 :
tradMillions = convertLessThanOneThousand(lesMillions)
+ " million ";
break;
default :
tradMillions = convertLessThanOneThousand(lesMillions)
+ " millions ";
}
resultat = resultat + tradMillions;
String tradCentMille;
switch (lesCentMille) {
case 0:
tradCentMille = "";
break;
case 1 :
tradCentMille = "mille ";
break;
default :
tradCentMille = convertLessThanOneThousand(lesCentMille)
+ " mille ";
}
resultat = resultat + tradCentMille;
String tradMille;
tradMille = convertLessThanOneThousand(lesMille);
resultat = resultat + tradMille;
return resultat;
}
public static void main(String[] args) {
System.out.println("*** " + FrenchNumberToWords.convert(0));
System.out.println("*** " + FrenchNumberToWords.convert(9));
System.out.println("*** " + FrenchNumberToWords.convert(19));
System.out.println("*** " + FrenchNumberToWords.convert(21));
System.out.println("*** " + FrenchNumberToWords.convert(28));
System.out.println("*** " + FrenchNumberToWords.convert(71));
System.out.println("*** " + FrenchNumberToWords.convert(72));
System.out.println("*** " + FrenchNumberToWords.convert(80));
System.out.println("*** " + FrenchNumberToWords.convert(81));
System.out.println("*** " + FrenchNumberToWords.convert(89));
System.out.println("*** " + FrenchNumberToWords.convert(90));
System.out.println("*** " + FrenchNumberToWords.convert(91));
System.out.println("*** " + FrenchNumberToWords.convert(97));
System.out.println("*** " + FrenchNumberToWords.convert(100));
System.out.println("*** " + FrenchNumberToWords.convert(101));
System.out.println("*** " + FrenchNumberToWords.convert(110));
System.out.println("*** " + FrenchNumberToWords.convert(120));
System.out.println("*** " + FrenchNumberToWords.convert(200));
System.out.println("*** " + FrenchNumberToWords.convert(201));
System.out.println("*** " + FrenchNumberToWords.convert(232));
System.out.println("*** " + FrenchNumberToWords.convert(999));
System.out.println("*** " + FrenchNumberToWords.convert(1000));
System.out.println("*** " + FrenchNumberToWords.convert(1001));
System.out.println("*** " + FrenchNumberToWords.convert(10000));
System.out.println("*** " + FrenchNumberToWords.convert(10001));
System.out.println("*** " + FrenchNumberToWords.convert(100000));
System.out.println("*** " + FrenchNumberToWords.convert(2000000));
System.out.println("*** " + FrenchNumberToWords.convert(3000000000L));
System.out.println("*** " + FrenchNumberToWords.convert(2147483647));
/*
*** OUTPUT
*** zro
*** neuf
*** dixneuf
*** vingt et un
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
**
*/
vingthuit
soixante et onze
soixantedouze
quatrevingt
quatrevingtun
quatrevingtneuf
quatrevingtdix
quatrevingtonze
quatrevingtdixsept
cent
cent un
cent dix
cent vingt
deux cents
deux cent un
deux cent trentedeux
neuf cent quatrevingtdixneuf
mille
mille un
dix mille
dix mille un
cent mille
deux millions
trois milliards
deux milliards cent quarantesept millions
quatre cent quatrevingttrois mille six cent quarantesept
}
}
You can handle "dollar and cent" conversion by calling the "convert" method two times.
String phrase = "12345.67" ;
Float num = new Float( phrase ) ;
int dollars = (int)Math.floor( num ) ;
int cent = (int)Math.floor( ( num dollars ) * 100.0f ) ;
String s = "$ " + EnglishNumberToWords.convert( dollars ) + " and "
+ EnglishNumberToWords.convert( cent ) + " cents" ;
'JSP' means :
J : the Julian format.
SP : spells the word for the number passed to to_date
The unexpected result is coming from the fact that internal floatingpoint number representation
is not well suited for that kind of operation.
The easiest way to solve this limitation is to the BigDecimal class :
import java.math.BigDecimal;
...
System.out.println
(BigDecimal.valueOf(1.33).subtract(BigDecimal.valueOf(1.3)));
if (x % 2 == 0) {
// even
}
if (x % 2 != 0) {
// odd
}
... or binary AND operator...
if (( x & 1 ) == 0) {
// even
}
if (( x & 1 ) != 0) {
// odd
}
return string.matches("^\\d+\\.\\d{2}$");
}
public static void main(String[] args) {
System.out.println("42 valid ? "
+ NumberUtils.isNumber("42"));
System.out.println("42.1 valid ? " + NumberUtils.isNumber("42.1"));
System.out.println("42 valid ? "
System.out.println("42.1 valid ? "
System.out.println("42.1 valid ? "
System.out.println("42.1a valid ? "
+
+
+
+
NumberUtils.isNumeric("42"));
NumberUtils.isNumeric("42.1"));
NumberUtils.isNumeric("42.1"));
NumberUtils.isNumeric("42.1a"));
+
+
+
+
NumberUtils.isNumberWith2Decimals("42.10"));
NumberUtils.isNumberWith2Decimals("42.101"));
NumberUtils.isNumberWith2Decimals("42,10"));
NumberUtils.isNumberWith2Decimals("42"));
/*
* output
* 42.1 valid ?
* 42
valid ?
*
* 42.1
valid
* 42.1 valid
* 42.1a valid
*
* 42.10 valid
* 42.101 valid
* 42,10 valid
* 42
valid
*/
false
true
? true
? true
? false
?
?
?
?
true
false
false
false
}
}
An address can be obtained for this host that is unique and constant for the lifetime of this
object.
The format is :
[2 chars for each byte in 4 byte ip address]:
[8 char unique string]:
[16 char from time in hex]:
[8 char from count]
Code :
public class TestVMID {
public static void main(String arg[]) {
System.out.println(new java.rmi.dgc.VMID().toString());
System.out.println(new java.rmi.dgc.VMID().toString());
System.out.println(new java.rmi.dgc.VMID().toString());
}
}
Output :
d578271282b42fce:2955b56e:107df3fbc96:8000
d578271282b42fce:2955b56e:107df3fbc96:7fff
d578271282b42fce:2955b56e:107df3fbc96:7ffe
}
}
See also this HowTo for unique numerical id based on the system time.
System.out.println(NumberUtils.getDoubleValue("42,24"));
System.out.println(NumberUtils.getDoubleValue("42.24"));
System.out.println(NumberUtils.convertStringAsStringNumberUnLocalized
(new Locale("fr"), "42,24"));
/*
* output
* fr_CA
* 42.24
* 42.0
* 42.24
*/
}
}
System.out.println(NumberUtils.fractionToDouble("4/5"));
System.out.println(NumberUtils.fractionToDouble("3/9"));
/*
* 0.5
* 0.6666666666666666
* 0.6666666666666666
* 0.8
* 0.3333333333333333
*/
}
}
21 Open Source
21.1 javaos
See http://johannburkard.de/software/nativecall/
21.4 com4j
A Java library that allows Java applications to seemlessly interoperate with Microsoft Component
Object Model.
First generate Java type definitions from a COM type library. Here we are doing for the type library
for the Windows Scripting Host.
> java jar tlbimp.jar o wsh p test.wsh %WINDIR%\system32\wshom.ocx
21 Open Source
IFileSystem3 fs = ClassFactory.createFileSystemObject();
for( String file : args )
System.out.println(fs.getFileVersion(file));
}
}
https://com4j.dev.java.net/
21.5 jinterop
Implementation of DCOM wire protocol (MSRPC) to enable development of Pure BiDirectional,
NonNative Java applications which can interoperate with any COM component. The
implementation is itself purely in Java and does not use JNI to provide COM access.
http://sourceforge.net/projects/jinterop
21.6 jxchange
Pure java implementation of the entire Collaboration Data Objects (CDO 1.21) library for accessing
Microsoft Exchange Server in a platform independent manner.
http://sourceforge.net/projects/jxchange/
See also this HowTo for an alternative package to access a COM package from Java.
http://www.techeez.com/windows_tips/service_under_nt.htm
SVRANY is used to run any EXE as a windows service. In our situation, SVRANY will run the
specified JAVA.EXE with our class a parameter. But this solution presents many problems. For
exemple, if you kill the SVRANY.EXE process (stop the service) then the JAVA.EXE is not killed,
you need to do it manually.
21.12 WinRun4J
http://winrun4j.sourceforge.net/
WinRun4j is a java launcher for Windows. It provides an alternative to javaw.exe and provides the
following benefits:
Use of INI file for specifying classpath, main class, vm args, program args.
Custom executable name that appears in task manager.
Builtin icon replacer for custom icon.
Windows NT Service wrapper.
Windows EventLog API
21.10 Create entityrelation diagramTag(s): Open Source Open Source
21.13 JSmooth
http://jsmooth.sourceforge.net/
JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for
your java applications.
When no VM is available, the wrapper can automatically download and install a suitable JVM, or
simply display a message or redirect the user to a web site.
A Swingbased project editor allows you to easily configure the executable binary for your software.
All the parameters are configured with a GUI, just click and compile the project.
21.14 Launch4J
http://launch4j.sourceforge.net/
Launch4j is a crossplatform tool for wrapping Java applications distributed as jars in lightweight
Windows native executables. The executable can be configured to search for a certain JRE version
or use a bundled one.
Supports GUI and console apps.
Supports Vista manifests and XP visual style manifests.
JVM options: set system properties, tweak the garbage collection...
Runtime JVM options from an .l4j.ini file.
Custom version information shown by Windows Explorer.
GUI, command line interface, Ant task and Maven plugin.
21.13 JSmooth
21.17 opencsv
A simple csv parser library for Java
http://opencsv.sourceforge.net/
21.18 ServingXML
Framework for flat/XML data transformations. Supported transformations : flatXML,
XMLflat, flatflat, and XMLXML
http://servingxml.sourceforge.net/
21.20 csvreader
Library for reading and writing CSV and plain delimited text files. All kinds of CSV files can
be handled, text qualified, Excel formatted, etc.
http://www.csvreader.com/java_csv.php
21.21 CSVFile
A simple set of Java classes used to handle CSV
http://sourceforge.net/projects/csvfile
21.22 FlatPack
Flat file parser that handles CSV, fixed length and custom delimiters. Export a DataSet to a
fixed length or delimited format. FlatPack provides a sorting mechanism for your flat files.
http://flatpack.sourceforge.net/
21.23 CSVJDBC
CsvJdbc is a simple readonly JDBC driver that uses Comma Separated Value (CSV) files
as database tables.
http://csvjdbc.sourceforge.net/
21.24 FFP
FFP Flat file parsing library, is used to parse text files where lines can be interpreted
21.16 com.Ostermiller.util CSV Utils
according to positional patterns. The library can handle both multiline formats and files
containing lines have different known formats ("mixed format" files).
http://jffp.sourceforge.net/
21.27 JExcel
Java Excel API is a java API enabling developers to read, write, and modify Excel
spreadsheets dynamically. Any operating system which can run a Java virtual machine can
both process and deliver Excel spreadsheets. One nice thing about JExcelApi is that it has
no dependencies on any third party libraries.
Example : output an Excel file from a Servlet
import java.io.IOException;
import java.io.OutputStream;
import
import
import
import
javax.servlet.ServletException;
javax.servlet.http.HttpServlet;
javax.servlet.http.HttpServletRequest;
javax.servlet.http.HttpServletResponse;
import
import
import
import
jxl.Workbook;
jxl.write.Label;
jxl.write.WritableSheet;
jxl.write.WritableWorkbook;
response.setHeader
("ContentDisposition", "attachment; filename=sampleName.xls");
WritableWorkbook w =
Workbook.createWorkbook(response.getOutputStream());
WritableSheet s = w.createSheet("Demo", 0);
s.addCell(new Label(0, 0, "Hello World"));
w.write();
w.close();
}
catch (Exception e){
throw new ServletException("Exception in Excel Sample Servlet", e);
}
finally{
if (out != null)
out.close();
}
}
}
See http://jexcelapi.sourceforge.net/
21.28 POI
The POI project consists of APIs for manipulating various file formats based upon Microsoft's
OLE 2 Compound Document format using pure Java. POI is your Java Excel solution as well
as your Java Word solution.
HSSF is the POI Project's pure Java implementation of the Excel '97(2002) file format and
it provides a way to read spreadsheets create, modify, read and write XLS spreadsheets.
Latest POI version seems to support the .XLSX format.
Since it's Jakarta project, POI has a dependencies with other JARs (commons,log4j,etc...).
Example : create an Excel file
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
HSSFRow row = sheet.createRow((short)0);
row.createCell((short)0).setCellValue("HelloWorld");
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();
The name was originally an acronym for "Poor Obfuscation Implementation" (ref: Wikipedia).
See http://jakarta.apache.org/poi/
21.29 JXLS
jXLS is a project that allows creation of extremely complex Excel reports just in several lines
of code. It is based on Jakarta POI.
With jXLS, all you need is to create XLS template file with all required formatting, formulas
etc using specific notation to indicate placement of data and then write a couple lines of
21.28 POI
code to invoke jXLS engine passing XLS template and the exported data as parameters.
Example :
The XLS Template
Employees
Name
${employee.name}
Age
Payment
Bonus
${employee.age} ${employee.payment} ${employee.bonus}
$[SUM(@employee.payment@)]
Payment Bonus
3000
30,00%
1500
15,00%
4500
Reading values from an XLS with jXLS is very simple. Suppose we have a worksheet with
policy numbers in the first column. We read and process them one by one.
import java.io.File;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
See http://jxls.sourceforge.net/
21.30 xlSQL
xlSQL is a JDBC Driver for Excel and CSV data sources. Documents can be read and
written with SQL as if they were tables in a database.
You can export XLS to XML or SQL INSERT statements. xlSQL includes its own
21.30 xlSQL
21.31 JCOM
JCOM is a Java to COM bridge library. With JCOM you can call a COM object from Java as
if it were a Java object without having to deal with the internals of JNI. The documentation is
minimal (in Japanese!).
Example :
import
import
import
import
jp.ne.so_net.ga2.no_ji.jcom.excel8.*;
jp.ne.so_net.ga2.no_ji.jcom.*;
java.io.File;
java.util.Date;
class TestExcel {
public static void main(String[] args) throws Exception {
ReleaseManager rm = new ReleaseManager();
try {
System.out.println("EXCEL startup...");
// if already started, open new window
ExcelApplication excel = new ExcelApplication(rm);
excel.Visible(true);
// display any information
System.out.println("Version="+excel.Version());
System.out.println("UserName="+excel.UserName());
System.out.println("Caption="+excel.Caption());
System.out.println("Value="+excel.Value());
ExcelWorkbooks xlBooks = excel.Workbooks();
ExcelWorkbook xlBook = xlBooks.Add();
// create new book
// enumurate all files
System.out.println
("set infomation of files in current directory to cell ...");
ExcelWorksheets xlSheets = xlBook.Worksheets();
ExcelWorksheet xlSheet = xlSheets.Item(1);
ExcelRange xlRange = xlSheet.Cells();
xlRange.Item(1,1).Value("filename" );
xlRange.Item(2,1).Value("size" );
xlRange.Item(3,1).Value("last modified time");
xlRange.Item(4,1).Value("is directory");
xlRange.Item(5,1).Value("is file");
xlRange.Item(6,1).Value("can read");
xlRange.Item(7,1).Value("can write");
File path = new File("./");
String[] filenames = path.list();
for(int i=0; i<filenames.length; i++) {
File file = new File(filenames[i]);
System.out.println(file);
xlRange.Item(1,i+2).Value( file.getName() );
xlRange.Item(2,i+2).Value( (int)file.length() );
xlRange.Item(3,i+2).Value( new Date(file.lastModified()) );
xlRange.Item(4,i+2).Value( file.isDirectory()?"Yes":"No" );
xlRange.Item(5,i+2).Value( file.isFile()?"Yes":"No" );
xlRange.Item(6,i+2).Value( file.canRead()?"Yes":"No" );
21.31 JCOM
xlRange.Item(7,i+2).Value( file.canWrite()?"Yes":"No" );
}
String expression = "=Sum(B2:B"+(filenames.length+1)+")";
System.out.println
("embed equation, calculate sum of filesize: "+expression);
xlRange.Item(1,filenames.length+2).Value("sum");
xlRange.Item(2,filenames.length+2).Formula(expression);
xlRange.Columns().AutoFit();
// fit columns
// comment out, if print out.
// output default printer.
//
System.out.println("print out...");
//
xlSheet.PrintOut();
//
//
//
//
//
xlBook.Close(false,null,false);
excel.Quit();
System.out.println("thank you .");
}
catch(Exception e) { e.printStackTrace(); }
finally { rm.release(); }
}
}
See http://sourceforge.net/projects/jcom
See also this HowTo for an alternative package to access a COM package from Java.
+ extracted[t].getName()+"."
+extracted[t].getType());
FileOutputStream outimg = new FileOutputStream
(workingdir + extracted[t].getName()+"."
+extracted[t].getType());
extracted[t].write(outimg);
outimg.flush();
outimg.close();
}
tbo = new WorkBookHandle();
sheet = tbo.getWorkSheet("Sheet1");
CellHandle a1 = sheet.add
("New workbook with 3 images: a gif, a jpg, and a png", "A1");
// get gif image input stream
FileInputStream fin = new FileInputStream
(workingdir + "testImages.gif");
// add to sheet
ImageHandle giffy = new ImageHandle(fin, sheet);
// set picture size and location in sheet
giffy.setBounds(100, 100, 400, 200);
giffy.setName("giffy");
sheet.insertImage(giffy);
// add to sheet
for(int x=0;x<100;x++) {
fin = new FileInputStream(workingdir + "testImages.png");
ImageHandle jpgy = new ImageHandle(fin, sheet);
jpgy.setName("heart" + x);
// set the random x/y coords of picture
int ix = Math.round((float)((x * (Math.random()*10))));
jpgy.setX(100 + ix);
ix = Math.round((float)((x * (Math.random()*10))));
jpgy.setY(100 + ix);
sheet.insertImage(jpgy);
}
// get png image input stream
fin = new FileInputStream(workingdir + "testImages.jpg");
// add to sheet
ImageHandle pngy = new ImageHandle(fin, sheet);
// set just the x/y coords of picture
pngy.setX(10);
pngy.setY(200);
sheet.insertImage(pngy);
}
catch(Exception e){
System.err.println("testImages failed: " + e.toString());
}
testWrite(tbo, workingdir + "testImagesOut.xls");
WorkBookHandle newbook = new WorkBookHandle
(workingdir + "testImagesOut.xls",0);
System.out.println("Successfully read: " + newbook);
}
public void testWrite(WorkBookHandle b, String fout){
try{
java.io.File f = new java.io.File(fout);
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bbout = new BufferedOutputStream(fos);
bbout.write(b.getBytes());
bbout.flush();
fos.close();
}
catch (java.io.IOException e){
System.err.println("IOException in Tester.
}
"+e);
See also this HowTo for a way to create a simple XLS without any additional library.
21.35 Jad
Jad, the fast JAva Decompiler, is a program that reads one or more Java class files and
converts them into Java source files which can be compiled again.
Jad is a 100% pure C++ program and it generally works several times faster than
decompilers written in Java. Jad doesn't use the Java runtime for its functioning, therefore
no special setup is required (like changes to the CLASSPATH variable).
Jad is not open source but it is free to use.
21.36 JadClipse
JadClipse is a plugin that seamlessly integrates Jad (the fast Java decompiler) with
Eclipse.
Normally, when opening a class file the Class File Viewer will show a brief API outline of the
class. If you install this plugin, however, the Class File Viewer will be replaced with the
JadClipse Class File Viewer that shows the decompiled source of the class.
http://jadclipse.sourceforge.net/wiki/index.php/Main_Page
21.38 JarPlug
By default, the support for viewing and editing JAR file in Eclipse is very limited.
With JarPlug, it is possible delete or update items stored in a JAR.
http://jarplug.sourceforge.net/
21.36 JadClipse
21.40 OneJar
Any nontrivial Java application is going to rely on any number of supporting Jar files. So
your deployment will include your application jar plus the supporting jars (ex. Apache
Commons, Log4j,...).
Unfortunately it's not possible to include a jar into another jar because the Java classloader
does not know how to load classes from a Jar inside a Jar.
OneJar is special classloader able to do this. The OneJAR JarClassLoader looks for a
main program inside a main directory in the Jar file, and looks for supporting Jar files inside
a lib directory.
The kit includes a special ANT task to simplify the process of preparing your application to
be distributed as a OneJar application.
http://onejar.sourceforge.net/
But Outlook (not the Express but the one with Office) can only save an email with the MSG
format which is Microsoft specific.
java.io.ByteArrayInputStream;
java.io.File;
java.io.FileOutputStream;
java.io.IOException;
java.io.OutputStream;
java.io.PrintWriter;
java.util.Iterator;
java.util.Map;
import org.apache.poi.hsmf.MAPIMessage;
import org.apache.poi.hsmf.datatypes.AttachmentChunks;
import org.apache.poi.hsmf.exceptions.ChunkNotFoundException;
// You need poiscratchpad3.6
fileOut.close();
}
}
}
}
}
else {
System.out.println("No attachment");
}
}
}
POI 3.7
import
import
import
import
import
import
import
import
java.io.ByteArrayInputStream;
java.io.File;
java.io.FileOutputStream;
java.io.IOException;
java.io.OutputStream;
java.io.PrintWriter;
java.util.Iterator;
java.util.Map;
import
import
import
import
import
org.apache.poi.hdgf.chunks.Chunk;
org.apache.poi.hsmf.MAPIMessage;
org.apache.poi.hsmf.datatypes.AttachmentChunks;
org.apache.poi.hsmf.datatypes.Chunks;
org.apache.poi.hsmf.exceptions.ChunkNotFoundException;
}
}
else {
System.out.println("No attachment");
}
}
}
21.44 msgparser
http://auxilii.com/msgparser/
msgparser is a small open source Java library that parses Outlook .msg files and provides
their content using Java objects. msgparser uses the Apache POI POIFS library to parse
the message files which use the OLE 2 Compound Document format.
import java.util.List;
import com.auxilii.msgparser.*;
import com.auxilii.msgparser.attachment.*;
public class SimpleMsgParser {
public static void main(String[] args) throws Exception{
MsgParser msgp = new MsgParser();
Message msg = msgp.parseMsg("c:/temp/test2.msg");
String
String
String
String
fromEmail = msg.getFromEmail();
fromName = msg.getFromName();
subject = msg.getSubject();
body = msg.getBodyText();
21.45 jmbox
https://jmbox.dev.java.net/
The jmbox project (read jambox) is a Local Store Provider for JavaMail, enabling developers
to use JavaMail api to manage the mail stored in local repositories like Outlook Express,
Mozilla, Netscape etc.
21.44 msgparser
At the moment are supported navigation and reading from Outlook Express 5/6 mail (dbx
format).
21.48 JNotify
http://jnotify.sourceforge.net/
JNotify is a java library that allow java application to listen to file system events. JNotify
works on both Windows (Windows 2000, XP, Vista) and Linux with INotify support (Kernel
2.6.14 and above).
http://johannburkard.de/blog/programming/java/CallnativemethodsinaDLLfromJavawithout
In this blog entry, the package NativeCall is used to call the Windows API to get notification
about modification in given folder.
21.51 Java 7
Java 7 provides a mechanism to get notificaton on file change without polling (JSR 203).
http://blogs.sun.com/thejavatutorials/entry/watching_a_directory_for_changes
21.54 Jansi
Jansi is a small java library that allows you to use ANSI escape sequences to format your
console output which works even on Windows.
import org.fusesource.jansi.AnsiConsole;
public class Test {
public static final
public static final
public static final
public static final
21.51 Java 7
String
String
String
String
ANSI_CLS = "\u001b[2J";
ANSI_HOME = "\u001b[H";
ANSI_BOLD = "\u001b[1m";
ANSI_AT55 = "\u001b[10;10H";
The above example shows that it's possible to use ANSI codes directly but Jansi provides a
neat mechanism to help building the required ANSI sequence.
21.55 JCurses
The Java Curses Library (JCurses) is a library for developing text terminal based
applications using Java programming language. It is implemented as a Windowing toolkit
similar to AWT, but built upon the UNIX "curses" windowing system.
JCurses works on Unix and Windows (32 bit only, on a 64bit OS you need to use JCurses
with a 32bit JVM).
This example will display a characterbased window with a label, a textfield and a button
(don't click with you mouse, use the keyboard!).
import
import
import
import
jcurses.system.*;
jcurses.widgets.*;
jcurses.util.*;
jcurses.event.*;
21.55 JCurses
<module name="Checker">
<property name="severity" value="warning"/>
<property name="localeLanguage" value="fr"/>
<module name="SuppressionCommentFilter"/>
<module name="TreeWalker">
<module name="FileContentsHolder"/>
...
<module name="HideUtilityClassConstructor"/>
</module>
</module>
//CHECKSTYLE:OFF
public void setDriverFileName(String driverFileName) { this.driverFileName = driverFileNa
public String getDriverFileName () { return this.driverFileName;}
//CHECKSTYLE:ON
PdfWriter.getInstance(document,
new FileOutputStream("HelloWorld.pdf"));
document.open();
document.add(new Paragraph("Hello World"));
}
catch (DocumentException de) {
System.err.println(de.getMessage());
}
catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
document.close();
}
}
com.lowagie.text.Element;
com.lowagie.text.Image;
com.lowagie.text.PageSize;
com.lowagie.text.pdf.BaseFont;
com.lowagie.text.pdf.PdfContentByte;
com.lowagie.text.pdf.PdfReader;
com.lowagie.text.pdf.PdfStamper;
}
// adding an extra page
stamp.insertPage(1, PageSize.A4);
over = stamp.getOverContent(1);
over.beginText();
over.setFontAndSize(bf, 18);
over.showTextAligned(Element.ALIGN_LEFT,
"DUPLICATE OF AN EXISTING PDF DOCUMENT", 30, 600, 0);
over.endText();
// adding a page from another document
PdfReader reader2 = new PdfReader("SimpleAnnotations1.pdf");
under = stamp.getUnderContent(1);
under.addTemplate
(stamp.getImportedPage(reader2, 3), 1, 0, 0, 1, 0, 0);
// closing PdfStamper will generate the new PDF file
stamp.close();
}
catch (Exception de) {
de.printStackTrace();
}
}
}
21.59 iText
http://www.lowagie.com/iText/
iText is a very simple to use package to create and manipulate PDF file.
For the simple need, only 1 jar is required (ex. itext2.1.3.jar, download at
http://www.lowagie.com/iText/download.html)
In this example, you pass on the command line a filename (plain text file args[0]) to
convert to a PDF file (args[1]).
import java.io.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;
public class TextFileToPDF {
/*
ex. java TextFileToPDF
c:\temp\text.txt
c:\temp\text.pdf
*/
public static void main (String [] args){
BufferedReader input = null;
Document output = null;
System.out.println("Convert text file to pdf");
System.out.println("input : " + args[0]);
System.out.println("output : " + args[1]);
try {
// text file to convert to pdf as args[0]
input =
new BufferedReader (new FileReader(args[0]));
// letter 8.5x11
//
see com.lowagie.text.PageSize for a complete list of pagesize constants.
output = new Document(PageSize.LETTER, 40, 40, 40, 40);
// pdf file as args[1]
PdfWriter.getInstance(output, new FileOutputStream (args[1]));
output.open();
output.addAuthor("RealHowTo");
output.addSubject(args[0]);
output.addTitle(args[0]);
String line = "";
while(null != (line = input.readLine())) {
System.out.println(line);
Paragraph p = new Paragraph(line);
p.setAlignment(Element.ALIGN_JUSTIFIED);
output.add(p);
}
System.out.println("Done.");
output.close();
input.close();
System.exit(0);
}
catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
}
This a command line utility. You specify the pdf file to be split. Each page is extracted to its
own pdf file.
/*
* java SplitPDFFile file.pdf
*
*
gives
file001.pdf ... filennn.pdf
*
* itext2.1.5.jar
*/
import java.io.FileOutputStream;
import
import
import
import
com.lowagie.text.Document;
com.lowagie.text.pdf.PdfCopy;
com.lowagie.text.pdf.PdfImportedPage;
com.lowagie.text.pdf.PdfReader;
com.lowagie.text.Document;
com.lowagie.text.pdf.PRAcroForm;
com.lowagie.text.pdf.PdfCopy;
com.lowagie.text.pdf.PdfImportedPage;
com.lowagie.text.pdf.PdfReader;
com.lowagie.text.pdf.SimpleBookmark;
if (f == 0) {
document = new Document(reader.getPageSizeWithRotation(1));
writer = new PdfCopy(document,
new FileOutputStream(outFile));
document.open();
}
PdfImportedPage page;
for (int i = 0; i < n;) {
++i;
page = writer.getImportedPage(reader, i);
writer.addPage(page);
}
PRAcroForm form = reader.getAcroForm();
if (form != null) {
writer.copyAcroForm(reader);
}
f++;
}
if (!master.isEmpty()) {
writer.setOutlines(master);
}
document.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
com.lowagie.text.Document;
com.lowagie.text.Image;
com.lowagie.text.PageSize;
com.lowagie.text.Rectangle;
com.lowagie.text.pdf.PdfContentByte;
com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.RandomAccessFileOrArray;
import com.lowagie.text.pdf.codec.TiffImage;
public class TiffToPDF {
public static void main(String[] args) {
if (args.length < 1) {
System.out
.println("Usage: Tiff2Pdf file1.tif [file2.tif ... fileN.tif]");
System.exit(1);
}
String tiff;
String pdf;
for (int i = 0; i < args.length; i++) {
tiff = args[i];
pdf = tiff.substring(0, tiff.lastIndexOf('.') + 1) + "pdf";
Document document = new Document(PageSize.LETTER, 0, 0, 0, 0);
try {
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream(pdf));
int pages = 0;
document.open();
PdfContentByte cb = writer.getDirectContent();
RandomAccessFileOrArray ra = null;
int comps = 0;
try {
ra = new RandomAccessFileOrArray(tiff);
comps = TiffImage.getNumberOfPages(ra);
}
catch (Throwable e) {
System.out.println("Exception in " + tiff + " "
+ e.getMessage());
continue;
}
System.out.println("Processing: " + tiff);
for (int c = 0; c < comps; ++c) {
try {
Image img = TiffImage.getTiffImage(ra, c + 1);
if (img != null) {
System.out.println("page " + (c + 1));
img.scalePercent
(7200f / img.getDpiX(), 7200f / img.getDpiY());
document.setPageSize
(new Rectangle(img.getScaledWidth(), img.getScaledHeight()));
img.setAbsolutePosition(0, 0);
cb.addImage(img);
document.newPage();
++pages;
}
}
catch (Throwable e) {
System.out.println("Exception " + tiff + " page "
+ (c + 1) + " " + e.getMessage());
}
}
ra.close();
document.close();
}
catch (Throwable e) {
e.printStackTrace();
}
System.out.println("done");
}
}
import java.io.FileOutputStream;
import java.io.StringReader;
import
import
import
import
com.itextpdf.text.Document;
com.itextpdf.text.PageSize;
com.itextpdf.text.html.simpleparser.HTMLWorker; // deprecated
com.itextpdf.text.pdf.PdfWriter;
}
catch (Exception e) {
e.printStackTrace();
}
}
}
As you can see, the validity of the parsed HTML (using HTMLWorker) is very relax. Closing
tags are not required : <BR> is ok (<BR/> is not mandatory).
HTMLWorker is ok with older iText version but the recommended approach with new iText
(HTMLWorker is now deprecated) is to use the XMLWorker. XMLWorker is stricter since you
must send XHTML document to it.
import java.io.FileOutputStream;
import java.io.StringReader;
import
import
import
import
public
com.itextpdf.text.Document;
com.itextpdf.text.PageSize;
com.itextpdf.text.pdf.PdfWriter;
com.itextpdf.tool.xml.XMLWorkerHelper;
class HtmlToPDF2 {
// itextpdf5.4.1.jar http://sourceforge.net/projects/itext/files/iText/
// xmlworker5.4.1.jar http://sourceforge.net/projects/xmlworker/files/
public static void main(String ... args ) {
try {
Document document = new Document(PageSize.LETTER);
PdfWriter pdfWriter = PdfWriter.getInstance
(document, new FileOutputStream("c://temp//testpdf.pdf"));
document.open();
document.addAuthor("Real Gagnon");
document.addCreator("Real's HowTo");
document.addSubject("Thanks for your support");
document.addCreationDate();
document.addTitle("Please read this");
XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
Note : To get the color on a table cell, you need to use a style because the bgcolor attribute
is not supported. By default, FORM elements are not rendered. Review this document to see
what is supported : http://demo.itextsupport.com/xmlworker/doc.html
See also Convert HTML to PDF using YAHP
java.io.File;
java.io.FileOutputStream;
java.util.ArrayList;
java.util.HashMap;
java.util.List;
java.util.Map;
// http://www.allcolor.org/YaHPConverter/
import org.allcolor.yahp.converter.CYaHPConverter;
import org.allcolor.yahp.converter.IHtmlToPdfTransformer;
public class HtmlToPdf_yahp {
public static void main(String ... args ) throws Exception {
htmlToPdfFile();
}
public static void htmlToPdfFile() throws Exception {
CYaHPConverter converter = new CYaHPConverter();
File fout = new File("c:/temp/x.pdf");
FileOutputStream out = new FileOutputStream(fout);
Map properties = new HashMap();
List headerFooterList = new ArrayList();
String str = "<HTML><HEAD></HEAD><BODY><H1>Testing</H1><FORM>" +
"check : <INPUT TYPE='checkbox' checked=checked/><br/>"
"</FORM></BODY></HTML>";
properties.put(IHtmlToPdfTransformer.PDF_RENDERER_CLASS,
IHtmlToPdfTransformer.FLYINGSAUCER_PDF_RENDERER);
//properties.put(IHtmlToPdfTransformer.FOP_TTF_FONT_PATH, fontPath);
converter.convertToPdf(str,
IHtmlToPdfTransformer.A4P,
headerFooterList,
In the next example, we read an existing HTML file and convert it to a PDF file.
import
import
import
import
import
import
import
java.io.File;
java.io.FileOutputStream;
java.util.ArrayList;
java.util.HashMap;
java.util.List;
java.util.Map;
java.util.Scanner;
// http://www.allcolor.org/YaHPConverter/
import org.allcolor.yahp.converter.CYaHPConverter;
import org.allcolor.yahp.converter.IHtmlToPdfTransformer;
public class HtmlToPdf_yahp_2 {
public static void main(String ... args ) throws Exception {
String root = "c:/temp/html";
String input = "file_1659686.htm"; // need to be charset utf8
htmlToPdfFile(new File(root, input),
new File(root, input + ".pdf"));
System.out.println("Done");
}
public static void htmlToPdfFile(File htmlIn, File pdfOut) throws Exception {
Scanner scanner =
new Scanner(htmlIn).useDelimiter("\\Z");
String htmlContents = scanner.next();
CYaHPConverter converter = new CYaHPConverter();
FileOutputStream out = new FileOutputStream(pdfOut);
Map properties = new HashMap();
List headerFooterList = new ArrayList();
properties.put(IHtmlToPdfTransformer.PDF_RENDERER_CLASS,
IHtmlToPdfTransformer.FLYINGSAUCER_PDF_RENDERER);
//properties.put(IHtmlToPdfTransformer.FOP_TTF_FONT_PATH, fontPath);
converter.convertToPdf(htmlContents,
IHtmlToPdfTransformer.A4P,
headerFooterList,
"file:///temp/html/",
out,
properties);
out.flush();
out.close();
}
}
NOTE : After downloading YAHP (and its dependencies), you still need to build a YAHP.JAR, it's done easily with Eclipse... but you
can get it here.
import java.io.FileOutputStream;
//com.lowagie...
old version
//com.itextpdf... recent version
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.Image;
Unfortunately, Acrobat Reader stays opened (but minimized because of the /h switch) after
the printing operation :(
You can use a special wrapper to force the closing the Acrobat Reader after the print
operation. See http://www.biopdf.com/acrowrap/close_adobe_reader.php (acrowrap.exe).
org.apache.tika.parser.pdf.PDFParser;
org.apache.tika.metadata.Metadata;
org.apache.tika.parser.ParseContext;
org.apache.tika.sax.BodyContentHandler;
org.xml.sax.ContentHandler;
See also Extract text from HTML, Get Mime Type from a file.
A nice extra step would be that to extract the content as text, do a trim() and check if the result is empty or not ... this is left as an
exercise to the reader for now ;).
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import
import
import
import
import
import
import
import
import
com.itextpdf.text.Document;
com.itextpdf.text.DocumentException;
com.itextpdf.text.io.RandomAccessSourceFactory;
com.itextpdf.text.pdf.PdfCopy;
com.itextpdf.text.pdf.PdfDictionary;
com.itextpdf.text.pdf.PdfImportedPage;
com.itextpdf.text.pdf.PdfName;
com.itextpdf.text.pdf.PdfReader;
com.itextpdf.text.pdf.RandomAccessFileOrArray;
if (!noFontsOrImages) {
byte bContent [] = r.getPageContent(i,raf);
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bs.write(bContent);
System.out.println
(i + bs.size() + " > BLANK_THRESHOLD " + (bs.size() > BLANK_THRESH