problem in deleting the file

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • madhuriks
    New Member
    • Jun 2010
    • 149

    problem in deleting the file

    hi,
    in my project...i need to do delete operation..i developed one XML file...when i do delete..it is deleting the whole information in the xml file....what ever value i enter in the jsp page it should take that value and do delete operation...for deleting i wrote servlet coding...here is my code...can anyone help me where i wrote wrong...

    delete.java

    Code:
      
    
    package proj;
    
    import java.io.*;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Properties;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.w3c.dom.*;
    import javax.xml.parsers.*;
    import javax.xml.transform.*;
    import javax.xml.transform.dom.*;
    import javax.xml.transform.stream.*;
    
    public class delete extends HttpServlet {
    
        public void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
    
            response.setContentType("text/html");
            PrintWriter pw = response.getWriter();
            String s = null;
    
            try {
                DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = builderFactory.newDocumentBuilder();
    
                // Creating the path for XML File using Properties
                ServletContext servletContextObj = request.getSession().getServletContext();
                String excelTemplatesPath = servletContextObj.getRealPath("/");
                String filePaths = excelTemplatesPath + File.separator
                        + "config.properties";
                Properties propObj = new Properties();
                propObj.load(new FileInputStream(filePaths));
                String gprsLoginPath = null;
                gprsLoginPath = propObj.getProperty("GPRS_LOGIN_PATH");
                if (gprsLoginPath == null || gprsLoginPath.trim().equals("")) {
                    gprsLoginPath = excelTemplatesPath;
                }
                gprsLoginPath += File.separator + "login.xml";
                java.io.File file = new java.io.File(gprsLoginPath);
                Document doc = null;
                if (file.exists()) {
                    try {
                        doc = docBuilder.parse(file);
                    } catch (Exception ex) {
                        doc = docBuilder.newDocument();
                        Element root = doc.createElement("PACKS");
                        doc.appendChild(root);
                    }
                } else {
                    doc = docBuilder.newDocument();
                    // Creating Root Tag
                    Element root = doc.createElement("PACKS");
                    doc.appendChild(root);
                }
    
                // creating a new instance of a DOM to build a DOM tree.
                // Document doc = docBuilder.newDocument();
                delNode(file, doc, "PACK_NAME");
                pw.println("<b>Xml File Deleted Successfully</b>");
            } catch (Exception e) {
                System.out.println(e);
                e.printStackTrace();
            }
        }
    
        public static void delNode(java.io.File file, Node parent, String filter)
                throws Exception {
    
            NodeList children = parent.getChildNodes();
    
            for (int i = 0; i < children.getLength(); i++) {
                Node child = children.item(i);
    
                if (child.getNodeType() == Node.ELEMENT_NODE) {
    
                    if (child.getNodeName().equals(filter)) {
                        parent.removeChild(child);
                    } else {
                        delNode(file, child, filter);
                    }
                }
            }
            // TransformerFactory instance is used to create Transformer objects.
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            // create string from xml tree
            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            Document doc = null;
            DOMSource source = new DOMSource(doc);
            transformer.transform(source, result);
            String xmlString = sw.toString();
    
            //File file = new File("E:/xgprs/xmlgprs/login.xml");
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                    new FileOutputStream(file)));
            bw.write(xmlString);
            bw.flush();
            bw.close();
    
        }
    }
    thanks,
    madhu.
  • chaarmann
    Recognized Expert Contributor
    • Nov 2007
    • 785

    #2
    Why are you using so many dots between your sentences? Do you have so less time that you need to use telegram style? Then the best help is to take more time for solving your problems. Software programming cannot be done quickly and in a hurry, but only through deep thinking and taking time. If you follow this important advice, then you will save time. Yes, you read right, you will save time! You will notice that you will do your job more slowly but finish earlier. Often I was in a situation where there is a big time pressure to finish a program and find a solution to a current problem. When I hastily go into try-and-error or copy-and-paste misunderstood code I didn't achive anything except a chaotic program. When I made a break, breathed deeply and start thinking hard, then suddenly the problem was solved in an instant. I am sure you'll figure out that this tip is worth more than the hundred of tips you will get for your hundred of small problems. Dig a well for a thirsty man instead of always giving him water.

    1.) you wrote:
    "....what ever value i enter in the jsp page it should take that value and do delete operation..".
    So the first conclusion is to check for this value and print it out.
    So deep thinking means "If I enter something on the web page, I must make sure that this value is available in my function doPost() where I need it".
    The second thought: "If it's there, I should print it out for verification".
    But I can't see a print statement here. Also I can't see the command to fetch that value anywhere (by using request.getPara meter()).
    2.) you wrote: "when i do delete..it is deleting the whole information in the xml file.."
    Reduce your code to the minimum code with the problem by commenting out (temporarily) all other code that has nothing to do with the problem. If you think the delNode() method is the problem, then just test it in isolation! You may think "But I am in a hurry and have no time for testing. Let me just assume that it is working the way I think it should. Let me continue messing with the other code". Wrong! Deep thinking means you will make sure it works the way you expect it! So just relax, take a deep breath and start a new program:

    Code:
    public class HelloWorld {
      public static void main(String[] args) {
        File file = new File("c:\temp\test.xml");
        doc = docBuilder.parse(file);       
        delNode(file, doc, "PACK_NAME");
      }
      public static void delNode(java.io.File file, Node parent, String filter) throws Exception { 
        ...
      }
    }
    So what happens with file test.xml exactly? Why is it always empty afterwards even if you put some xml-text inside it? I mean after isolating the code you can see it has nothing to do with the browser, jsp-page etc. You could have posted this smaller problem here in the forum to speed up getting a solution and to cause less work for the helpers. You could even help yourself more (and helpers like me) and put in some statements that prints out the xml-code before it gets saved. Deep thinking means "I don't get the result I expected, so let me print out the intermediate results" That means, just insert a System.out.prin tln (xmlString) after line 102! You will see that whatever value you assign as "Node parent" and "String filter", it always is empty! You will ask yourself "Is my input not relevant fr the output? And why is it printing the empty string many times instead of only once in a complex xml-file where a root node has many children?". So go through the source code line by line with a parser (or in your mind). You will probably stop reading at line 88, where the method delNode() calls itself! Bingo! That's why it prints out many lines! You may think "I don't fully understand what it is doing here". So put it on your list as "second problem, to be solved after first problem is solved" and comment out the whole functionality (commenting out line 78 to 91). This is to simplify and isolate your problem more. Recursion is gone now, so you only get one line printed, but still empty! Wait, you should think, when the program still works, then it doesn't need my input "parent" and "filter", and that's the bug! Now try to figure out what is really necessary for your program, but commenting out every line of source code left and try-compiling it. You will come up with these lines left:
    Code:
    public class HelloWorld {
      public static void main(String[] args) {
        File file = new File("c:\temp\test.xml");
        delNode(file);
      }
      public static void delNode(java.io.File file) throws Exception { 
        TransformerFactory factory = TransformerFactory.newInstance(); 
            Transformer transformer = factory.newTransformer(); 
            StringWriter sw = new StringWriter(); 
            StreamResult result = new StreamResult(sw); 
            Document doc = null; 
            DOMSource source = new DOMSource(doc); 
            transformer.transform(source, result); 
            String xmlString = sw.toString();
            System.out.println(xmlString); 
      }
    }
    And that's exactly what happens!
    You create an DOM-source from a Document that is null, so the DOM-source is empty! Then you transformed your DOM-source to a string which then must be emty! Then you saved the empty string to file, so overwriting the orignal file!
    All the other code was irrelevant and distracted you from the problem. By using method "isolation" you figured out the problem yourself!
    So how to solve? First, you should not assign a null-document, but the original document that contained your xml-code. Second, you should make sure that you don't overwrite your document each time in every recursive call. So you must split up the function in two: one function that deletes all unwanted nodes from the document by recursively parsing through all child-nodes, and one function that gets the changed document and writes it back to a file.

    Summary: follow this advice to solve this (and your future) problems to become a good programmer:
    - isolate the problem by commenting out all unnecessary code.
    - print the results after each step (or use a debugger where you can see the results after each step).
    - don't skip many steps or take too big steps, (no telegram), just think deeply by taking each small step one by one (analysing the code line by line thoroughly.
    - No copy-and-paste! Write the code of your own! If you even copy a single line into your code that you don't understand 100%, then this line may cause a big error that you may not immediately detect. So feel responsible for the code. You can't sell a huge and nice apple if it has a small worm hole!

    Comment

    • madhuriks
      New Member
      • Jun 2010
      • 149

      #3
      hi chaarmann,
      thanks for ur reply and suggestion..i'l l follow it...and i got solved that problem..thanks a lot..

      Comment

      Working...