You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@pdfbox.apache.org by ja...@apache.org on 2014/03/13 21:43:48 UTC

svn commit: r1577312 - in /pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel: PDDocument.java PDPageNode.java interactive/form/PDAcroForm.java

Author: jahewson
Date: Thu Mar 13 20:43:47 2014
New Revision: 1577312

URL: http://svn.apache.org/r1577312
Log:
PDFBOX-1985: Enhance type safety and cleanup

Modified:
    pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDDocument.java
    pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDPageNode.java
    pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDAcroForm.java

Modified: pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDDocument.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDDocument.java?rev=1577312&r1=1577311&r2=1577312&view=diff
==============================================================================
--- pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDDocument.java (original)
+++ pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDDocument.java Thu Mar 13 20:43:47 2014
@@ -68,52 +68,42 @@ import org.apache.pdfbox.pdmodel.interac
 import org.apache.pdfbox.pdmodel.interactive.form.PDSignatureField;
 
 /**
- * This is the in-memory representation of the PDF document. You need to call close() on this object when you are done
- * using it!!
- * 
- * @author <a href="mailto:ben@benlitchfield.com">Ben Litchfield</a>
+ * This is the in-memory representation of the PDF document.
+ * The #close() method must be called once the document is no longer needed.
  * 
+ * @author Ben Litchfield
  */
 public class PDDocument implements Closeable
 {
-
     private COSDocument document;
 
     // cached values
     private PDDocumentInformation documentInformation;
     private PDDocumentCatalog documentCatalog;
 
-    // The encParameters will be cached here. When the document is decrypted then
-    // the COSDocument will not have an "Encrypt" dictionary anymore and this object
-    // must be used.
-    private PDEncryptionDictionary encParameters = null;
+    // the encParameters will be cached here. When the document is decrypted then
+    // the COSDocument will not have an "Encrypt" dictionary anymore and this object must be used
+    private PDEncryptionDictionary encParameters;
+
+    // the security handler used to decrypt / encrypt the document
+    private SecurityHandler securityHandler;
+
+    // associates object ids with a page number. Used to determine the page number for bookmarks
+    // (or page numbers for anything else for which you have an object id for that matter)
+    private Map<String, Integer> pageMap;
 
-    /**
-     * The security handler used to decrypt / encrypt the document.
-     */
-    private SecurityHandler securityHandler = null;
-
-    /**
-     * This assocates object ids with a page number. It's used to determine the page number for bookmarks (or page
-     * numbers for anything else for which you have an object id for that matter).
-     */
-    private Map<String, Integer> pageMap = null;
+    // holds a flag which tells us if we should remove all security from this documents.
+    private boolean allSecurityToBeRemoved;
 
-    /**
-     * This will hold a flag which tells us if we should remove all security from this documents.
-     */
-    private boolean allSecurityToBeRemoved = false;
-
-    /**
-     * Keep tracking customized documentId for the trailer. If null, a new id will be generated for the document. This
-     * ID doesn't represent the actual documentId from the trailer.
-     */
+    // keep tracking customized documentId for the trailer. If null, a new id will be generated
+    // this ID doesn't represent the actual documentId from the trailer
     private Long documentId;
 
     private BaseParser parser; 
+
     /**
-     * Constructor, creates a new PDF Document with no pages. You need to add at least one page for the document to be
-     * valid.
+     * Creates an empty PDF document.
+     * You need to add at least one page for the document to be valid.
      * 
      * @throws IOException If there is an error creating this document.
      */
@@ -168,10 +158,8 @@ public class PDDocument implements Close
         }
     }
 
-    /**
-     * This will either add the page passed in, or, if it's a pointer to an array of pages, it'll recursivly call itself
-     * and process everything in the list.
-     */
+    // either adds the page passed in, or, if it's a pointer to an array of pages,
+    // it will recursively call itself and process everything in the list
     private void parseCatalogObject(COSObject thePageOrArrayObject)
     {
         COSBase arrayCountBase = thePageOrArrayObject.getItem(COSName.COUNT);
@@ -193,7 +181,7 @@ public class PDDocument implements Close
             // these cases occur when we have a page, not an array of pages
             String objStr = String.valueOf(thePageOrArrayObject.getObjectNumber().intValue());
             String genStr = String.valueOf(thePageOrArrayObject.getGenerationNumber().intValue());
-            getPageMap().put(objStr + "," + genStr, new Integer(getPageMap().size() + 1));
+            getPageMap().put(objStr + "," + genStr, getPageMap().size() + 1);
         }
         else
         {
@@ -201,29 +189,22 @@ public class PDDocument implements Close
             if (arrayCount == kidsCount)
             {
                 // process the kids... they're all references to pages
-                COSArray kidsArray = ((COSArray) kidsBase);
+                COSArray kidsArray = (COSArray) kidsBase;
                 for (int i = 0; i < kidsArray.size(); ++i)
                 {
                     COSObject thisObject = (COSObject) kidsArray.get(i);
                     String objStr = String.valueOf(thisObject.getObjectNumber().intValue());
                     String genStr = String.valueOf(thisObject.getGenerationNumber().intValue());
-                    getPageMap().put(objStr + "," + genStr, new Integer(getPageMap().size() + 1));
+                    getPageMap().put(objStr + "," + genStr, getPageMap().size() + 1);
                 }
             }
             else
             {
                 // this object is an array of references to other arrays
-                COSArray list = null;
-                if (kidsBase instanceof COSArray)
+                COSArray list = (COSArray) kidsBase;
+                for (int arrayCounter = 0; arrayCounter < list.size(); ++arrayCounter)
                 {
-                    list = ((COSArray) kidsBase);
-                }
-                if (list != null)
-                {
-                    for (int arrayCounter = 0; arrayCounter < list.size(); ++arrayCounter)
-                    {
-                        parseCatalogObject((COSObject) list.get(arrayCounter));
-                    }
+                    parseCatalogObject((COSObject) list.get(arrayCounter));
                 }
             }
         }
@@ -494,9 +475,12 @@ public class PDDocument implements Close
             annotations = new COSArrayList();
             page.setAnnotations(annotations);
         }
+
         // take care that page and acroforms do not share the same array (if so, we don't need to add it twice)
-        if (!((annotations instanceof COSArrayList) && (acroFormFields instanceof COSArrayList) && (((COSArrayList) annotations)
-                .toList().equals(((COSArrayList) acroFormFields).toList()))) && !checkFields)
+        if (!(annotations instanceof COSArrayList &&
+              acroFormFields instanceof COSArrayList &&
+              ((COSArrayList) annotations).toList().equals(((COSArrayList) acroFormFields).toList()) &&
+              checkFields))
         {
             annotations.add(signatureField.getWidget());
         }
@@ -1236,8 +1220,7 @@ public class PDDocument implements Close
      * @param output stream to write
      * @throws IOException if the output could not be written
      */
-    public void saveIncremental(FileInputStream input, OutputStream output)
-            throws IOException
+    public void saveIncremental(FileInputStream input, OutputStream output) throws IOException
     {
         // update the count in case any pages have been added behind the scenes.
         getDocumentCatalog().getPages().updateCount();
@@ -1288,26 +1271,27 @@ public class PDDocument implements Close
      * 
      * @throws IOException If there is an error releasing resources.
      */
+    @Override
     public void close() throws IOException
     {
-    	documentCatalog = null;
-    	documentInformation = null;
-    	encParameters = null;
-    	if (pageMap != null)
-    	{
-    		pageMap.clear();
-    		pageMap = null;
-    	}
-    	securityHandler = null;
-    	if (document != null)
-    	{
-	        document.close();
-	        document = null;
-    	}
+        documentCatalog = null;
+        documentInformation = null;
+        encParameters = null;
+        if (pageMap != null)
+        {
+            pageMap.clear();
+            pageMap = null;
+        }
+        securityHandler = null;
+        if (document != null)
+        {
+            document.close();
+            document = null;
+        }
         if (parser != null)
         {
-        	parser.clearResources();
-        	parser = null;
+            parser.clearResources();
+            parser = null;
         }
     }
 
@@ -1371,7 +1355,7 @@ public class PDDocument implements Close
 
     public AccessPermission getCurrentAccessPermission()
     {
-        if (this.securityHandler == null)
+        if (securityHandler == null)
         {
             return AccessPermission.getOwnerAccessPermission();
         }

Modified: pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDPageNode.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDPageNode.java?rev=1577312&r1=1577311&r2=1577312&view=diff
==============================================================================
--- pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDPageNode.java (original)
+++ pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/PDPageNode.java Thu Mar 13 20:43:47 2014
@@ -34,29 +34,27 @@ import java.util.Iterator;
 import java.util.List;
 
 /**
- * This represents a page node in a pdf document.
+ * A page tree node. This is an intermediate node in the page tree, and may have page objects or
+ * other page tree nodes as children, but does not itself represent a page.
  *
- * @author <a href="mailto:ben@benlitchfield.com">Ben Litchfield</a>
- * @version $Revision: 1.8 $
+ * @author Ben Litchfield
  */
 public class PDPageNode implements COSObjectable
 {
-    private COSDictionary page;
-
-    /**
-     * Log instance.
-     */
     private static final Log log = LogFactory.getLog(PDPageNode.class);
 
+    private COSDictionary node;
+
     /**
      * Creates a new instance of PDPage.
+     * Creates a new instance of PDPage.
      */
     public PDPageNode()
     {
-        page = new COSDictionary();
-        page.setItem( COSName.TYPE, COSName.PAGES );
-        page.setItem( COSName.KIDS, new COSArray() );
-        page.setItem( COSName.COUNT, COSInteger.ZERO );
+        node = new COSDictionary();
+        node.setItem(COSName.TYPE, COSName.PAGES);
+        node.setItem(COSName.KIDS, new COSArray());
+        node.setItem(COSName.COUNT, COSInteger.ZERO);
     }
 
     /**
@@ -66,7 +64,7 @@ public class PDPageNode implements COSOb
      */
     public PDPageNode( COSDictionary pages )
     {
-        page = pages;
+        node = pages;
     }
 
     /**
@@ -95,22 +93,22 @@ public class PDPageNode implements COSOb
                 totalCount += node.updateCount();
             }
         }
-        page.setLong( COSName.COUNT, totalCount );
+        node.setLong(COSName.COUNT, totalCount);
         return totalCount;
     }
 
     /**
-     * This will get the count of descendent page objects.
+     * This will get the count of descendant page objects.
      *
-     * @return The total number of descendent page objects.
+     * @return The total number of descendant page objects.
      */
     public long getCount()
     {
-        if(page == null)
+        if(node == null)
         {
             return 0L;
         }
-        COSBase num = page.getDictionaryObject(COSName.COUNT);
+        COSBase num = node.getDictionaryObject(COSName.COUNT);
         if(num == null)
         {
             return 0L;
@@ -125,7 +123,7 @@ public class PDPageNode implements COSOb
      */
     public COSDictionary getDictionary()
     {
-        return page;
+        return node;
     }
 
     /**
@@ -136,7 +134,7 @@ public class PDPageNode implements COSOb
     public PDPageNode getParent()
     {
         PDPageNode parent = null;
-        COSDictionary parentDic = (COSDictionary)page.getDictionaryObject(COSName.PARENT, COSName.P);
+        COSDictionary parentDic = (COSDictionary) node.getDictionaryObject(COSName.PARENT, COSName.P);
         if( parentDic != null )
         {
             parent = new PDPageNode( parentDic );
@@ -151,52 +149,52 @@ public class PDPageNode implements COSOb
      */
     public void setParent( PDPageNode parent )
     {
-        page.setItem( COSName.PARENT, parent.getDictionary() );
+        node.setItem(COSName.PARENT, parent.getDictionary());
     }
 
-    /**
-     * {@inheritDoc}
-     */
+    @Override
     public COSBase getCOSObject()
     {
-        return page;
+        return node;
     }
 
     /**
      * This will return all kids of this node, either PDPageNode or PDPage.
      *
-     * @return All direct descendents of this node.
+     * @return All direct descendants of this node.
      */
     public List getKids()
     {
         List actuals = new ArrayList();
-        COSArray kids = getAllKids(actuals, page, false);
+        COSArray kids = getAllKids(actuals, node, false);
         return new COSArrayList( actuals, kids );
     }
 
     /**
      * This will return all kids of this node as PDPage.
      *
-     * @param result All direct and indirect descendents of this node are added to this list.
+     * @param result All direct and indirect descendants of this node are added to this list.
      */
     public void getAllKids(List result)
     {
-        getAllKids(result, page, true);
+        getAllKids(result, node, true);
     }
 
     /**
      * This will return all kids of the given page node as PDPage.
      *
-     * @param result All direct and optionally indirect descendents of this node are added to this list.
+     * @param result All direct and optionally indirect descendants of this node are added to this list.
      * @param page Page dictionary of a page node.
-     * @param recurse if true indirect descendents are processed recursively
+     * @param recurse if true indirect descendants are processed recursively
      */
     private static COSArray getAllKids(List result, COSDictionary page, boolean recurse)
     {
-        if(page == null)
+        if( page == null )
+        {
             return null;
+        }
         COSArray kids = (COSArray)page.getDictionaryObject( COSName.KIDS );
-        if ( kids == null)
+        if( kids == null)
         {
             log.error("No Kids found in getAllKids(). Probably a malformed pdf.");
             return null;
@@ -237,7 +235,7 @@ public class PDPageNode implements COSOb
     public PDResources getResources()
     {
         PDResources retval = null;
-        COSDictionary resources = (COSDictionary)page.getDictionaryObject( COSName.RESOURCES );
+        COSDictionary resources = (COSDictionary) node.getDictionaryObject( COSName.RESOURCES );
         if( resources != null )
         {
             retval = new PDResources( resources );
@@ -271,11 +269,11 @@ public class PDPageNode implements COSOb
     {
         if( resources == null )
         {
-            page.removeItem( COSName.RESOURCES );
+            node.removeItem(COSName.RESOURCES);
         }
         else
         {
-            page.setItem( COSName.RESOURCES, resources.getCOSDictionary() );
+            node.setItem(COSName.RESOURCES, resources.getCOSDictionary());
         }
     }
 
@@ -289,7 +287,7 @@ public class PDPageNode implements COSOb
     public PDRectangle getMediaBox()
     {
         PDRectangle retval = null;
-        COSArray array = (COSArray)page.getDictionaryObject( COSName.MEDIA_BOX );
+        COSArray array = (COSArray) node.getDictionaryObject( COSName.MEDIA_BOX );
         if( array != null )
         {
             retval = new PDRectangle( array );
@@ -323,11 +321,11 @@ public class PDPageNode implements COSOb
     {
         if( mediaBox == null )
         {
-            page.removeItem( COSName.MEDIA_BOX  );
+            node.removeItem(COSName.MEDIA_BOX);
         }
         else
         {
-            page.setItem( COSName.MEDIA_BOX , mediaBox.getCOSArray() );
+            node.setItem(COSName.MEDIA_BOX, mediaBox.getCOSArray());
         }
     }
 
@@ -341,7 +339,7 @@ public class PDPageNode implements COSOb
     public PDRectangle getCropBox()
     {
         PDRectangle retval = null;
-        COSArray array = (COSArray)page.getDictionaryObject( COSName.CROP_BOX );
+        COSArray array = (COSArray) node.getDictionaryObject( COSName.CROP_BOX );
         if( array != null )
         {
             retval = new PDRectangle( array );
@@ -398,11 +396,11 @@ public class PDPageNode implements COSOb
     {
         if( cropBox == null )
         {
-            page.removeItem( COSName.CROP_BOX );
+            node.removeItem(COSName.CROP_BOX);
         }
         else
         {
-            page.setItem( COSName.CROP_BOX, cropBox.getCOSArray() );
+            node.setItem(COSName.CROP_BOX, cropBox.getCOSArray());
         }
     }
 
@@ -421,10 +419,10 @@ public class PDPageNode implements COSOb
     public Integer getRotation()
     {
         Integer retval = null;
-        COSNumber value = (COSNumber)page.getDictionaryObject( COSName.ROTATE );
+        COSNumber value = (COSNumber) node.getDictionaryObject( COSName.ROTATE );
         if( value != null )
         {
-            retval = new Integer( value.intValue() );
+            retval = value.intValue();
         }
         return retval;
     }
@@ -441,7 +439,7 @@ public class PDPageNode implements COSOb
         Integer rotation = getRotation();
         if( rotation != null )
         {
-            retval = rotation.intValue();
+            retval = rotation;
         }
         else
         {
@@ -462,6 +460,6 @@ public class PDPageNode implements COSOb
      */
     public void setRotation( int rotation )
     {
-        page.setInt( COSName.ROTATE, rotation );
+        node.setInt(COSName.ROTATE, rotation);
     }
 }

Modified: pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDAcroForm.java
URL: http://svn.apache.org/viewvc/pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDAcroForm.java?rev=1577312&r1=1577311&r2=1577312&view=diff
==============================================================================
--- pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDAcroForm.java (original)
+++ pdfbox/trunk/pdfbox/src/main/java/org/apache/pdfbox/pdmodel/interactive/form/PDAcroForm.java Thu Mar 13 20:43:47 2014
@@ -184,31 +184,29 @@ public final class PDAcroForm implements
      * @return A list of all the fields.
      * @throws IOException If there is an error while getting the list of fields.
      */
-    public List getFields() throws IOException
+    public List<PDField> getFields() throws IOException
     {
-        List retval = null;
-        COSArray fields =
-            (COSArray) acroForm.getDictionaryObject(
-                COSName.getPDFName("Fields"));
+        COSArray cosFields = (COSArray) acroForm.getDictionaryObject(COSName.getPDFName("Fields"));
 
-        if( fields != null )
+        if( cosFields == null )
         {
-            List actuals = new ArrayList();
-            for (int i = 0; i < fields.size(); i++)
+            return null;
+        }
+
+        List<PDField> pdFields = new ArrayList<PDField>();
+        for (int i = 0; i < cosFields.size(); i++)
+        {
+            COSDictionary element = (COSDictionary) cosFields.getObject(i);
+            if (element != null)
             {
-                COSDictionary element = (COSDictionary) fields.getObject(i);
-                if (element != null)
+                PDField field = PDFieldFactory.createField( this, element );
+                if( field != null )
                 {
-                    PDField field = PDFieldFactory.createField( this, element );
-                    if( field != null )
-                    {
-                        actuals.add(field);
-                    }
+                    pdFields.add(field);
                 }
             }
-            retval = new COSArrayList( actuals, fields );
         }
-        return retval;
+        return new COSArrayList<PDField>( pdFields, cosFields );
     }
 
     /**
@@ -348,9 +346,7 @@ public final class PDAcroForm implements
         acroForm.setItem( COSName.getPDFName( "DR" ), drDict );
     }
 
-    /**
-     * {@inheritDoc}
-     */
+    @Override
     public COSBase getCOSObject()
     {
         return acroForm;