#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2002
    Location
    Phoenix AZ
    Posts
    30
    Rep Power
    23

    Return Javascript Alert from Servlet


    I have a download servlet (boldfaced) that can be accessed directly as long as the link sent out includes the full path of the file:

    http://our.download.site/DownloadContnet?file=/content/prospectDownload/prospect1.xls

    We have some users who send out the link with spaces in between the path and the filename so that the process sends out an error. I can capture the error, but I want to create a javascript alert that will tell the user that only a portion of the file's path was read because of a space in the name. How would I go about returning a javascript message?

    Thanks for any help.
    Programmer at large
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2005
    Location
    Internet
    Posts
    7,625
    Rep Power
    6089
    Print out some javascript on the page that shows up?
    Chat Server Project & Tutorial | WiFi-remote-control sailboat (building) | Joke Thread
    “Rational thinkers deplore the excesses of democracy; it abuses the individual and elevates the mob. The death of Socrates was its finest fruit.”
    Use XXX in a comment to flag something that is bogus but works. Use FIXME to flag something that is bogus and broken. Use TODO to leave yourself reminders. Calling a program finished before all these points are checked off is lazy.
    -Partial Credit: Sun

    If I ask you to redescribe your problem, it's because when you describe issues in detail, you often get a *click* and you suddenly know the solutions.
    Ches Koblents
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2002
    Location
    Phoenix AZ
    Posts
    30
    Rep Power
    23
    Originally Posted by gimp
    Print out some javascript on the page that shows up?
    I am using a servlet that uses HttpServletResponse and HttpServletRequest. I am downloading whatever files the user thinks are on the server, whether they be .doc, .xls, or even .pdf. Everything works when the link sent is correct; when it's not, I get an error posted. I would like to return a javascript alert. Since the DownloadContent is a servlet and not a jsp, I do not know how to "print out some javascript on the page that shows up". There is no page that shows up, just an error message that may or may not be passed in what the recipient thought was the file. I do not want the bogus file to display, but rather the popup message.

    Can you do that?
    Programmer at large
  6. #4
  7. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2005
    Location
    Internet
    Posts
    7,625
    Rep Power
    6089
    So when a user types in something wrong, does a page get loaded? Does DownloadContent get shown in some way, shape, or form, in the browser?
    Chat Server Project & Tutorial | WiFi-remote-control sailboat (building) | Joke Thread
    “Rational thinkers deplore the excesses of democracy; it abuses the individual and elevates the mob. The death of Socrates was its finest fruit.”
    Use XXX in a comment to flag something that is bogus but works. Use FIXME to flag something that is bogus and broken. Use TODO to leave yourself reminders. Calling a program finished before all these points are checked off is lazy.
    -Partial Credit: Sun

    If I ask you to redescribe your problem, it's because when you describe issues in detail, you often get a *click* and you suddenly know the solutions.
    Ches Koblents
  8. #5
  9. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2002
    Location
    Phoenix AZ
    Posts
    30
    Rep Power
    23
    Originally Posted by gimp
    So when a user types in something wrong, does a page get loaded? Does DownloadContent get shown in some way, shape, or form, in the browser?
    No, it does not. It is strictly a file downloader. If the file is valid, it downloads that file. It's just real basic stuff. It uses a bufferedOutputStream to download the files. No rocket science, just steal-and-paste that I got from other users with my own little touch after I discovered that we had files that freaked out one of the objects:

    Code:
    		response.reset();
    		String filename = request.getParameter("file");
    
    		String type = filename.substring(filename.lastIndexOf(".") + 1);
    		String name = filename.substring(filename.lastIndexOf("/") + 1);
    
    		String contentType = null;
    
    		// get the contentType
    		if (type.equals("doc"))
    			contentType = "application/msword";
    		else if (type.equals("xls") || type.equals("csv"))
    			contentType = "application/x-excel";
    		else if (type.equals("pdf"))
    			contentType = "application/pdf";
    		else if (type.equals("txt"))
    			contentType = "text/plain";
    		else if (type.equals("ppt"))
    			contentType = "application/vnd.ms-powerpoint";
    		else if (
    			type.equals("html") || type.equals("htm") || type.equals("jsp"))
    			contentType = "text/html";
    		else if (type.equals("zip"))
    			contentType = "application/zip";
    		else
    			contentType = "application";
    
    		// as long as the contentType is not "text/html", get the file
    		// as an attachment
    		if (!contentType.equals("text/html"))
    		{
    			response.setContentType(contentType);
    			response.setHeader(
    				"Content-Disposition",
    				"attachment; filename=" + name);
    		}
    
    		ServletOutputStream outStream = response.getOutputStream();
    
    		BufferedInputStream buffInStream = null;
    		BufferedOutputStream buffOutStream = null;
    
    		try
    		{
    			// Use Buffered Stream for reading/writing.
    			InputStream in =
    				new BufferedInputStream(new FileInputStream(filename));
    
    			buffInStream = new BufferedInputStream(in);
    			buffOutStream = new BufferedOutputStream(outStream);
    
    			// if the length is > 10 meg then break it up into 20 smaller
    			// parts to prevent IlligalStateException because the byte array
    			// is too large
    			int len = (int) new File(filename).length();
    			response.setContentLength(len);
    
    			int breakLenUp[];
    			if (len > 10000000)
    			{
    				breakLenUp = new int[20];
    				int holdLen = 0;
    				for (int i = 0; i < 20; i++)
    				{
    					breakLenUp[i] = len / 20;
    					holdLen += breakLenUp[i];
    				}
    				if (holdLen < len)
    				{
    					int last = len - holdLen;
    					breakLenUp[19] += last;
    				}
    			}
    			else
    			{
    				breakLenUp = new int[1];
    				breakLenUp[0] = len;
    			}
    			for (int i = 0; i < breakLenUp.length; i++)
    			{
    				byte[] buff = new byte[breakLenUp[i]];
    				int bytesRead;
    
    				// Simple read/write loop.
    				while (-1
    					!= (bytesRead = buffInStream.read(buff, 0, buff.length)))
    				{
    					buffOutStream.write(buff, 0, bytesRead);
    				}
    			}
    		}
    		catch (IOException e)
    		{
    			throw new IOException(e.getMessage());
    		}
    		catch (Exception e)
    		{
    			throw new Exception(e.getMessage());
    		}
    		finally
    		{
    			if (buffInStream != null)
    			{
    				buffInStream.close();
    			}
    			if (buffOutStream != null)
    			{
    				buffOutStream.close();
    			}
    			if (outStream != null)
    			{
    				outStream.flush();
    				outStream.close();
    			}
    		}
    I did try code to force it to execute a html page, but it didn't work correctly. It just showed the original bad filename (dummy.txt) and the html's data inside the data. Does this help?
    Programmer at large
  10. #6
  11. No Profile Picture
    Clueless llama
    Devshed Regular (2000 - 2499 posts)

    Join Date
    Feb 2001
    Location
    Lincoln, NE. USA
    Posts
    2,353
    Rep Power
    122
    First thing you should do is determine if the file does indeed exist. If it does, carry on as normal, setting your response headers and streaming the file.

    If it doesn't exist, you should forward to an html file or a jsp instead, or optionally output some html from the servlet.

    It is important that you don't set any response headers or get the servletOutputStream until you determine if the file exists or not. e.g., if you set the contentType to a pdf file, and then try to send html because of an error, the browser (or acrobat reader, in this case) may puke, to use a technical term.
    Last edited by Nemi; May 9th, 2007 at 01:13 PM.
    ~Nemi

    Before posting did you try:
    [ Javadocs | Google ]
  12. #7
  13. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2002
    Location
    Phoenix AZ
    Posts
    30
    Rep Power
    23
    Originally Posted by Nemi
    First thing you should do is determine if the file does indeed exist. If it does, carry on as normal, setting your response headers and streaming the file.

    If it doesn't exist, you should forward to an html file or a jsp instead, or optionally output some html from the servlet.

    It is important that you don't set any response headers or get the servletOutputStream until you determine if the file exists or not. e.g., if you set the contentType to a pdf file, and then try to send html because of an error, the browser (or acrobat reader, in this case) may puke, to use a technical term.
    Oh, that makes sense. That would explain why I'm getting the illegalstateexception errors, too. I can fix that. It's just a matter of switching things around. I'll let you know how it works out since I haven't stopped playing with it. Thanks!
    Programmer at large
  14. #8
  15. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2002
    Location
    Phoenix AZ
    Posts
    30
    Rep Power
    23

    Talking It Worked!!!


    Everything worked. I moved the ServletOutputStream to be created after I attempted to load the file into the InputStream object. After that, all I had to do was set the contentType to "text/html" and I was golden. The popup popped up and everything worked as planned.

    Thanks so very much. Your suggestion put me on the right track.

    Pat
    Programmer at large
  16. #9
  17. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2002
    Location
    Phoenix AZ
    Posts
    30
    Rep Power
    23
    I realized this morning that there was a slightly easier way to do this:

    Code:
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    		throws ServletException, IOException
    	{
    		try
    		{
    			String filename = request.getParameter("file");
    			File testFile = new File(filename);
    			// if passed file is not a file, replace the "filename" with the
    			// full path of the badLink.html file
    			if (!testFile.isFile())
    				filename = BADLINK;
    
    			getFile(filename, request, response);
    			System.gc();
    		}
    		catch (Exception e)
    		{
    			System.gc();
    			String msg = e.getMessage();
    
    			// If a bad link was emailed to the user, return a javasccript
    			// alert popup so that the user will not keep trying to use the
    			// same link but either fix the link or contact the person who
    			// emailed the link in the first place
    			if (msg.indexOf("directory") > -1
    				|| msg.indexOf("File not found") > -1)
    			{
    				try
    				{
    					displayJavascript(msg, response);
    				}
    				catch (Exception e1)
    				{
    					throw new ServletException(e1.getMessage());
    				}
    			}
    			// only throw error if user didn't cancel the download
    			else if (
    				msg.indexOf("Connection reset by peer: socket write error") < 0
    					&& msg.indexOf("Broken pipe") < 0)
    				throw new ServletException(e.getMessage());
    		}
    	}

    Comments on this post

    • gimp agrees
    Programmer at large

IMN logo majestic logo threadwatch logo seochat tools logo