You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@poi.apache.org by fa...@apache.org on 2017/10/31 10:24:47 UTC

svn commit: r1813869 [1/2] - in /poi/trunk/src: java/org/apache/poi/hssf/model/ ooxml/java/org/apache/poi/ ooxml/java/org/apache/poi/openxml4j/opc/ ooxml/java/org/apache/poi/openxml4j/opc/internal/ ooxml/java/org/apache/poi/xssf/eventusermodel/ ooxml/j...

Author: fanningpj
Date: Tue Oct 31 10:24:47 2017
New Revision: 1813869

URL: http://svn.apache.org/viewvc?rev=1813869&view=rev
Log:
use StringBuilder in more places

Modified:
    poi/trunk/src/java/org/apache/poi/hssf/model/LinkTable.java
    poi/trunk/src/ooxml/java/org/apache/poi/POIXMLPropertiesTextExtractor.java
    poi/trunk/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagingURIHelper.java
    poi/trunk/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentType.java
    poi/trunk/src/ooxml/java/org/apache/poi/xssf/eventusermodel/ReadOnlySharedStringsTable.java
    poi/trunk/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFSheetXMLHandler.java
    poi/trunk/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFBEventBasedExcelExtractor.java
    poi/trunk/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFEventBasedExcelExtractor.java
    poi/trunk/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChart.java
    poi/trunk/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/HeaderFooterHelper.java
    poi/trunk/src/ooxml/java/org/apache/poi/xwpf/extractor/XWPFWordExtractor.java
    poi/trunk/src/ooxml/java/org/apache/poi/xwpf/model/XWPFCommentsDecorator.java
    poi/trunk/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFComment.java
    poi/trunk/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java
    poi/trunk/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFParagraph.java
    poi/trunk/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRun.java
    poi/trunk/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTable.java
    poi/trunk/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTableCell.java

Modified: poi/trunk/src/java/org/apache/poi/hssf/model/LinkTable.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/java/org/apache/poi/hssf/model/LinkTable.java?rev=1813869&r1=1813868&r2=1813869&view=diff
==============================================================================
--- poi/trunk/src/java/org/apache/poi/hssf/model/LinkTable.java (original)
+++ poi/trunk/src/java/org/apache/poi/hssf/model/LinkTable.java Tue Oct 31 10:24:47 2017
@@ -41,137 +41,139 @@ import org.apache.poi.ss.usermodel.Workb
 
 /**
  * Link Table (OOO pdf reference: 4.10.3 ) <p>
- *
+ * <p>
  * The main data of all types of references is stored in the Link Table inside the Workbook Globals
  * Substream (4.2.5). The Link Table itself is optional and occurs only if there are any
  * references in the document.
- *  <p>
- *
- *  In BIFF8 the Link Table consists of
- *  <ul>
- *  <li>zero or more EXTERNALBOOK Blocks<p>
- *  	each consisting of
- *  	<ul>
- *  	<li>exactly one EXTERNALBOOK (0x01AE) record</li>
- *  	<li>zero or more EXTERNALNAME (0x0023) records</li>
- *  	<li>zero or more CRN Blocks<p>
- *			each consisting of
- *  		<ul>
- *  		<li>exactly one XCT (0x0059)record</li>
- *  		<li>zero or more CRN (0x005A) records (documentation says one or more)</li>
- *  		</ul>
- *  	</li>
- *  	</ul>
- *  </li>
- *  <li>zero or one EXTERNSHEET (0x0017) record</li>
- *  <li>zero or more DEFINEDNAME (0x0018) records</li>
- *  </ul>
+ * <p>
+ * <p>
+ * In BIFF8 the Link Table consists of
+ * <ul>
+ * <li>zero or more EXTERNALBOOK Blocks<p>
+ * each consisting of
+ * <ul>
+ * <li>exactly one EXTERNALBOOK (0x01AE) record</li>
+ * <li>zero or more EXTERNALNAME (0x0023) records</li>
+ * <li>zero or more CRN Blocks<p>
+ * each consisting of
+ * <ul>
+ * <li>exactly one XCT (0x0059)record</li>
+ * <li>zero or more CRN (0x005A) records (documentation says one or more)</li>
+ * </ul>
+ * </li>
+ * </ul>
+ * </li>
+ * <li>zero or one EXTERNSHEET (0x0017) record</li>
+ * <li>zero or more DEFINEDNAME (0x0018) records</li>
+ * </ul>
  */
 final class LinkTable {
 
-	// TODO make this class into a record aggregate
-	private static final class CRNBlock {
+    // TODO make this class into a record aggregate
+    private static final class CRNBlock {
 
-		private final CRNCountRecord _countRecord;
-		private final CRNRecord[] _crns;
+        private final CRNCountRecord _countRecord;
+        private final CRNRecord[] _crns;
 
-		public CRNBlock(RecordStream rs) {
-			_countRecord = (CRNCountRecord) rs.getNext();
-			int nCRNs = _countRecord.getNumberOfCRNs();
-			CRNRecord[] crns = new CRNRecord[nCRNs];
-			for (int i = 0; i < crns.length; i++) {
-				crns[i] = (CRNRecord) rs.getNext();
-			}
-			_crns = crns;
-		}
-		public CRNRecord[] getCrns() {
-			return _crns.clone();
-		}
-	}
-
-	private static final class ExternalBookBlock {
-		private final SupBookRecord _externalBookRecord;
-		private ExternalNameRecord[] _externalNameRecords;
-		private final CRNBlock[] _crnBlocks;
-
-		public ExternalBookBlock(RecordStream rs) {
-			_externalBookRecord = (SupBookRecord) rs.getNext();
-			List<Object> temp = new ArrayList<>();
-			while(rs.peekNextClass() == ExternalNameRecord.class) {
-			   temp.add(rs.getNext());
-			}
-			_externalNameRecords = new ExternalNameRecord[temp.size()];
-			temp.toArray(_externalNameRecords);
-
-			temp.clear();
-
-			while(rs.peekNextClass() == CRNCountRecord.class) {
-				temp.add(new CRNBlock(rs));
-			}
-			_crnBlocks = new CRNBlock[temp.size()];
-			temp.toArray(_crnBlocks);
-		}
-		
-       /**
-        * Create a new block for external references.
-        */
-       public ExternalBookBlock(String url, String[] sheetNames) {
-           _externalBookRecord = SupBookRecord.createExternalReferences(url, sheetNames);
-           _crnBlocks = new CRNBlock[0];
-       }
-
-       /**
-        * Create a new block for internal references. It is called when constructing a new LinkTable.
-        *
-        * @see org.apache.poi.hssf.model.LinkTable#LinkTable(int, WorkbookRecordList)
-        */
-       public ExternalBookBlock(int numberOfSheets) {
-           _externalBookRecord = SupBookRecord.createInternalReferences((short)numberOfSheets);
-           _externalNameRecords = new ExternalNameRecord[0];
-           _crnBlocks = new CRNBlock[0];
-       }
-
-       /**
-        * Create a new block for registering add-in functions
-        *
-        * @see org.apache.poi.hssf.model.LinkTable#addNameXPtg(String)
-        */
-       public ExternalBookBlock() {
-           _externalBookRecord = SupBookRecord.createAddInFunctions();
-           _externalNameRecords = new ExternalNameRecord[0];
-           _crnBlocks = new CRNBlock[0];
-       }
-
-		public SupBookRecord getExternalBookRecord() {
-		    return _externalBookRecord;
-		}
-
-		public String getNameText(int definedNameIndex) {
-			return _externalNameRecords[definedNameIndex].getText();
-		}
-		
-		public int getNameIx(int definedNameIndex) {
-		   return _externalNameRecords[definedNameIndex].getIx();
-		}
-
-		/**
-		 * Performs case-insensitive search
-		 * @return -1 if not found
-		 */
-		public int getIndexOfName(String name) {
-			for (int i = 0; i < _externalNameRecords.length; i++) {
-				if(_externalNameRecords[i].getText().equalsIgnoreCase(name)) {
-					return i;
-				}
-			}
-			return -1;
-		}
+        public CRNBlock(RecordStream rs) {
+            _countRecord = (CRNCountRecord) rs.getNext();
+            int nCRNs = _countRecord.getNumberOfCRNs();
+            CRNRecord[] crns = new CRNRecord[nCRNs];
+            for (int i = 0; i < crns.length; i++) {
+                crns[i] = (CRNRecord) rs.getNext();
+            }
+            _crns = crns;
+        }
+
+        public CRNRecord[] getCrns() {
+            return _crns.clone();
+        }
+    }
+
+    private static final class ExternalBookBlock {
+        private final SupBookRecord _externalBookRecord;
+        private ExternalNameRecord[] _externalNameRecords;
+        private final CRNBlock[] _crnBlocks;
+
+        public ExternalBookBlock(RecordStream rs) {
+            _externalBookRecord = (SupBookRecord) rs.getNext();
+            List<Object> temp = new ArrayList<>();
+            while (rs.peekNextClass() == ExternalNameRecord.class) {
+                temp.add(rs.getNext());
+            }
+            _externalNameRecords = new ExternalNameRecord[temp.size()];
+            temp.toArray(_externalNameRecords);
+
+            temp.clear();
+
+            while (rs.peekNextClass() == CRNCountRecord.class) {
+                temp.add(new CRNBlock(rs));
+            }
+            _crnBlocks = new CRNBlock[temp.size()];
+            temp.toArray(_crnBlocks);
+        }
+
+        /**
+         * Create a new block for external references.
+         */
+        public ExternalBookBlock(String url, String[] sheetNames) {
+            _externalBookRecord = SupBookRecord.createExternalReferences(url, sheetNames);
+            _crnBlocks = new CRNBlock[0];
+        }
+
+        /**
+         * Create a new block for internal references. It is called when constructing a new LinkTable.
+         *
+         * @see org.apache.poi.hssf.model.LinkTable#LinkTable(int, WorkbookRecordList)
+         */
+        public ExternalBookBlock(int numberOfSheets) {
+            _externalBookRecord = SupBookRecord.createInternalReferences((short) numberOfSheets);
+            _externalNameRecords = new ExternalNameRecord[0];
+            _crnBlocks = new CRNBlock[0];
+        }
+
+        /**
+         * Create a new block for registering add-in functions
+         *
+         * @see org.apache.poi.hssf.model.LinkTable#addNameXPtg(String)
+         */
+        public ExternalBookBlock() {
+            _externalBookRecord = SupBookRecord.createAddInFunctions();
+            _externalNameRecords = new ExternalNameRecord[0];
+            _crnBlocks = new CRNBlock[0];
+        }
+
+        public SupBookRecord getExternalBookRecord() {
+            return _externalBookRecord;
+        }
+
+        public String getNameText(int definedNameIndex) {
+            return _externalNameRecords[definedNameIndex].getText();
+        }
+
+        public int getNameIx(int definedNameIndex) {
+            return _externalNameRecords[definedNameIndex].getIx();
+        }
+
+        /**
+         * Performs case-insensitive search
+         *
+         * @return -1 if not found
+         */
+        public int getIndexOfName(String name) {
+            for (int i = 0; i < _externalNameRecords.length; i++) {
+                if (_externalNameRecords[i].getText().equalsIgnoreCase(name)) {
+                    return i;
+                }
+            }
+            return -1;
+        }
 
         public int getNumberOfNames() {
             return _externalNameRecords.length;
         }
 
-        public int addExternalName(ExternalNameRecord rec){
+        public int addExternalName(ExternalNameRecord rec) {
             ExternalNameRecord[] tmp = new ExternalNameRecord[_externalNameRecords.length + 1];
             System.arraycopy(_externalNameRecords, 0, tmp, 0, _externalNameRecords.length);
             tmp[tmp.length - 1] = rec;
@@ -181,245 +183,243 @@ final class LinkTable {
     }
 
     private ExternalBookBlock[] _externalBookBlocks;
-	private final ExternSheetRecord _externSheetRecord;
-	private final List<NameRecord> _definedNames;
-	private final int _recordCount;
-	private final WorkbookRecordList _workbookRecordList; // TODO - would be nice to remove this
-
-	public LinkTable(List<Record> inputList, int startIndex, WorkbookRecordList workbookRecordList, Map<String, NameCommentRecord> commentRecords) {
-
-		_workbookRecordList = workbookRecordList;
-		RecordStream rs = new RecordStream(inputList, startIndex);
-
-		List<ExternalBookBlock> temp = new ArrayList<>();
-		while(rs.peekNextClass() == SupBookRecord.class) {
-		   temp.add(new ExternalBookBlock(rs));
-		}
-
-		_externalBookBlocks = new ExternalBookBlock[temp.size()];
-		temp.toArray(_externalBookBlocks);
-		temp.clear();
-
-		if (_externalBookBlocks.length > 0) {
-			// If any ExternalBookBlock present, there is always 1 of ExternSheetRecord
-			if (rs.peekNextClass() != ExternSheetRecord.class) {
-				// not quite - if written by google docs
-				_externSheetRecord = null;
-			} else {
-				_externSheetRecord = readExtSheetRecord(rs);
-			}
-		} else {
-			_externSheetRecord = null;
-		}
-
-		_definedNames = new ArrayList<>();
-		// collect zero or more DEFINEDNAMEs id=0x18,
-		//  with their comments if present
-		while(true) {
-		  Class<? extends Record> nextClass = rs.peekNextClass();
-		  if (nextClass == NameRecord.class) {
-		    NameRecord nr = (NameRecord)rs.getNext();
-		    _definedNames.add(nr);
-		  }
-		  else if (nextClass == NameCommentRecord.class) {
-		    NameCommentRecord ncr = (NameCommentRecord)rs.getNext();
-		    commentRecords.put(ncr.getNameText(), ncr);
-		  }
-		  else {
-		    break;
-		  }
-		}
-
-		_recordCount = rs.getCountRead();
-		_workbookRecordList.getRecords().addAll(inputList.subList(startIndex, startIndex + _recordCount));
-	}
-
-	private static ExternSheetRecord readExtSheetRecord(RecordStream rs) {
-		List<ExternSheetRecord> temp = new ArrayList<>(2);
-		while(rs.peekNextClass() == ExternSheetRecord.class) {
-			temp.add((ExternSheetRecord) rs.getNext());
-		}
-
-		int nItems = temp.size();
-		if (nItems < 1) {
-			throw new RuntimeException("Expected an EXTERNSHEET record but got ("
-					+ rs.peekNextClass().getName() + ")");
-		}
-		if (nItems == 1) {
-			// this is the normal case. There should be just one ExternSheetRecord
-			return temp.get(0);
-		}
-		// Some apps generate multiple ExternSheetRecords (see bug 45698).
-		// It seems like the best thing to do might be to combine these into one
-		ExternSheetRecord[] esrs = new ExternSheetRecord[nItems];
-		temp.toArray(esrs);
-		return ExternSheetRecord.combine(esrs);
-	}
-
-	public LinkTable(int numberOfSheets, WorkbookRecordList workbookRecordList) {
-		_workbookRecordList = workbookRecordList;
-		_definedNames = new ArrayList<>();
-		_externalBookBlocks = new ExternalBookBlock[] {
-				new ExternalBookBlock(numberOfSheets),
-		};
-		_externSheetRecord = new ExternSheetRecord();
-		_recordCount = 2;
-
-		// tell _workbookRecordList about the 2 new records
-
-		SupBookRecord supbook = _externalBookBlocks[0].getExternalBookRecord();
-
-		int idx = findFirstRecordLocBySid(CountryRecord.sid);
-		if(idx < 0) {
-			throw new RuntimeException("CountryRecord not found");
-		}
-		_workbookRecordList.add(idx+1, _externSheetRecord);
-		_workbookRecordList.add(idx+1, supbook);
-	}
-
-	/**
-	 * TODO - would not be required if calling code used RecordStream or similar
-	 */
-	public int getRecordCount() {
-		return _recordCount;
-	}
-
-
-	/**
-	 * @param builtInCode a BUILTIN_~ constant from {@link NameRecord}
-	 * @param sheetNumber 1-based sheet number
-	 */
-	public NameRecord getSpecificBuiltinRecord(byte builtInCode, int sheetNumber) {
-		Iterator<NameRecord> iterator = _definedNames.iterator();
-		while (iterator.hasNext()) {
-			NameRecord record = iterator.next();
-
-			//print areas are one based
-			if (record.getBuiltInName() == builtInCode && record.getSheetNumber() == sheetNumber) {
-				return record;
-			}
-		}
-
-		return null;
-	}
-
-	public void removeBuiltinRecord(byte name, int sheetIndex) {
-		//the name array is smaller so searching through it should be faster than
-		//using the findFirstXXXX methods
-		NameRecord record = getSpecificBuiltinRecord(name, sheetIndex);
-		if (record != null) {
-			_definedNames.remove(record);
-		}
-		// TODO - do we need "Workbook.records.remove(...);" similar to that in Workbook.removeName(int namenum) {}?
-	}
-
-	public int getNumNames() {
-		return _definedNames.size();
-	}
-
-	public NameRecord getNameRecord(int index) {
-		return _definedNames.get(index);
-	}
-
-	public void addName(NameRecord name) {
-		_definedNames.add(name);
-
-		// TODO - this is messy
-		// Not the most efficient way but the other way was causing too many bugs
-		int idx = findFirstRecordLocBySid(ExternSheetRecord.sid);
-		if (idx == -1) idx = findFirstRecordLocBySid(SupBookRecord.sid);
-		if (idx == -1) idx = findFirstRecordLocBySid(CountryRecord.sid);
-		int countNames = _definedNames.size();
-		_workbookRecordList.add(idx+countNames, name);
-	}
-
-	public void removeName(int namenum) {
-		_definedNames.remove(namenum);
-	}
-
-	/**
-	 * checks if the given name is already included in the linkTable
-	 */
-	public boolean nameAlreadyExists(NameRecord name)
-	{
-		// Check to ensure no other names have the same case-insensitive name
-		for ( int i = getNumNames()-1; i >=0; i-- ) {
-			NameRecord rec = getNameRecord(i);
-			if (rec != name) {
-				if (isDuplicatedNames(name, rec))
-					return true;
-			}
-		}
-		return false;
-	}
-
-	private static boolean isDuplicatedNames(NameRecord firstName, NameRecord lastName) {
-		return lastName.getNameText().equalsIgnoreCase(firstName.getNameText())
-			&& isSameSheetNames(firstName, lastName);
-	}
-	private static boolean isSameSheetNames(NameRecord firstName, NameRecord lastName) {
-		return lastName.getSheetNumber() == firstName.getSheetNumber();
-	}
-
-	public String[] getExternalBookAndSheetName(int extRefIndex) {
-		int ebIx = _externSheetRecord.getExtbookIndexFromRefIndex(extRefIndex);
-		SupBookRecord ebr = _externalBookBlocks[ebIx].getExternalBookRecord();
-		if (!ebr.isExternalReferences()) {
-			return null;
-		}
-		// Sheet name only applies if not a global reference
-		int shIx1 = _externSheetRecord.getFirstSheetIndexFromRefIndex(extRefIndex);
+    private final ExternSheetRecord _externSheetRecord;
+    private final List<NameRecord> _definedNames;
+    private final int _recordCount;
+    private final WorkbookRecordList _workbookRecordList; // TODO - would be nice to remove this
+
+    public LinkTable(List<Record> inputList, int startIndex, WorkbookRecordList workbookRecordList, Map<String, NameCommentRecord> commentRecords) {
+
+        _workbookRecordList = workbookRecordList;
+        RecordStream rs = new RecordStream(inputList, startIndex);
+
+        List<ExternalBookBlock> temp = new ArrayList<>();
+        while (rs.peekNextClass() == SupBookRecord.class) {
+            temp.add(new ExternalBookBlock(rs));
+        }
+
+        _externalBookBlocks = new ExternalBookBlock[temp.size()];
+        temp.toArray(_externalBookBlocks);
+        temp.clear();
+
+        if (_externalBookBlocks.length > 0) {
+            // If any ExternalBookBlock present, there is always 1 of ExternSheetRecord
+            if (rs.peekNextClass() != ExternSheetRecord.class) {
+                // not quite - if written by google docs
+                _externSheetRecord = null;
+            } else {
+                _externSheetRecord = readExtSheetRecord(rs);
+            }
+        } else {
+            _externSheetRecord = null;
+        }
+
+        _definedNames = new ArrayList<>();
+        // collect zero or more DEFINEDNAMEs id=0x18,
+        //  with their comments if present
+        while (true) {
+            Class<? extends Record> nextClass = rs.peekNextClass();
+            if (nextClass == NameRecord.class) {
+                NameRecord nr = (NameRecord) rs.getNext();
+                _definedNames.add(nr);
+            } else if (nextClass == NameCommentRecord.class) {
+                NameCommentRecord ncr = (NameCommentRecord) rs.getNext();
+                commentRecords.put(ncr.getNameText(), ncr);
+            } else {
+                break;
+            }
+        }
+
+        _recordCount = rs.getCountRead();
+        _workbookRecordList.getRecords().addAll(inputList.subList(startIndex, startIndex + _recordCount));
+    }
+
+    private static ExternSheetRecord readExtSheetRecord(RecordStream rs) {
+        List<ExternSheetRecord> temp = new ArrayList<>(2);
+        while (rs.peekNextClass() == ExternSheetRecord.class) {
+            temp.add((ExternSheetRecord) rs.getNext());
+        }
+
+        int nItems = temp.size();
+        if (nItems < 1) {
+            throw new RuntimeException("Expected an EXTERNSHEET record but got ("
+                    + rs.peekNextClass().getName() + ")");
+        }
+        if (nItems == 1) {
+            // this is the normal case. There should be just one ExternSheetRecord
+            return temp.get(0);
+        }
+        // Some apps generate multiple ExternSheetRecords (see bug 45698).
+        // It seems like the best thing to do might be to combine these into one
+        ExternSheetRecord[] esrs = new ExternSheetRecord[nItems];
+        temp.toArray(esrs);
+        return ExternSheetRecord.combine(esrs);
+    }
+
+    public LinkTable(int numberOfSheets, WorkbookRecordList workbookRecordList) {
+        _workbookRecordList = workbookRecordList;
+        _definedNames = new ArrayList<>();
+        _externalBookBlocks = new ExternalBookBlock[]{
+                new ExternalBookBlock(numberOfSheets),
+        };
+        _externSheetRecord = new ExternSheetRecord();
+        _recordCount = 2;
+
+        // tell _workbookRecordList about the 2 new records
+
+        SupBookRecord supbook = _externalBookBlocks[0].getExternalBookRecord();
+
+        int idx = findFirstRecordLocBySid(CountryRecord.sid);
+        if (idx < 0) {
+            throw new RuntimeException("CountryRecord not found");
+        }
+        _workbookRecordList.add(idx + 1, _externSheetRecord);
+        _workbookRecordList.add(idx + 1, supbook);
+    }
+
+    /**
+     * TODO - would not be required if calling code used RecordStream or similar
+     */
+    public int getRecordCount() {
+        return _recordCount;
+    }
+
+
+    /**
+     * @param builtInCode a BUILTIN_~ constant from {@link NameRecord}
+     * @param sheetNumber 1-based sheet number
+     */
+    public NameRecord getSpecificBuiltinRecord(byte builtInCode, int sheetNumber) {
+        Iterator<NameRecord> iterator = _definedNames.iterator();
+        while (iterator.hasNext()) {
+            NameRecord record = iterator.next();
+
+            //print areas are one based
+            if (record.getBuiltInName() == builtInCode && record.getSheetNumber() == sheetNumber) {
+                return record;
+            }
+        }
+
+        return null;
+    }
+
+    public void removeBuiltinRecord(byte name, int sheetIndex) {
+        //the name array is smaller so searching through it should be faster than
+        //using the findFirstXXXX methods
+        NameRecord record = getSpecificBuiltinRecord(name, sheetIndex);
+        if (record != null) {
+            _definedNames.remove(record);
+        }
+        // TODO - do we need "Workbook.records.remove(...);" similar to that in Workbook.removeName(int namenum) {}?
+    }
+
+    public int getNumNames() {
+        return _definedNames.size();
+    }
+
+    public NameRecord getNameRecord(int index) {
+        return _definedNames.get(index);
+    }
+
+    public void addName(NameRecord name) {
+        _definedNames.add(name);
+
+        // TODO - this is messy
+        // Not the most efficient way but the other way was causing too many bugs
+        int idx = findFirstRecordLocBySid(ExternSheetRecord.sid);
+        if (idx == -1) idx = findFirstRecordLocBySid(SupBookRecord.sid);
+        if (idx == -1) idx = findFirstRecordLocBySid(CountryRecord.sid);
+        int countNames = _definedNames.size();
+        _workbookRecordList.add(idx + countNames, name);
+    }
+
+    public void removeName(int namenum) {
+        _definedNames.remove(namenum);
+    }
+
+    /**
+     * checks if the given name is already included in the linkTable
+     */
+    public boolean nameAlreadyExists(NameRecord name) {
+        // Check to ensure no other names have the same case-insensitive name
+        for (int i = getNumNames() - 1; i >= 0; i--) {
+            NameRecord rec = getNameRecord(i);
+            if (rec != name) {
+                if (isDuplicatedNames(name, rec))
+                    return true;
+            }
+        }
+        return false;
+    }
+
+    private static boolean isDuplicatedNames(NameRecord firstName, NameRecord lastName) {
+        return lastName.getNameText().equalsIgnoreCase(firstName.getNameText())
+                && isSameSheetNames(firstName, lastName);
+    }
+
+    private static boolean isSameSheetNames(NameRecord firstName, NameRecord lastName) {
+        return lastName.getSheetNumber() == firstName.getSheetNumber();
+    }
+
+    public String[] getExternalBookAndSheetName(int extRefIndex) {
+        int ebIx = _externSheetRecord.getExtbookIndexFromRefIndex(extRefIndex);
+        SupBookRecord ebr = _externalBookBlocks[ebIx].getExternalBookRecord();
+        if (!ebr.isExternalReferences()) {
+            return null;
+        }
+        // Sheet name only applies if not a global reference
+        int shIx1 = _externSheetRecord.getFirstSheetIndexFromRefIndex(extRefIndex);
         int shIx2 = _externSheetRecord.getLastSheetIndexFromRefIndex(extRefIndex);
-		String firstSheetName = null;
+        String firstSheetName = null;
         String lastSheetName = null;
-		if(shIx1 >= 0) {
-		    firstSheetName = ebr.getSheetNames()[shIx1];
-		}
-		if (shIx2 >= 0) {
-		    lastSheetName = ebr.getSheetNames()[shIx2];
-		}
-		if (shIx1 == shIx2) {
-    		return new String[] {
-    				ebr.getURL(),
-    				firstSheetName
-    		};
-		} else {
-            return new String[] {
+        if (shIx1 >= 0) {
+            firstSheetName = ebr.getSheetNames()[shIx1];
+        }
+        if (shIx2 >= 0) {
+            lastSheetName = ebr.getSheetNames()[shIx2];
+        }
+        if (shIx1 == shIx2) {
+            return new String[]{
+                    ebr.getURL(),
+                    firstSheetName
+            };
+        } else {
+            return new String[]{
                     ebr.getURL(),
                     firstSheetName,
                     lastSheetName
             };
-		}
-	}
-	
-	private int getExternalWorkbookIndex(String workbookName) {
-	    for (int i=0; i<_externalBookBlocks.length; i++) {
-	        SupBookRecord ebr = _externalBookBlocks[i].getExternalBookRecord();
-	        if (!ebr.isExternalReferences()) {
-	            continue;
-	        }
-	        if (workbookName.equals(ebr.getURL())) { // not sure if 'equals()' works when url has a directory
-	            return i;
-	        }
-	    } 
-	    return -1;
-	}
-	
-	public int linkExternalWorkbook(String name, Workbook externalWorkbook) {
+        }
+    }
+
+    private int getExternalWorkbookIndex(String workbookName) {
+        for (int i = 0; i < _externalBookBlocks.length; i++) {
+            SupBookRecord ebr = _externalBookBlocks[i].getExternalBookRecord();
+            if (!ebr.isExternalReferences()) {
+                continue;
+            }
+            if (workbookName.equals(ebr.getURL())) { // not sure if 'equals()' works when url has a directory
+                return i;
+            }
+        }
+        return -1;
+    }
+
+    public int linkExternalWorkbook(String name, Workbook externalWorkbook) {
         int extBookIndex = getExternalWorkbookIndex(name);
         if (extBookIndex != -1) {
             // Already linked!
             return extBookIndex;
         }
-        
+
         // Create a new SupBookRecord
         String[] sheetNames = new String[externalWorkbook.getNumberOfSheets()];
-        for (int sn=0; sn<sheetNames.length; sn++) {
+        for (int sn = 0; sn < sheetNames.length; sn++) {
             sheetNames[sn] = externalWorkbook.getSheetName(sn);
         }
         String url = "\000" + name;
         ExternalBookBlock block = new ExternalBookBlock(url, sheetNames);
-        
+
         // Add it into the list + records
         extBookIndex = extendExternalBookBlocks(block);
 
@@ -429,54 +429,55 @@ final class LinkTable {
             idx = _workbookRecordList.size();
         }
         _workbookRecordList.add(idx, block.getExternalBookRecord());
-        
+
         // Setup links for the sheets
-        for (int sn=0; sn<sheetNames.length; sn++) {
+        for (int sn = 0; sn < sheetNames.length; sn++) {
             _externSheetRecord.addRef(extBookIndex, sn, sn);
         }
-        
+
         // Report where it went
         return extBookIndex;
-	}
+    }
 
-	public int getExternalSheetIndex(String workbookName, String firstSheetName, String lastSheetName) {
-	    int externalBookIndex = getExternalWorkbookIndex(workbookName);
+    public int getExternalSheetIndex(String workbookName, String firstSheetName, String lastSheetName) {
+        int externalBookIndex = getExternalWorkbookIndex(workbookName);
         if (externalBookIndex == -1) {
             throw new RuntimeException("No external workbook with name '" + workbookName + "'");
         }
         SupBookRecord ebrTarget = _externalBookBlocks[externalBookIndex].getExternalBookRecord();
 
-		int firstSheetIndex = getSheetIndex(ebrTarget.getSheetNames(), firstSheetName);
+        int firstSheetIndex = getSheetIndex(ebrTarget.getSheetNames(), firstSheetName);
         int lastSheetIndex = getSheetIndex(ebrTarget.getSheetNames(), lastSheetName);
 
         // Find or add the external sheet record definition for this
-		int result = _externSheetRecord.getRefIxForSheet(externalBookIndex, firstSheetIndex, lastSheetIndex);
-		if (result < 0) {
-		    result = _externSheetRecord.addRef(externalBookIndex, firstSheetIndex, lastSheetIndex);
-		}
-		return result;
-	}
-
-	private static int getSheetIndex(String[] sheetNames, String sheetName) {
-		for (int i = 0; i < sheetNames.length; i++) {
-			if (sheetNames[i].equals(sheetName)) {
-				return i;
-			}
-
-		}
-		throw new RuntimeException("External workbook does not contain sheet '" + sheetName + "'");
-	}
-
-	/**
-	 * @param extRefIndex as from a {@link Ref3DPtg} or {@link Area3DPtg}
-	 * @return -1 if the reference is to an external book
-	 */
-	public int getFirstInternalSheetIndexForExtIndex(int extRefIndex) {
+        int result = _externSheetRecord.getRefIxForSheet(externalBookIndex, firstSheetIndex, lastSheetIndex);
+        if (result < 0) {
+            result = _externSheetRecord.addRef(externalBookIndex, firstSheetIndex, lastSheetIndex);
+        }
+        return result;
+    }
+
+    private static int getSheetIndex(String[] sheetNames, String sheetName) {
+        for (int i = 0; i < sheetNames.length; i++) {
+            if (sheetNames[i].equals(sheetName)) {
+                return i;
+            }
+
+        }
+        throw new RuntimeException("External workbook does not contain sheet '" + sheetName + "'");
+    }
+
+    /**
+     * @param extRefIndex as from a {@link Ref3DPtg} or {@link Area3DPtg}
+     * @return -1 if the reference is to an external book
+     */
+    public int getFirstInternalSheetIndexForExtIndex(int extRefIndex) {
         if (extRefIndex >= _externSheetRecord.getNumOfRefs() || extRefIndex < 0) {
             return -1;
         }
-		return _externSheetRecord.getFirstSheetIndexFromRefIndex(extRefIndex);
-	}
+        return _externSheetRecord.getFirstSheetIndexFromRefIndex(extRefIndex);
+    }
+
     /**
      * @param extRefIndex as from a {@link Ref3DPtg} or {@link Area3DPtg}
      * @return -1 if the reference is to an external book
@@ -488,117 +489,120 @@ final class LinkTable {
         return _externSheetRecord.getLastSheetIndexFromRefIndex(extRefIndex);
     }
 
-	public void removeSheet(int sheetIdx) {
-		_externSheetRecord.removeSheet(sheetIdx);
-	}
-
-	public int checkExternSheet(int sheetIndex) {
-	    return checkExternSheet(sheetIndex, sheetIndex);
-	}
+    public void removeSheet(int sheetIdx) {
+        _externSheetRecord.removeSheet(sheetIdx);
+    }
+
+    public int checkExternSheet(int sheetIndex) {
+        return checkExternSheet(sheetIndex, sheetIndex);
+    }
+
     public int checkExternSheet(int firstSheetIndex, int lastSheetIndex) {
-		int thisWbIndex = -1; // this is probably always zero
-		for (int i=0; i<_externalBookBlocks.length; i++) {
-			SupBookRecord ebr = _externalBookBlocks[i].getExternalBookRecord();
-			if (ebr.isInternalReferences()) {
-				thisWbIndex = i;
-				break;
-			}
-		}
-		if (thisWbIndex < 0) {
-			throw new RuntimeException("Could not find 'internal references' EXTERNALBOOK");
-		}
-
-		//Trying to find reference to this sheet
-		int i = _externSheetRecord.getRefIxForSheet(thisWbIndex, firstSheetIndex, lastSheetIndex);
-		if (i>=0) {
-			return i;
-		}
-		//We haven't found reference to this sheet
-		return _externSheetRecord.addRef(thisWbIndex, firstSheetIndex, lastSheetIndex);
-	}
-
-	/**
-	 * copied from Workbook
-	 */
-	private int findFirstRecordLocBySid(short sid) {
-		int index = 0;
-		for (Record record : _workbookRecordList.getRecords()) {
-			if (record.getSid() == sid) {
-				return index;
-			}
-			index ++;
-		}
-		return -1;
-	}
-	
-	public String resolveNameXText(int refIndex, int definedNameIndex, InternalWorkbook workbook) {
+        int thisWbIndex = -1; // this is probably always zero
+        for (int i = 0; i < _externalBookBlocks.length; i++) {
+            SupBookRecord ebr = _externalBookBlocks[i].getExternalBookRecord();
+            if (ebr.isInternalReferences()) {
+                thisWbIndex = i;
+                break;
+            }
+        }
+        if (thisWbIndex < 0) {
+            throw new RuntimeException("Could not find 'internal references' EXTERNALBOOK");
+        }
+
+        //Trying to find reference to this sheet
+        int i = _externSheetRecord.getRefIxForSheet(thisWbIndex, firstSheetIndex, lastSheetIndex);
+        if (i >= 0) {
+            return i;
+        }
+        //We haven't found reference to this sheet
+        return _externSheetRecord.addRef(thisWbIndex, firstSheetIndex, lastSheetIndex);
+    }
+
+    /**
+     * copied from Workbook
+     */
+    private int findFirstRecordLocBySid(short sid) {
+        int index = 0;
+        for (Record record : _workbookRecordList.getRecords()) {
+            if (record.getSid() == sid) {
+                return index;
+            }
+            index++;
+        }
+        return -1;
+    }
+
+    public String resolveNameXText(int refIndex, int definedNameIndex, InternalWorkbook workbook) {
         int extBookIndex = _externSheetRecord.getExtbookIndexFromRefIndex(refIndex);
         int firstTabIndex = _externSheetRecord.getFirstSheetIndexFromRefIndex(refIndex);
-		if (firstTabIndex == -1) {
-		    // The referenced sheet could not be found
+        if (firstTabIndex == -1) {
+            // The referenced sheet could not be found
             throw new RuntimeException("Referenced sheet could not be found");
-		}
-		
-		// Does it exist via the external book block?
-		ExternalBookBlock externalBook = _externalBookBlocks[extBookIndex];
-		if (externalBook._externalNameRecords.length > definedNameIndex) {
+        }
+
+        // Does it exist via the external book block?
+        ExternalBookBlock externalBook = _externalBookBlocks[extBookIndex];
+        if (externalBook._externalNameRecords.length > definedNameIndex) {
             return _externalBookBlocks[extBookIndex].getNameText(definedNameIndex);
-		} else if (firstTabIndex == -2) {
-		    // Workbook scoped name, not actually external after all
-		    NameRecord nr = getNameRecord(definedNameIndex);
-		    int sheetNumber = nr.getSheetNumber();
-
-			StringBuilder text = new StringBuilder(64);
-		    if (sheetNumber > 0) {
-		        String sheetName = workbook.getSheetName(sheetNumber-1);
-		        SheetNameFormatter.appendFormat(text, sheetName);
-		        text.append("!");
-		    }
-		    text.append(nr.getNameText());
-		    return text.toString();
-		} else {
-		    throw new ArrayIndexOutOfBoundsException(
-		            "Ext Book Index relative but beyond the supported length, was " +
-		            extBookIndex + " but maximum is " + _externalBookBlocks.length
-		    );
-		}
-	}
-	public int resolveNameXIx(int refIndex, int definedNameIndex) {
-      int extBookIndex = _externSheetRecord.getExtbookIndexFromRefIndex(refIndex);
-      return _externalBookBlocks[extBookIndex].getNameIx(definedNameIndex);
-	}
-
-	/**
-	 * Finds the external name definition for the given name,
-	 *  optionally restricted by externsheet index, and returns
-	 *  (if found) as a NameXPtg.
-	 * @param sheetRefIndex The Extern Sheet Index to look for, or -1 if any
-	 */
-	public NameXPtg getNameXPtg(String name, int sheetRefIndex) {
-		// first find any external book block that contains the name:
-		for (int i = 0; i < _externalBookBlocks.length; i++) {
-			int definedNameIndex = _externalBookBlocks[i].getIndexOfName(name);
-			if (definedNameIndex < 0) {
-				continue;
-			}
-			
-			// Found one
-			int thisSheetRefIndex = findRefIndexFromExtBookIndex(i);
-			if (thisSheetRefIndex >= 0) {
-			    // Check for the sheet index match, if requested
-			    if (sheetRefIndex == -1 || thisSheetRefIndex == sheetRefIndex) {
-			        return new NameXPtg(thisSheetRefIndex, definedNameIndex);
-			    }
-			}
-		}
-		return null;
-	}
+        } else if (firstTabIndex == -2) {
+            // Workbook scoped name, not actually external after all
+            NameRecord nr = getNameRecord(definedNameIndex);
+            int sheetNumber = nr.getSheetNumber();
+
+            StringBuilder text = new StringBuilder(64);
+            if (sheetNumber > 0) {
+                String sheetName = workbook.getSheetName(sheetNumber - 1);
+                SheetNameFormatter.appendFormat(text, sheetName);
+                text.append("!");
+            }
+            text.append(nr.getNameText());
+            return text.toString();
+        } else {
+            throw new ArrayIndexOutOfBoundsException(
+                    "Ext Book Index relative but beyond the supported length, was " +
+                            extBookIndex + " but maximum is " + _externalBookBlocks.length
+            );
+        }
+    }
+
+    public int resolveNameXIx(int refIndex, int definedNameIndex) {
+        int extBookIndex = _externSheetRecord.getExtbookIndexFromRefIndex(refIndex);
+        return _externalBookBlocks[extBookIndex].getNameIx(definedNameIndex);
+    }
+
+    /**
+     * Finds the external name definition for the given name,
+     * optionally restricted by externsheet index, and returns
+     * (if found) as a NameXPtg.
+     *
+     * @param sheetRefIndex The Extern Sheet Index to look for, or -1 if any
+     */
+    public NameXPtg getNameXPtg(String name, int sheetRefIndex) {
+        // first find any external book block that contains the name:
+        for (int i = 0; i < _externalBookBlocks.length; i++) {
+            int definedNameIndex = _externalBookBlocks[i].getIndexOfName(name);
+            if (definedNameIndex < 0) {
+                continue;
+            }
+
+            // Found one
+            int thisSheetRefIndex = findRefIndexFromExtBookIndex(i);
+            if (thisSheetRefIndex >= 0) {
+                // Check for the sheet index match, if requested
+                if (sheetRefIndex == -1 || thisSheetRefIndex == sheetRefIndex) {
+                    return new NameXPtg(thisSheetRefIndex, definedNameIndex);
+                }
+            }
+        }
+        return null;
+    }
 
     /**
      * Register an external name in this workbook
      *
-     * @param name  the name to register
-     * @return a NameXPtg describing this name 
+     * @param name the name to register
+     * @return a NameXPtg describing this name
      */
     public NameXPtg addNameXPtg(String name) {
         int extBlockIndex = -1;
@@ -650,6 +654,7 @@ final class LinkTable {
         int ix = _externSheetRecord.getRefIxForSheet(extBlockIndex, fakeSheetIdx, fakeSheetIdx);
         return new NameXPtg(ix, nameIndex);
     }
+
     private int extendExternalBookBlocks(ExternalBookBlock newBlock) {
         ExternalBookBlock[] tmp = new ExternalBookBlock[_externalBookBlocks.length + 1];
         System.arraycopy(_externalBookBlocks, 0, tmp, 0, _externalBookBlocks.length);
@@ -660,29 +665,30 @@ final class LinkTable {
     }
 
     private int findRefIndexFromExtBookIndex(int extBookIndex) {
-		return _externSheetRecord.findRefIndexFromExtBookIndex(extBookIndex);
-	}
-   
-	/**
-	 * Changes an external referenced file to another file.
-	 * A formular in Excel which refers a cell in another file is saved in two parts: 
-	 * The referenced file is stored in an reference table. the row/cell information is saved separate.
-	 * This method invokation will only change the reference in the lookup-table itself.
-	 * @param oldUrl The old URL to search for and which is to be replaced
-	 * @param newUrl The URL replacement
-	 * @return true if the oldUrl was found and replaced with newUrl. Otherwise false
-	 */
-	public boolean changeExternalReference(String oldUrl, String newUrl) {
-		for(ExternalBookBlock ex : _externalBookBlocks) {
-			SupBookRecord externalRecord = ex.getExternalBookRecord();
-			if (externalRecord.isExternalReferences() 
-				&& externalRecord.getURL().equals(oldUrl)) {
-				
-				externalRecord.setURL(newUrl);
-				return true;
-			}
-		}
-		return false;
-	}
+        return _externSheetRecord.findRefIndexFromExtBookIndex(extBookIndex);
+    }
+
+    /**
+     * Changes an external referenced file to another file.
+     * A formular in Excel which refers a cell in another file is saved in two parts:
+     * The referenced file is stored in an reference table. the row/cell information is saved separate.
+     * This method invokation will only change the reference in the lookup-table itself.
+     *
+     * @param oldUrl The old URL to search for and which is to be replaced
+     * @param newUrl The URL replacement
+     * @return true if the oldUrl was found and replaced with newUrl. Otherwise false
+     */
+    public boolean changeExternalReference(String oldUrl, String newUrl) {
+        for (ExternalBookBlock ex : _externalBookBlocks) {
+            SupBookRecord externalRecord = ex.getExternalBookRecord();
+            if (externalRecord.isExternalReferences()
+                    && externalRecord.getURL().equals(oldUrl)) {
+
+                externalRecord.setURL(newUrl);
+                return true;
+            }
+        }
+        return false;
+    }
 
 }

Modified: poi/trunk/src/ooxml/java/org/apache/poi/POIXMLPropertiesTextExtractor.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/POIXMLPropertiesTextExtractor.java?rev=1813869&r1=1813868&r2=1813869&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/POIXMLPropertiesTextExtractor.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/POIXMLPropertiesTextExtractor.java Tue Oct 31 10:24:47 2017
@@ -30,211 +30,206 @@ import org.openxmlformats.schemas.office
 
 /**
  * A {@link POITextExtractor} for returning the textual
- *  content of the OOXML file properties, eg author
- *  and title.
+ * content of the OOXML file properties, eg author
+ * and title.
  */
 public class POIXMLPropertiesTextExtractor extends POIXMLTextExtractor {
-    
+
     private final DateFormat dateFormat;
-    
-	/**
-	 * Creates a new POIXMLPropertiesTextExtractor for the given open document.
-	 * 
-	 * @param doc the given open document
-	 */
-	public POIXMLPropertiesTextExtractor(POIXMLDocument doc) {
-		super(doc);
+
+    /**
+     * Creates a new POIXMLPropertiesTextExtractor for the given open document.
+     *
+     * @param doc the given open document
+     */
+    public POIXMLPropertiesTextExtractor(POIXMLDocument doc) {
+        super(doc);
         DateFormatSymbols dfs = DateFormatSymbols.getInstance(Locale.ROOT);
         dateFormat = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", dfs);
-        dateFormat.setTimeZone(LocaleUtil.TIMEZONE_UTC);       
-	}
-	
-	/**
-	 * Creates a new POIXMLPropertiesTextExtractor, for the
-	 *  same file that another TextExtractor is already
-	 *  working on.
-	 * 
-	 * @param otherExtractor the extractor referencing the given file
-	 */
-	public POIXMLPropertiesTextExtractor(POIXMLTextExtractor otherExtractor) {
-		this(otherExtractor.getDocument());
-	}
-	
-   private void appendIfPresent(StringBuffer text, String thing, boolean value) {
-      appendIfPresent(text, thing, Boolean.toString(value));
-   }
-   private void appendIfPresent(StringBuffer text, String thing, int value) {
-      appendIfPresent(text, thing, Integer.toString(value));
-   }
-   private void appendIfPresent(StringBuffer text, String thing, Date value) {
-      if(value == null) { return; }
-      appendIfPresent(text, thing, dateFormat.format(value));
-   }
-	private void appendIfPresent(StringBuffer text, String thing, String value) {
-	   if(value == null) { return; }
-	   text.append(thing);
-	   text.append(" = ");
-	   text.append(value);
-	   text.append("\n");
-	}
-
-	/**
-	 * Returns the core document properties, eg author
-	 * 
-	 * @return the core document properties
-	 */
-	@SuppressWarnings("resource")
+        dateFormat.setTimeZone(LocaleUtil.TIMEZONE_UTC);
+    }
+
+    /**
+     * Creates a new POIXMLPropertiesTextExtractor, for the
+     * same file that another TextExtractor is already
+     * working on.
+     *
+     * @param otherExtractor the extractor referencing the given file
+     */
+    public POIXMLPropertiesTextExtractor(POIXMLTextExtractor otherExtractor) {
+        this(otherExtractor.getDocument());
+    }
+
+    private void appendIfPresent(StringBuilder text, String thing, boolean value) {
+        appendIfPresent(text, thing, Boolean.toString(value));
+    }
+
+    private void appendIfPresent(StringBuilder text, String thing, int value) {
+        appendIfPresent(text, thing, Integer.toString(value));
+    }
+
+    private void appendIfPresent(StringBuilder text, String thing, Date value) {
+        if (value == null) {
+            return;
+        }
+        appendIfPresent(text, thing, dateFormat.format(value));
+    }
+
+    private void appendIfPresent(StringBuilder text, String thing, String value) {
+        if (value == null) {
+            return;
+        }
+        text.append(thing);
+        text.append(" = ");
+        text.append(value);
+        text.append("\n");
+    }
+
+    /**
+     * Returns the core document properties, eg author
+     *
+     * @return the core document properties
+     */
+    @SuppressWarnings("resource")
     public String getCorePropertiesText() {
-	    POIXMLDocument document = getDocument();
-        if(document == null) {  // event based extractor does not have a document
+        POIXMLDocument document = getDocument();
+        if (document == null) {  // event based extractor does not have a document
             return "";
         }
 
-		StringBuffer text = new StringBuffer();
+        StringBuilder text = new StringBuilder(64);
         PackagePropertiesPart props =
-			document.getProperties().getCoreProperties().getUnderlyingProperties();
+                document.getProperties().getCoreProperties().getUnderlyingProperties();
 
-		appendIfPresent(text, "Category", props.getCategoryProperty().getValue());
-		appendIfPresent(text, "Category", props.getCategoryProperty().getValue());
-		appendIfPresent(text, "ContentStatus", props.getContentStatusProperty().getValue());
-		appendIfPresent(text, "ContentType", props.getContentTypeProperty().getValue());
-		appendIfPresent(text, "Created", props.getCreatedProperty().getValue());
-		appendIfPresent(text, "CreatedString", props.getCreatedPropertyString());
-		appendIfPresent(text, "Creator", props.getCreatorProperty().getValue());
-		appendIfPresent(text, "Description", props.getDescriptionProperty().getValue());
-		appendIfPresent(text, "Identifier", props.getIdentifierProperty().getValue());
-		appendIfPresent(text, "Keywords", props.getKeywordsProperty().getValue());
-		appendIfPresent(text, "Language", props.getLanguageProperty().getValue());
-		appendIfPresent(text, "LastModifiedBy", props.getLastModifiedByProperty().getValue());
-		appendIfPresent(text, "LastPrinted", props.getLastPrintedProperty().getValue());
-		appendIfPresent(text, "LastPrintedString", props.getLastPrintedPropertyString());
-		appendIfPresent(text, "Modified", props.getModifiedProperty().getValue());
-		appendIfPresent(text, "ModifiedString", props.getModifiedPropertyString());
-		appendIfPresent(text, "Revision", props.getRevisionProperty().getValue());
-		appendIfPresent(text, "Subject", props.getSubjectProperty().getValue());
-		appendIfPresent(text, "Title", props.getTitleProperty().getValue());
-		appendIfPresent(text, "Version", props.getVersionProperty().getValue());
-
-		return text.toString();
-	}
-	/**
-	 * Returns the extended document properties, eg application
-	 * 
-	 * @return the extended document properties
-	 */
-	@SuppressWarnings("resource")
+        appendIfPresent(text, "Category", props.getCategoryProperty().getValue());
+        appendIfPresent(text, "Category", props.getCategoryProperty().getValue());
+        appendIfPresent(text, "ContentStatus", props.getContentStatusProperty().getValue());
+        appendIfPresent(text, "ContentType", props.getContentTypeProperty().getValue());
+        appendIfPresent(text, "Created", props.getCreatedProperty().getValue());
+        appendIfPresent(text, "CreatedString", props.getCreatedPropertyString());
+        appendIfPresent(text, "Creator", props.getCreatorProperty().getValue());
+        appendIfPresent(text, "Description", props.getDescriptionProperty().getValue());
+        appendIfPresent(text, "Identifier", props.getIdentifierProperty().getValue());
+        appendIfPresent(text, "Keywords", props.getKeywordsProperty().getValue());
+        appendIfPresent(text, "Language", props.getLanguageProperty().getValue());
+        appendIfPresent(text, "LastModifiedBy", props.getLastModifiedByProperty().getValue());
+        appendIfPresent(text, "LastPrinted", props.getLastPrintedProperty().getValue());
+        appendIfPresent(text, "LastPrintedString", props.getLastPrintedPropertyString());
+        appendIfPresent(text, "Modified", props.getModifiedProperty().getValue());
+        appendIfPresent(text, "ModifiedString", props.getModifiedPropertyString());
+        appendIfPresent(text, "Revision", props.getRevisionProperty().getValue());
+        appendIfPresent(text, "Subject", props.getSubjectProperty().getValue());
+        appendIfPresent(text, "Title", props.getTitleProperty().getValue());
+        appendIfPresent(text, "Version", props.getVersionProperty().getValue());
+
+        return text.toString();
+    }
+
+    /**
+     * Returns the extended document properties, eg application
+     *
+     * @return the extended document properties
+     */
+    @SuppressWarnings("resource")
     public String getExtendedPropertiesText() {
         POIXMLDocument document = getDocument();
-        if(document == null) {  // event based extractor does not have a document
+        if (document == null) {  // event based extractor does not have a document
             return "";
         }
 
-		StringBuffer text = new StringBuffer();
-		org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties
-			props = document.getProperties().getExtendedProperties().getUnderlyingProperties();
-
-		appendIfPresent(text, "Application", props.getApplication());
-		appendIfPresent(text, "AppVersion", props.getAppVersion());
-		appendIfPresent(text, "Characters", props.getCharacters());
-		appendIfPresent(text, "CharactersWithSpaces", props.getCharactersWithSpaces());
-		appendIfPresent(text, "Company", props.getCompany());
-		appendIfPresent(text, "HyperlinkBase", props.getHyperlinkBase());
-		appendIfPresent(text, "HyperlinksChanged", props.getHyperlinksChanged());
-		appendIfPresent(text, "Lines", props.getLines());
-		appendIfPresent(text, "LinksUpToDate", props.getLinksUpToDate());
-		appendIfPresent(text, "Manager", props.getManager());
-		appendIfPresent(text, "Pages", props.getPages());
-		appendIfPresent(text, "Paragraphs", props.getParagraphs());
-		appendIfPresent(text, "PresentationFormat", props.getPresentationFormat());
-		appendIfPresent(text, "Template", props.getTemplate());
-		appendIfPresent(text, "TotalTime", props.getTotalTime());
-
-		return text.toString();
-	}
-   /**
-    * Returns the custom document properties, if there are any
-    * 
-    * @return the custom document properties
-    */
-   @SuppressWarnings({ "resource" })
-   public String getCustomPropertiesText() {
-       POIXMLDocument document = getDocument();
-       if(document == null) {  // event based extractor does not have a document
-           return "";
-       }
-
-      StringBuilder text = new StringBuilder();
-      org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperties
-      props = document.getProperties().getCustomProperties().getUnderlyingProperties();
-
-       for(CTProperty property : props.getPropertyArray()) {
-         String val = "(not implemented!)";
+        StringBuilder text = new StringBuilder(64);
+        org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties
+                props = document.getProperties().getExtendedProperties().getUnderlyingProperties();
+
+        appendIfPresent(text, "Application", props.getApplication());
+        appendIfPresent(text, "AppVersion", props.getAppVersion());
+        appendIfPresent(text, "Characters", props.getCharacters());
+        appendIfPresent(text, "CharactersWithSpaces", props.getCharactersWithSpaces());
+        appendIfPresent(text, "Company", props.getCompany());
+        appendIfPresent(text, "HyperlinkBase", props.getHyperlinkBase());
+        appendIfPresent(text, "HyperlinksChanged", props.getHyperlinksChanged());
+        appendIfPresent(text, "Lines", props.getLines());
+        appendIfPresent(text, "LinksUpToDate", props.getLinksUpToDate());
+        appendIfPresent(text, "Manager", props.getManager());
+        appendIfPresent(text, "Pages", props.getPages());
+        appendIfPresent(text, "Paragraphs", props.getParagraphs());
+        appendIfPresent(text, "PresentationFormat", props.getPresentationFormat());
+        appendIfPresent(text, "Template", props.getTemplate());
+        appendIfPresent(text, "TotalTime", props.getTotalTime());
+
+        return text.toString();
+    }
+
+    /**
+     * Returns the custom document properties, if there are any
+     *
+     * @return the custom document properties
+     */
+    @SuppressWarnings({"resource"})
+    public String getCustomPropertiesText() {
+        POIXMLDocument document = getDocument();
+        if (document == null) {  // event based extractor does not have a document
+            return "";
+        }
 
-         if (property.isSetLpwstr()) {
-            val = property.getLpwstr(); 
-         }
-         else if (property.isSetLpstr()) {
-            val = property.getLpstr(); 
-         }
-         else if (property.isSetDate()) {
-            val = property.getDate().toString(); 
-         }
-         else if (property.isSetFiletime()) {
-            val = property.getFiletime().toString(); 
-         }
-         else if (property.isSetBool()) {
-            val = Boolean.toString( property.getBool() );
-         }
+        StringBuilder text = new StringBuilder();
+        org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProperties
+                props = document.getProperties().getCustomProperties().getUnderlyingProperties();
+
+        for (CTProperty property : props.getPropertyArray()) {
+            String val = "(not implemented!)";
+
+            if (property.isSetLpwstr()) {
+                val = property.getLpwstr();
+            } else if (property.isSetLpstr()) {
+                val = property.getLpstr();
+            } else if (property.isSetDate()) {
+                val = property.getDate().toString();
+            } else if (property.isSetFiletime()) {
+                val = property.getFiletime().toString();
+            } else if (property.isSetBool()) {
+                val = Boolean.toString(property.getBool());
+            }
 
-         // Integers
-         else if (property.isSetI1()) {
-            val = Integer.toString(property.getI1()); 
-         }
-         else if (property.isSetI2()) {
-            val = Integer.toString(property.getI2()); 
-         }
-         else if (property.isSetI4()) {
-            val = Integer.toString(property.getI4()); 
-         }
-         else if (property.isSetI8()) {
-            val = Long.toString(property.getI8()); 
-         }
-         else if (property.isSetInt()) {
-            val = Integer.toString( property.getInt() ); 
-         }
+            // Integers
+            else if (property.isSetI1()) {
+                val = Integer.toString(property.getI1());
+            } else if (property.isSetI2()) {
+                val = Integer.toString(property.getI2());
+            } else if (property.isSetI4()) {
+                val = Integer.toString(property.getI4());
+            } else if (property.isSetI8()) {
+                val = Long.toString(property.getI8());
+            } else if (property.isSetInt()) {
+                val = Integer.toString(property.getInt());
+            }
 
-         // Unsigned Integers
-         else if (property.isSetUi1()) {
-            val = Integer.toString(property.getUi1()); 
-         }
-         else if (property.isSetUi2()) {
-            val = Integer.toString(property.getUi2()); 
-         }
-         else if (property.isSetUi4()) {
-            val = Long.toString(property.getUi4()); 
-         }
-         else if (property.isSetUi8()) {
-            val = property.getUi8().toString(); 
-         }
-         else if (property.isSetUint()) {
-            val = Long.toString(property.getUint()); 
-         }
+            // Unsigned Integers
+            else if (property.isSetUi1()) {
+                val = Integer.toString(property.getUi1());
+            } else if (property.isSetUi2()) {
+                val = Integer.toString(property.getUi2());
+            } else if (property.isSetUi4()) {
+                val = Long.toString(property.getUi4());
+            } else if (property.isSetUi8()) {
+                val = property.getUi8().toString();
+            } else if (property.isSetUint()) {
+                val = Long.toString(property.getUint());
+            }
 
-         // Reals
-         else if (property.isSetR4()) {
-            val = Float.toString( property.getR4() ); 
-         }
-         else if (property.isSetR8()) {
-            val = Double.toString( property.getR8() ); 
-         }
-         else if (property.isSetDecimal()) {
-            BigDecimal d = property.getDecimal();
-            if (d == null) {
-               val = null;
-            } else {
-               val = d.toPlainString();
+            // Reals
+            else if (property.isSetR4()) {
+                val = Float.toString(property.getR4());
+            } else if (property.isSetR8()) {
+                val = Double.toString(property.getR8());
+            } else if (property.isSetDecimal()) {
+                BigDecimal d = property.getDecimal();
+                if (d == null) {
+                    val = null;
+                } else {
+                    val = d.toPlainString();
+                }
             }
-         }
 
          /*else if (property.isSetArray()) {
             // TODO Fetch the array values and output 
@@ -254,26 +249,26 @@ public class POIXMLPropertiesTextExtract
             // TODO Decode, if possible
          }*/
 
-         text.append(property.getName()).append(" = ").append(val).append("\n");
-      }
+            text.append(property.getName()).append(" = ").append(val).append("\n");
+        }
 
-      return text.toString();
-   }
+        return text.toString();
+    }
 
-	@Override
+    @Override
     public String getText() {
-		try {
-			return
-				getCorePropertiesText() +
-				getExtendedPropertiesText() +
-				getCustomPropertiesText();
-		} catch(Exception e) {
-			throw new RuntimeException(e);
-		}
-	}
+        try {
+            return
+                    getCorePropertiesText() +
+                            getExtendedPropertiesText() +
+                            getCustomPropertiesText();
+        } catch (Exception e) {
+            throw new RuntimeException(e);
+        }
+    }
 
-	@Override
+    @Override
     public POIXMLPropertiesTextExtractor getMetadataTextExtractor() {
-		throw new IllegalStateException("You already have the Metadata Text Extractor, not recursing!");
-	}
+        throw new IllegalStateException("You already have the Metadata Text Extractor, not recursing!");
+    }
 }

Modified: poi/trunk/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagingURIHelper.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagingURIHelper.java?rev=1813869&r1=1813868&r2=1813869&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagingURIHelper.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagingURIHelper.java Tue Oct 31 10:24:47 2017
@@ -601,7 +601,7 @@ public final class PackagingURIHelper {
 	 *         characters.
 	 */
 	public static String decodeURI(URI uri) {
-		StringBuffer retVal = new StringBuffer();
+		StringBuilder retVal = new StringBuilder(64);
 		String uriStr = uri.toASCIIString();
 		char c;
 		final int length = uriStr.length();

Modified: poi/trunk/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentType.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentType.java?rev=1813869&r1=1813868&r2=1813869&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentType.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentType.java Tue Oct 31 10:24:47 2017
@@ -188,16 +188,16 @@ public final class ContentType {
 	}
 
 	public final String toString(boolean withParameters) {
-	    StringBuffer retVal = new StringBuffer();
+		StringBuilder retVal = new StringBuilder(64);
 	    retVal.append(this.getType());
-	    retVal.append("/");
+	    retVal.append('/');
 	    retVal.append(this.getSubType());
 
 	    if (withParameters) {
 	        for (Entry<String, String> me : parameters.entrySet()) {
-	            retVal.append(";");
+	            retVal.append(';');
 	            retVal.append(me.getKey());
-	            retVal.append("=");
+	            retVal.append('=');
 	            retVal.append(me.getValue());
 	        }
 	    }

Modified: poi/trunk/src/ooxml/java/org/apache/poi/xssf/eventusermodel/ReadOnlySharedStringsTable.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/xssf/eventusermodel/ReadOnlySharedStringsTable.java?rev=1813869&r1=1813868&r2=1813869&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/xssf/eventusermodel/ReadOnlySharedStringsTable.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/xssf/eventusermodel/ReadOnlySharedStringsTable.java Tue Oct 31 10:24:47 2017
@@ -223,7 +223,7 @@ public class ReadOnlySharedStringsTable
 
     //// ContentHandler methods ////
 
-    private StringBuffer characters;
+    private StringBuilder characters;
     private boolean tIsOpen;
     private boolean inRPh;
 
@@ -241,7 +241,7 @@ public class ReadOnlySharedStringsTable
 
             this.strings = new ArrayList<>(this.uniqueCount);
             this.phoneticStrings = new HashMap<>();
-            characters = new StringBuffer();
+            characters = new StringBuilder(64);
         } else if ("si".equals(localName)) {
             characters.setLength(0);
         } else if ("t".equals(localName)) {

Modified: poi/trunk/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFSheetXMLHandler.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFSheetXMLHandler.java?rev=1813869&r1=1813868&r2=1813869&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFSheetXMLHandler.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFSheetXMLHandler.java Tue Oct 31 10:24:47 2017
@@ -102,9 +102,9 @@ public class XSSFSheetXMLHandler extends
    private boolean formulasNotResults;
 
    // Gathers characters as they are seen.
-   private StringBuffer value = new StringBuffer();
-   private StringBuffer formula = new StringBuffer();
-   private StringBuffer headerFooter = new StringBuffer();
+   private StringBuilder value = new StringBuilder(64);
+   private StringBuilder formula = new StringBuilder(64);
+   private StringBuilder headerFooter = new StringBuilder(64);
 
    private Queue<CellAddress> commentCellRefs;
 

Modified: poi/trunk/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFBEventBasedExcelExtractor.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFBEventBasedExcelExtractor.java?rev=1813869&r1=1813868&r2=1813869&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFBEventBasedExcelExtractor.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFBEventBasedExcelExtractor.java Tue Oct 31 10:24:47 2017
@@ -122,7 +122,7 @@ public class XSSFBEventBasedExcelExtract
             XSSFBStylesTable styles = xssfbReader.getXSSFBStylesTable();
             XSSFBReader.SheetIterator iter = (XSSFBReader.SheetIterator) xssfbReader.getSheetsData();
 
-            StringBuffer text = new StringBuffer();
+            StringBuilder text = new StringBuilder(64);
             SheetTextExtractor sheetExtractor = new SheetTextExtractor();
             XSSFBHyperlinksTable hyperlinksTable = null;
             while (iter.hasNext()) {

Modified: poi/trunk/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFEventBasedExcelExtractor.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFEventBasedExcelExtractor.java?rev=1813869&r1=1813868&r2=1813869&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFEventBasedExcelExtractor.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFEventBasedExcelExtractor.java Tue Oct 31 10:24:47 2017
@@ -52,10 +52,10 @@ import org.xml.sax.XMLReader;
 
 /**
  * Implementation of a text extractor from OOXML Excel
- *  files that uses SAX event based parsing.
+ * files that uses SAX event based parsing.
  */
-public class XSSFEventBasedExcelExtractor extends POIXMLTextExtractor 
-       implements org.apache.poi.ss.extractor.ExcelExtractor {
+public class XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
+        implements org.apache.poi.ss.extractor.ExcelExtractor {
 
     private static final POILogger LOGGER = POILogFactory.getLogger(XSSFEventBasedExcelExtractor.class);
 
@@ -73,6 +73,7 @@ public class XSSFEventBasedExcelExtracto
     public XSSFEventBasedExcelExtractor(String path) throws XmlException, OpenXML4JException, IOException {
         this(OPCPackage.open(path));
     }
+
     public XSSFEventBasedExcelExtractor(OPCPackage container) throws XmlException, OpenXML4JException, IOException {
         super(null);
         this.container = container;
@@ -81,13 +82,13 @@ public class XSSFEventBasedExcelExtracto
     }
 
     public static void main(String[] args) throws Exception {
-        if(args.length < 1) {
+        if (args.length < 1) {
             System.err.println("Use:");
             System.err.println("  XSSFEventBasedExcelExtractor <filename.xlsx>");
             System.exit(1);
         }
         POIXMLTextExtractor extractor =
-            new XSSFEventBasedExcelExtractor(args[0]);
+                new XSSFEventBasedExcelExtractor(args[0]);
         System.out.println(extractor.getText());
         extractor.close();
     }
@@ -101,9 +102,7 @@ public class XSSFEventBasedExcelExtracto
 
 
     /**
-     *
      * @return whether to include sheet names
-     *
      * @since 3.16-beta3
      */
     public boolean getIncludeSheetNames() {
@@ -112,16 +111,14 @@ public class XSSFEventBasedExcelExtracto
 
     /**
      * Should we return the formula itself, and not
-     *  the result it produces? Default is false
+     * the result it produces? Default is false
      */
     public void setFormulasNotResults(boolean formulasNotResults) {
         this.formulasNotResults = formulasNotResults;
     }
 
     /**
-     *
      * @return whether to include formulas but not results
-     *
      * @since 3.16-beta3
      */
     public boolean getFormulasNotResults() {
@@ -136,14 +133,13 @@ public class XSSFEventBasedExcelExtracto
     }
 
     /**
-     *
      * @return whether or not to include headers and footers
-     *
      * @since 3.16-beta3
      */
     public boolean getIncludeHeadersFooters() {
         return includeHeadersFooters;
     }
+
     /**
      * Should text from textboxes be included? Default is true
      */
@@ -152,14 +148,13 @@ public class XSSFEventBasedExcelExtracto
     }
 
     /**
-     *
      * @return whether or not to extract textboxes
-     *
      * @since 3.16-beta3
      */
     public boolean getIncludeTextBoxes() {
         return includeTextBoxes;
     }
+
     /**
      * Should cell comments be included? Default is false
      */
@@ -169,32 +164,34 @@ public class XSSFEventBasedExcelExtracto
 
     /**
      * @return whether cell comments should be included
-     *
      * @since 3.16-beta3
      */
     public boolean getIncludeCellComments() {
         return includeCellComments;
     }
+
     /**
      * Concatenate text from &lt;rPh&gt; text elements in SharedStringsTable
      * Default is true;
+     *
      * @param concatenatePhoneticRuns true if runs should be concatenated, false otherwise
      */
     public void setConcatenatePhoneticRuns(boolean concatenatePhoneticRuns) {
         this.concatenatePhoneticRuns = concatenatePhoneticRuns;
     }
+
     public void setLocale(Locale locale) {
         this.locale = locale;
     }
 
     /**
      * @return locale
-     *
      * @since 3.16-beta3
      */
     public Locale getLocale() {
         return locale;
     }
+
     /**
      * Returns the opened OPCPackage container.
      */
@@ -210,6 +207,7 @@ public class XSSFEventBasedExcelExtracto
     public CoreProperties getCoreProperties() {
         return properties.getCoreProperties();
     }
+
     /**
      * Returns the extended document properties
      */
@@ -217,6 +215,7 @@ public class XSSFEventBasedExcelExtracto
     public ExtendedProperties getExtendedProperties() {
         return properties.getExtendedProperties();
     }
+
     /**
      * Returns the custom document properties
      */
@@ -226,7 +225,6 @@ public class XSSFEventBasedExcelExtracto
     }
 
 
-
     /**
      * Processes the given sheet
      */
@@ -238,96 +236,95 @@ public class XSSFEventBasedExcelExtracto
             InputStream sheetInputStream)
             throws IOException, SAXException {
 
-       DataFormatter formatter;
-       if(locale == null) {
-          formatter = new DataFormatter();
-       } else  {
-          formatter = new DataFormatter(locale);
-       }
-      
-       InputSource sheetSource = new InputSource(sheetInputStream);
-       try {
-          XMLReader sheetParser = SAXHelper.newXMLReader();
-          ContentHandler handler = new XSSFSheetXMLHandler(
-                styles, comments, strings, sheetContentsExtractor, formatter, formulasNotResults);
-          sheetParser.setContentHandler(handler);
-          sheetParser.parse(sheetSource);
-       } catch(ParserConfigurationException e) {
-          throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());
-       }
-   }
-
-   /**
-    * Processes the file and returns the text
-    */
-   public String getText() {
-       try {
-          ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(container, concatenatePhoneticRuns);
-          XSSFReader xssfReader = new XSSFReader(container);
-          StylesTable styles = xssfReader.getStylesTable();
-          XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
-   
-          StringBuffer text = new StringBuffer();
-          SheetTextExtractor sheetExtractor = new SheetTextExtractor();
-          
-          while (iter.hasNext()) {
-              InputStream stream = iter.next();
-              if(includeSheetNames) {
-                 text.append(iter.getSheetName());
-                 text.append('\n');
-              }
-              CommentsTable comments = includeCellComments ? iter.getSheetComments() : null;
-              processSheet(sheetExtractor, styles, comments, strings, stream);
-              if (includeHeadersFooters) {
-                  sheetExtractor.appendHeaderText(text);
-              }
-              sheetExtractor.appendCellText(text);
-              if (includeTextBoxes){
-                  processShapes(iter.getShapes(), text);
-              }
-              if (includeHeadersFooters) {
-                  sheetExtractor.appendFooterText(text);
-              }
-              sheetExtractor.reset();
-              stream.close();
-          }
-          
-          return text.toString();
-       } catch(IOException | OpenXML4JException | SAXException e) {
-          LOGGER.log(POILogger.WARN, e);
-          return null;
-       }
-   }
-   
-    void processShapes(List<XSSFShape> shapes, StringBuffer text) {
-        if (shapes == null){
+        DataFormatter formatter;
+        if (locale == null) {
+            formatter = new DataFormatter();
+        } else {
+            formatter = new DataFormatter(locale);
+        }
+
+        InputSource sheetSource = new InputSource(sheetInputStream);
+        try {
+            XMLReader sheetParser = SAXHelper.newXMLReader();
+            ContentHandler handler = new XSSFSheetXMLHandler(
+                    styles, comments, strings, sheetContentsExtractor, formatter, formulasNotResults);
+            sheetParser.setContentHandler(handler);
+            sheetParser.parse(sheetSource);
+        } catch (ParserConfigurationException e) {
+            throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());
+        }
+    }
+
+    /**
+     * Processes the file and returns the text
+     */
+    public String getText() {
+        try {
+            ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(container, concatenatePhoneticRuns);
+            XSSFReader xssfReader = new XSSFReader(container);
+            StylesTable styles = xssfReader.getStylesTable();
+            XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
+            StringBuilder text = new StringBuilder(64);
+            SheetTextExtractor sheetExtractor = new SheetTextExtractor();
+
+            while (iter.hasNext()) {
+                InputStream stream = iter.next();
+                if (includeSheetNames) {
+                    text.append(iter.getSheetName());
+                    text.append('\n');
+                }
+                CommentsTable comments = includeCellComments ? iter.getSheetComments() : null;
+                processSheet(sheetExtractor, styles, comments, strings, stream);
+                if (includeHeadersFooters) {
+                    sheetExtractor.appendHeaderText(text);
+                }
+                sheetExtractor.appendCellText(text);
+                if (includeTextBoxes) {
+                    processShapes(iter.getShapes(), text);
+                }
+                if (includeHeadersFooters) {
+                    sheetExtractor.appendFooterText(text);
+                }
+                sheetExtractor.reset();
+                stream.close();
+            }
+
+            return text.toString();
+        } catch (IOException | OpenXML4JException | SAXException e) {
+            LOGGER.log(POILogger.WARN, e);
+            return null;
+        }
+    }
+
+    void processShapes(List<XSSFShape> shapes, StringBuilder text) {
+        if (shapes == null) {
             return;
         }
-        for (XSSFShape shape : shapes){
-            if (shape instanceof XSSFSimpleShape){
-                String sText = ((XSSFSimpleShape)shape).getText();
-                if (sText != null && sText.length() > 0){
+        for (XSSFShape shape : shapes) {
+            if (shape instanceof XSSFSimpleShape) {
+                String sText = ((XSSFSimpleShape) shape).getText();
+                if (sText != null && sText.length() > 0) {
                     text.append(sText).append('\n');
                 }
             }
         }
     }
+
     @Override
-	public void close() throws IOException {
-		if (container != null) {
-			container.close();
-			container = null;
-		}
-		super.close();
-	}
+    public void close() throws IOException {
+        if (container != null) {
+            container.close();
+            container = null;
+        }
+        super.close();
+    }
 
     protected class SheetTextExtractor implements SheetContentsHandler {
-        private final StringBuffer output;
+        private final StringBuilder output = new StringBuilder(64);
         private boolean firstCellOfRow;
         private final Map<String, String> headerFooterMap;
 
         protected SheetTextExtractor() {
-            this.output = new StringBuffer();
             this.firstCellOfRow = true;
             this.headerFooterMap = includeHeadersFooters ? new HashMap<>() : null;
         }
@@ -344,7 +341,7 @@ public class XSSFEventBasedExcelExtracto
 
         @Override
         public void cell(String cellRef, String formattedValue, XSSFComment comment) {
-            if(firstCellOfRow) {
+            if (firstCellOfRow) {
                 firstCellOfRow = false;
             } else {
                 output.append('\t');
@@ -375,7 +372,7 @@ public class XSSFEventBasedExcelExtracto
         /**
          * Append the text for the named header or footer if found.
          */
-        private void appendHeaderFooterText(StringBuffer buffer, String name) {
+        private void appendHeaderFooterText(StringBuilder buffer, String name) {
             String text = headerFooterMap.get(name);
             if (text != null && text.length() > 0) {
                 // this is a naive way of handling the left, center, and right
@@ -387,6 +384,7 @@ public class XSSFEventBasedExcelExtracto
                 buffer.append(text).append('\n');
             }
         }
+
         /**
          * Remove the delimiter if its found at the beginning of the text,
          * or replace it with a tab if its in the middle.
@@ -405,10 +403,11 @@ public class XSSFEventBasedExcelExtracto
         /**
          * Append the text for each header type in the same order
          * they are appended in XSSFExcelExtractor.
+         *
          * @see XSSFExcelExtractor#getText()
          * @see org.apache.poi.hssf.extractor.ExcelExtractor#_extractHeaderFooter(org.apache.poi.ss.usermodel.HeaderFooter)
          */
-        void appendHeaderText(StringBuffer buffer) {
+        void appendHeaderText(StringBuilder buffer) {
             appendHeaderFooterText(buffer, "firstHeader");
             appendHeaderFooterText(buffer, "oddHeader");
             appendHeaderFooterText(buffer, "evenHeader");
@@ -417,10 +416,11 @@ public class XSSFEventBasedExcelExtracto
         /**
          * Append the text for each footer type in the same order
          * they are appended in XSSFExcelExtractor.
+         *
          * @see XSSFExcelExtractor#getText()
          * @see org.apache.poi.hssf.extractor.ExcelExtractor#_extractHeaderFooter(org.apache.poi.ss.usermodel.HeaderFooter)
          */
-        void appendFooterText(StringBuffer buffer) {
+        void appendFooterText(StringBuilder buffer) {
             // append the text for each footer type in the same order
             // they are appended in XSSFExcelExtractor
             appendHeaderFooterText(buffer, "firstFooter");
@@ -431,7 +431,7 @@ public class XSSFEventBasedExcelExtracto
         /**
          * Append the cell contents we have collected.
          */
-        void appendCellText(StringBuffer buffer) {
+        void appendCellText(StringBuilder buffer) {
             checkMaxTextSize(buffer, output.toString());
             buffer.append(output);
         }

Modified: poi/trunk/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChart.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChart.java?rev=1813869&r1=1813868&r2=1813869&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChart.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChart.java Tue Oct 31 10:24:47 2017
@@ -292,7 +292,7 @@ public final class XSSFChart extends POI
 		// TODO Do properly
 		CTTitle title = chart.getTitle();
 
-		StringBuffer text = new StringBuffer();
+		StringBuilder text = new StringBuilder(64);
 		XmlObject[] t = title
 			.selectPath("declare namespace a='"+XSSFDrawing.NAMESPACE_A+"' .//a:t");
 		for (int m = 0; m < t.length; m++) {

Modified: poi/trunk/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/HeaderFooterHelper.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/HeaderFooterHelper.java?rev=1813869&r1=1813868&r2=1813869&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/HeaderFooterHelper.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/HeaderFooterHelper.java Tue Oct 31 10:24:47 2017
@@ -98,7 +98,7 @@ public class HeaderFooterHelper {
     	return joinParts(parts[0], parts[1], parts[2]);
     }
     private String joinParts(String l, String c, String r) {
-    	StringBuffer ret = new StringBuffer();
+		StringBuilder ret = new StringBuilder(64);
 
     	// Join as c, l, r
     	if(c.length() > 0) {

Modified: poi/trunk/src/ooxml/java/org/apache/poi/xwpf/extractor/XWPFWordExtractor.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/xwpf/extractor/XWPFWordExtractor.java?rev=1813869&r1=1813868&r2=1813869&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/xwpf/extractor/XWPFWordExtractor.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/xwpf/extractor/XWPFWordExtractor.java Tue Oct 31 10:24:47 2017
@@ -97,7 +97,7 @@ public class XWPFWordExtractor extends P
     }
 
     public String getText() {
-        StringBuffer text = new StringBuffer();
+        StringBuilder text = new StringBuilder(64);
         XWPFHeaderFooterPolicy hfPolicy = document.getHeaderFooterPolicy();
 
         // Start out with all headers
@@ -115,7 +115,7 @@ public class XWPFWordExtractor extends P
         return text.toString();
     }
 
-    public void appendBodyElementText(StringBuffer text, IBodyElement e) {
+    public void appendBodyElementText(StringBuilder text, IBodyElement e) {
         if (e instanceof XWPFParagraph) {
             appendParagraphText(text, (XWPFParagraph) e);
         } else if (e instanceof XWPFTable) {
@@ -125,7 +125,7 @@ public class XWPFWordExtractor extends P
         }
     }
 
-    public void appendParagraphText(StringBuffer text, XWPFParagraph paragraph) {
+    public void appendParagraphText(StringBuilder text, XWPFParagraph paragraph) {
         CTSectPr ctSectPr = null;
         if (paragraph.getCTP().getPPr() != null) {
             ctSectPr = paragraph.getCTP().getPPr().getSectPr();
@@ -170,7 +170,7 @@ public class XWPFWordExtractor extends P
         }
     }
 
-    private void appendTableText(StringBuffer text, XWPFTable table) {
+    private void appendTableText(StringBuilder text, XWPFTable table) {
         //this works recursively to pull embedded tables from tables
         for (XWPFTableRow row : table.getRows()) {
             List<ICell> cells = row.getTableICells();
@@ -189,7 +189,7 @@ public class XWPFWordExtractor extends P
         }
     }
 
-    private void extractFooters(StringBuffer text, XWPFHeaderFooterPolicy hfPolicy) {
+    private void extractFooters(StringBuilder text, XWPFHeaderFooterPolicy hfPolicy) {
         if (hfPolicy == null) return;
 
         if (hfPolicy.getFirstPageFooter() != null) {
@@ -203,7 +203,7 @@ public class XWPFWordExtractor extends P
         }
     }
 
-    private void extractHeaders(StringBuffer text, XWPFHeaderFooterPolicy hfPolicy) {
+    private void extractHeaders(StringBuilder text, XWPFHeaderFooterPolicy hfPolicy) {
         if (hfPolicy == null) return;
 
         if (hfPolicy.getFirstPageHeader() != null) {

Modified: poi/trunk/src/ooxml/java/org/apache/poi/xwpf/model/XWPFCommentsDecorator.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/xwpf/model/XWPFCommentsDecorator.java?rev=1813869&r1=1813868&r2=1813869&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/xwpf/model/XWPFCommentsDecorator.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/xwpf/model/XWPFCommentsDecorator.java Tue Oct 31 10:24:47 2017
@@ -27,7 +27,7 @@ import org.openxmlformats.schemas.wordpr
  * @author Yury Batrakov (batrakov at gmail.com)
  */
 public class XWPFCommentsDecorator extends XWPFParagraphDecorator {
-    private StringBuffer commentText;
+    private StringBuilder commentText;
 
     public XWPFCommentsDecorator(XWPFParagraphDecorator nextDecorator) {
         this(nextDecorator.paragraph, nextDecorator);
@@ -37,11 +37,15 @@ public class XWPFCommentsDecorator exten
         super(paragraph, nextDecorator);
 
         XWPFComment comment;
-        commentText = new StringBuffer();
+        commentText = new StringBuilder(64);
 
         for (CTMarkupRange anchor : paragraph.getCTP().getCommentRangeStartArray()) {
-            if ((comment = paragraph.getDocument().getCommentByID(anchor.getId().toString())) != null)
-                commentText.append("\tComment by " + comment.getAuthor() + ": " + comment.getText());
+            if ((comment = paragraph.getDocument().getCommentByID(anchor.getId().toString())) != null) {
+                commentText.append("\tComment by ")
+                    .append(comment.getAuthor())
+                    .append(": ")
+                    .append(comment.getText());
+            }
         }
     }
 

Modified: poi/trunk/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFComment.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFComment.java?rev=1813869&r1=1813868&r2=1813869&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFComment.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFComment.java Tue Oct 31 10:24:47 2017
@@ -27,10 +27,10 @@ import org.openxmlformats.schemas.wordpr
 public class XWPFComment {
     protected String id;
     protected String author;
-    protected StringBuffer text;
+    protected StringBuilder text;
 
     public XWPFComment(CTComment comment, XWPFDocument document) {
-        text = new StringBuffer();
+        text = new StringBuilder(64);
         id = comment.getId().toString();
         author = comment.getAuthor();
 

Modified: poi/trunk/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java
URL: http://svn.apache.org/viewvc/poi/trunk/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java?rev=1813869&r1=1813868&r2=1813869&view=diff
==============================================================================
--- poi/trunk/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java (original)
+++ poi/trunk/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java Tue Oct 31 10:24:47 2017
@@ -127,7 +127,7 @@ public abstract class XWPFHeaderFooter e
      * by flattening out the text of its paragraph(s)
      */
     public String getText() {
-        StringBuffer t = new StringBuffer();
+        StringBuilder t = new StringBuilder(64);
         //TODO: simplify this to get ibody elements in order
         for (int i = 0; i < paragraphs.size(); i++) {
             if (!paragraphs.get(i).isEmpty()) {



---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@poi.apache.org
For additional commands, e-mail: commits-help@poi.apache.org