PageRenderTime 52ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/projects/poi-3.6/src/java/org/apache/poi/hssf/record/aggregates/RowRecordsAggregate.java

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Java | 506 lines | 345 code | 56 blank | 105 comment | 66 complexity | e1a296a3b228f86c59290d064bd50236 MD5 | raw file
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.hssf.record.aggregates;
  16. import java.util.ArrayList;
  17. import java.util.Iterator;
  18. import java.util.List;
  19. import java.util.Map;
  20. import java.util.TreeMap;
  21. import org.apache.poi.hssf.model.RecordStream;
  22. import org.apache.poi.hssf.record.ArrayRecord;
  23. import org.apache.poi.hssf.record.CellValueRecordInterface;
  24. import org.apache.poi.hssf.record.ContinueRecord;
  25. import org.apache.poi.hssf.record.DBCellRecord;
  26. import org.apache.poi.hssf.record.DimensionsRecord;
  27. import org.apache.poi.hssf.record.FormulaRecord;
  28. import org.apache.poi.hssf.record.IndexRecord;
  29. import org.apache.poi.hssf.record.MergeCellsRecord;
  30. import org.apache.poi.hssf.record.MulBlankRecord;
  31. import org.apache.poi.hssf.record.Record;
  32. import org.apache.poi.hssf.record.RowRecord;
  33. import org.apache.poi.hssf.record.SharedFormulaRecord;
  34. import org.apache.poi.hssf.record.TableRecord;
  35. import org.apache.poi.hssf.record.UnknownRecord;
  36. import org.apache.poi.hssf.record.formula.FormulaShifter;
  37. import org.apache.poi.ss.SpreadsheetVersion;
  38. /**
  39. *
  40. * @author andy
  41. * @author Jason Height (jheight at chariot dot net dot au)
  42. */
  43. public final class RowRecordsAggregate extends RecordAggregate {
  44. private int _firstrow = -1;
  45. private int _lastrow = -1;
  46. private final Map<Integer, RowRecord> _rowRecords;
  47. private final ValueRecordsAggregate _valuesAgg;
  48. private final List<Record> _unknownRecords;
  49. private final SharedValueManager _sharedValueManager;
  50. /** Creates a new instance of ValueRecordsAggregate */
  51. public RowRecordsAggregate() {
  52. this(SharedValueManager.EMPTY);
  53. }
  54. private RowRecordsAggregate(SharedValueManager svm) {
  55. _rowRecords = new TreeMap<Integer, RowRecord>();
  56. _valuesAgg = new ValueRecordsAggregate();
  57. _unknownRecords = new ArrayList<Record>();
  58. _sharedValueManager = svm;
  59. }
  60. /**
  61. * @param rs record stream with all {@link SharedFormulaRecord}
  62. * {@link ArrayRecord}, {@link TableRecord} {@link MergeCellsRecord} Records removed
  63. */
  64. public RowRecordsAggregate(RecordStream rs, SharedValueManager svm) {
  65. this(svm);
  66. while(rs.hasNext()) {
  67. Record rec = rs.getNext();
  68. switch (rec.getSid()) {
  69. case RowRecord.sid:
  70. insertRow((RowRecord) rec);
  71. continue;
  72. case DBCellRecord.sid:
  73. // end of 'Row Block'. Should only occur after cell records
  74. // ignore DBCELL records because POI generates them upon re-serialization
  75. continue;
  76. }
  77. if (rec instanceof UnknownRecord) {
  78. // might need to keep track of where exactly these belong
  79. addUnknownRecord(rec);
  80. while (rs.peekNextSid() == ContinueRecord.sid) {
  81. addUnknownRecord(rs.getNext());
  82. }
  83. continue;
  84. }
  85. if (rec instanceof MulBlankRecord) {
  86. _valuesAgg.addMultipleBlanks((MulBlankRecord) rec);
  87. continue;
  88. }
  89. if (!(rec instanceof CellValueRecordInterface)) {
  90. throw new RuntimeException("Unexpected record type (" + rec.getClass().getName() + ")");
  91. }
  92. _valuesAgg.construct((CellValueRecordInterface)rec, rs, svm);
  93. }
  94. }
  95. /**
  96. * Handles UnknownRecords which appear within the row/cell records
  97. */
  98. private void addUnknownRecord(Record rec) {
  99. // ony a few distinct record IDs are encountered by the existing POI test cases:
  100. // 0x1065 // many
  101. // 0x01C2 // several
  102. // 0x0034 // few
  103. // No documentation could be found for these
  104. // keep the unknown records for re-serialization
  105. _unknownRecords.add(rec);
  106. }
  107. public void insertRow(RowRecord row) {
  108. // Integer integer = Integer.valueOf(row.getRowNumber());
  109. _rowRecords.put(Integer.valueOf(row.getRowNumber()), row);
  110. if ((row.getRowNumber() < _firstrow) || (_firstrow == -1)) {
  111. _firstrow = row.getRowNumber();
  112. }
  113. if ((row.getRowNumber() > _lastrow) || (_lastrow == -1)) {
  114. _lastrow = row.getRowNumber();
  115. }
  116. }
  117. public void removeRow(RowRecord row) {
  118. int rowIndex = row.getRowNumber();
  119. _valuesAgg.removeAllCellsValuesForRow(rowIndex);
  120. Integer key = Integer.valueOf(rowIndex);
  121. RowRecord rr = _rowRecords.remove(key);
  122. if (rr == null) {
  123. throw new RuntimeException("Invalid row index (" + key.intValue() + ")");
  124. }
  125. if (row != rr) {
  126. _rowRecords.put(key, rr);
  127. throw new RuntimeException("Attempt to remove row that does not belong to this sheet");
  128. }
  129. }
  130. public RowRecord getRow(int rowIndex) {
  131. int maxrow = SpreadsheetVersion.EXCEL97.getLastRowIndex();
  132. if (rowIndex < 0 || rowIndex > maxrow) {
  133. throw new IllegalArgumentException("The row number must be between 0 and " + maxrow);
  134. }
  135. return _rowRecords.get(Integer.valueOf(rowIndex));
  136. }
  137. public int getPhysicalNumberOfRows()
  138. {
  139. return _rowRecords.size();
  140. }
  141. public int getFirstRowNum()
  142. {
  143. return _firstrow;
  144. }
  145. public int getLastRowNum()
  146. {
  147. return _lastrow;
  148. }
  149. /** Returns the number of row blocks.
  150. * <p/>The row blocks are goupings of rows that contain the DBCell record
  151. * after them
  152. */
  153. public int getRowBlockCount() {
  154. int size = _rowRecords.size()/DBCellRecord.BLOCK_SIZE;
  155. if ((_rowRecords.size() % DBCellRecord.BLOCK_SIZE) != 0)
  156. size++;
  157. return size;
  158. }
  159. private int getRowBlockSize(int block) {
  160. return RowRecord.ENCODED_SIZE * getRowCountForBlock(block);
  161. }
  162. /** Returns the number of physical rows within a block*/
  163. public int getRowCountForBlock(int block) {
  164. int startIndex = block * DBCellRecord.BLOCK_SIZE;
  165. int endIndex = startIndex + DBCellRecord.BLOCK_SIZE - 1;
  166. if (endIndex >= _rowRecords.size())
  167. endIndex = _rowRecords.size()-1;
  168. return endIndex-startIndex+1;
  169. }
  170. /** Returns the physical row number of the first row in a block*/
  171. private int getStartRowNumberForBlock(int block) {
  172. //Given that we basically iterate through the rows in order,
  173. // TODO - For a performance improvement, it would be better to return an instance of
  174. //an iterator and use that instance throughout, rather than recreating one and
  175. //having to move it to the right position.
  176. int startIndex = block * DBCellRecord.BLOCK_SIZE;
  177. Iterator rowIter = _rowRecords.values().iterator();
  178. RowRecord row = null;
  179. //Position the iterator at the start of the block
  180. for (int i=0; i<=startIndex;i++) {
  181. row = (RowRecord)rowIter.next();
  182. }
  183. if (row == null) {
  184. throw new RuntimeException("Did not find start row for block " + block);
  185. }
  186. return row.getRowNumber();
  187. }
  188. /** Returns the physical row number of the end row in a block*/
  189. private int getEndRowNumberForBlock(int block) {
  190. int endIndex = ((block + 1)*DBCellRecord.BLOCK_SIZE)-1;
  191. if (endIndex >= _rowRecords.size())
  192. endIndex = _rowRecords.size()-1;
  193. Iterator rowIter = _rowRecords.values().iterator();
  194. RowRecord row = null;
  195. for (int i=0; i<=endIndex;i++) {
  196. row = (RowRecord)rowIter.next();
  197. }
  198. if (row == null) {
  199. throw new RuntimeException("Did not find start row for block " + block);
  200. }
  201. return row.getRowNumber();
  202. }
  203. private int visitRowRecordsForBlock(int blockIndex, RecordVisitor rv) {
  204. final int startIndex = blockIndex*DBCellRecord.BLOCK_SIZE;
  205. final int endIndex = startIndex + DBCellRecord.BLOCK_SIZE;
  206. Iterator rowIterator = _rowRecords.values().iterator();
  207. //Given that we basically iterate through the rows in order,
  208. //For a performance improvement, it would be better to return an instance of
  209. //an iterator and use that instance throughout, rather than recreating one and
  210. //having to move it to the right position.
  211. int i=0;
  212. for (;i<startIndex;i++)
  213. rowIterator.next();
  214. int result = 0;
  215. while(rowIterator.hasNext() && (i++ < endIndex)) {
  216. Record rec = (Record)rowIterator.next();
  217. result += rec.getRecordSize();
  218. rv.visitRecord(rec);
  219. }
  220. return result;
  221. }
  222. public void visitContainedRecords(RecordVisitor rv) {
  223. PositionTrackingVisitor stv = new PositionTrackingVisitor(rv, 0);
  224. //DBCells are serialized before row records.
  225. final int blockCount = getRowBlockCount();
  226. for (int blockIndex = 0; blockIndex < blockCount; blockIndex++) {
  227. // Serialize a block of rows.
  228. // Hold onto the position of the first row in the block
  229. int pos=0;
  230. // Hold onto the size of this block that was serialized
  231. final int rowBlockSize = visitRowRecordsForBlock(blockIndex, rv);
  232. pos += rowBlockSize;
  233. // Serialize a block of cells for those rows
  234. final int startRowNumber = getStartRowNumberForBlock(blockIndex);
  235. final int endRowNumber = getEndRowNumberForBlock(blockIndex);
  236. DBCellRecord.Builder dbcrBuilder = new DBCellRecord.Builder();
  237. // Note: Cell references start from the second row...
  238. int cellRefOffset = (rowBlockSize - RowRecord.ENCODED_SIZE);
  239. for (int row = startRowNumber; row <= endRowNumber; row++) {
  240. if (_valuesAgg.rowHasCells(row)) {
  241. stv.setPosition(0);
  242. _valuesAgg.visitCellsForRow(row, stv);
  243. int rowCellSize = stv.getPosition();
  244. pos += rowCellSize;
  245. // Add the offset to the first cell for the row into the
  246. // DBCellRecord.
  247. dbcrBuilder.addCellOffset(cellRefOffset);
  248. cellRefOffset = rowCellSize;
  249. }
  250. }
  251. // Calculate Offset from the start of a DBCellRecord to the first Row
  252. rv.visitRecord(dbcrBuilder.build(pos));
  253. }
  254. for (int i=0; i< _unknownRecords.size(); i++) {
  255. // Potentially breaking the file here since we don't know exactly where to write these records
  256. rv.visitRecord(_unknownRecords.get(i));
  257. }
  258. }
  259. public Iterator getIterator() {
  260. return _rowRecords.values().iterator();
  261. }
  262. public int findStartOfRowOutlineGroup(int row) {
  263. // Find the start of the group.
  264. RowRecord rowRecord = this.getRow( row );
  265. int level = rowRecord.getOutlineLevel();
  266. int currentRow = row;
  267. while (this.getRow( currentRow ) != null) {
  268. rowRecord = this.getRow( currentRow );
  269. if (rowRecord.getOutlineLevel() < level) {
  270. return currentRow + 1;
  271. }
  272. currentRow--;
  273. }
  274. return currentRow + 1;
  275. }
  276. public int findEndOfRowOutlineGroup(int row) {
  277. int level = getRow( row ).getOutlineLevel();
  278. int currentRow;
  279. for (currentRow = row; currentRow < getLastRowNum(); currentRow++) {
  280. if (getRow(currentRow) == null || getRow(currentRow).getOutlineLevel() < level) {
  281. break;
  282. }
  283. }
  284. return currentRow-1;
  285. }
  286. /**
  287. * Hide all rows at or below the current outline level
  288. * @return index of the <em>next<em> row after the last row that gets hidden
  289. */
  290. private int writeHidden(RowRecord pRowRecord, int row) {
  291. int rowIx = row;
  292. RowRecord rowRecord = pRowRecord;
  293. int level = rowRecord.getOutlineLevel();
  294. while (rowRecord != null && getRow(rowIx).getOutlineLevel() >= level) {
  295. rowRecord.setZeroHeight(true);
  296. rowIx++;
  297. rowRecord = getRow(rowIx);
  298. }
  299. return rowIx;
  300. }
  301. public void collapseRow(int rowNumber) {
  302. // Find the start of the group.
  303. int startRow = findStartOfRowOutlineGroup(rowNumber);
  304. RowRecord rowRecord = getRow(startRow);
  305. // Hide all the columns until the end of the group
  306. int nextRowIx = writeHidden(rowRecord, startRow);
  307. RowRecord row = getRow(nextRowIx);
  308. if (row == null) {
  309. row = createRow(nextRowIx);
  310. insertRow(row);
  311. }
  312. // Write collapse field
  313. row.setColapsed(true);
  314. }
  315. /**
  316. * Create a row record.
  317. *
  318. * @param rowNumber row number
  319. * @return RowRecord created for the passed in row number
  320. * @see org.apache.poi.hssf.record.RowRecord
  321. */
  322. public static RowRecord createRow(int rowNumber) {
  323. return new RowRecord(rowNumber);
  324. }
  325. public boolean isRowGroupCollapsed(int row) {
  326. int collapseRow = findEndOfRowOutlineGroup(row) + 1;
  327. if (getRow(collapseRow) == null) {
  328. return false;
  329. }
  330. return getRow( collapseRow ).getColapsed();
  331. }
  332. public void expandRow(int rowNumber) {
  333. int idx = rowNumber;
  334. if (idx == -1)
  335. return;
  336. // If it is already expanded do nothing.
  337. if (!isRowGroupCollapsed(idx)) {
  338. return;
  339. }
  340. // Find the start of the group.
  341. int startIdx = findStartOfRowOutlineGroup(idx);
  342. RowRecord row = getRow(startIdx);
  343. // Find the end of the group.
  344. int endIdx = findEndOfRowOutlineGroup(idx);
  345. // expand:
  346. // collapsed bit must be unset
  347. // hidden bit gets unset _if_ surrounding groups are expanded you can determine
  348. // this by looking at the hidden bit of the enclosing group. You will have
  349. // to look at the start and the end of the current group to determine which
  350. // is the enclosing group
  351. // hidden bit only is altered for this outline level. ie. don't un-collapse contained groups
  352. if (!isRowGroupHiddenByParent(idx)) {
  353. for (int i = startIdx; i <= endIdx; i++) {
  354. RowRecord otherRow = getRow(i);
  355. if (row.getOutlineLevel() == otherRow.getOutlineLevel() || !isRowGroupCollapsed(i)) {
  356. otherRow.setZeroHeight(false);
  357. }
  358. }
  359. }
  360. // Write collapse field
  361. getRow(endIdx + 1).setColapsed(false);
  362. }
  363. public boolean isRowGroupHiddenByParent(int row) {
  364. // Look out outline details of end
  365. int endLevel;
  366. boolean endHidden;
  367. int endOfOutlineGroupIdx = findEndOfRowOutlineGroup(row);
  368. if (getRow(endOfOutlineGroupIdx + 1) == null) {
  369. endLevel = 0;
  370. endHidden = false;
  371. } else {
  372. endLevel = getRow(endOfOutlineGroupIdx + 1).getOutlineLevel();
  373. endHidden = getRow(endOfOutlineGroupIdx + 1).getZeroHeight();
  374. }
  375. // Look out outline details of start
  376. int startLevel;
  377. boolean startHidden;
  378. int startOfOutlineGroupIdx = findStartOfRowOutlineGroup( row );
  379. if (startOfOutlineGroupIdx - 1 < 0 || getRow(startOfOutlineGroupIdx - 1) == null) {
  380. startLevel = 0;
  381. startHidden = false;
  382. } else {
  383. startLevel = getRow(startOfOutlineGroupIdx - 1).getOutlineLevel();
  384. startHidden = getRow(startOfOutlineGroupIdx - 1).getZeroHeight();
  385. }
  386. if (endLevel > startLevel) {
  387. return endHidden;
  388. }
  389. return startHidden;
  390. }
  391. public CellValueRecordInterface[] getValueRecords() {
  392. return _valuesAgg.getValueRecords();
  393. }
  394. public IndexRecord createIndexRecord(int indexRecordOffset, int sizeOfInitialSheetRecords) {
  395. IndexRecord result = new IndexRecord();
  396. result.setFirstRow(_firstrow);
  397. result.setLastRowAdd1(_lastrow + 1);
  398. // Calculate the size of the records from the end of the BOF
  399. // and up to the RowRecordsAggregate...
  400. // Add the references to the DBCells in the IndexRecord (one for each block)
  401. // Note: The offsets are relative to the Workbook BOF. Assume that this is
  402. // 0 for now.....
  403. int blockCount = getRowBlockCount();
  404. // Calculate the size of this IndexRecord
  405. int indexRecSize = IndexRecord.getRecordSizeForBlockCount(blockCount);
  406. int currentOffset = indexRecordOffset + indexRecSize + sizeOfInitialSheetRecords;
  407. for (int block = 0; block < blockCount; block++) {
  408. // each row-block has a DBCELL record.
  409. // The offset of each DBCELL record needs to be updated in the INDEX record
  410. // account for row records in this row-block
  411. currentOffset += getRowBlockSize(block);
  412. // account for cell value records after those
  413. currentOffset += _valuesAgg.getRowCellBlockSize(
  414. getStartRowNumberForBlock(block), getEndRowNumberForBlock(block));
  415. // currentOffset is now the location of the DBCELL record for this row-block
  416. result.addDbcell(currentOffset);
  417. // Add space required to write the DBCELL record (whose reference was just added).
  418. currentOffset += (8 + (getRowCountForBlock(block) * 2));
  419. }
  420. return result;
  421. }
  422. public void insertCell(CellValueRecordInterface cvRec) {
  423. _valuesAgg.insertCell(cvRec);
  424. }
  425. public void removeCell(CellValueRecordInterface cvRec) {
  426. if (cvRec instanceof FormulaRecordAggregate) {
  427. ((FormulaRecordAggregate)cvRec).notifyFormulaChanging();
  428. }
  429. _valuesAgg.removeCell(cvRec);
  430. }
  431. public FormulaRecordAggregate createFormula(int row, int col) {
  432. FormulaRecord fr = new FormulaRecord();
  433. fr.setRow(row);
  434. fr.setColumn((short) col);
  435. return new FormulaRecordAggregate(fr, null, _sharedValueManager);
  436. }
  437. public void updateFormulasAfterRowShift(FormulaShifter formulaShifter, int currentExternSheetIndex) {
  438. _valuesAgg.updateFormulasAfterRowShift(formulaShifter, currentExternSheetIndex);
  439. }
  440. public DimensionsRecord createDimensions() {
  441. DimensionsRecord result = new DimensionsRecord();
  442. result.setFirstRow(_firstrow);
  443. result.setLastRow(_lastrow);
  444. result.setFirstCol((short) _valuesAgg.getFirstCellNum());
  445. result.setLastCol((short) _valuesAgg.getLastCellNum());
  446. return result;
  447. }
  448. }