]> source.dussan.org Git - poi.git/commitdiff
close cursors in finally blocks
authorPJ Fanning <fanningpj@apache.org>
Tue, 28 Dec 2021 10:41:06 +0000 (10:41 +0000)
committerPJ Fanning <fanningpj@apache.org>
Tue, 28 Dec 2021 10:41:06 +0000 (10:41 +0000)
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1896471 13f79535-47bb-0310-9956-ffa450edef68

poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFGraphicFrame.java
poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFObjectData.java
poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFRichTextString.java
poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFTableStyle.java
poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/XSSFVMLDrawing.java
poi-ooxml/src/main/java/org/apache/poi/xssf/usermodel/helpers/XSSFPasswordHelper.java
poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFAbstractFootnoteEndnote.java
poi-ooxml/src/main/java/org/apache/poi/xwpf/usermodel/XWPFFooter.java

index 8ba78484849d9e579758b88e6c3cbfef07ac292a..a62253aa327f1c7d7cffc65a85b09e25aad14d19 100644 (file)
@@ -193,10 +193,13 @@ public final class XSSFGraphicFrame extends XSSFShape {
         String r_namespaceUri = STRelationshipId.type.getName().getNamespaceURI();
         String c_namespaceUri = XSSFDrawing.NAMESPACE_C;
         XmlCursor cursor = data.newCursor();
-        cursor.toNextToken();
-        cursor.beginElement(new QName(c_namespaceUri, "chart", "c"));
-        cursor.insertAttributeWithValue(new QName(r_namespaceUri, "id", "r"), id);
-        cursor.dispose();
+        try {
+            cursor.toNextToken();
+            cursor.beginElement(new QName(c_namespaceUri, "chart", "c"));
+            cursor.insertAttributeWithValue(new QName(r_namespaceUri, "id", "r"), id);
+        } finally {
+            cursor.dispose();
+        }
         data.setUri(c_namespaceUri);
     }
 
index 7001c88b5cf8edb911ccc8ae440cbaf9402c4c51..0aee53f44cc7d3b961a56e036249f811f678446d 100644 (file)
@@ -83,11 +83,14 @@ public class XSSFObjectData extends XSSFSimpleShape implements ObjectData {
             CTOfficeArtExtension ext = extLst.addNewExt();
             ext.setUri("{63B3BB69-23CF-44E3-9099-C40C66FF867C}");
             XmlCursor cur = ext.newCursor();
-            cur.toEndToken();
-            cur.beginElement(new QName(drawNS, "compatExt", "a14"));
-            cur.insertNamespace("a14", drawNS);
-            cur.insertAttributeWithValue("spid", "_x0000_s1");
-            cur.dispose();
+            try {
+                cur.toEndToken();
+                cur.beginElement(new QName(drawNS, "compatExt", "a14"));
+                cur.insertNamespace("a14", drawNS);
+                cur.insertAttributeWithValue("spid", "_x0000_s1");
+            } finally {
+                cur.dispose();
+            }
 
             nv.addNewCNvSpPr();
 
index 3210dabebec3167218d0de432a82bbd030da22ee..a88fae862ccabfedf2077d37b57cb93cc893f447 100644 (file)
@@ -490,9 +490,12 @@ public class XSSFRichTextString implements RichTextString {
             char lastChar  = text.charAt(text.length() - 1);
             if(Character.isWhitespace(firstChar) || Character.isWhitespace(lastChar)) {
                 XmlCursor c = xs.newCursor();
-                c.toNextToken();
-                c.insertAttributeWithValue(new QName("http://www.w3.org/XML/1998/namespace", "space"), "preserve");
-                c.dispose();
+                try {
+                    c.toNextToken();
+                    c.insertAttributeWithValue(new QName("http://www.w3.org/XML/1998/namespace", "space"), "preserve");
+                } finally {
+                    c.dispose();
+                }
             }
         }
     }
index 6497f727b4fbe440dfcbee69061f413f749848e2..5b708d4f6c1be627a17b34090b0c406391baf3b0 100644 (file)
@@ -59,27 +59,31 @@ public class XSSFTableStyle implements TableStyle {
         List<CTDxf> dxfList = new ArrayList<>();
 
         // CT* classes don't handle "mc:AlternateContent" elements, so get the Dxf instances manually
-        XmlCursor cur = dxfs.newCursor();
-        // sometimes there are namespaces sometimes not.
-        String xquery = "declare namespace x='"+XSSFRelation.NS_SPREADSHEETML+"' .//x:dxf | .//dxf";
-        cur.selectPath(xquery);
-        while (cur.toNextSelection()) {
-            XmlObject obj = cur.getObject();
-            String parentName = obj.getDomNode().getParentNode().getNodeName();
-            // ignore alternate content choices, we won't know anything about their namespaces
-            if (parentName.equals("mc:Fallback") || parentName.equals("x:dxfs") || parentName.contentEquals("dxfs")) {
-                CTDxf dxf;
-                try {
-                    if (obj instanceof CTDxf) {
-                        dxf = (CTDxf) obj;
-                    } else {
-                        dxf = CTDxf.Factory.parse(obj.newXMLStreamReader(), new XmlOptions().setDocumentType(CTDxf.type));
+        final XmlCursor cur = dxfs.newCursor();
+        try {
+            // sometimes there are namespaces sometimes not.
+            String xquery = "declare namespace x='"+XSSFRelation.NS_SPREADSHEETML+"' .//x:dxf | .//dxf";
+            cur.selectPath(xquery);
+            while (cur.toNextSelection()) {
+                XmlObject obj = cur.getObject();
+                String parentName = obj.getDomNode().getParentNode().getNodeName();
+                // ignore alternate content choices, we won't know anything about their namespaces
+                if (parentName.equals("mc:Fallback") || parentName.equals("x:dxfs") || parentName.contentEquals("dxfs")) {
+                    CTDxf dxf;
+                    try {
+                        if (obj instanceof CTDxf) {
+                            dxf = (CTDxf) obj;
+                        } else {
+                            dxf = CTDxf.Factory.parse(obj.newXMLStreamReader(), new XmlOptions().setDocumentType(CTDxf.type));
+                        }
+                        if (dxf != null) dxfList.add(dxf);
+                    } catch (XmlException e) {
+                        LOG.atWarn().withThrowable(e).log("Error parsing XSSFTableStyle");
                     }
-                    if (dxf != null) dxfList.add(dxf);
-                } catch (XmlException e) {
-                    LOG.atWarn().withThrowable(e).log("Error parsing XSSFTableStyle");
                 }
             }
+        } finally {
+            cur.dispose();
         }
 
         for (CTTableStyleElement element : tableStyle.getTableStyleElementList()) {
index ba8d5849eb65aee899d0cec1a9c49661bca47056..2ed99ad900004c364f1278ca049458ccab8f51fe 100644 (file)
@@ -207,36 +207,46 @@ public final class XSSFVMLDrawing extends POIXMLDocumentPart {
      */
     private void newDrawing(){
         root = XmlDocument.Factory.newInstance();
-        XmlCursor xml = root.addNewXml().newCursor();
-
-        ShapelayoutDocument layDoc = ShapelayoutDocument.Factory.newInstance();
-        CTShapeLayout layout = layDoc.addNewShapelayout();
-        layout.setExt(STExt.EDIT);
-        CTIdMap idmap = layout.addNewIdmap();
-        idmap.setExt(STExt.EDIT);
-        idmap.setData("1");
+        final XmlCursor xml = root.addNewXml().newCursor();
+        try {
+            ShapelayoutDocument layDoc = ShapelayoutDocument.Factory.newInstance();
+            CTShapeLayout layout = layDoc.addNewShapelayout();
+            layout.setExt(STExt.EDIT);
+            CTIdMap idmap = layout.addNewIdmap();
+            idmap.setExt(STExt.EDIT);
+            idmap.setData("1");
+
+            xml.toEndToken();
+            final XmlCursor layCur = layDoc.newCursor();
+            try {
+                layCur.copyXmlContents(xml);
+            } finally {
+                layCur.dispose();
+            }
 
-        xml.toEndToken();
-        XmlCursor layCur = layDoc.newCursor();
-        layCur.copyXmlContents(xml);
-        layCur.dispose();
+            CTGroup grp = CTGroup.Factory.newInstance();
+            CTShapetype shapetype = grp.addNewShapetype();
+            _shapeTypeId = COMMENT_SHAPE_TYPE_ID;
+            shapetype.setId(_shapeTypeId);
+            shapetype.setCoordsize("21600,21600");
+            shapetype.setSpt(202);
+            shapetype.setPath2("m,l,21600r21600,l21600,xe");
+            shapetype.addNewStroke().setJoinstyle(STStrokeJoinStyle.MITER);
+            CTPath path = shapetype.addNewPath();
+            path.setGradientshapeok(STTrueFalse.T);
+            path.setConnecttype(STConnectType.RECT);
+
+            xml.toEndToken();
+            final XmlCursor grpCur = grp.newCursor();
+            try {
+                grpCur.copyXmlContents(xml);
+            } finally {
+                grpCur.dispose();
+            }
+        } finally {
+            xml.dispose();
+        }
 
-        CTGroup grp = CTGroup.Factory.newInstance();
-        CTShapetype shapetype = grp.addNewShapetype();
-        _shapeTypeId = COMMENT_SHAPE_TYPE_ID;
-        shapetype.setId(_shapeTypeId);
-        shapetype.setCoordsize("21600,21600");
-        shapetype.setSpt(202);
-        shapetype.setPath2("m,l,21600r21600,l21600,xe");
-        shapetype.addNewStroke().setJoinstyle(STStrokeJoinStyle.MITER);
-        CTPath path = shapetype.addNewPath();
-        path.setGradientshapeok(STTrueFalse.T);
-        path.setConnecttype(STConnectType.RECT);
-
-        xml.toEndToken();
-        XmlCursor grpCur = grp.newCursor();
-        grpCur.copyXmlContents(xml);
-        grpCur.dispose();
     }
 
     /**
@@ -269,13 +279,19 @@ public final class XSSFVMLDrawing extends POIXMLDocumentPart {
         cldata.addNewColumn().setBigIntegerValue(BigInteger.valueOf(0));
 
         XmlCursor xml = root.getXml().newCursor();
-        xml.toEndToken();
-        XmlCursor grpCur = grp.newCursor();
-        grpCur.copyXmlContents(xml);
-        xml.toPrevSibling();
-        shape = (CTShape)xml.getObject();
-        grpCur.dispose();
-        xml.dispose();
+        try {
+            xml.toEndToken();
+            XmlCursor grpCur = grp.newCursor();
+            try {
+                grpCur.copyXmlContents(xml);
+                xml.toPrevSibling();
+                shape = (CTShape)xml.getObject();
+            } finally {
+                grpCur.dispose();
+            }
+        } finally {
+            xml.dispose();
+        }
 
         return shape;
     }
@@ -287,11 +303,15 @@ public final class XSSFVMLDrawing extends POIXMLDocumentPart {
      */
     public CTShape findCommentShape(int row, int col){
         XmlCursor cur = root.getXml().newCursor();
-        for (boolean found = cur.toFirstChild(); found; found = cur.toNextSibling()) {
-            XmlObject itm = cur.getObject();
-            if (matchCommentShape(itm, row, col)) {
-                return (CTShape)itm;
+        try {
+            for (boolean found = cur.toFirstChild(); found; found = cur.toNextSibling()) {
+                XmlObject itm = cur.getObject();
+                if (matchCommentShape(itm, row, col)) {
+                    return (CTShape)itm;
+                }
             }
+        } finally {
+            cur.dispose();
         }
         return null;
     }
@@ -318,12 +338,16 @@ public final class XSSFVMLDrawing extends POIXMLDocumentPart {
 
     protected boolean removeCommentShape(int row, int col){
         XmlCursor cur = root.getXml().newCursor();
-        for (boolean found = cur.toFirstChild(); found; found = cur.toNextSibling()) {
-            XmlObject itm = cur.getObject();
-            if (matchCommentShape(itm, row, col)) {
-                cur.removeXml();
-                return true;
+        try {
+            for (boolean found = cur.toFirstChild(); found; found = cur.toNextSibling()) {
+                XmlObject itm = cur.getObject();
+                if (matchCommentShape(itm, row, col)) {
+                    cur.removeXml();
+                    return true;
+                }
             }
+        } finally {
+            cur.dispose();
         }
         return false;
     }
index 2933bc8c44d5fd47748ade9f6482d2ced24d5910..fafac08ee9a3d47ed6c7d49ecbf1c3adc3eef381 100644 (file)
@@ -50,41 +50,43 @@ public final class XSSFPasswordHelper {
      */
     public static void setPassword(XmlObject xobj, String password, HashAlgorithm hashAlgo, String prefix) {
         XmlCursor cur = xobj.newCursor();
+        try {
+            if (password == null) {
+                cur.removeAttribute(getAttrName(prefix, "password"));
+                cur.removeAttribute(getAttrName(prefix, "algorithmName"));
+                cur.removeAttribute(getAttrName(prefix, "hashValue"));
+                cur.removeAttribute(getAttrName(prefix, "saltValue"));
+                cur.removeAttribute(getAttrName(prefix, "spinCount"));
+                return;
+            }
 
-        if (password == null) {
-            cur.removeAttribute(getAttrName(prefix, "password"));
-            cur.removeAttribute(getAttrName(prefix, "algorithmName"));
-            cur.removeAttribute(getAttrName(prefix, "hashValue"));
-            cur.removeAttribute(getAttrName(prefix, "saltValue"));
-            cur.removeAttribute(getAttrName(prefix, "spinCount"));
-            return;
-        } 
-        
-        cur.toFirstContentToken();
-        if (hashAlgo == null) {
-            int hash = CryptoFunctions.createXorVerifier1(password);
-            cur.insertAttributeWithValue(getAttrName(prefix, "password"),
-                                         String.format(Locale.ROOT, "%04X", hash).toUpperCase(Locale.ROOT));
-        } else {
-            byte[] salt = RandomSingleton.getInstance().generateSeed(16);
-    
-            // Iterations specifies the number of times the hashing function shall be iteratively run (using each
-            // iteration's result as the input for the next iteration).
-            int spinCount = 100000;
+            cur.toFirstContentToken();
+            if (hashAlgo == null) {
+                int hash = CryptoFunctions.createXorVerifier1(password);
+                cur.insertAttributeWithValue(getAttrName(prefix, "password"),
+                        String.format(Locale.ROOT, "%04X", hash).toUpperCase(Locale.ROOT));
+            } else {
+                byte[] salt = RandomSingleton.getInstance().generateSeed(16);
+
+                // Iterations specifies the number of times the hashing function shall be iteratively run (using each
+                // iteration's result as the input for the next iteration).
+                int spinCount = 100000;
 
-            // Implementation Notes List:
-            // --> In this third stage, the reversed byte order legacy hash from the second stage shall
-            //     be converted to Unicode hex string representation
-            byte[] hash = CryptoFunctions.hashPassword(password, hashAlgo, salt, spinCount, false);
+                // Implementation Notes List:
+                // --> In this third stage, the reversed byte order legacy hash from the second stage shall
+                //     be converted to Unicode hex string representation
+                byte[] hash = CryptoFunctions.hashPassword(password, hashAlgo, salt, spinCount, false);
 
-            Base64.Encoder enc64 = Base64.getEncoder();
+                Base64.Encoder enc64 = Base64.getEncoder();
 
-            cur.insertAttributeWithValue(getAttrName(prefix, "algorithmName"), hashAlgo.jceId); 
-            cur.insertAttributeWithValue(getAttrName(prefix, "hashValue"), enc64.encodeToString(hash));
-            cur.insertAttributeWithValue(getAttrName(prefix, "saltValue"), enc64.encodeToString(salt));
-            cur.insertAttributeWithValue(getAttrName(prefix, "spinCount"), ""+spinCount);
+                cur.insertAttributeWithValue(getAttrName(prefix, "algorithmName"), hashAlgo.jceId);
+                cur.insertAttributeWithValue(getAttrName(prefix, "hashValue"), enc64.encodeToString(hash));
+                cur.insertAttributeWithValue(getAttrName(prefix, "saltValue"), enc64.encodeToString(salt));
+                cur.insertAttributeWithValue(getAttrName(prefix, "spinCount"), ""+spinCount);
+            }
+        } finally {
+            cur.dispose();
         }
-        cur.dispose();
     }
 
     /**
@@ -103,30 +105,32 @@ public final class XSSFPasswordHelper {
         if (password == null) return false;
         
         XmlCursor cur = xobj.newCursor();
-        String xorHashVal = cur.getAttributeText(getAttrName(prefix, "password"));
-        String algoName = cur.getAttributeText(getAttrName(prefix, "algorithmName"));
-        String hashVal = cur.getAttributeText(getAttrName(prefix, "hashValue"));
-        String saltVal = cur.getAttributeText(getAttrName(prefix, "saltValue"));
-        String spinCount = cur.getAttributeText(getAttrName(prefix, "spinCount"));
-        cur.dispose();
+        try {
+            String xorHashVal = cur.getAttributeText(getAttrName(prefix, "password"));
+            String algoName = cur.getAttributeText(getAttrName(prefix, "algorithmName"));
+            String hashVal = cur.getAttributeText(getAttrName(prefix, "hashValue"));
+            String saltVal = cur.getAttributeText(getAttrName(prefix, "saltValue"));
+            String spinCount = cur.getAttributeText(getAttrName(prefix, "spinCount"));
+            if (xorHashVal != null) {
+                int hash1 = Integer.parseInt(xorHashVal, 16);
+                int hash2 = CryptoFunctions.createXorVerifier1(password);
+                return hash1 == hash2;
+            } else {
+                if (hashVal == null || algoName == null || saltVal == null || spinCount == null) {
+                    return false;
+                }
 
-        if (xorHashVal != null) {
-            int hash1 = Integer.parseInt(xorHashVal, 16);
-            int hash2 = CryptoFunctions.createXorVerifier1(password);
-            return hash1 == hash2;
-        } else {
-            if (hashVal == null || algoName == null || saltVal == null || spinCount == null) {
-                return false;
-            }
+                Base64.Decoder dec64 = Base64.getDecoder();
 
-            Base64.Decoder dec64 = Base64.getDecoder();
-
-            byte[] hash1 = dec64.decode(hashVal);
-            HashAlgorithm hashAlgo = HashAlgorithm.fromString(algoName);
-            byte[] salt = dec64.decode(saltVal);
-            int spinCnt = Integer.parseInt(spinCount);
-            byte[] hash2 = CryptoFunctions.hashPassword(password, hashAlgo, salt, spinCnt, false);
-            return Arrays.equals(hash1, hash2);
+                byte[] hash1 = dec64.decode(hashVal);
+                HashAlgorithm hashAlgo = HashAlgorithm.fromString(algoName);
+                byte[] salt = dec64.decode(saltVal);
+                int spinCnt = Integer.parseInt(spinCount);
+                byte[] hash2 = CryptoFunctions.hashPassword(password, hashAlgo, salt, spinCnt, false);
+                return Arrays.equals(hash1, hash2);
+            }
+        } finally {
+            cur.dispose();
         }
     }
     
index e1e0df9bb3f5dde75dfebc50284467535067bbf9..7c97b908cd8512072d0723d2aef7c17574cdd364 100644 (file)
@@ -73,26 +73,29 @@ public abstract class XWPFAbstractFootnoteEndnote  implements Iterable<XWPFParag
 
     protected void init() {
         XmlCursor cursor = ctFtnEdn.newCursor();
-        //copied from XWPFDocument...should centralize this code
-        //to avoid duplication
-        cursor.selectPath("./*");
-        while (cursor.toNextSelection()) {
-            XmlObject o = cursor.getObject();
-            if (o instanceof CTP) {
-                XWPFParagraph p = new XWPFParagraph((CTP) o, this);
-                bodyElements.add(p);
-                paragraphs.add(p);
-            } else if (o instanceof CTTbl) {
-                XWPFTable t = new XWPFTable((CTTbl) o, this);
-                bodyElements.add(t);
-                tables.add(t);
-            } else if (o instanceof CTSdtBlock) {
-                XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this);
-                bodyElements.add(c);
-            }
+        try {
+            //copied from XWPFDocument...should centralize this code
+            //to avoid duplication
+            cursor.selectPath("./*");
+            while (cursor.toNextSelection()) {
+                XmlObject o = cursor.getObject();
+                if (o instanceof CTP) {
+                    XWPFParagraph p = new XWPFParagraph((CTP) o, this);
+                    bodyElements.add(p);
+                    paragraphs.add(p);
+                } else if (o instanceof CTTbl) {
+                    XWPFTable t = new XWPFTable((CTTbl) o, this);
+                    bodyElements.add(t);
+                    tables.add(t);
+                } else if (o instanceof CTSdtBlock) {
+                    XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this);
+                    bodyElements.add(c);
+                }
 
+            }
+        } finally {
+            cursor.dispose();
         }
-        cursor.dispose();
     }
 
     /**
@@ -283,10 +286,13 @@ public abstract class XWPFAbstractFootnoteEndnote  implements Iterable<XWPFParag
      */
     private boolean isCursorInFtn(XmlCursor cursor) {
         XmlCursor verify = cursor.newCursor();
-        verify.toParent();
-        boolean result = (verify.getObject() == this.ctFtnEdn);
-        verify.dispose();
-        return result;
+        try {
+            verify.toParent();
+            return  (verify.getObject() == this.ctFtnEdn);
+        } finally {
+            verify.dispose();
+
+        }
     }
 
     /**
@@ -331,9 +337,12 @@ public abstract class XWPFAbstractFootnoteEndnote  implements Iterable<XWPFParag
             }
             bodyElements.add(i, newT);
             XmlCursor c2 = t.newCursor();
-            cursor.toCursor(c2);
-            cursor.toEndToken();
-            c2.dispose();
+            try {
+                cursor.toCursor(c2);
+                cursor.toEndToken();
+            } finally {
+                c2.dispose();
+            }
             return newT;
         }
         return null;
@@ -365,8 +374,11 @@ public abstract class XWPFAbstractFootnoteEndnote  implements Iterable<XWPFParag
             }
             int i = 0;
             XmlCursor p2 = p.newCursor();
-            cursor.toCursor(p2);
-            p2.dispose();
+            try {
+                cursor.toCursor(p2);
+            } finally {
+                p2.dispose();
+            }
             while (cursor.toPrevSibling()) {
                 o = cursor.getObject();
                 if (o instanceof CTP || o instanceof CTTbl)
index c86ce8b74d2467f5a872612256a041c66251b916..90f7bc1f0ecbe846dc703c949d51a7eefdcb8feb 100644 (file)
@@ -48,22 +48,25 @@ public class XWPFFooter extends XWPFHeaderFooter {
     public XWPFFooter(XWPFDocument doc, CTHdrFtr hdrFtr) throws IOException {
         super(doc, hdrFtr);
         XmlCursor cursor = headerFooter.newCursor();
-        cursor.selectPath("./*");
-        while (cursor.toNextSelection()) {
-            XmlObject o = cursor.getObject();
-            if (o instanceof CTP) {
-                XWPFParagraph p = new XWPFParagraph((CTP) o, this);
-                paragraphs.add(p);
-                bodyElements.add(p);
-            }
-            if (o instanceof CTTbl) {
-                XWPFTable t = new XWPFTable((CTTbl) o, this);
-                tables.add(t);
-                bodyElements.add(t);
-            }
+        try {
+            cursor.selectPath("./*");
+            while (cursor.toNextSelection()) {
+                XmlObject o = cursor.getObject();
+                if (o instanceof CTP) {
+                    XWPFParagraph p = new XWPFParagraph((CTP) o, this);
+                    paragraphs.add(p);
+                    bodyElements.add(p);
+                }
+                if (o instanceof CTTbl) {
+                    XWPFTable t = new XWPFTable((CTTbl) o, this);
+                    tables.add(t);
+                    bodyElements.add(t);
+                }
 
+            }
+        } finally {
+            cursor.dispose();
         }
-        cursor.dispose();
     }
 
     /**
@@ -96,25 +99,28 @@ public class XWPFFooter extends XWPFHeaderFooter {
             // parse the document with cursor and add
             // the XmlObject to its lists
             XmlCursor cursor = headerFooter.newCursor();
-            cursor.selectPath("./*");
-            while (cursor.toNextSelection()) {
-                XmlObject o = cursor.getObject();
-                if (o instanceof CTP) {
-                    XWPFParagraph p = new XWPFParagraph((CTP) o, this);
-                    paragraphs.add(p);
-                    bodyElements.add(p);
-                }
-                if (o instanceof CTTbl) {
-                    XWPFTable t = new XWPFTable((CTTbl) o, this);
-                    tables.add(t);
-                    bodyElements.add(t);
-                }
-                if (o instanceof CTSdtBlock) {
-                    XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this);
-                    bodyElements.add(c);
+            try {
+                cursor.selectPath("./*");
+                while (cursor.toNextSelection()) {
+                    XmlObject o = cursor.getObject();
+                    if (o instanceof CTP) {
+                        XWPFParagraph p = new XWPFParagraph((CTP) o, this);
+                        paragraphs.add(p);
+                        bodyElements.add(p);
+                    }
+                    if (o instanceof CTTbl) {
+                        XWPFTable t = new XWPFTable((CTTbl) o, this);
+                        tables.add(t);
+                        bodyElements.add(t);
+                    }
+                    if (o instanceof CTSdtBlock) {
+                        XWPFSDT c = new XWPFSDT((CTSdtBlock) o, this);
+                        bodyElements.add(c);
+                    }
                 }
+            } finally {
+                cursor.dispose();
             }
-            cursor.dispose();
         } catch (Exception e) {
             throw new POIXMLException(e);
         }