Useful Code of the Day:  Multipart Form File Upload

So, you want to upload files to your web server, do ya? Well, I've seen this topic posted a few times in the last month or so and many of the response I've seen here haven't included definitive answers. Of course, the actual problems vary, but ultimately, a bunch of people want to do file upload from an applet or application to an existing file upload script (CGI, PHP, JSP, etc.) on a web server. And invariably, there are problems with formatting the HTTP request to get things working.
Well, I had a need to do the same thing. I realize there are other solutions out there, such as some sample code that comes with Jakarta Commons Upload. But since we all like reusable code, and we also all seem to like reinventing wheels, here's my go at it: MultiPartFormOutputStream!
MultiPartFormOutputStream is a specialized OutputStream-like class. You create your URLConnection to the server (a static method included can do this for a URL for you, as some of the settings, doInput and doOutput specifically, seem to confuse people). Then get the OutputStream from it and create a boundary string (a static method to create one is provided as well) and pass them to the constructor. Now you have a MultiPartFormOutputStream which you can use to write form fields like text fields, checkboxes, etc., as well as write file data (from Files, InputStreams or raw bytes).
There are some convenience methods for writing primative type values as well as strings, but any higher level objects (aside from Files or InputStreams) aren't supported. (You can always serialize and pass the raw bytes.)
Sample usage code is below. Also, any recommendations for improvement are requested. The code was tested with the Jakarta Struts.
import java.io.*;
import java.net.*;
* <code>MultiPartFormOutputStream</code> is used to write
* "multipart/form-data" to a <code>java.net.URLConnection</code> for
* POSTing.  This is primarily for file uploading to HTTP servers. 
* @since  JDK1.3
public class MultiPartFormOutputStream {
      * The line end characters. 
     private static final String NEWLINE = "\r\n";
      * The boundary prefix. 
     private static final String PREFIX = "--";
      * The output stream to write to. 
     private DataOutputStream out = null;
      * The multipart boundary string. 
     private String boundary = null;
      * Creates a new <code>MultiPartFormOutputStream</code> object using
      * the specified output stream and boundary.  The boundary is required
      * to be created before using this method, as described in the
      * description for the <code>getContentType(String)</code> method. 
      * The boundary is only checked for <code>null</code> or empty string,
      * but it is recommended to be at least 6 characters.  (Or use the
      * static createBoundary() method to create one.)
      * @param  os        the output stream
      * @param  boundary  the boundary
      * @see  #createBoundary()
      * @see  #getContentType(String)
     public MultiPartFormOutputStream(OutputStream os, String boundary) {
          if(os == null) {
               throw new IllegalArgumentException("Output stream is required.");
          if(boundary == null || boundary.length() == 0) {
               throw new IllegalArgumentException("Boundary stream is required.");
          this.out = new DataOutputStream(os);
          this.boundary = boundary;
      * Writes an boolean field value. 
      * @param  name   the field name (required)
      * @param  value  the field value
      * @throws  java.io.IOException  on input/output errors
     public void writeField(String name, boolean value)
               throws java.io.IOException {
          writeField(name, new Boolean(value).toString());
      * Writes an double field value. 
      * @param  name   the field name (required)
      * @param  value  the field value
      * @throws  java.io.IOException  on input/output errors
     public void writeField(String name, double value)
               throws java.io.IOException {
          writeField(name, Double.toString(value));
      * Writes an float field value. 
      * @param  name   the field name (required)
      * @param  value  the field value
      * @throws  java.io.IOException  on input/output errors
     public void writeField(String name, float value)
               throws java.io.IOException {
          writeField(name, Float.toString(value));
      * Writes an long field value. 
      * @param  name   the field name (required)
      * @param  value  the field value
      * @throws  java.io.IOException  on input/output errors
     public void writeField(String name, long value)
               throws java.io.IOException {
          writeField(name, Long.toString(value));
      * Writes an int field value. 
      * @param  name   the field name (required)
      * @param  value  the field value
      * @throws  java.io.IOException  on input/output errors
     public void writeField(String name, int value)
               throws java.io.IOException {
          writeField(name, Integer.toString(value));
      * Writes an short field value. 
      * @param  name   the field name (required)
      * @param  value  the field value
      * @throws  java.io.IOException  on input/output errors
     public void writeField(String name, short value)
               throws java.io.IOException {
          writeField(name, Short.toString(value));
      * Writes an char field value. 
      * @param  name   the field name (required)
      * @param  value  the field value
      * @throws  java.io.IOException  on input/output errors
     public void writeField(String name, char value)
               throws java.io.IOException {
          writeField(name, new Character(value).toString());
      * Writes an string field value.  If the value is null, an empty string
      * is sent (""). 
      * @param  name   the field name (required)
      * @param  value  the field value
      * @throws  java.io.IOException  on input/output errors
     public void writeField(String name, String value)
               throws java.io.IOException {
          if(name == null) {
               throw new IllegalArgumentException("Name cannot be null or empty.");
          if(value == null) {
               value = "";
          --boundary\r\n
          Content-Disposition: form-data; name="<fieldName>"\r\n
          \r\n
          <value>\r\n
          // write boundary
          out.writeBytes(PREFIX);
          out.writeBytes(boundary);
          out.writeBytes(NEWLINE);
          // write content header
          out.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"");
          out.writeBytes(NEWLINE);
          out.writeBytes(NEWLINE);
          // write content
          out.writeBytes(value);
          out.writeBytes(NEWLINE);
          out.flush();
      * Writes a file's contents.  If the file is null, does not exists, or
      * is a directory, a <code>java.lang.IllegalArgumentException</code>
      * will be thrown. 
      * @param  name      the field name
      * @param  mimeType  the file content type (optional, recommended)
      * @param  file      the file (the file must exist)
      * @throws  java.io.IOException  on input/output errors
     public void writeFile(String name, String mimeType, File file)
               throws java.io.IOException {
          if(file == null) {
               throw new IllegalArgumentException("File cannot be null.");
          if(!file.exists()) {
               throw new IllegalArgumentException("File does not exist.");
          if(file.isDirectory()) {
               throw new IllegalArgumentException("File cannot be a directory.");
          writeFile(name, mimeType, file.getCanonicalPath(), new FileInputStream(file));
      * Writes a input stream's contents.  If the input stream is null, a
      * <code>java.lang.IllegalArgumentException</code> will be thrown. 
      * @param  name      the field name
      * @param  mimeType  the file content type (optional, recommended)
      * @param  fileName  the file name (required)
      * @param  is        the input stream
      * @throws  java.io.IOException  on input/output errors
     public void writeFile(String name, String mimeType,
               String fileName, InputStream is)
               throws java.io.IOException {
          if(is == null) {
               throw new IllegalArgumentException("Input stream cannot be null.");
          if(fileName == null || fileName.length() == 0) {
               throw new IllegalArgumentException("File name cannot be null or empty.");
          --boundary\r\n
          Content-Disposition: form-data; name="<fieldName>"; filename="<filename>"\r\n
          Content-Type: <mime-type>\r\n
          \r\n
          <file-data>\r\n
          // write boundary
          out.writeBytes(PREFIX);
          out.writeBytes(boundary);
          out.writeBytes(NEWLINE);
          // write content header
          out.writeBytes("Content-Disposition: form-data; name=\"" + name +
               "\"; filename=\"" + fileName + "\"");
          out.writeBytes(NEWLINE);
          if(mimeType != null) {
               out.writeBytes("Content-Type: " + mimeType);
               out.writeBytes(NEWLINE);
          out.writeBytes(NEWLINE);
          // write content
          byte[] data = new byte[1024];
          int r = 0;
          while((r = is.read(data, 0, data.length)) != -1) {
               out.write(data, 0, r);
          // close input stream, but ignore any possible exception for it
          try {
               is.close();
          } catch(Exception e) {}
          out.writeBytes(NEWLINE);
          out.flush();
      * Writes the given bytes.  The bytes are assumed to be the contents
      * of a file, and will be sent as such.  If the data is null, a
      * <code>java.lang.IllegalArgumentException</code> will be thrown. 
      * @param  name      the field name
      * @param  mimeType  the file content type (optional, recommended)
      * @param  fileName  the file name (required)
      * @param  data      the file data
      * @throws  java.io.IOException  on input/output errors
     public void writeFile(String name, String mimeType,
               String fileName, byte[] data)
               throws java.io.IOException {
          if(data == null) {
               throw new IllegalArgumentException("Data cannot be null.");
          if(fileName == null || fileName.length() == 0) {
               throw new IllegalArgumentException("File name cannot be null or empty.");
          --boundary\r\n
          Content-Disposition: form-data; name="<fieldName>"; filename="<filename>"\r\n
          Content-Type: <mime-type>\r\n
          \r\n
          <file-data>\r\n
          // write boundary
          out.writeBytes(PREFIX);
          out.writeBytes(boundary);
          out.writeBytes(NEWLINE);
          // write content header
          out.writeBytes("Content-Disposition: form-data; name=\"" + name +
               "\"; filename=\"" + fileName + "\"");
          out.writeBytes(NEWLINE);
          if(mimeType != null) {
               out.writeBytes("Content-Type: " + mimeType);
               out.writeBytes(NEWLINE);
          out.writeBytes(NEWLINE);
          // write content
          out.write(data, 0, data.length);
          out.writeBytes(NEWLINE);
          out.flush();
      * Flushes the stream.  Actually, this method does nothing, as the only
      * write methods are highly specialized and automatically flush. 
      * @throws  java.io.IOException  on input/output errors
     public void flush() throws java.io.IOException {
          // out.flush();
      * Closes the stream.  <br />
      * <br />
      * <b>NOTE:</b> This method <b>MUST</b> be called to finalize the
      * multipart stream.
      * @throws  java.io.IOException  on input/output errors
     public void close() throws java.io.IOException {
          // write final boundary
          out.writeBytes(PREFIX);
          out.writeBytes(boundary);
          out.writeBytes(PREFIX);
          out.writeBytes(NEWLINE);
          out.flush();
          out.close();
      * Gets the multipart boundary string being used by this stream. 
      * @return  the boundary
     public String getBoundary() {
          return this.boundary;
      * Creates a new <code>java.net.URLConnection</code> object from the
      * specified <code>java.net.URL</code>.  This is a convenience method
      * which will set the <code>doInput</code>, <code>doOutput</code>,
      * <code>useCaches</code> and <code>defaultUseCaches</code> fields to
      * the appropriate settings in the correct order. 
      * @return  a <code>java.net.URLConnection</code> object for the URL
      * @throws  java.io.IOException  on input/output errors
     public static URLConnection createConnection(URL url)
               throws java.io.IOException {
          URLConnection urlConn = url.openConnection();
          if(urlConn instanceof HttpURLConnection) {
               HttpURLConnection httpConn = (HttpURLConnection)urlConn;
               httpConn.setRequestMethod("POST");
          urlConn.setDoInput(true);
          urlConn.setDoOutput(true);
          urlConn.setUseCaches(false);
          urlConn.setDefaultUseCaches(false);
          return urlConn;
      * Creates a multipart boundary string by concatenating 20 hyphens (-)
      * and the hexadecimal (base-16) representation of the current time in
      * milliseconds. 
      * @return  a multipart boundary string
      * @see  #getContentType(String)
     public static String createBoundary() {
          return "--------------------" +
               Long.toString(System.currentTimeMillis(), 16);
      * Gets the content type string suitable for the
      * <code>java.net.URLConnection</code> which includes the multipart
      * boundary string.  <br />
      * <br />
      * This method is static because, due to the nature of the
      * <code>java.net.URLConnection</code> class, once the output stream
      * for the connection is acquired, it's too late to set the content
      * type (or any other request parameter).  So one has to create a
      * multipart boundary string first before using this class, such as
      * with the <code>createBoundary()</code> method. 
      * @param  boundary  the boundary string
      * @return  the content type string
      * @see  #createBoundary()
     public static String getContentType(String boundary) {
          return "multipart/form-data; boundary=" + boundary;
}Usage: (try/catch left out to shorten the post a bit)
URL url = new URL("http://www.domain.com/webems/upload.do");
// create a boundary string
String boundary = MultiPartFormOutputStream.createBoundary();
URLConnection urlConn = MultiPartFormOutputStream.createConnection(url);
urlConn.setRequestProperty("Accept", "*/*");
urlConn.setRequestProperty("Content-Type",
     MultiPartFormOutputStream.getContentType(boundary));
// set some other request headers...
urlConn.setRequestProperty("Connection", "Keep-Alive");
urlConn.setRequestProperty("Cache-Control", "no-cache");
// no need to connect cuz getOutputStream() does it
MultiPartFormOutputStream out =
     new MultiPartFormOutputStream(urlConn.getOutputStream(), boundary);
// write a text field element
out.writeField("myText", "text field text");
// upload a file
out.writeFile("myFile", "text/plain", new File("C:\\test.txt"));
// can also write bytes directly
//out.writeFile("myFile", "text/plain", "C:\\test.txt",
//     "This is some file text.".getBytes("ASCII"));
out.close();
// read response from server
BufferedReader in = new BufferedReader(
     new InputStreamReader(urlConn.getInputStream()));
String line = "";
while((line = in.readLine()) != null) {
      System.out.println(line);
in.close();------
"Useful Code of the Day" is supplied by the person who posted this message. This code is not guaranteed by any warranty whatsoever. The code is free to use and modify as you see fit. The code was tested and worked for the author. If anyone else has some useful code, feel free to post it under this heading.

I have a weird problem here. I'm using the Java POST (slightly altered for my purposes) mechanism but the receiving script doesn't receive any form variables (neither files nor regular form fields). If I try using the same receiving script with a regular upload form, it works. Because I've been pulling my hair out, I even went so far as to analyze the ip-packets. I can see that the file is actually sent through the Java POST mecahnism. Anybody any ideas. Here's the ip-packet of the failing upload:
----- Hypertext Transfer Protocol -----
HTTP: POST /fotoxs/upload.cfm HTTP/1.1
HTTP: Connection: Keep-Alive
HTTP: Content-Type: multipart/form-data; boundary=-----------------------------fb2649be18
HTTP: User-Agent: Mozilla/4.7 [en] (WinNT; U)
HTTP: Accept-Language: en-us
HTTP: Accept-Encoding: gzip, deflate
HTTP: Accept: image/gif, image/jpeg, image/pjpeg, */*
HTTP: CACHE-CONTROL: no-cache
HTTP: Host: newmarc
HTTP: Content-Length: 15511
----- Hypertext Transfer Protocol -----
HTTP: -----------------------------fb2649be18
HTTP: Content-Disposition: form-data; name="uploadFile"; filename="out.jpg"
HTTP: Content-Type: image/jpeg
HTTP: Data
....[data packets]
The one that works (from the regular post) is as follows:
----- Hypertext Transfer Protocol -----
HTTP: POST /fotoxs/upload.cfm HTTP/1.1
HTTP: Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-gsarcade-launch, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
HTTP: Referer: http://localhost:8500/fotoxs/test.cfm
HTTP: Accept-Language: nl
HTTP: Content-Type: multipart/form-data; boundary=---------------------------7d41961f201c0
HTTP: Accept-Encoding: gzip, deflate
HTTP: User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
HTTP: Host: newmarc
HTTP: Content-Length: 59022
HTTP: Connection: Keep-Alive
HTTP: Cache-Control: no-cache
----- Hypertext Transfer Protocol -----
HTTP: -----------------------------7d41961f201c0
HTTP: Content-Disposition: form-data; name="FiletoUpload"; filename="D:\My Documents\My Pictures\fotomarc.jpg"
HTTP: Content-Type: image/pjpeg
HTTP: Data
----- Hypertext Transfer Protocol -----
HTTP: HTTP/1.1 100 Continue
HTTP: Server: Microsoft-IIS/5.0
HTTP: Date: Sun, 07 Mar 2004 17:14:41 GMT
....[data packets]
One detail worth mentioning is that I don't read a file from harddisk, I'm streaming it directly to the connection outputstream from an image compression utility. But I can see the data in the ip-packets, and even if that somehow didn't work right, it doesn't explaing the fact that the receiving scripts reports no form fields whatsoever.
Thanks,
Marc

Similar Messages

  • Useful Code of the Day:  Button fires events while held

    Have you ever been making a GUI application with Swing and used some JButtons? Fun, right? Have you ever wanted to have the button fire action events while the button was being held down? Well, if you just stick a plain JButton in your application and press and hold the mouse button on it, you'll see it doesn't do anything except sit there looking pressed in. Insolent button!
    RepeatButton (code below, couldn't think of a better name) is a JButton subclass which contains a timer that is set when the mouse button presses the button, and after a slight initial delay (configurable), fires action events to all registered action listeners repeatedly (with another configurable delay between events) until either the mouse is released or the mouse moves out of the button (it starts up again if the mouse moves back over without releasing the mouse button) or the button is disabled. The event modifiers are passed on as well, so you know if the shift or control buttons (or whatever) are being pressed at the same time.
    There is also a method to disable the repeated action firing while holding. This, in effect, turns the button into a normal JButton, if needed.
    There is a main method for testing which will show a button in a frame and print out the action command for each action event fired.
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import javax.swing.*;
    import javax.swing.event.*;
    * <code>RepeatButton</code> is a <code>JButton</code> which contains a timer
    * for firing events while the button is held down.  There is a default
    * initial delay of 300ms before the first event is fired and a 60ms delay
    * between subsequent events.  When the user holds the button down and moves
    * the mouse out from over the button, the timer stops, but if the user moves
    * the mouse back over the button without having released the mouse button,
    * the timer starts up again at the same delay rate.  If the enabled state is
    * changed while the timer is active, it will be stopped.
    * NOTE:  The normal button behavior is that the action event is fired after
    * the button is released.  It may be important to konw then that this is
    * still the case.  So in effect, listeners will get 1 more event then what
    * the internal timer fires.  It's not a "bug", per se, just something to be
    * aware of.  There seems to be no way to suppress the final event from
    * firing anyway, except to process all ActionListeners internally.  But
    * realistically, it probably doesn't matter. 
    public class RepeatButton extends JButton
              implements ActionListener, MouseListener {
          * The pressed state for this button.
         private boolean pressed = false;
          * Flag to indicate that the button should fire events when held. 
          * If false, the button is effectively a plain old JButton, but
          * there may be times when this feature might wish to be disabled. 
         private boolean repeatEnabled = true;
          * The hold-down timer for this button.
         private Timer timer = null;
          * The pressed state for this button.
         private int delay = 60;
          * The pressed state for this button.
         private int initialDelay = 300;
          * Holder of the modifiers used when the mouse pressed the button. 
          * This is used for subsequently fired action events.  This may change
          * after mouse pressed if the user moves the mouse out, releases a key
          * and then moves the mouse back in. 
         private int modifiers = 0;
          * Creates a button with no set text or icon.
         public RepeatButton() {
              super();
              init();
          * Creates a button where properties are taken from the Action supplied.
          * @param  a  the button action
         public RepeatButton(Action a) {
              super(a);
              init();
          * Creates a button with an icon.
          * @param  icon  the button icon
         public RepeatButton(Icon icon) {
              super(icon);
              init();
          * Creates a button with text.
          * @param  text  the button text
         public RepeatButton(String text) {
              super(text);
              init();
          * Creates a button with initial text and an icon.
          * @param  text  the button text
          * @param  icon  the button icon
         public RepeatButton(String text, Icon icon) {
              super(text, icon);
              init();
          * Initializes the button.
         private void init() {
              this.addMouseListener(this);
              // initialize timers for button holding...
              this.timer = new Timer(this.delay, this);
              this.timer.setRepeats(true);
          * Gets the delay for the timer of this button. 
          * @return  the delay
         public int getDelay() {
              return this.delay;
          * Set the delay for the timer of this button. 
          * @param  d  the delay
         public void setDelay(int d) {
              this.delay = d;
          * Gets the initial delay for the timer of this button. 
          * @return  the initial delay
         public int getInitialDelay() {
              return this.initialDelay;
          * Sets the initial delay for the timer of this button. 
          * @param  d  the initial delay
         public void setInitialDelay(int d) {
              this.initialDelay = d;
          * Checks if the button should fire events when held.  If false, the
          * button is effectively a plain old JButton, but there may be times
          * when this feature might wish to be disabled. 
          * @return  if true, the button should fire events when held
         public boolean isRepeatEnabled() {
              return this.repeatEnabled;
          * Sets if the button should fire events when held.  If false, the
          * button is effectively a plain old JButton, but there may be times
          * when this feature might wish to be disabled.  If false, it will
          * also stop the timer if it's running.
          * @param  en  if true, the button should fire events when held
         public void setRepeatEnabled(boolean en) {
              if(!en) {
                   this.pressed = false;
                   if(timer.isRunning()) {
                        timer.stop();
              this.repeatEnabled = en;
          * Sets the enabled state of this button.  Overridden to stop the timer
          * if it's running.
          * @param  en  if true, enables the button
         public void setEnabled(boolean en) {
              if(en != super.isEnabled()) {
                   this.pressed = false;
                   if(timer.isRunning()) {
                        timer.stop();
              super.setEnabled(en);
          * Handle action events.
          * @param  ae  the action event
         public void actionPerformed(ActionEvent ae) {
              // process events only from this components
              if(ae.getSource() == this.timer) {
                   ActionEvent event = new ActionEvent(
                        this, ActionEvent.ACTION_PERFORMED,
                        super.getActionCommand(), this.modifiers);
                   super.fireActionPerformed(event);
              // testing code...
              else if(testing && ae.getSource() == this) {
                   System.out.println(ae.getActionCommand());
          * Handle mouse clicked events.
          * @param  me  the mouse event
         public void mouseClicked(MouseEvent me) {
              // process events only from this components
              if(me.getSource() == this) {
                   this.pressed = false;
                   if(this.timer.isRunning()) {
                        this.timer.stop();
          * Handle mouse pressed events.
          * @param  me  the mouse event
         public void mousePressed(MouseEvent me) {
              // process events only from this components
              if(me.getSource() == this && this.isEnabled() && this.isRepeatEnabled()) {
                   this.pressed = true;
                   if(!this.timer.isRunning()) {
                        this.modifiers = me.getModifiers();
                        this.timer.setInitialDelay(this.initialDelay);
                        this.timer.start();
          * Handle mouse released events.
          * @param  me  the mouse event
         public void mouseReleased(MouseEvent me) {
              // process events only from this components
              if(me.getSource() == this) {
                   this.pressed = false;
                   if(this.timer.isRunning()) {
                        this.timer.stop();
          * Handle mouse entered events.
          * @param  me  the mouse event
         public void mouseEntered(MouseEvent me) {
              // process events only from this components
              if(me.getSource() == this && this.isEnabled() && this.isRepeatEnabled()) {
                   if(this.pressed && !this.timer.isRunning()) {
                        this.modifiers = me.getModifiers();
                        this.timer.setInitialDelay(this.delay);
                        this.timer.start();
          * Handle mouse exited events.
          * @param  me  the mouse event
         public void mouseExited(MouseEvent me) {
              // process events only from this components
              if(me.getSource() == this) {
                   if(this.timer.isRunning()) {
                        this.timer.stop();
          * Testing flag.  Set in main method.
         private static boolean testing = false;
          * Main method, for testing.  Creates a frame with both styles of menu.
          * @param  args  the command-line arguments
         public static void main(String[] args) {
              testing = true;
              JFrame f = new JFrame("RepeatButton Test");
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              JPanel p = new JPanel();
              RepeatButton b = new RepeatButton("hold me");
              b.setActionCommand("test");
              b.addActionListener(b);
              p.add(b);
              f.getContentPane().add(p);
              f.pack();
              f.show();
    "Useful Code of the Day" is supplied by the person who posted this message. This code is not guaranteed by any warranty whatsoever. The code is free to use and modify as you see fit. The code was tested and worked for the author. If anyone else has some useful code, feel free to post it under this heading.

    This makes word completion possible for JTextArea:
    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
    import javax.swing.event.*;
    import javax.swing.text.*;
    import java.util.*;
    * This class provides word completion for JTextArea.
    public class WordCompleteArea extends JTextArea {
        private boolean isTextComplete = true;
        public WordCompleteArea (Document doc, String text,
                                      int rows, int columns, KeyStroke expandKey) {
            super (doc, text, rows, columns);
            String s = "word-complete";
            Action wordComplete = new AbstractAction () {
                public void actionPerformed (ActionEvent e) {
                    wordComplete ();
            getInputMap ().put (expandKey, s);
            getActionMap ().put (s, wordComplete);
        public WordCompleteArea (Document doc, String text, int rows, int columns) {
            this (doc, text, rows, columns,
                            KeyStroke.getKeyStroke ("ctrl pressed SPACE"));
        public WordCompleteArea (Document doc) {
            this (doc, null, 0, 0);
        public WordCompleteArea (String text, int rows, int columns) {
            this (new PlainDocument (), text, rows, columns);
        public WordCompleteArea (int rows, int columns) {
            this (null, rows, columns);
        public WordCompleteArea (String text) {
            this (text, 0, 0);
        public WordCompleteArea () {
            this (0, 0);
         * Define if text already written in the JTextArea will be used
         * for expansion.
        public void setTextComplete (boolean b) {
            isTextComplete = b;
         * Find out if text already written in the JTextArea will be used
         * for expansion.
        public boolean isTextComplete () {
            return isTextComplete;
        private String tokenDelimiters = "\t\r\n ,;()[]{}%+/-*<>=&|!\"\'.@#";
         * Get delimiters that form a word.
        public String getTokenDelimiters () {
            return tokenDelimiters;
         * Set delimiters that form a word.
        public void setTokenDelimiters (String s) {
            tokenDelimiters = s;
        // Additional words used for expansion.
        private LinkedList wordCompleteList = new LinkedList ();
         * Add words that will be used as expansion.
        public void addCompleteWords (java.util.List words) {
            wordCompleteList.add (words);
         * Add a word that will be used as expansion.
        public void addCompleteWord (String word) {
            wordCompleteList.add (word);
        private String lastExpanded = null;
        private String lastExpansion = null;
        private Set dontAccept = new HashSet ();
        protected void wordComplete () {
            int caret = getCaretPosition ();
            if (caret == 0)
                return;
            String text = getText ();
            if (caret != text.length () && isCompletionLetter (text.charAt (caret)))
                return;
            StringBuffer sb = new StringBuffer ();
            int index = caret - 1;
            char ch;
            while (index >= 0 && isCompletionLetter ((ch = text.charAt (index)))) {
                sb.append (ch);
                index--;
            if (sb.length () == 0)
                return;
            sb.reverse ();
            String word = sb.toString ();
            String toExpand = word;
            if (toExpand.equals (lastExpansion)) {
                dontAccept.add (lastExpansion);
                toExpand = lastExpanded;
            } else {
                dontAccept.clear ();
            String s = findExpansion (toExpand, caret);
            if (s != null) {
                lastExpanded = toExpand;
                lastExpansion = s;
                replaceRange (s, caret - word.length (), caret);
            } else {
                dontAccept.clear ();
                lastExpanded = null;
                lastExpansion = null;
                int diff = word.length () - toExpand.length ();
                replaceRange ("", caret - diff, caret);
        private boolean isCompletionLetter (char ch) {
            return tokenDelimiters.indexOf (ch) < 0;
        protected String findExpansion (String word, int caret) {
            StringTokenizer st;
            if (isTextComplete) {
                st = new StringTokenizer (getText (), getTokenDelimiters ());
                while (st.hasMoreTokens ()) {
                    String s = st.nextToken ();
                    if (    s.startsWith (word)
                            && s.length () != word.length ()
                            && !dontAccept.contains (s)      ) {
                        return s;
            for (Iterator it = wordCompleteList.iterator (); it.hasNext (); ) {
                st = new StringTokenizer
                                ((String) it.next (), getTokenDelimiters ());
                while (st.hasMoreTokens ()) {
                    String s = st.nextToken ();
                    if (    s.startsWith (word)
                            && s.length () != word.length ()
                            && !dontAccept.contains (s)      ) {
                        return s;
            return null;
        // TEST
        public static void main (String[] args) {
            WordCompleteArea a = new WordCompleteArea ();
            JFrame window = new JFrame ();
            window.getContentPane ().add (a, BorderLayout.CENTER);
            window.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
            window.setSize (300, 300);
            window.setVisible (true);
    }

  • Useful Code of the Day:  Splash Screen & Busy Application

    So you are making an Swing application. So what are two common things to do in it?
    1) Display a splash screen.
    2) Block user input when busy.
    Enter AppFrame! It's a JFrame subclass which has a glass pane overlay option to block input (setBusy()). While "busy", it displays the system wait cursor.
    It also supports display of a splash screen. There's a default splash screen if you don't provide a component to be the splash screen, and an initializer runner which takes a Runnable object. The Runnable object can then modify the splash screen component, for example to update a progress bar or text. See the main method for example usage.
    It also has a method to center a component on another component (useful for dialogs) or center the component on the screen.
    NOTE on setBusy: I do recall issues with the setBusy option to block input. I recall it having a problem on some Unix systems, but I can't remember the details offhand (sorry).
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    * <CODE>AppFrame</CODE> is a <CODE>javax.swing.JFrame</CODE> subclass that
    * provides some convenient methods for applications.  This class implements
    * all the same constructors as <CODE>JFrame</CODE>, plus a few others. 
    * Methods exist to show the frame centered on the screen, display a splash
    * screen, run an initializer thread and set the frame as "busy" to block 
    * user input. 
    public class AppFrame extends JFrame implements KeyListener, MouseListener {
          * The splash screen window. 
         private JWindow splash = null;
          * The busy state of the frame. 
         private boolean busy = false;
          * The glass pane used when busy. 
         private Component glassPane = null;
          * The original glass pane, which is reset when not busy. 
         private Component defaultGlassPane = null;
          * Creates a new <CODE>AppFrame</CODE>. 
         public AppFrame() {
              super();
              init();
          * Creates a new <CODE>AppFrame</CODE> with the specified
          * <CODE>GraphicsConfiguration</CODE>. 
          * @param  gc  the GraphicsConfiguration of a screen device
         public AppFrame(GraphicsConfiguration gc) {
              super(gc);
              init();
          * Creates a new <CODE>AppFrame</CODE> with the specified title. 
          * @param  title  the title
         public AppFrame(String title) {
              super(title);
              init();
          * Creates a new <CODE>AppFrame</CODE> with the specified title and
          * <CODE>GraphicsConfiguration</CODE>. 
          * @param  title  the title
          * @param  gc     the GraphicsConfiguration of a screen device
         public AppFrame(String title, GraphicsConfiguration gc) {
              super(title, gc);
              init();
          * Creates a new <CODE>AppFrame</CODE> with the specified title and
          * icon image. 
          * @param  title  the title
          * @param  icon   the image icon
         public AppFrame(String title, Image icon) {
              super(title);
              setIconImage(icon);
              init();
          * Creates a new <CODE>AppFrame</CODE> with the specified title and
          * icon image. 
          * @param  title  the title
          * @param  icon  the image icon
         public AppFrame(String title, ImageIcon icon) {
              this(title, icon.getImage());
          * Initializes internal frame settings. 
         protected void init() {
              // set default close operation (which will likely be changed later)
              setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
              // set up the glass pane
              glassPane = new JPanel();
              ((JPanel)glassPane).setOpaque(false);
              glassPane.addKeyListener(this);
              glassPane.addMouseListener(this);
          * Displays a new <CODE>JWindow</CODE> as a splash screen using the
          * specified component as the content.  The default size of the
          * component will be used to size the splash screen.  See the
          * <CODE>showSplash(Component, int, int)</CODE> method description for
          * more details. 
          * @param  c  the splash screen contents
          * @return  the window object
          * @see  #showSplash(Component, int, int)
          * @see  #hideSplash()
         public JWindow showSplash(Component c) {
              return showSplash(c, -1, -1);
          * Displays a new <CODE>JWindow</CODE> as a splash screen using the
          * specified component as the content.  The component should have all
          * the content it needs to display, like borders, images, text, etc. 
          * The splash screen is centered on monitor.  If width and height are
          * <CODE><= 0</CODE>, the default size of the component will be used
          * to size the splash screen. 
          * <P>
          * The window object is returned to allow the application to manipulate
          * it, (such as move it or resize it, etc.).  However, <B>do not</B>
          * dispose the window directly.  Instead, use <CODE>hideSplash()</CODE>
          * to allow internal cleanup. 
          * <P>
          * If the component is <CODE>null</CODE>, a default component with the
          * frame title and icon will be created. 
          * <P>
          * The splash screen window will be passed the same
          * <CODE>GraphicsConfiguration</CODE> as this frame uses. 
          * @param  c  the splash screen contents
          * @param  w  the splash screen width
          * @param  h  the splash screen height
          * @return  the window object
          * @see  #showSplash(Component)
          * @see  #hideSplash()
         public JWindow showSplash(Component c, int w, int h) {
              // if a splash window was already created...
              if(splash != null) {
                   // if it's showing, leave it; else null it
                   if(splash.isShowing()) {
                        return splash;
                   } else {
                        splash = null;
              // if the component is null, then create a generic splash screen
              // based on the frame title and icon
              if(c == null) {
                   JPanel p = new JPanel();
                   p.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createRaisedBevelBorder(),
                        BorderFactory.createEmptyBorder(10, 10, 10, 10)
                   JLabel l = new JLabel("Loading application...");
                   if(getTitle() != null) {
                        l.setText("Loading " + getTitle() + "...");
                   if(getIconImage() != null) {
                        l.setIcon(new ImageIcon(getIconImage()));
                   p.add(l);
                   c = p;
              splash = new JWindow(this, getGraphicsConfiguration());
              splash.getContentPane().add(c);
              splash.pack();
              // set the splash screen size
              if(w > 0 && h > 0) {
                   splash.setSize(w, h);
              } else {
                   splash.setSize(c.getPreferredSize().width, c.getPreferredSize().height);
              centerComponent(splash);
              splash.show();
              return splash;
          * Disposes the splash window. 
          * @see  #showSplash(Component, int, int)
          * @see  #showSplash(Component)
         public void hideSplash() {
              if(splash != null) {
                   splash.dispose();
                   splash = null;
          * Runs an initializer <CODE>Runnable</CODE> object in a new thread. 
          * The initializer object should handle application initialization
          * steps.  A typical use would be:
          * <OL>
          *   <LI>Create the frame.
          *   <LI>Create the splash screen component.
          *   <LI>Call <CODE>showSplash()</CODE> to display splash screen.
          *   <LI>Run the initializer, in which: 
          *   <UL>
          *     <LI>Build the UI contents of the frame.
          *     <LI>Perform other initialization (load settings, data, etc.).
          *     <LI>Pack and show the frame.
          *     <LI>Call <CODE>hideSplash()</CODE>.
          *   </UL>
          * </OL>
          * <P>
          * <B>NOTE:</B>  Since this will be done in a new thread that is
          * external to the event thread, any updates to the splash screen that
          * might be done should be triggered through with
          * <CODE>SwingUtilities.invokeAndWait(Runnable)</CODE>. 
          * @param  r  the <CODE>Runnable</CODE> initializer
         public void runInitializer(Runnable r) {
              Thread t = new Thread(r);
              t.start();
          * Shows the frame centered on the screen. 
         public void showCentered() {
              centerComponent(this);
              this.show();
          * Checks the busy state.
          * @return  <CODE>true</CODE> if the frame is disabled;
          *          <CODE>false</CODE> if the frame is enabled
          * @see  #setBusy(boolean)
         public boolean isBusy() {
              return this.busy;
          * Sets the busy state.  When busy, the glasspane is shown which will
          * consume all mouse and keyboard events, and a wait cursor is
          * set for the frame. 
          * @param  busy  if <CODE>true</CODE>, disables frame;
          *               if <CODE>false</CODE>, enables frame
          * @see  #getBusy()
         public void setBusy(boolean busy) {
              // only set if changing
              if(this.busy != busy) {
                   this.busy = busy;
                   // If busy, keep current glass pane to put back when not
                   // busy.  This is done in case the application is using
                   // it's own glass pane for something special. 
                   if(busy) {
                        defaultGlassPane = getGlassPane();
                        setGlassPane(glassPane);
                   } else {
                        setGlassPane(defaultGlassPane);
                        defaultGlassPane = null;
                   glassPane.setVisible(busy);
                   glassPane.setCursor(busy ?
                        Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR) :
                        Cursor.getDefaultCursor()
                   setCursor(glassPane.getCursor());
          * Handle key typed events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  ke  the key event
         public void keyTyped(KeyEvent ke) {
              ke.consume();
          * Handle key released events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  ke  the key event
         public void keyReleased(KeyEvent ke) {
              ke.consume();
          * Handle key pressed events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  ke  the key event
         public void keyPressed(KeyEvent ke) {
              ke.consume();
          * Handle mouse clicked events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  me  the mouse event
         public void mouseClicked(MouseEvent me) {
              me.consume();
          * Handle mouse entered events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  me  the mouse event
         public void mouseEntered(MouseEvent me) {
              me.consume();
          * Handle mouse exited events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  me  the mouse event
         public void mouseExited(MouseEvent me) {
              me.consume();
          * Handle mouse pressed events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  me  the mouse event
         public void mousePressed(MouseEvent me) {
              me.consume();
          * Handle mouse released events.  Consumes the event for the glasspane
          * when the frame is busy. 
          * @param  me  the mouse event
         public void mouseReleased(MouseEvent me) {
              me.consume();
          * Centers the component <CODE>c</CODE> on the screen. 
          * @param  c  the component to center
          * @see  #centerComponent(Component, Component)
         public static void centerComponent(Component c) {
              centerComponent(c, null);
          * Centers the component <CODE>c</CODE> on component <CODE>p</CODE>. 
          * If <CODE>p</CODE> is null, the component <CODE>c</CODE> will be
          * centered on the screen. 
          * @param  c  the component to center
          * @param  p  the parent component to center on or null for screen
          * @see  #centerComponent(Component)
         public static void centerComponent(Component c, Component p) {
              if(c != null) {
                   Dimension d = (p != null ? p.getSize() :
                        Toolkit.getDefaultToolkit().getScreenSize()
                   c.setLocation(
                        Math.max(0, (d.getSize().width/2)  - (c.getSize().width/2)),
                        Math.max(0, (d.getSize().height/2) - (c.getSize().height/2))
          * Main method.  Used for testing.
          * @param  args  the arguments
         public static void main(String[] args) {
              final AppFrame f = new AppFrame("Test Application",
                   new ImageIcon("center.gif"));
              f.showSplash(null);
              f.runInitializer(new Runnable() {
                   public void run() {
                        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        f.getContentPane().add(new JButton("this is a frame"));
                        f.pack();
                        f.setSize(300, 400);
                        try {
                             Thread.currentThread().sleep(3000);
                        } catch(Exception e) {}
                        f.showCentered();
                        f.setBusy(true);
                        try {
                             Thread.currentThread().sleep(100);
                        } catch(Exception e) {}
                        f.hideSplash();
                        try {
                             Thread.currentThread().sleep(3000);
                        } catch(Exception e) {}
                        f.setBusy(false);
    "Useful Code of the Day" is supplied by the person who posted this message. This code is not guaranteed by any warranty whatsoever. The code is free to use and modify as you see fit. The code was tested and worked for the author. If anyone else has some useful code, feel free to post it under this heading.

    Hi
    Thanks fo this piece of code. This one really help me
    Deepa

  • Useful Code of the Day:  Hideable Tree Nodes

    Someone posted about how they could selectively hide tree nodes, and I already had this AbstractTreeModel class (which does some things DefaultTreeModel does and some it doesn't) and a concrete subclass for TreeNode objects, so I was thinking how one could do hideable nodes. So I came up with this solution.
    There's 4 classes here:
    - AbstractTreeModel is the base for the concrete TreeNodeTreeModel
    - TreeNodeTreeModel extends AbstractTreeModel to support TreeNodes (DefautlMutableTreeNode, etc.)
    - HideableMutableTreeNode which is a DefautlMutableTreeNode subclass which has a visible field (with is/set methods, of course).
    - HideableTreeModel is the hideable model which is a subclass of TreeNodeTreeModel.
    A HideableMutableTreeNode can be set invisible directly, but the tree still needs to be notified to update. So it's best to use the methods in HideableTreeModel which set a node's visibility which notify the tree of changes accordingly. Methods are also provided to check a full path's visibility or ensure a node including all parent nodes are visible.
    A HideableTreeModel can take any TreeNode class, it doesn't have to be all HideableMutableTreeNodes, but only HideableMutableTreeNodes can be made invisible, of course. Any other TreeNode type would just be considered visible.
    Hiding nodes works basically by making the tree think there's less nodes then there are. And to do this, the node counts and child index search just works by looping thru the parent's children. This has potential perfomance drawbacks of course, since one has to loop thru the node's children to get nodes every time. This could be alleviated by not supporting non-hideable nodes changing the internal maintenance of HideableMutableTreeNode contents. But I'll leave that to whoever really needs it. It shouldn't be a problem if there are are a relatively small set of child nodes in any given parent.
    Also, note that the root node in the model cannot be made invisible, cuz it'd be redundant since JTree can be set to hide the root node.
    // *** HideableTreeModel ***
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    * <code>HideableTreeModel</code> is an <code>TreeNodeTreeModel</code>
    * implementation for <code>HideableMutableTreeNode</code> objects.  The
    * model can also take any other <code>javax.swing.tree.TreeNode</code>
    * objects. 
    public class HideableTreeModel extends TreeNodeTreeModel {
          * Creates a new <code>HideableTreeModel</code> object.
          * @param  root  the root node
         public HideableTreeModel(TreeNode root) {
              super(root);
          * Checks if the specified node is visible.  A node can only be
          * hidden if the node is an instance of <code>HideableMutableTreeNode</code>.  <br />
          * <br />
          * Note that this only test the visibility of the specified node, not
          * whether a parent node is visible.  Use <code>isPathToNodeVisible(Object)</code>
          * to check if the full path is visible. 
          * @param  node  the node
          * @param  true if the node is visible, else false
         public boolean isNodeVisible(Object node) {
              if(node != getRoot()) {
                   if(node instanceof HideableMutableTreeNode) {
                        return ((HideableMutableTreeNode)node).isVisible();
              return true;
          * Sets the specified node to be hidden.  A node can only be made hidden
          * if the node is an instance of <code>HideableMutableTreeNode</code>.  <br />
          * <br />
          * Note that this method will notify the tree to reflect any changes to
          * node visibility.  <br />
          * <br />
          * Note that this will not alter the visibility of any nodes in the
          * specified node's path to the root node.  Use
          * <code>ensurePathToNodeVisible(Object)</code> instead to make sure the
          * full path down to that node is visible.  <br />
          * <br />
          * Note that this method will notify the tree to reflect any changes to
          * node visibility. 
          * @param  node  the node
          * @param  v     true for visible, false for hidden
          * @param  true if the node's visibility could actually change, else false
         public boolean setNodeVisible(Object node, boolean v) {
              // can't hide root
              if(node != getRoot()) {
                   if(node instanceof HideableMutableTreeNode) {
                        HideableMutableTreeNode n = (HideableMutableTreeNode)node;
                        // don't fix what ain't broke...
                        if(v != n.isVisible()) {
                             TreeNode parent = n.getParent();
                             if(v) {
                                  // need to get index after showing...
                                  n.setVisible(v);
                                  int index = getIndexOfChild(parent, n);
                                  super.nodeInserted(parent, n, index);
                             } else {
                                  // need to get index before hiding...
                                  int index = getIndexOfChild(parent, n);
                                  n.setVisible(v);
                                  super.nodeRemoved(parent, n, index);
                        return true;
              return false;
          * Checks if the specified node is visible and all nodes above it are
          * visible. 
          * @param  node  the node
          * @param  true if the path is visible, else false
         public boolean isPathToNodeVisible(Object node) {
              Object[] path = getPathToRoot(node);
              for(int i = 0; i < path.length; i++) {
                   if(!isNodeVisible(path)) {
                        return false;
              return true;
         * Sets the specified node and all nodes above it to be visible.
         * Note that this method will notify the tree to reflect any changes to
         * node visibility.
         * @param node the node
         public void ensurePathToNodeVisible(Object node) {
              Object[] path = getPathToRoot(node);
              for(int i = 0; i < path.length; i++) {
                   setNodeVisible(path[i], true);
         * Returns the child of parent at index index in the parent's child array.
         * @param parent the parent node
         * @param index the index
         * @return the child or null if no children
         public Object getChild(Object parent, int index) {
              if(parent instanceof TreeNode) {
                   TreeNode p = (TreeNode)parent;
                   for(int i = 0, j = -1; i < p.getChildCount(); i++) {
                        TreeNode pc = (TreeNode)p.getChildAt(i);
                        if(isNodeVisible(pc)) {
                             j++;
                        if(j == index) {
                             return pc;
              return null;
         * Returns the number of children of parent.
         * @param parent the parent node
         * @return the child count
         public int getChildCount(Object parent) {
              int count = 0;
              if(parent instanceof TreeNode) {
                   TreeNode p = (TreeNode)parent;
                   for(int i = 0; i < p.getChildCount(); i++) {
                        TreeNode pc = (TreeNode)p.getChildAt(i);
                        if(isNodeVisible(pc)) {
                             count++;
              return count;
         * Returns the index of child in parent.
         * @param parent the parent node
         * @param child the child node
         * @return the index of the child node in the parent
         public int getIndexOfChild(Object parent, Object child) {
              int index = -1;
              if(parent instanceof TreeNode && child instanceof TreeNode) {
                   TreeNode p = (TreeNode)parent;
                   TreeNode c = (TreeNode)child;
                   if(isNodeVisible(c)) {
                        index = 0;
                        for(int i = 0; i < p.getChildCount(); i++) {
                             TreeNode pc = (TreeNode)p.getChildAt(i);
                             if(pc.equals(c)) {
                                  return index;
                             if(isNodeVisible(pc)) {
                                  index++;
              return index;
         * Main method for testing.
         * @param args the command-line arguments
         public static void main(String[] args) {
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              HideableMutableTreeNode root = new HideableMutableTreeNode("root");
              root.add(new HideableMutableTreeNode("child_1"));
              final HideableMutableTreeNode c2 = new HideableMutableTreeNode("child_2");
              c2.setVisible(false);
              final HideableMutableTreeNode c2a = new HideableMutableTreeNode("child_2_A");
              c2.add(c2a);
              c2.add(new HideableMutableTreeNode("child_2_B"));
              root.add(c2);
              HideableMutableTreeNode c3 = new HideableMutableTreeNode("child_3");
              HideableMutableTreeNode cC = new HideableMutableTreeNode("child_3_C");
              cC.setVisible(false);
              c3.add(cC);
              c3.add(new HideableMutableTreeNode("child_3_D"));
              root.add(c3);
              root.add(new HideableMutableTreeNode("child_4"));
              root.add(new HideableMutableTreeNode("child_5"));
              DefaultMutableTreeNode c6 = new DefaultMutableTreeNode("child_6");
              c6.add(new DefaultMutableTreeNode("child_6_A"));
              c6.add(new DefaultMutableTreeNode("child_6_B"));
              root.add(c6);
              final HideableTreeModel model = new HideableTreeModel(root);
              JTree tree = new JTree(model);
              f.getContentPane().add(new JScrollPane(tree), BorderLayout.CENTER);
              JButton b = new JButton("toggle");
              b.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        model.setNodeVisible(c2, !model.isNodeVisible(c2));
                        //model.ensurePathToNodeVisible(c2a);
              f.getContentPane().add(b, BorderLayout.SOUTH);
              f.pack();
              f.setSize(300, 500);
              f.show();
    // *** HideableMutableTreeNode ***
    import javax.swing.*;
    import javax.swing.tree.*;
    * <code>HideableMutableTreeNode</code> is a <code>DefaultMutableTreeNode</code>
    * implementation that works with <code>HideableTreeModel</code>.
    public class HideableMutableTreeNode extends DefaultMutableTreeNode {
         * The node is visible flag.
         public boolean visible = true;
         * Creates a tree node that has no parent and no children, but which
         * allows children.
         public HideableMutableTreeNode() {
              super();
         * Creates a tree node with no parent, no children, but which allows
         * children, and initializes it with the specified user object.
         * @param userObject - an Object provided by the user that
         * constitutes the node's data
         public HideableMutableTreeNode(Object userObject) {
              super(userObject);
         * Creates a tree node with no parent, no children, initialized with the
         * specified user object, and that allows children only if specified.
         * @param userObject - an Object provided by the user that
         * constitutes the node's data
         * @param allowsChildren - if true, the node is allowed to have child
         * nodes -- otherwise, it is always a leaf node
         public HideableMutableTreeNode(Object userObject, boolean allowsChildren) {
              super(userObject, allowsChildren);
         * Checks if the node is visible.
         * @return true if the node is visible, else false
         public boolean isVisible() {
              return this.visible;
         * Sets if the node is visible.
         * @param v true if the node is visible, else false
         public void setVisible(boolean v) {
              this.visible = v;
    // *** TreeNodeTreeModel ***
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    * <code>TreeNodeTreeModel</code> is an <code>AbstractTreeModel</code>
    * implementation for <code>javax.swing.tree.TreeNode</code> objects.
    public class TreeNodeTreeModel extends AbstractTreeModel {
         * Creates a new <code>TreeNodeTreeModel</code> object.
         * @param root the root node
         public TreeNodeTreeModel(TreeNode root) {
              super();
              setRoot(root);
         * Returns the parent of the child node.
         * @param node the child node
         * @return the parent or null if root
         public Object getParent(Object node) {
              if(node != getRoot() && (node instanceof TreeNode)) {
                   return ((TreeNode)node).getParent();
              return null;
         * Returns the child of parent at index index in the parent's child array.
         * @param parent the parent node
         * @param index the index
         * @return the child or null if no children
         public Object getChild(Object parent, int index) {
              if(parent instanceof TreeNode) {
                   return ((TreeNode)parent).getChildAt(index);
              return null;
         * Returns the number of children of parent.
         * @param parent the parent node
         * @return the child count
         public int getChildCount(Object parent) {
              if(parent instanceof TreeNode) {
                   return ((TreeNode)parent).getChildCount();
              return 0;
         * Returns the index of child in parent.
         * @param parent the parent node
         * @param child the child node
         * @return the index of the child node in the parent
         public int getIndexOfChild(Object parent, Object child) {
              if(parent instanceof TreeNode && child instanceof TreeNode) {
                   return ((TreeNode)parent).getIndex((TreeNode)child);
              return -1;
         * Returns true if node is a leaf.
         * @param node the node
         * @return true if the node is a leaf
         public boolean isLeaf(Object node) {
              if(node instanceof TreeNode) {
                   return ((TreeNode)node).isLeaf();
              return true;
         * Main method for testing.
         * @param args the command-line arguments
         public static void main(String[] args) {
              JFrame f = new JFrame();
              f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
              root.add(new DefaultMutableTreeNode("child_1"));
              DefaultMutableTreeNode c2 = new DefaultMutableTreeNode("child_2");
              c2.add(new DefaultMutableTreeNode("child_2_A"));
              c2.add(new DefaultMutableTreeNode("child_2_B"));
              root.add(c2);
              root.add(new DefaultMutableTreeNode("child_3"));
              root.add(new DefaultMutableTreeNode("child_4"));
              JTree tree = new JTree(new TreeNodeTreeModel(root));
              f.getContentPane().add(new JScrollPane(tree));
              f.pack();
              f.setSize(300, 500);
              f.show();
    // *** AbstractTreeModel ***
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    import java.text.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    public abstract class AbstractTreeModel implements TreeModel {
         * The list of tree model listeners.
         private Vector modelListeners = new Vector();
         * The root object of the tree.
         private Object root = null;
         * Basic no-op constructor.
         public AbstractTreeModel() {
         * Gets the root object of the tree.
         * @return the root object
         public Object getRoot() {
              return this.root;
         * Sets the root object of the tree.
         * @param r the root object
         protected void setRoot(Object r) {
              this.root = r;
         * Gets the path to the root node for the specified object.
         * @param node the root node
         * @return the path to the object or <CODE>null</CODE>
         public Object[] getPathToRoot(Object node) {
              return getPathToRoot(node, 0);
         * Gets the path to the root node for the specified object.
         * @param node the root node
         * @param i the current index
         * @return the path to the object or <CODE>null</CODE>
         private Object[] getPathToRoot(Object node, int i) {
              Object anode[];
              if(node == null) {
                   if(i == 0) {
                        return null;
                   anode = new Object[i];
              } else {
                   i++;
                   if(node == getRoot()) {
                        anode = new Object[i];
                   } else {
                        anode = getPathToRoot(getParent(node), i);
                   anode[anode.length - i] = node;
              return anode;
         * Gets the parent object of the specified object. This method is not
         * part of the <code>javax.swing.tree.TreeModel</code> interface, but is
         * required to support the <code>getPathToRoot(Object)</code> method,
         * which is widely used in this class. Therefore, it is important to
         * correctly implement this method.
         * @param obj the object
         * @parma the parent object or null if no parent or invalid object
         protected abstract Object getParent(Object obj);
         * Adds a listener for the <CODE>TreeModelEvent</CODE> posted after the
         * tree changes.
         * @param l the tree model listener
         public void addTreeModelListener(TreeModelListener l) {
              modelListeners.addElement(l);
         * Removes a listener previously added with addTreeModelListener().
         * @param l the tree model listener
         public void removeTreeModelListener(TreeModelListener l) {
              modelListeners.removeElement(l);
         * Forces the tree to reload. This is useful when many changes occur
         * under the root node in the tree structure.
         * <b>NOTE:</b> This will cause the tree to be collapsed. To maintain
         * the expanded nodes, see the <code>getExpandedPaths(JTree)</code>
         * and <code>expandPaths(JTree, ArrayList)</code> methods.
         * @see #getExpandedPaths(JTree)
         * @see #expandPaths(JTree, ArrayList)
         public void reload() {
              reload(getRoot());
         * Forces the tree to repaint. This is useful when many changes occur
         * under a specific node in the tree structure.
         * <b>NOTE:</b> This will cause the tree to be collapsed below the
         * updated node.
         * @param node the node that changed
         public void reload(Object node) {
              if(node != null) {
                   TreePath tp = new TreePath(getPathToRoot(node));
                   fireTreeStructureChanged(new TreeModelEvent(this, tp));
         * Messaged when the user has altered the value for the item identified
         * by <CODE>path</CODE> to <CODE>newValue</CODE>.
         * @param path the path to the changed object
         * @param newValue the new value
         public void valueForPathChanged(TreePath path, Object newValue) {
              nodeChanged(path.getLastPathComponent());
         * Notifies the tree that nodes were inserted. The index is looked up
         * automatically.
         * @param node the parent node
         * @param child the inserted child node
         public void nodeInserted(Object node, Object child) {
              nodeInserted(node, child, -1);
         * Notifies the tree that nodes were inserted.
         * @param node the parent node
         * @param child the inserted child node
         * @param index the index of the child
         public void nodeInserted(Object node, Object child, int index) {
              if(index < 0) {
                   index = getIndexOfChild(node, child);
              if(node != null && child != null && index >= 0) {
                   TreePath tp = new TreePath(getPathToRoot(node));
                   int[] ai = { index };
                   Object[] ac = { child };
                   fireTreeNodesInserted(new TreeModelEvent(this, tp, ai, ac));
         * Notifies the tree that nodes were removed. The index is required
         * since by this point, the object will no longer be in the tree.
         * @param node the parent node
         * @param child the removed child node
         * @param index the index of the child
         public void nodeRemoved(Object node, Object child, int index) {
              if(node != null && child != null && index >= 0) {
                   TreePath tp = new TreePath(getPathToRoot(node));
                   int[] ai = { index };
                   Object[] ac = { child };
                   fireTreeNodesRemoved(new TreeModelEvent(this, tp, ai, ac));
         * Notifies the tree that a node was changed.
         * @param node the changed node
         public void nodeChanged(Object node) {
              if(node != null) {
                   TreePath tp = new TreePath(getPathToRoot(node));
                   fireTreeNodesChanged(new TreeModelEvent(this, tp, null, null));
         * Fires "tree nodes changed" events to all listeners.
         * @param event the tree model event
         protected void fireTreeNodesChanged(TreeModelEvent event) {
              for(int i = 0; i < modelListeners.size(); i++) {
                   ((TreeModelListener)modelListeners.elementAt(i)).treeNodesChanged(event);
         * Fires "tree nodes inserted" events to all listeners.
         * @param event the tree model event
         protected void fireTreeNodesInserted(TreeModelEvent event) {
              for(int i = 0; i < modelListeners.size(); i++) {
                   ((TreeModelListener)modelListeners.elementAt(i)).treeNodesInserted(event);
         * Fires "tree nodes removed" events to all listeners.
         * @param event the tree model event
         protected void fireTreeNodesRemoved(TreeModelEvent event) {
              for(int i = 0; i < modelListeners.size(); i++) {
                   ((TreeModelListener)modelListeners.elementAt(i)).treeNodesRemoved(event);
         * Fires "tree structure changed" events to all listeners.
         * @param event the tree model event
         protected void fireTreeStructureChanged(TreeModelEvent event) {
              for(int i = 0; i < modelListeners.size(); i++) {
                   ((TreeModelListener)modelListeners.elementAt(i)).treeStructureChanged(event);
         * Records the list of currently expanded paths in the specified tree.
         * This method is meant to be called before calling the
         * <code>reload()</code> methods to allow the tree to store the paths.
         * @param tree the tree
         * @param pathlist the list of expanded paths
         public ArrayList getExpandedPaths(JTree tree) {
              ArrayList expandedPaths = new ArrayList();
              addExpandedPaths(tree, tree.getPathForRow(0), expandedPaths);
              return expandedPaths;
         * Adds the expanded descendants of the specifed path in the specified
         * tree to the internal expanded list.
         * @param tree the tree
         * @param path the path
         * @param pathlist the list of expanded paths
         private void addExpandedPaths(JTree tree, TreePath path, ArrayList pathlist) {
              Enumeration enum = tree.getExpandedDescendants(path);
              while(enum.hasMoreElements()) {
                   TreePath tp = (TreePath)enum.nextElement();
                   pathlist.add(tp);
                   addExpandedPaths(tree, tp, pathlist);
         * Re-expands the expanded paths in the specified tree. This method is
         * meant to be called before calling the <code>reload()</code> methods
         * to allow the tree to store the paths.
         * @param tree the tree
         * @param pathlist the list of expanded paths
         public void expandPaths(JTree tree, ArrayList pathlist) {
              for(int i = 0; i < pathlist.size(); i++) {
                   tree.expandPath((TreePath)pathlist.get(i));

    Hey
    I'm not trying to show anyone up here, but having just built a tree model for displaying an XML document in a tree, I thought this seemed like a neat exercise.
    I implemented this very differently from the @OP. I only have one class, HiddenNodeTreeModel. All the hidden node data is stored in the model itself in my class. The advantage of what I've created is it will work with any TreeModel. The disadvantage is that I think it's not going to be very scalable - the additional computing to get the number of child nodes and to adjust indexes is heavy. So if you need a scalable solution definitely don't use this.
    Anyway here you go
    HiddenNodeTreeModel.java
    ======================
    package tjacobs.ui.tree;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.Iterator;
    import javax.swing.JFrame;
    import javax.swing.JMenu;
    import javax.swing.JMenuBar;
    import javax.swing.JMenuItem;
    import javax.swing.JTree;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    import tjacobs.ui.WindowUtilities;
    public class HiddenNodeTreeModel implements TreeModel {
         TreeModel mModel;
         ArrayList<Object> mHidden = new ArrayList<Object>();
         public HiddenNodeTreeModel (TreeModel model) {
              mModel = model;
         public void addTreeModelListener(TreeModelListener arg0) {
              mModel.addTreeModelListener(arg0);
         private ArrayList<Integer> getHiddenChildren(Object parent) {
              ArrayList<Integer> spots = new ArrayList<Integer>();
              Iterator _i = mHidden.iterator();
              while (_i.hasNext()) {
                   Object hidden = _i.next();
                   int idx = mModel.getIndexOfChild(parent, hidden);
                   if (idx != -1) {
                        spots.add(idx);
              return spots;
         public Object getChild(Object arg0, int index) {
              ArrayList<Integer> spots = getHiddenChildren(arg0);
              Collections.sort(spots);
              Iterator<Integer> _i = spots.iterator();
              while (_i.hasNext()) {
                   int num = _i.next();
                   if (num <= index) {
                        index++;
              return mModel.getChild(arg0, index);
         public int getChildCount(Object arg0) {
              ArrayList list = getHiddenChildren(arg0);
              System.out.println("size = " + list.size());
              return mModel.getChildCount(arg0) - list.size();
         public int getIndexOfChild(Object arg0, Object arg1) {
              int index = mModel.getIndexOfChild(arg0, arg1);
              ArrayList<Integer> spots = getHiddenChildren(arg0);
              Collections.sort(spots);
              Iterator<Integer> _i = spots.iterator();
              int toSub = 0;
              while (_i.hasNext()) {
                   int num = _i.next();
                   if (num <= index) {
                        toSub++;
              return index - toSub;
         public Object getRoot() {
              // TODO Auto-generated method stub
              return mModel.getRoot();
         public boolean isLeaf(Object arg0) {
              // TODO Auto-generated method stub
              return mModel.isLeaf(arg0);
         public void removeTreeModelListener(TreeModelListener arg0) {
              mModel.removeTreeModelListener(arg0);
         public void valueForPathChanged(TreePath arg0, Object arg1) {
              mModel.valueForPathChanged(arg0, arg1);
         public void hideNode(Object node) {
              if (node instanceof TreePath) {
                   node = ((TreePath)node).getLastPathComponent();
              mHidden.add(node);
         public void showNode(Object node) {
              mHidden.remove(node);
         public void showAll() {
              mHidden.clear();
          * @param args
         public static void main(String[] args) {
              // TODO Auto-generated method stub
              DefaultMutableTreeNode A = new DefaultMutableTreeNode("A");
              DefaultMutableTreeNode B = new DefaultMutableTreeNode("B");
              DefaultMutableTreeNode C = new DefaultMutableTreeNode("C");
              DefaultMutableTreeNode D = new DefaultMutableTreeNode("D");
              DefaultMutableTreeNode E = new DefaultMutableTreeNode("E");
              DefaultMutableTreeNode F = new DefaultMutableTreeNode("F");
              A.add(B);
              B.add(C);
              B.add(D);
              B.add(E);
              E.add(F);
              DefaultTreeModel model = new DefaultTreeModel(A);
              final HiddenNodeTreeModel hmodel = new HiddenNodeTreeModel(model);
              final JTree tree = new JTree(hmodel);
              JFrame jf = new JFrame("HiddenNodeTreeModel Test");
              jf.add(tree);
              JMenuBar bar = new JMenuBar();
              jf.setJMenuBar(bar);
              JMenu menu = new JMenu("Options");
              bar.add(menu);
              final JMenuItem hide = new JMenuItem("Hide");
              final JMenuItem show = new JMenuItem("ShowAll");
              menu.add(hide);
              menu.add(show);
              ActionListener al = new ActionListener() {
                   public void actionPerformed(ActionEvent ae) {
                        if (ae.getSource() == hide) {
                             hmodel.hideNode(tree.getSelectionPath());
                             tree.updateUI();
                        else {
                             hmodel.showAll();
                             tree.updateUI();
              hide.addActionListener(al);
              show.addActionListener(al);
              jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              jf.setBounds(100,100,100,100);
              jf.setVisible(true);
    }

  • Multipart form (file upload) processing in providers

    Hello,
    Just want to find out if anyone has successfully implemented a file upload mechanism within a Portal channel.
    According to the Provider API (http://docs.sun.com/source/816-6428-10/com/sun/portal/providers/Provider.html), the wrapped request/response objects do not support several methods that are essential to process file uploads, namely "getContentLength" and "getInputStream". I am currently trying to use the Apache commons-fileupload utility which uses those methods to process file uploads. This is also the case for another popular file upload utility from servlets.com.
    Does anyone have any info/explanation regarding this limitation in Portal Server 6, and any workarounds to this issue. One workaround is to have a window popup that interacts directly with an external webapp.
    Any ideas/suggestions will be appreciated, thanks in advance.
    jeff

    Hi Jeff,
    The Sun ONE Portal Server DesktopServlet does not have the ability to process a request with the content encoding type of multipart/form-data. DesktopServlet does not pass the input stream for the request on to the Provider.
    To accomplish handling of multipart/form-data type requests, it is necessary to create a companion servlet or JSP that process the multipart/form-data. This servlet can then pass control back to the Portal channel. The data from the file can be shared between the servlet and the provider by using static Java members or by storing the data in a back-end database and then passing a reference to the data over to the provider.
    Sanjeev

  • JSP Multipart Form File Upload

    Good morning to all.
    I searched and googled but camu up with little.
    I want to upload a file from an HTML form. I have the enctype set etc. I am receiving all of the data on the server boundaries and all. I know there are readymade packages to do this but I'm one of these types that like to know why something works instead of simply plopping a jar on the server and using it (STD java excepted).
    My question is how to parse the data. If you read line by line, looking for the boundaries and you are trying to store the file bytes don't the bytes get corrupted when converting to String (in reader.readLine()) if they are not STD ASCII chars?
    Can anyone point me in the direction of a good tutorial on the subject?
    Thank you in advance.
    ST

    The basic idea of sending binary data via HTML is to encode into BASE64. This basically involves turning 3 bytes (8-bit) into 4 bytes (6-bit). This is done by representing a 6-bit byte with an ascii character. Instead of me confusing you I've found some code that does it, with lots of helpful comments.
    [url http://ostermiller.org/utils/Base64.java.html] dont know if this code works but hey, it looks the part
    Ted.

  • How do I access my encrypted User Account files from my Back Up hard drive?  Time Machine  was used to create the back up disk; File Vault was used to encrypt the files.

    How do I access my encrypted User Account files from my Back Up hard drive?  Time Machine  was used to create the back up disk; File Vault was used to encrypt the files.

    Thanks.  I will try going through TM.  Since my Simpletech is on the way out, I'll be plugging in a new external hard drive (other than the back-up drive) and trying to restore the library to the new drive.  Any advice or warning if this is NOT the right thing to do?
    Meanwhile, that is a great tip to do an alternate back-up using a different means.  It's been tough to figure out how to "preserve access" to digital images and files for posterity, knowing the hardware will always fail/obsolesce sooner or later, and that "clouds" are only as good as their consistent and reliable accessibility.  Upping the odds with redundancy will help dull the edge of my "access anxiety", though logically, it can never relieve it.  Will look into
    Carbon Copy Cloner.

  • What web service & xml will be used for deleting the packged epub/pdf file from Admin Console

    What web service & xml will be used for deleting the packged epub/pdf file from Admin Console?
    I am able to delete the files from Admin console directy but not able to get which web service is calling on deleting the file from admin console:
    Mangal

    Hi Jim,
    I tired following web service and xml to delete the packaged ebook but it is giving me error instead of response:
    Web Service & XML
    http://myserver_url/admin/ManageResourceKey
    <request action="delete" auth="builtin" xmlns="http://ns.adobe.com/adept">
    <nonce>" . $nonce . "</nonce>
    <expiration>'. $expiration .'</expiration>
    <resourceKey>
    <resource>resource_id</resource>
    <resourceItem>1</resourceItem>
    </resourceKey>
    </request>
    Error Message
    <error xmlns="http://ns.adobe.com/adept"
    data="E_ADEPT_DATABASE http://myserver_url/admin/ManageResourceKey
    Cannot%20delete%20or%20update%20a%20parent%20row:%20a%20foreign%20key%20constraint%20fails %20(`adept`.`distributionrights`,%20CONSTRAINT%20`distributionrights_ibfk_2`%20FOREIGN%20K EY%20(`resourceid`)%20REFERENCES%20`resourcekey`%20(`resourceid`))"/>
    Magal Varshney

  • ALBPM 6.0 : The maximum size for file uploads has been exceeded.

    Hi,
    I use AquaLogic BPM Entreprise server to deploy my Process. When I try to publish a process on my server I get the following error:
    An unexpected error ocurred.
    The error's technical description is:
    "javax.servlet.jsp.JspException: null"
    Possible causes are:
    The maximum size for file uploads has been exceeded.
    If you are trying to publish an exported project you should publish it using the remote project option.
    If you are trying to upload the participant's photo you should choose a smaller one.
    An internal error has ocurred, please contact support attaching this page's source code.
    Has someone resolve it?
    Thank's.

    Hi,
    Sure you've figured this out by now, but when you get the "Maximum size for file uploads" error during publish consider:
    1. if your export project file is over 10mb, use "Remote Project" (instead of "Exported Project") as the publication source. That way when you select the remote project, you will point to ".fpr" directory of the project you are trying to publish.
    Most times your project is not on a network drive that the server has access to. If this is the case, upload the .exp file to the machine where the Process Administrator is running, then expand it in any directory (just unzip the file). Then, from the Process Administrator, use the option to publish a Remote Project by entering the path to the .fpr directory you just created when unzipping the project.
    2. Check to see if you have cataloged any jars and marked them as non-versionable. Most of the times the project size is big just because of the external jar files. So as a best practice, when you do a project export select the option "include only-versionable jars", that will get reduce the project size considerably (usually to Kb's). Of course you have to manually copy the Jar files to your Ext folder.
    hth,
    Dan

  • How to read the complete path in file upload UI

    Hi,
    I want to know how to read the complete path in file upload UI in java web dynpro.
    I have created 1 file upload UI and than when i do browse and select some file say small.jpg from my local PC, desktop , its path is coming in file upload UI like E:\small.jpg,
    I want to know how to get this path in java webdynpro code.
    please let me know..

    Hi Satyam,
    In webdynpro java, first file stores in server location then it reads from server.
    Create a button with upload and write this code OnAction
    Resource is the attribute name in context of type com.sap.ide.webdynpro.uielementdefinitions.Resource, this attribute is for Resource property for Upload UI Element.
    Then in OnAction of button
    InputStream text = null;
           int temp=0;
           try{
                File file = new File(wdContext.currentContextElement().getResource().getResourceName().toString());
               String path = file.getAbsolutePath();
                wdComponentAPI.getMessageManager().reportSuccess(path);
           }catch(Exception e){
                e.printStackTrace();
        //@@end
    Regards,
    Pradeep
    Edited by: pradeep_546 on May 11, 2011 12:22 PM

  • Upload a file to the server - multipart/form-data ?

    I need to upload a file from my local machine to the server from a jsp page. I was asked to use a form with ENCTYPE = "multipart/form-data". but I am not sure how it works. Can any one enlighten me on the process or is there any other way to do it.
    null

    You can find the jsp source & the java sources which exactly does that in the iFS CMS sample code section. Go to Products -> Internet File system -> sample code -> Content Management System. This application allows the user to upload files from a local file system into iFS. This application creates the file in the iFS repository. You may want to save it in the file system of the web server. You may have to make little changes but the functionality is exactly what you are looking for.
    Hope this helps.
    Rajesh

  • What's the error of this file-upload code?

    hi,
    I have written following code for file selection:
    <form action="display.jsp" method="POST" enctype="multipart/form-data">
    <input type="file" name="File1">
    <input type="submit" name = "button" value="Submit">
    </form>And my project another file display.jsp which code is:
    <%@ page import="org.apache.commons.fileupload.*"%>
    <%@page import="java.io.*" %>
    <%@page import="java.util.*" %>
    <%
         out.println("Content Type: "+request.getContentType());
         boolean isMultipart=FileUpload.isMultipartContent(request);
         DiskFileUpload upload=new DiskFileUpload();
         List items=upload.parseRequest(request);
         Iterator iter=items.iterator();
         while(iter.hasNext()){
              FileItem item=(FileItem)iter.next();
              if(item.isFormField()){
                   out.println("SIZE: "+item.getSize());
                File fNew= new File(application.getRealPath("/"), item.getName());
                 out.println(fNew.getAbsolutePath());
                item.write(fNew);
              else
         out.println("Field ="+item.getFieldName());
    %>After that, i put on common-fileupload-1.1..jar on the project's /WebConcontent/WEB-INF/lib/ directory. And i have also add the common--fileupload-1.1.1. jar in the project build path. Further that i have got following error:
    Error is:
    exception
    org.apache.jasper.JasperException: org/apache/commons/io/output/DeferredFileOutputStream
         org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:510)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:375)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    root cause
    javax.servlet.ServletException: org/apache/commons/io/output/DeferredFileOutputStream
         org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:858)
         org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:791)
         org.apache.jsp.display_jsp._jspService(display_jsp.java:78)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:332)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    root cause
    java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream
         org.apache.commons.fileupload.DefaultFileItemFactory.createItem(DefaultFileItemFactory.java:102)
         org.apache.commons.fileupload.FileUploadBase.createItem(FileUploadBase.java:500)
         org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:367)
         org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:268)
         org.apache.jsp.display_jsp._jspService(display_jsp.java:53)
         org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:332)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)Why i have got this error? IS there anybody can help me? What will be the solution?Please Help me?
    With regards
    Bina

    java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream
    Means you are missing a class file from the class path. Most likely cause is a missing jar file. The Apache Commons utilities often have dependancies on other Commons projects. This looks like it is looking for the Apache Commons IO jar file. Download the jar file and add it to the WEB-INF/lib directory.

  • I use the apple email in my mac air. When I foward messages, people that use Outlook receive the text in form of attachment instead of the message opened in the body of the email. How can I solve this?

    I use the apple email in my mac air. When I foward messages, people that use Outlook receive the text fowarded in form of attachment instead of the message opened in the body of the email. How can I solve this? Thanks. Best regards.

    this:
    Did not exist at the point of delivery to the consumer.
    Nor did the white corrosive agent present exist at the point of sale.
    " exposure   of copper   alloys   to   moisture   or   salt   spray   will   cause   the formation  of  blue  or  green  salts  called  verdigris.  The presence   of   verdigris   indicates   active   corrosion."
    I see also 2 contact points with DEEP corrosion pitting not indicative of any defect from the factory.

  • How to keep HTML code in the applet source (.java) file itself?

    Hi,
    How to keep HTML code (APPLET tag) in the applet source (.java) file itself?
    Please give an example?
    thank you,

    R6i wrote:
    ...What I mean is without writing external HTML file, how to run an applet (during practice)?'Practice'? What does that mean? During development? If that is what you are referring to, add an applet tag at the top of YourApplet.java inside a Java comment area. Then AppletViewer (in recent SDKs) can then run it with just..
    prompt:javac YourApplet.java
    prompt:// the '.java' extension is not a mistake
    prompt:appletviewer YourApplet.javaIf you do not mean 'during development', then that brings us back to +"What advantages do you see that is bringing to the end user?".+

  • Last Q of the day (dealing with file saving)

    When I save my data to the file it gives me a bunch of tabs and stuff that I don't know how to fix. I tried match pattern, and remove white spaces and neither did if for me. Is there a way that I can get it to only output spaces, periods, and commas?

    Simple suggestion - reccomend you try my VI version 2 (from the first thread) and see if that gives you th same string out. If not, it is because you are adding in extra random spaces in the pig latin subVI. I noticed that you deal with spaces in a funny way and had to do something to avoid that.
    James
    edit:
    (Last post of the day - have a nice weekend)
    I have debugged the spacing in my VI loads, I can only debug your subVI so much
    Suggest you just read file in, wrte string into VI, and write string straight out of VI. It'll take you 5 mins to try.
    Message Edited by James W on 04-16-2010 01:03 PM

Maybe you are looking for

  • How to connect a printer to a wireless connection using airport/time capsule

    How do you connect a Cannon MP620 printer to the wireless network with my time capsule/airport?  It was set up before but I've had to redo all the settings with a new Time Capsule and now the printer isn't working.  Can't remember how I set it up bef

  • [SOLVED]MPD, PulseAudio & Systemd/User

    Since the advent of skype 4.3 I've had to switch to using pulseaudio. Things seems to be working fine except for the interaction between pulseaudio and mpd. My goal is to attain the same functionality as I had before when I was just using alsa. The m

  • How do I export 72ppi jpegs from InDesign without losing quality?

    I need to export indesign files that I design to 72ppi for web without losing any quality (or as minimal as possible). Countless times I have tried different methods, but alwasy manage to create a workaround, whether it be good quality, or just reada

  • How would I know if any one post a thread in the Forum

    Hi All, Please tell me how would I know if any body post a thread in the  forum?? Regards krishhna

  • Price in PO

    Dear Experts, I've created PO subcontracting with check box Info Update is ticked. No precedence PIR is created. Price in PO is taken automatically from last PO's price. After PO is saved, PIR is automatically created with no price value. After GR is