Discussions

Web tier: servlets, JSP, Web frameworks: help! Download servlet issues. Smart? - can you solve it?

  1. Ok, I could definitely use some advice on how to solve this little issue. If anyone can give me explicit examples of how I can clean these things up, please give me all the help you can. Here it is:


    I have a download servlet that gets called from a jsp page (using STRUTS)

    The servlet downloads a file for the user (pdf, txt file, etc...).

    The download code looks like:

    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,HttpServletResponse response) throws Exception, IOException, ServletException {
    .........
    //different declarations, etc.....

    response.reset();

    ServletOutputStream sOutStream = response.getOutputStream();//this is for binary data

    response.setContentType("application/octet-stream");
    response.setHeader( "Content-Disposition", "attachment; filename=" + downloadFileName );

    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
        try{
    URL url = new URL(urlstr);
    URLConnection urlc= url.openConnection();
    int length = urlc.getContentLength();
    response.setContentLength(length);
    // Use Buffered Stream for reading/writing.
    InputStream in = urlc.getInputStream();
    bis = new BufferedInputStream(in);
    bos = new BufferedOutputStream(sOutStream);
    byte[] buff = new byte[length];
    int bytesRead;
    // Simple read/write loop.
    while(-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
    bos.write(buff, 0, bytesRead);
    }
    } catch (Exception e) {
    e.printStackTrace();
    ErrorStr = "Error Streaming the Data";
    sOutStream.print(ErrorStr);
    return(mapping.findForward("portalindex"));
    } finally {
    if( bis != null ) {
    bis.close();
    }
    if( bos != null ) {
    bos.close();
    }
    if( sOutStream != null ) {
    sOutStream.flush();
    sOutStream.close();
    }
    }


    return(mapping.findForward("portalindex"));
    ///////////////////////////////////////////////////////////////

    The two problems I have are:

    [8/17/05 15:11:01:371 EDT] 6a552551 WebGroup E SRVE0026E: [Servlet Error]-[OutputStream already obtained]: java.lang.IllegalStateException: OutputStream already obtained
    at com.ibm.ws.webcontainer.srt.SRTServletResponse.getWriter(SRTServletResponse.java:511)
    at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:202)
    at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:193)
    at org.apache.jasper.runtime.JspWriterImpl.write(JspWriterImpl.java(Compiled Code))
    at org.apache.jasper.runtime.JspWriterImpl.write(JspWriterImpl.java(Compiled Code))
    at org.apache.jsp._PortalIndex._jspService(_PortalIndex.java:389)
    at com.ibm.ws.webcontainer.jsp.runtime.HttpJspBase.service(HttpJspBase.java:89)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at com.ibm.ws.webcontainer.jsp.servlet.JspServlet$JspServletWrapper.service(JspServlet.java:344)
    at com.ibm.ws.webcontainer.jsp.servlet.JspServlet.serviceJspFile(JspServlet.java:669)
    at com.ibm.ws.webcontainer.jsp.servlet.JspServlet.service(JspServlet.java:767)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at com.ibm.ws.webcontainer.servlet.StrictServletInstance.doService(StrictServletInstance.java:110)
    at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet._service(StrictLifecycleServlet.java:174)
    at com.ibm.ws.webcontainer.servlet.IdleServletState.service(StrictLifecycleServlet.java:313)
    at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet.service(StrictLifecycleServlet.java:116)
    at com.ibm.ws.webcontainer.servlet.ServletInstance.service(ServletInstance.java:283)
    at com.ibm.ws.webcontainer.servlet.ValidServletReferenceState.dispatch(ValidServletReferenceState.java:42)
    at com.ibm.ws.webcontainer.servlet.ServletInstanceReference.dispatch(ServletInstanceReference.java:40)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.handleWebAppDispatch(WebAppRequestDispatcher.java:983)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:564)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.include(WebAppRequestDispatcher.java:253)
    at org.apache.struts.action.RequestProcessor.doInclude(RequestProcessor.java:1099)
    at org.apache.struts.tiles.TilesRequestProcessor.doForward(TilesRequestProcessor.java:272)
    at org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:455)
    at org.apache.struts.tiles.TilesRequestProcessor.processForwardConfig(TilesRequestProcessor.java:320)
    at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:279)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
    at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:507)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at com.ibm.ws.webcontainer.servlet.StrictServletInstance.doService(StrictServletInstance.java:110)
    at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet._service(StrictLifecycleServlet.java:174)
    at com.ibm.ws.webcontainer.servlet.ServicingServletState.service(StrictLifecycleServlet.java:333)
    at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet.service(StrictLifecycleServlet.java:116)
    at com.ibm.ws.webcontainer.servlet.ServletInstance.service(ServletInstance.java:283)
    at com.ibm.ws.webcontainer.servlet.ValidServletReferenceState.dispatch(ValidServletReferenceState.java:42)
    at com.ibm.ws.webcontainer.servlet.ServletInstanceReference.dispatch(ServletInstanceReference.java:40)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.handleWebAppDispatch(WebAppRequestDispatcher.java:983)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:564)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.include(WebAppRequestDispatcher.java:253)
    at org.apache.struts.action.RequestProcessor.doInclude(RequestProcessor.java:1099)
    at org.apache.struts.tiles.TilesRequestProcessor.doForward(TilesRequestProcessor.java:272)
    at org.apache.struts.action.RequestProcessor.processForwardConfig(RequestProcessor.java:455)
    at org.apache.struts.tiles.TilesRequestProcessor.processForwardConfig(TilesRequestProcessor.java:320)
    at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:279)
    at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1482)
    at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:507)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
    at com.ibm.ws.webcontainer.servlet.StrictServletInstance.doService(StrictServletInstance.java:110)
    at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet._service(StrictLifecycleServlet.java:174)
    at com.ibm.ws.webcontainer.servlet.ServicingServletState.service(StrictLifecycleServlet.java:333)
    at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet.service(StrictLifecycleServlet.java:116)
    at com.ibm.ws.webcontainer.servlet.ServletInstance.service(ServletInstance.java:283)
    at com.ibm.ws.webcontainer.servlet.ValidServletReferenceState.dispatch(ValidServletReferenceState.java:42)
    at com.ibm.ws.webcontainer.servlet.ServletInstanceReference.dispatch(ServletInstanceReference.java:40)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.handleWebAppDispatch(WebAppRequestDispatcher.java:983)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:564)
    at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:200)
    at com.ibm.ws.webcontainer.srt.WebAppInvoker.doForward(WebAppInvoker.java:119)
    at com.ibm.ws.webcontainer.srt.WebAppInvoker.handleInvocationHook(WebAppInvoker.java:276)
    at com.ibm.ws.webcontainer.cache.invocation.CachedInvocation.handleInvocation(CachedInvocation.java:71)
    at com.ibm.ws.webcontainer.cache.invocation.CacheableInvocationContext.invoke(CacheableInvocationContext.java:116)
    at com.ibm.ws.webcontainer.srp.ServletRequestProcessor.dispatchByURI(ServletRequestProcessor.java:186)
    at com.ibm.ws.webcontainer.oselistener.OSEListenerDispatcher.service(OSEListener.java:334)
    at com.ibm.ws.webcontainer.http.HttpConnection.handleRequest(HttpConnection.java:56)
    at com.ibm.ws.http.HttpConnection.readAndHandleRequest(HttpConnection.java:618)
    at com.ibm.ws.http.HttpConnection.run(HttpConnection.java:443)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java(Compiled Code))

    [8/17/05 15:11:01:381 EDT] 6a552551 TraceNLS u No message text associated with key HttpConnection.run:.java.lang.IllegalStateException:.525742.response.bytes.written,.but.Content-Length.header.equals.525700 in bundle com.ibm.ejs.resources.seriousMessages
    [8/17/05 15:11:01:381 EDT] 6a552551 HttpConnectio E HttpConnection.run: java.lang.IllegalStateException: 525742 response bytes written, but Content-Length header equals 525700
    [8/17/05 15:11:01:381 EDT] 6a552551 SystemOut O java.lang.IllegalStateException: 525742 response bytes written, but Content-Length header equals 525700
    [8/17/05 15:11:01:381 EDT] 6a552551 SystemOut O at com.ibm.ws.http.HttpResponse.finish(HttpResponse.java:103)
    [8/17/05 15:11:01:381 EDT] 6a552551 SystemOut O at com.ibm.ws.http.HttpConnection.readAndHandleRequest(HttpConnection.java:689)
    [8/17/05 15:11:01:381 EDT] 6a552551 SystemOut O at com.ibm.ws.http.HttpConnection.run(HttpConnection.java:443)
    [8/17/05 15:11:01:381 EDT] 6a552551 SystemOut O at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java(Compiled Code))


    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    Who can help me??? Thanks!!!!

    Threaded Messages (10)

  2. Try something like the following...

    public ActionForward execute(ActionMapping mapping, ActionForm form,
                HttpServletRequest request,
                HttpServletResponse response)
                 throws IOException, ServletException, ResourceException {
            try {

    // Build absolute path
                    String fileName = "blah";
                    String selectedFile = directory + "/" + fileName;

                    // set headers
                    response.setContentType("application/unknown");
                    response.setHeader("Content-disposition",
                            "attachment;filename=" + fileName);

                    // Get file
                    dumpFile(selectedFile, response.getOutputStream());

            } catch (Throwable t) {
    // do whatever
            }
            return null;
        }

        /**
         * dumps the contents of the file into the outputStream
         *
         *@param fileName fileName to dump
         *@param outputstream where to dump the file to
         */
        private void dumpFile(String fileName, OutputStream outputstream) {
            byte[] abyte0 = new byte[4096];

            try {
                BufferedInputStream bufferedinputstream = new BufferedInputStream(
                        new FileInputStream(
                        fileName));
                int i;

                while ((i = bufferedinputstream.read(abyte0, 0, 4096)) != -1) {
                    outputstream.write(abyte0, 0, i);
                }

                bufferedinputstream.close();
            } catch (Exception _ex) {
            }
        }
  3. U can use Something Like this....

    public ActionForward uploadMethod(ActionMapping mapping,ActionForm form,HtpServletRequest request,HttpServletResponse response) throws Exception {

     String file="someFile";
     response.setContentType("application/x-file-download");
     response.setHeader("Content-disposition","attatchment;filename="+file);
    ServletOutputStream out = respnse.getOutputStream();
     try {
           getFileContent(file,out);
     }catch(IOException ioe) {}
      catch(FileNotFoundException fnf) {}
    out.flush();
    return null;
    }

    public void getFileContent(String file,OutputStream out) throws IOException,FileNotFoundException {
       InputStream is = new FileInputStream(file);
       byte b= new byte[4096];
       int i=0;
       while( (i=is.read(b) != -1) {
       out.write(b,0,i);
       }
     is.close();
    }
  4. Hi,
    I'm using the same code in the Jsp, how to avoid this illegal state problem.
  5. Did u find the answer to this ? I am facing the same problem in JSP on Websphere 5.1. I have cheked the various fourms ...where in they mentioned this problem due to extra carriage returns..I have taken care of all that but still this problem is bugging me. Here is the Code: <% File f = new File ("C:/TEMP/" + queryFilename.toString() ); response.setContentType ("application/octet-stream"); //set the header and also the Name by which user will be prompted to save response.setHeader ("Content-Disposition", "attachment;filename=\"" + queryFilename.toString() + "\""); //get the file name String name = f.getName().substring(f.getName().lastIndexOf("/") + 1,f.getName().length()); //out.println("***** NAME IS:" + name); //OPen an input stream to the file and post the file contents thru the //servlet output stream to the client m/c InputStream in = new FileInputStream(f); ServletOutputStream outs = response.getOutputStream(); int bit = 256; int i = 0; try {// Read till EOF while((bit = in.read()) != -1){outs.write(bit);} } catch (IOException ioe) { return; } outs.flush(); outs.close(); in.close(); %> Here is the stack trace......... [Servlet Error]-[OutputStream already obtained]: java.lang.IllegalStateException: OutputStream already obtained at com.ibm.ws.webcontainer.srt.SRTServletResponse.getWriter(SRTServletResponse.java:523) at org.apache.jasper.runtime.JspWriterImpl.initOut(JspWriterImpl.java:202) at org.apache.jasper.runtime.JspWriterImpl.flushBuffer(JspWriterImpl.java:193) at org.apache.jasper.runtime.JspWriterImpl.flush(JspWriterImpl.java:246) at org.apache.jasper.runtime.PageContextImpl.release(PageContextImpl.java:197) at org.apache.jasper.runtime.JspFactoryImpl.internalReleasePageContext(JspFactoryImpl.java:255) at org.apache.jasper.runtime.JspFactoryImpl.releasePageContext(JspFactoryImpl.java:249) at org.apache.jsp._ViewAttachment._jspService(_ViewAttachment.java(Compiled Code)) at com.ibm.ws.webcontainer.jsp.runtime.HttpJspBase.service(HttpJspBase.java:89) at javax.servlet.http.HttpServlet.service(HttpServlet.java:853) at com.ibm.ws.webcontainer.jsp.servlet.JspServlet$JspServletWrapper.service(JspServlet.java:344) at com.ibm.ws.webcontainer.jsp.servlet.JspServlet.serviceJspFile(JspServlet.java:683) at com.ibm.ws.webcontainer.jsp.servlet.JspServlet.service(JspServlet.java:781) at javax.servlet.http.HttpServlet.service(HttpServlet.java:853) at com.ibm.ws.webcontainer.servlet.StrictServletInstance.doService(StrictServletInstance.java:110) at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet._service(StrictLifecycleServlet.java:174) at com.ibm.ws.webcontainer.servlet.IdleServletState.service(StrictLifecycleServlet.java:313) at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet.service(StrictLifecycleServlet.java:116) at com.ibm.ws.webcontainer.servlet.ServletInstance.service(ServletInstance.java:283) at com.ibm.ws.webcontainer.servlet.ValidServletReferenceState.dispatch(ValidServletReferenceState.java:42) at com.ibm.ws.webcontainer.servlet.ServletInstanceReference.dispatch(ServletInstanceReference.java:40) at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.handleWebAppDispatch(WebAppRequestDispatcher.java:1019) at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:592) at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:204) at com.ibm.ws.webcontainer.srt.WebAppInvoker.doForward(WebAppInvoker.java:125) at com.ibm.ws.webcontainer.srt.WebAppInvoker.handleInvocationHook(WebAppInvoker.java:286) at com.ibm.ws.webcontainer.cache.invocation.CachedInvocation.handleInvocation(CachedInvocation.java:71) at com.ibm.ws.webcontainer.srp.ServletRequestProcessor.dispatchByURI(ServletRequestProcessor.java:182) at com.ibm.ws.webcontainer.oselistener.OSEListenerDispatcher.service(OSEListener.java:334) at com.ibm.ws.webcontainer.http.HttpConnection.handleRequest(HttpConnection.java:56) at com.ibm.ws.http.HttpConnection.readAndHandleRequest(HttpConnection.java:615) at com.ibm.ws.http.HttpConnection.run(HttpConnection.java:439) at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:912)
  6. Here's the problem though[ Go to top ]

    Guys, the problem is at this line:

    ServletOutputStream sOutStream = response.getOutputStream();//this is for binary data

    It has to do with that getOutputStream, but I don't know how to fix it. I can comment out the whole function and just have that getoutputsteam line, and it will through the outputstream already obtained error. How can I get this working. By the way, the file downloads correctly, but the error is thrown. Thanks for any more help you can give!
  7. Here's the problem though[ Go to top ]

    return(mapping.findForward("portalindex"));

    Try changing that to

    return null;
  8. yes!!![ Go to top ]

    return null works!!!! Thanks!!!!

    So, what's the deal with it? I assume when it does the forward that it tries to do a getOutputStream(); or getwriter (i think that's what its called :)), but only can have one open? Can you explain why the fix works for all our knowledge? Thank you sir :)
  9. yes!!![ Go to top ]

    Actually the posters before me had return null in their code. You chose to ignore it and they chose not to highlight it ;-)

    Your assumption is correct. Do look at the getOutputStream API and the execute method API. It is very clear. For better understanding, you can also grab the struts src and look at the code to see exactly what it does.
  10. Use Struts Download Action[ Go to top ]

    Hi, for the same Action of downloading a file from the server has anyone used Download Action provided by Struts.

    If so, Please let me know. I need to use this to download a file.

    Thanks.
  11. http://java.sun.com/j2ee/sdk_1.2.1/techdocs/api/javax/servlet/ServletResponse.html#getOutputStream() clearly states that: public ServletOutputStream getOutputStream() throws java.io.IOException Throws: java.lang.IllegalStateException - if the getWriter method has been called on this response and a JSP page does have an implicit out object which causes that exception. Work around: 1> Convert your JSP to servlet code. 2> Live with the Exception if it does not really bother you by appending nuisance to the end of your OutputStream text.