1

I would like to handle exceptions when directory is not present and also when the file is already created with the same prefix in the Servlet.

If my servlet after getting a request writes a PDF to FileOutputStream and sends redirect to previous receipt page successfully I don't want a message explaining cause written to request scope.

But when the directory does not exist (directory variable brings in path like 'D:\pdf') or if similar named file exist I want to send a sample error message in request scope.

So is my conditional expression correct? Am I using FileOutputStream and also ServletOutputStream the way it is meant to be? I have read that one servlet can either send to ServletOutputStream or write to PrintWriter.

I would be much obliged for any guidance or for sending me in the right direction.

Here is the overridden method of the servlet,

public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        System.out.println("headr " + request.getHeader("referer"));
        // response.setContentType("application/pdf");
        // response.setHeader("content-disposition", "attachment; filename=pdf.pdf");
        // response.setStatus(HttpServletResponse.SC_NO_CONTENT);  

        String prefix = request.getParameter("prefix");
        String no = request.getParameter("no");
        String html = request.getParameter("source");

        String directory = new SibsDelegate().getDirectoryPath();

        File file = new File(directory);
        if ( file.exists() && !new File(file, "prefix"+"-"+"no").exists())
        {
            System.out.println("exists");
           try 
           {
              HtmlCleaner cleaner = new HtmlCleaner();
              CleanerProperties props = cleaner.getProperties();

              TagNode node = cleaner.clean(html);

              // OutputStream os = response.getOutputStream();

              final XmlSerializer xmlSerializer = new PrettyXmlSerializer(props);
              final String html1 = xmlSerializer.getAsString(node);

              ITextRenderer renderer = new ITextRenderer();
              renderer.setDocumentFromString(html1);
              renderer.layout();

              String filename = prefix + "-" + no +".pdf";
              String fileNameWithPath = "D:\\pdf\\" + filename;
              FileOutputStream fos = new FileOutputStream( fileNameWithPath, false);
              renderer.createPDF( fos );
              fos.close();

              System.out.println( "PDF: '" + fileNameWithPath + "' created." );

              RequestDispatcher rd = null;
              // set message in request scope -- TODO
              request.getRequestDispatcher("Common_Receipt.jsp").forward(request, response);


              //  response.sendRedirect("Common_Receipt.jsp");


            } 
            catch (Exception ex) 
            {
               ex.printStackTrace();
            }
            finally
            {
                // fos.close();
            }

        }  

    }

1 Answer 1

1

Your file checking looks good but I won't break it up to 2 differents errors types handled differently instead I would put the directory checking outside the try catch and the file checking inside so you can handle the error with your IOExceptions:

if (!file.exists() || !file.isDirectory()) {
    // handle directory doesnt exist
    // note that "error" is just a string variable you can make it whatever you want
    request.setAttribute("error", "Directory already exists!!!!!");
    // you can output this attribue in your jsp to tell the user there was an error
    request.getRequestDispatcher("Common_Receipt.jsp").forward(request, response);
}
FileOutputStream fos = null;
try {
    File outputFile = new File(file, "prefix"+"-"+"no");
    if(outputFile.exists()) {
        // handle file output already exists
        throw new FileAlreadyExistsException(prefix+"-"+no+".pdf");
    }
    fos = new FileOutputStream( outputFile, false);

    // do your writing to the file here
} catch(FileAlreadyExistsException e) {
    request.setAttribute("error", "your file already exists dummy");
    request.getRequestDispatcher("Common_Receipt.jsp").forward(request, response);
} catch(IOException e) {
    // had a problem writing to the file, you decide how to handle it, or group it with the FileAlreadyExistsException. Note that FileAlreadyExistsException extends IOException so to group then just put
    // your code from the FileAlreadyExistsException block into here
    request.setAttribute("error", "woah something bad happened");
    request.getRequestDispatcher("Common_Receipt.jsp").forward(request, response);
} finnaly {
    if(fos != null) fos.close();
}

Let me know if that answered your question, I was a little confused reading through your question.

2
  • Thanks for taking the time answering my question. Your approach looks promising to me. Would you care to explain your strategy where you keep the check-if-directory-exists code outide the try-catch block?
    – yoda
    Sep 11, 2013 at 17:45
  • I try to not put code inside try catches that I dont want handled by the exception. In this case if something were to go wrong with the directory exists code (like an IOException) I dont want it being handled in the try catch I want it to throw an error back to me so I can see what went wrong and fix the problem so it doesnt happen again.
    – ug_
    Sep 11, 2013 at 18:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.