yoda
yoda

Reputation: 569

Handle exceptional condition when file name already exists and also if directory path fetched is invalid

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();
            }

        }  

    }

Upvotes: 1

Views: 6161

Answers (1)

ug_
ug_

Reputation: 11440

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.

Upvotes: 1

Related Questions