aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorPJ Fanning <fanningpj@apache.org>2017-10-31 10:24:47 +0000
committerPJ Fanning <fanningpj@apache.org>2017-10-31 10:24:47 +0000
commitaa9b57774f628bd3a67dcc6afa94f7e128bfa8a7 (patch)
tree650e203f4c432a160d1f16a4a7c682925c4da3ce
parentcb28546f501a5802e250ff1fc07383472b1cbac7 (diff)
downloadpoi-aa9b57774f628bd3a67dcc6afa94f7e128bfa8a7.tar.gz
poi-aa9b57774f628bd3a67dcc6afa94f7e128bfa8a7.zip
use StringBuilder in more places
git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1813869 13f79535-47bb-0310-9956-ffa450edef68
-rw-r--r--src/java/org/apache/poi/hssf/model/LinkTable.java1002
-rw-r--r--src/ooxml/java/org/apache/poi/POIXMLPropertiesTextExtractor.java403
-rw-r--r--src/ooxml/java/org/apache/poi/openxml4j/opc/PackagingURIHelper.java2
-rw-r--r--src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentType.java8
-rw-r--r--src/ooxml/java/org/apache/poi/xssf/eventusermodel/ReadOnlySharedStringsTable.java4
-rw-r--r--src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFSheetXMLHandler.java6
-rw-r--r--src/ooxml/java/org/apache/poi/xssf/extractor/XSSFBEventBasedExcelExtractor.java2
-rw-r--r--src/ooxml/java/org/apache/poi/xssf/extractor/XSSFEventBasedExcelExtractor.java196
-rw-r--r--src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChart.java2
-rw-r--r--src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/HeaderFooterHelper.java2
-rw-r--r--src/ooxml/java/org/apache/poi/xwpf/extractor/XWPFWordExtractor.java12
-rw-r--r--src/ooxml/java/org/apache/poi/xwpf/model/XWPFCommentsDecorator.java12
-rw-r--r--src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFComment.java4
-rw-r--r--src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java2
-rw-r--r--src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFParagraph.java8
-rw-r--r--src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRun.java18
-rw-r--r--src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTable.java2
-rw-r--r--src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTableCell.java4
18 files changed, 847 insertions, 842 deletions
diff --git a/src/java/org/apache/poi/hssf/model/LinkTable.java b/src/java/org/apache/poi/hssf/model/LinkTable.java
index b55e7b952f..53ef5d6e96 100644
--- a/src/java/org/apache/poi/hssf/model/LinkTable.java
+++ b/src/java/org/apache/poi/hssf/model/LinkTable.java
@@ -41,137 +41,139 @@ import org.apache.poi.ss.usermodel.Workbook;
/**
* 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 {
-
- 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;
- }
+ // TODO make this class into a record aggregate
+ private static final class CRNBlock {
+
+ 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 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 void removeSheet(int sheetIdx) {
+ _externSheetRecord.removeSheet(sheetIdx);
+ }
+
+ public int checkExternSheet(int sheetIndex) {
+ return checkExternSheet(sheetIndex, sheetIndex);
+ }
- 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;
+ }
}
diff --git a/src/ooxml/java/org/apache/poi/POIXMLPropertiesTextExtractor.java b/src/ooxml/java/org/apache/poi/POIXMLPropertiesTextExtractor.java
index b2621ebd16..f0fe9c30f7 100644
--- a/src/ooxml/java/org/apache/poi/POIXMLPropertiesTextExtractor.java
+++ b/src/ooxml/java/org/apache/poi/POIXMLPropertiesTextExtractor.java
@@ -30,211 +30,206 @@ import org.openxmlformats.schemas.officeDocument.x2006.customProperties.CTProper
/**
* 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();
-
- 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")
+ 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")
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!)";
-
- 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(64);
+ org.openxmlformats.schemas.officeDocument.x2006.extendedProperties.CTProperties
+ props = document.getProperties().getExtendedProperties().getUnderlyingProperties();
- // 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() );
- }
+ 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());
- // 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());
- }
+ return text.toString();
+ }
- // 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();
+ /**
+ * 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!)";
+
+ 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());
+ }
+
+ // 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();
+ }
}
- }
/*else if (property.isSetArray()) {
// TODO Fetch the array values and output
@@ -254,26 +249,26 @@ public class POIXMLPropertiesTextExtractor extends POIXMLTextExtractor {
// 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);
- }
- }
-
- @Override
+ try {
+ return
+ getCorePropertiesText() +
+ getExtendedPropertiesText() +
+ getCustomPropertiesText();
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ @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!");
+ }
}
diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagingURIHelper.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagingURIHelper.java
index 397e579ab3..2ed32223df 100644
--- a/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagingURIHelper.java
+++ b/src/ooxml/java/org/apache/poi/openxml4j/opc/PackagingURIHelper.java
@@ -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();
diff --git a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentType.java b/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentType.java
index 276aba59cd..43449b20a9 100644
--- a/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentType.java
+++ b/src/ooxml/java/org/apache/poi/openxml4j/opc/internal/ContentType.java
@@ -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());
}
}
diff --git a/src/ooxml/java/org/apache/poi/xssf/eventusermodel/ReadOnlySharedStringsTable.java b/src/ooxml/java/org/apache/poi/xssf/eventusermodel/ReadOnlySharedStringsTable.java
index 991ccdb3e3..6fd47a9022 100644
--- a/src/ooxml/java/org/apache/poi/xssf/eventusermodel/ReadOnlySharedStringsTable.java
+++ b/src/ooxml/java/org/apache/poi/xssf/eventusermodel/ReadOnlySharedStringsTable.java
@@ -223,7 +223,7 @@ public class ReadOnlySharedStringsTable extends DefaultHandler {
//// ContentHandler methods ////
- private StringBuffer characters;
+ private StringBuilder characters;
private boolean tIsOpen;
private boolean inRPh;
@@ -241,7 +241,7 @@ public class ReadOnlySharedStringsTable extends DefaultHandler {
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)) {
diff --git a/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFSheetXMLHandler.java b/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFSheetXMLHandler.java
index e5f5e5c503..2c8e0e2d37 100644
--- a/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFSheetXMLHandler.java
+++ b/src/ooxml/java/org/apache/poi/xssf/eventusermodel/XSSFSheetXMLHandler.java
@@ -102,9 +102,9 @@ public class XSSFSheetXMLHandler extends DefaultHandler {
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;
diff --git a/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFBEventBasedExcelExtractor.java b/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFBEventBasedExcelExtractor.java
index 4772bca593..155a5fc22b 100644
--- a/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFBEventBasedExcelExtractor.java
+++ b/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFBEventBasedExcelExtractor.java
@@ -122,7 +122,7 @@ public class XSSFBEventBasedExcelExtractor extends XSSFEventBasedExcelExtractor
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()) {
diff --git a/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFEventBasedExcelExtractor.java b/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFEventBasedExcelExtractor.java
index d94df4cf28..b41966d027 100644
--- a/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFEventBasedExcelExtractor.java
+++ b/src/ooxml/java/org/apache/poi/xssf/extractor/XSSFEventBasedExcelExtractor.java
@@ -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 XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
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 XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
}
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 XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
/**
- *
* @return whether to include sheet names
- *
* @since 3.16-beta3
*/
public boolean getIncludeSheetNames() {
@@ -112,16 +111,14 @@ public class XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
/**
* 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 XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
}
/**
- *
* @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 XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
}
/**
- *
* @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 XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
/**
* @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 XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
public CoreProperties getCoreProperties() {
return properties.getCoreProperties();
}
+
/**
* Returns the extended document properties
*/
@@ -217,6 +215,7 @@ public class XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
public ExtendedProperties getExtendedProperties() {
return properties.getExtendedProperties();
}
+
/**
* Returns the custom document properties
*/
@@ -226,7 +225,6 @@ public class XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
}
-
/**
* Processes the given sheet
*/
@@ -238,96 +236,95 @@ public class XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
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 XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
@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 XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
/**
* 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 XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
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 XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
/**
* 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 XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
/**
* 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 XSSFEventBasedExcelExtractor extends POIXMLTextExtractor
/**
* Append the cell contents we have collected.
*/
- void appendCellText(StringBuffer buffer) {
+ void appendCellText(StringBuilder buffer) {
checkMaxTextSize(buffer, output.toString());
buffer.append(output);
}
diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChart.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChart.java
index df0e951c10..55f71479f7 100644
--- a/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChart.java
+++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/XSSFChart.java
@@ -292,7 +292,7 @@ public final class XSSFChart extends POIXMLDocumentPart implements Chart, ChartA
// 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++) {
diff --git a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/HeaderFooterHelper.java b/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/HeaderFooterHelper.java
index 41e3ea462e..e4731dae11 100644
--- a/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/HeaderFooterHelper.java
+++ b/src/ooxml/java/org/apache/poi/xssf/usermodel/helpers/HeaderFooterHelper.java
@@ -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) {
diff --git a/src/ooxml/java/org/apache/poi/xwpf/extractor/XWPFWordExtractor.java b/src/ooxml/java/org/apache/poi/xwpf/extractor/XWPFWordExtractor.java
index aaf4453623..a162a62003 100644
--- a/src/ooxml/java/org/apache/poi/xwpf/extractor/XWPFWordExtractor.java
+++ b/src/ooxml/java/org/apache/poi/xwpf/extractor/XWPFWordExtractor.java
@@ -97,7 +97,7 @@ public class XWPFWordExtractor extends POIXMLTextExtractor {
}
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 POIXMLTextExtractor {
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 POIXMLTextExtractor {
}
}
- 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 POIXMLTextExtractor {
}
}
- 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 POIXMLTextExtractor {
}
}
- 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 POIXMLTextExtractor {
}
}
- private void extractHeaders(StringBuffer text, XWPFHeaderFooterPolicy hfPolicy) {
+ private void extractHeaders(StringBuilder text, XWPFHeaderFooterPolicy hfPolicy) {
if (hfPolicy == null) return;
if (hfPolicy.getFirstPageHeader() != null) {
diff --git a/src/ooxml/java/org/apache/poi/xwpf/model/XWPFCommentsDecorator.java b/src/ooxml/java/org/apache/poi/xwpf/model/XWPFCommentsDecorator.java
index 7b83560505..6a29cd3898 100644
--- a/src/ooxml/java/org/apache/poi/xwpf/model/XWPFCommentsDecorator.java
+++ b/src/ooxml/java/org/apache/poi/xwpf/model/XWPFCommentsDecorator.java
@@ -27,7 +27,7 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTMarkupRange;
* @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 extends XWPFParagraphDecorator {
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());
+ }
}
}
diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFComment.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFComment.java
index 5f7fa5d8df..72de790840 100644
--- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFComment.java
+++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFComment.java
@@ -27,10 +27,10 @@ import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
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();
diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java
index 24d83925a6..5c14b2f5a6 100644
--- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java
+++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFHeaderFooter.java
@@ -127,7 +127,7 @@ public abstract class XWPFHeaderFooter extends POIXMLDocumentPart implements IBo
* 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()) {
diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFParagraph.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFParagraph.java
index e7ced6239e..989c93db5f 100644
--- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFParagraph.java
+++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFParagraph.java
@@ -45,7 +45,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
protected List<XWPFRun> runs;
protected List<IRunElement> iruns;
- private StringBuffer footnoteText = new StringBuffer();
+ private StringBuilder footnoteText = new StringBuilder(64);
public XWPFParagraph(CTP prgrph, IBody part) {
this.paragraph = prgrph;
@@ -184,7 +184,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
* and sdt elements in it.
*/
public String getText() {
- StringBuffer out = new StringBuffer();
+ StringBuilder out = new StringBuilder(64);
for (IRunElement run : iruns) {
if (run instanceof XWPFRun) {
XWPFRun xRun = (XWPFRun) run;
@@ -398,7 +398,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
* paragraph
*/
public String getParagraphText() {
- StringBuffer out = new StringBuffer();
+ StringBuilder out = new StringBuilder(64);
for (XWPFRun run : runs) {
out.append(run);
}
@@ -409,7 +409,7 @@ public class XWPFParagraph implements IBodyElement, IRunBody, ISDTContents, Para
* Returns any text from any suitable pictures in the paragraph
*/
public String getPictureText() {
- StringBuffer out = new StringBuffer();
+ StringBuilder out = new StringBuilder(64);
for (XWPFRun run : runs) {
out.append(run.getPictureText());
}
diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRun.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRun.java
index 8b9c527aae..dd93105c56 100644
--- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRun.java
+++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFRun.java
@@ -1060,7 +1060,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* carriage returns in place of their xml equivalents.
*/
public String text() {
- StringBuffer text = new StringBuffer();
+ StringBuilder text = new StringBuilder(64);
// Grab the text and tabs of the text run
// Do so in a way that preserves the ordering
@@ -1084,7 +1084,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* @return the phonetic (ruby) string associated with this run or an empty String if none exists
*/
public String getPhonetic() {
- StringBuffer text = new StringBuffer();
+ StringBuilder text = new StringBuilder(64);
// Grab the text and tabs of the text run
// Do so in a way that preserves the ordering
@@ -1110,7 +1110,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
* @param text buffer to which to append the content
* @param extractPhonetic extract the phonetic (rt) component or the base component
*/
- private void handleRuby(XmlObject rubyObj, StringBuffer text, boolean extractPhonetic) {
+ private void handleRuby(XmlObject rubyObj, StringBuilder text, boolean extractPhonetic) {
XmlCursor c = rubyObj.newCursor();
//according to the spec, a ruby object
@@ -1141,7 +1141,7 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
c.dispose();
}
- private void _getText(XmlObject o, StringBuffer text) {
+ private void _getText(XmlObject o, StringBuilder text) {
if (o instanceof CTText) {
String tagName = o.getDomNode().getNodeName();
@@ -1170,10 +1170,10 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
}
if (o instanceof CTPTab) {
- text.append("\t");
+ text.append('\t');
}
if (o instanceof CTBr) {
- text.append("\n");
+ text.append('\n');
}
if (o instanceof CTEmpty) {
// Some inline text elements get returned not as
@@ -1183,13 +1183,13 @@ public class XWPFRun implements ISDTContents, IRunElement, CharacterRun {
// rules for that case
String tagName = o.getDomNode().getNodeName();
if ("w:tab".equals(tagName) || "tab".equals(tagName)) {
- text.append("\t");
+ text.append('\t');
}
if ("w:br".equals(tagName) || "br".equals(tagName)) {
- text.append("\n");
+ text.append('\n');
}
if ("w:cr".equals(tagName) || "cr".equals(tagName)) {
- text.append("\n");
+ text.append('\n');
}
}
if (o instanceof CTFtnEdnRef) {
diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTable.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTable.java
index 43f36c74ce..388e0fb045 100644
--- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTable.java
+++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTable.java
@@ -71,7 +71,7 @@ public class XWPFTable implements IBodyElement, ISDTContents {
stBorderTypeMap.put(STBorder.INT_DOT_DASH, XWPFBorderType.DOT_DASH);
}
- protected StringBuffer text = new StringBuffer();
+ protected StringBuilder text = new StringBuilder(64);
protected List<XWPFTableRow> tableRows;
// Unused: UUF_UNUSED_PUBLIC_OR_PROTECTED_FIELD
diff --git a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTableCell.java b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTableCell.java
index 4ce566bc44..661912c8e7 100644
--- a/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTableCell.java
+++ b/src/ooxml/java/org/apache/poi/xwpf/usermodel/XWPFTableCell.java
@@ -435,7 +435,7 @@ public class XWPFTableCell implements IBody, ICell {
*/
public String getTextRecursively() {
- StringBuffer text = new StringBuffer();
+ StringBuilder text = new StringBuilder(64);
for (int i = 0; i < bodyElements.size(); i++) {
boolean isLast = (i == bodyElements.size() - 1);
appendBodyElementText(text, bodyElements.get(i), isLast);
@@ -444,7 +444,7 @@ public class XWPFTableCell implements IBody, ICell {
return text.toString();
}
- private void appendBodyElementText(StringBuffer text, IBodyElement e, boolean isLast) {
+ private void appendBodyElementText(StringBuilder text, IBodyElement e, boolean isLast) {
if (e instanceof XWPFParagraph) {
text.append(((XWPFParagraph) e).getText());
if (!isLast) {