DataOutputStream appears to be buffering and then overflowing?? 10 Duke Pts

Hi folks,
Hope someone can help. I am trying to put together a file upload applet (yes I know....security this and signing that and so on...). It "works" (erm...kind of) using the JFileChooser and JProgressMonitorInputStream to carry out an HTTP post to a server side CGI script.
I have it "working" in so far as with small files it does actually complete although usually some time after the progress bar shows it completed.
With larger files though the progress bar still rushes through too quickly but then it crashes with an OutOfMemory exception (at around 40MB).
It looks to me almost as if the DataOutputStream is buffering and returning (not blocking) before the data has actually been sent. I have tried including a .flush() after the write but it made no difference.
Why does the DataOutputStream return from write before the data has actually been sent?
If anyone can help in any way it will be massively appreciated! I have included code below its not neat since I have been bashing it around trying to make it work.
What I am looking for is to have the progress bar show the progress as the contents of the file is uploaded to the server via the HTTP post.
package videoupload;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;
import java.io.*;
public class VideoUpload extends JApplet implements ActionListener
  class HTTPPoster extends SwingWorker {
    String sBoundary="2db8c22f75474a58cd13fa2d3425017015d392ce";
    URL u;
    public URLConnection postConnect(URL urlTarget)
      URLConnection c = null;
      try {
        c = urlTarget.openConnection();
        // post multipart data
        c.setDoOutput(true);
        c.setDoInput(true);
        c.setUseCaches(false);
      } catch (Exception ex)
         ex.printStackTrace();
      return c;
    public void postHeaders(URLConnection pCon)
      // set some request headers
      pCon.setRequestProperty("Connection", "Keep-Alive");
      pCon.setRequestProperty("HTTP_REFERER", "http://www.<THEWEBSITE>.com/");
      pCon.setRequestProperty("Content-Type",
                              "multipart/form-data; boundary="+sBoundary);
    public DataOutputStream getFormBodyOutput(URLConnection pCon)
      DataOutputStream dos = null;
      try
        dos = new DataOutputStream(pCon.getOutputStream());
        sendBoundary(dos);
      } catch (Exception ex)
        ex.printStackTrace();
      return dos;
    public void sendBoundary(DataOutputStream dos)
      try
        dos.writeBytes("--"+sBoundary+"\r\n");
      } catch (Exception ex)
        ex.printStackTrace();
    public void postFile(DataOutputStream dos, String name, File f)
      try
        dos.writeBytes(
            "Content-Disposition: form-data; name=\"" + name +
            "\"; filename=\"" + f.getName() +
            "\"\r\nContent-Type: application/octet-stream\r\n\r\n");
        System.out.println("Opening - "+f.getAbsoluteFile());
        FileInputStream fis = new FileInputStream(f.getAbsoluteFile());
        ProgressMonitorInputStream pmis = new ProgressMonitorInputStream(
            content, f.getName(), fis);
        ProgressMonitor pm = pmis.getProgressMonitor();
        pm.setMillisToDecideToPopup(500);
        byte[] bt = new byte[1024];
        int cnt = pmis.read(bt);
        while (cnt == bt.length)
          dos.write(bt, 0, cnt);
          cnt = pmis.read(bt);
        // send the last bit to the server
        dos.write(bt, 0, cnt);
        // now close the file and let the web server know this is the end of this form part
        pmis.close();
        fis.close();
        sendBoundary(dos);
      } catch (Exception ex)
        ex.printStackTrace();
    public void endPost(DataOutputStream dos)
      try
        dos.writeBytes(
            "\r\n--" + sBoundary + "--\r\n\r\n");
        dos.flush();
        dos.close();
      } catch (Exception ex)
        ex.printStackTrace();
    public void getResponse(URLConnection pCon)
      try
        DataInputStream dis =
            new DataInputStream(
                new BufferedInputStream(pCon.getInputStream()));
        String sIn = dis.readLine();
        while (sIn != null)
          if (sIn != null)
            System.out.println(sIn);
          sIn = dis.readLine();
      } catch (Exception ex)
        ex.printStackTrace();
    public Object construct()
      try
          u = new URL("http://www.<THEWEBSITE>.com/cgi-bin/upload.cgi");
          // System.out's here for debugging only...
          System.out.println("Connect");
          URLConnection pCon = postConnect(u);
          System.out.println("Send headers");
          postHeaders(pCon);
          System.out.println("Begin body");
          DataOutputStream dos = getFormBodyOutput(pCon);
          System.out.println("Send file");
          this.postFile(dos, "file", f);
          System.out.println("End body");
          endPost(dos);
          System.out.println("Get response");
          getResponse(pCon);
          System.out.println("Done");
        catch (Exception ex)
          ex.printStackTrace();
      return null;
  Container content;
  File f;
  protected boolean isStandalone = false;
  protected BorderLayout borderLayout1 = new BorderLayout();
  String uploadPath;
  //Get a parameter value
  public String getParameter(String key, String def)
    return isStandalone ? System.getProperty(key, def) :
        (getParameter(key) != null ? getParameter(key) : def);
  //Construct the applet
  public VideoUpload()
  //Initialize the applet
  public void init()
    try
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    catch (Exception e)
      System.err.println("Error setting native LAF: " + e);
    content = getContentPane();
    content.setBackground(Color.white);
    content.setLayout(new FlowLayout());
    // Come back to this later
    JTextField txtFileName = new JTextField();
    txtFileName.addActionListener(this);
    content.add(txtFileName);
    JButton btnUpload = new JButton("Upload");
    btnUpload.setMnemonic('u');
    btnUpload.addActionListener(this);
    content.add(btnUpload);
    //Create a file chooser
    final JFileChooser fc = new JFileChooser();
    int returnVal = fc.showOpenDialog(content);
    f=fc.getSelectedFile();
    try
      uploadPath = this.getParameter("uploadPath", "/");
    catch (Exception e)
      e.printStackTrace();
  public void actionPerformed(ActionEvent e){
    HTTPPoster worker = new HTTPPoster();
    worker.start();
  //Start the applet
  public void start()
  //Stop the applet
  public void stop()
  //Destroy the applet
  public void destroy()
  //Get Applet information
  public String getAppletInfo()
    return "Applet Information";
  //Get parameter info
  public String[][] getParameterInfo()
    java.lang.String[][] pinfo =
        {"uploadPath", "String", ""},
    return pinfo;
  //Main method
  public static void main(String[] args)
    VideoUpload applet = new VideoUpload();
    applet.isStandalone = true;
    Frame frame;
    frame = new Frame();
    frame.setTitle("Applet Frame");
    frame.add(applet, BorderLayout.CENTER);
    applet.init();
    applet.start();
    frame.setSize(400, 320);
    Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    frame.setLocation( (d.width - frame.getSize().width) / 2,
                      (d.height - frame.getSize().height) / 2);
    frame.setVisible(true);
}

Well after much ploughing through internet I have found much to my dismay that URLConnection is not as great as it may appear as it does buffer all output prior to sending.
This is fine for everything but file transfers, especially large ones as memory can be an issue.
Answered own question, doh!

Similar Messages

  • My ipod classic got wet back in August.. it seemed to work fine for about a month, but recently is not working at all..screen appeared to get cloudy and then it just stopped working. thanks.

    my ipod classic got wet back in August.. it seemed to work fine for about a month, but recently is not working at all..screen appeared to get cloudy and then it just stopped working. thanks.

    Most likely, water damage.
    You can try putting your iPod in a tupperware, half filled (maybe half inch) with rice grains, close the cover for about a week.
    If you have done this, as soon as it got wet, higher chances of success, now looks like the water moisture is getting to the LCD screen.
    Then you can always bring it to Apple Genius bar, for a an overhaul. (may cost you half the price of a new iPod classic.)

  • TS3694 My phone keeps freezing, the apple sign appears on the screen and then it freezes again and repeats itself.. has anyone had this before? it's also not letting me restore it from iTunes, it keeps coming up with error (9) or error (14).. help?

    My phone keeps freezing, the apple sign appears on the screen and then it freezes again and repeats itself.. has anyone had this before? if so, what is it? & it's also not letting me restore it from iTunes, it keeps coming up with error (9) or error (14).. help?

    Hi there Holly N,
    You may find the troubleshooting steps in the article below helpful.
    Resolve specific iTunes update and restore errors
    http://support.apple.com/kb/ts3694
    Configure your security software
    Related errors: 2, 4, 6, 9, 1000, 1611, 9006, 9807, or 9844. Sometimes as a result of this issue, a device might stop responding during the restore process.
    Check your security software and settings, which can block ports and prevent connection to Apple servers during update and restore.
    -Griff W. 

  • Well I was using my iphone 5, When restart and it did not turn on gets stuck in the presentation of apple (the apple) and at the top left of the screen above the apple logo reincia Appears this text, down and then turns back on and i get the same error ,

    Well I was using my iphone 5, When restart and it did not turn on gets stuck in the presentation of apple (the apple) and at the top left of the screen above the apple logo reincia Appears this text, down and then turns back on and i get the same error , i try to restore with itunes restore mode and throws me error!, could anyone help? I'm going crazy!. Thank you!
    This is the mistake That I get up the logo and then reboots iphone and Continues to Appear;
    (NAND) _findflashmediaandkeepout: 601 physical nand block offset 1
    (NAND) start: 356 this 0x96959400 PROVIDER = 0x96b1de80 falshmedia = 0x96b1de80
    (NAND) WMR_Start: 149 apple PNN  NAND Driver, Read / Write
    (NAND) WMR_Start: 174 FIL_INT (OK)
    (NAND) WMR_open :371 vfl_open (ok)
    (NAND) s_cxt_boot:88 sftl: error, unclean shutdown; adopted 7775 spans
    (NAND) WMR_open:420 FTL_open      (ok)
    (NAND)_publishServices:642 FTL capabilities: 0x00000001
    (NAND)_ppnvflGetStruct:3469 checking borrowed blocks-count:23 max_count:23
    (NAND)_fetchBorrowedList:881 number of borrowed blocks 16

    Hi Guys!
    I'm German, so my english writing might not be perfect
    I had the same Issue on a 5 i bought. Exact same screen and writing. Battery was totally drawn, first thing I had to replace. The screen had been replaced and since then it wouldn't work anymore according to the previous owner.
    It took me a couple hours, after recieving a few errors like 4013 it just never completed the restore, got really hot as well. The Flexwire of the Dock Connector seemed damaged, replaced the dock, but that didn't help.
    I almost gave up, thought the Logic Board was bad.
    BUT! Then i deceided to check if it has anything to do with the Screen assembly, and it did.
    Long story short, on mine the front facing camera, and sensor assy were bad.
    Anyhow, the phone works ''perfect'' when i leave them unplugged. So I just ordered a new one and we will see if thats the problem or if the damage is in the Logic Board.
    If so, i can live without the sensor and front cam.
    Just wanted to share, good luck everyone.

  • Bought a new HD for my Mac mini, and now i can not do anything, i press com r and nothing appears, only gray screen and then appears a folder with a ? in it, can anyone help me how to solve this. Thank you

    ought a new HD for my Mac mini, and now i can not do anything, i press com r and nothing appears, only gray screen and then appears a folder with a ? in it, can anyone help me how to solve this. Thank you

    Thank you so much for your attention, it is allready working well.

  • My ipod touch wont turn on!! the apple logo appears for five seconds and then it goes to a black screen and it has been repeating this when im not even touching it!! help!!

    my ipod touch wont turn on! i pressed the power button and the white apple logo appeared for five seconds and went to a black screen, and then back to the logo for 5 secs and back to the black screen for 5 secs. im not touching my ipod and it is still doing this. i did leave it onover night to update ios, is this why??

    Try:
    - iOS: Not responding or does not turn on
    - Also try DFU mode after try recovery mode
    How to put iPod touch / iPhone into DFU mode « Karthik's scribblings
    - If not successful and you can't fully turn the iOS device fully off, let the battery fully drain. After charging for an least an hour try the above again.
    - Try on another computer                            
    - If still not successful that usually indicates a hardware problem and an appointment at the Genius Bar of an Apple store is in order.
      Apple Retail Store - Genius Bar                              

  • When I try to get an app, it appears to be installing and then kicks back to the price.  The app never installs.

    I have been trying to install new apps to an iPad that I use with my students.  I click on the app, then click the Free button, click install app, enter the password.  It will say installing briefly and then kick back to free.  This has happened with multiple apps.  I thought that maybe it was the schools Internet filter, even though it has worked in the past.  I have also tried this on my home Internet and have the same results.  Any assistance would be appreciated as I am currently unable to get more instructional apps for my students.

    If resetting the iPad doesn't help, try these things.
    Quit the App Store app completely and restart the iPad. Go to the home screen first by tapping the home button. Double tap the home button and the task bar will appear with all of your recent/open apps displayed at the bottom. Tap and hold down on any app icon until it begins to wiggle. Tap the minus sign in the upper left corner of the app that you want to close. Tap the home button or anywhere above the task bar. Restart the iPad.
    Restart the iPad by holding down on the sleep button until the red slider appears and then slide to shut off. To power up hold the sleep button until the Apple logo appears and let go of the button.
    If that doesn't work - sign out of your account, restart the iPad and then sign in again. Settings>iTunes & App Store>Apple ID. Tap your ID and sign out. Restart the iPad by holding down on the sleep button until the red slider appears and then slide to shut off. To power up hold the sleep button until the Apple logo appears and let go of the button. Go back to Settings>iTunes & App Store>Sign in and then try to download an app again.
    If that fails, try downloading something in iTunes. There is free content in there so find something that you don't have to pay for and download it. If that works, try the App store again.

  • I cannot start up my macbook pro past the logo with the loading sign.. the bar appears at the bottom and then goes away but it just loads forever??

    Turned on my macbook pro and it just didn't make that welcoming noise and the sign the apple logo came with the loading sign and that's all it does. I tried command option P and R and then the welcoming sound came but it does the same thing. I've also tried shift s and pressing reboot and return...but still no thing..helppp

    Hi Djokovic2013,
    If you are having issues with your MacBook Pro not booting past the Apple logo, you may find the following articles helpful:
    Mac OS X: Gray screen appears during startup
    http://support.apple.com/kb/TS2570
    OS X: About OS X Recovery
    http://support.apple.com/kb/HT4718
    Regards,
    - Brenden

  • I hv a 3GS iphone. it could not be boot up.  When i press the sleep/wake button, the apple logo appeared for a while and then disappear.  My phone could not be start up.  When i go to itune, it does not have the logo for me to sync.

    I have a iphone3GS.  It could not be boot up.  When i press the sleep/wake button, the apple logo appear and then disappear.  The password login screen didnt' come on.  When i tried to connect my phone to the itune on my laptop, there isnt this button that i can sync my phone with the laptop.

    Sounds like your iPhones software may be corrupt. Try placing the iPhone into recovery mode. To do this, follow the steps in this article:
    http://support.apple.com/kb/HT1808
    Hope this helps
    - Greg

  • How to reset my ipod touch 4G if everytime i turn on it, a white screen appear about 2 seconds and then it turn off again, and again starts?

    Please i tried everything but i cant, answer¡¡¡¡¡¡
    I tried to turn off it, reboot it, conect it but the pc doesny recognize it, EVERYTHING¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡¡ Please

    I'm a little unclear regarding what you've already done so I'll start from the beginning.
    First, try a system reset.  It cures many ills and it's quick, easy and harmless...
    Hold down the on/off switch and the Home button simultaneously until the screen blacks out or you see the Apple logo.  Ignore the "Slide to power off" text if it appears.  You will not lose any apps, data, music, movies, settings, etc.
    http://support.apple.com/kb/TS1538
    There have been some problems accessing pages on the Apple web site.  If the hyperlink gives you a "We're sorry" message, try again.
    If the Reset doesn't work, try a Restore.  Note that it's nowhere near as quick as a Reset.  Connect via cable to the computer that you use for sync.  From iTunes, select the iPad/iPod and then select the Summary tab.  Follow directions for Restore and be sure to say "yes" to the backup.  You will be warned that all data (apps, music, movies, etc.) will be erased but, as the Restore finishes, you will be asked if you wish the contents of the backup to be copied to the iPad/iPod.  Again, say "yes."
    Finally, if the Restore doesn't work, let the battery drain completely.  Then recharge for at least an hour and Restore again.

  • I keep getting the incoming messages bar appearing under mail activity and then all my old emails start to enter inbox. why and how do i stop this and permanently delete these emails?

    i keep getting the incoming messagrs bar appearing under mail activity and all my old emails start to fill my inbox.Why and how do i stop this and how do i permanently delete old e mails?

    Maybe this will help:
    https://discussions.apple.com/message/21026706#21026706

  • I have downloaded itunes (windows vista), when I try to open the store it appears for a second and then disappears...what do I do?

    The store goes away as soon as I open it...what's up and how do I fix it?

    I have the same problem.  I search for something, it flashes the results for a second or two and then it's gone.  I'me running windows 7.  I hope someone has a solution!

  • HT1363 whenever I do this, the apple symbol appears for a second and then it has the red cross symbol again - which tells me to go to the support part of the apple website; so i end up back where i started, anybody know what i can do?

    I just wanted to restore my ipod nano, it told me to go to the support area of the apple website which i did andi followed the steps and they worked for about 2 seconds and then it told me to go back to the support area. it is fairly old but i dont understand why it will not reset?

    Hey Megan,
    If you are getting the Red X on your iPod nano, check out the following article. Of it does not work check out the second section in the article.
    iPod Displays a Red "X" Icon
    http://support.apple.com/kb/ts1463
    Thanks for using Apple Support Communities.
    Regards,
    -Norm G.

  • Im sure this is a complette mystery and has never ever edver happened to anyone else. But when i start firefox it appears on my screen and then disappears. Why am i the first person these bugs always occur to?

    i have the latest version im running vista. i dont know if you would define it as a crash but it simply disappears. I know you want more information, right . ?what part of disappears dont you understrand? is no one keeping track. have not a million people wriiteeen in to say the browser started and then disappeared? there is no crash id. just thjrow me a bone would ya?

    A possible cause is security software (firewall) that blocks or restricts Firefox or the plugin-container process without informing you, possibly after detecting changes (update) to the Firefox program.
    Remove all rules for Firefox from the permissions list in the firewall and let your firewall ask again for permission to get full unrestricted access to internet for Firefox and the plugin-container process and the updater process.
    See:
    * https://support.mozilla.com/kb/Server+not+found
    * https://support.mozilla.com/kb/Firewalls
    * http://kb.mozillazine.org/Firewalls
    * http://kb.mozillazine.org/Browser_will_not_start_up

  • My computer is freaking out! A bunch of weird lined symbols appeared on my screen and then it told

    Weird symbols appeared on my screen. The screen then told me to restart. I did and this happened 3 times. I just did a sage reboot but it has a gray screen andseems to be taking a long time . what happened and how do I fix it??

    And now the lined symbols are back!

Maybe you are looking for