You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

PAPBinTable.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  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.hwpf.model;
  16. import java.io.ByteArrayOutputStream;
  17. import java.io.IOException;
  18. import java.util.ArrayList;
  19. import java.util.Comparator;
  20. import java.util.IdentityHashMap;
  21. import java.util.LinkedList;
  22. import java.util.List;
  23. import java.util.Map;
  24. import org.apache.poi.hwpf.sprm.SprmBuffer;
  25. import org.apache.poi.hwpf.sprm.SprmIterator;
  26. import org.apache.poi.hwpf.sprm.SprmOperation;
  27. import org.apache.poi.poifs.common.POIFSConstants;
  28. import org.apache.poi.util.Internal;
  29. import org.apache.poi.util.LittleEndian;
  30. import org.apache.poi.util.POILogFactory;
  31. import org.apache.poi.util.POILogger;
  32. /**
  33. * This class represents the bin table of Word document but it also serves as a
  34. * holder for all of the paragraphs of document that have been loaded into
  35. * memory.
  36. */
  37. @Internal
  38. public class PAPBinTable
  39. {
  40. private static final POILogger logger = POILogFactory
  41. .getLogger( PAPBinTable.class );
  42. protected final ArrayList<PAPX> _paragraphs = new ArrayList<>();
  43. public PAPBinTable()
  44. {
  45. }
  46. public PAPBinTable( byte[] documentStream, byte[] tableStream,
  47. byte[] dataStream, int offset, int size,
  48. CharIndexTranslator charIndexTranslator )
  49. {
  50. long start = System.currentTimeMillis();
  51. {
  52. PlexOfCps binTable = new PlexOfCps( tableStream, offset, size, 4 );
  53. int length = binTable.length();
  54. for ( int x = 0; x < length; x++ )
  55. {
  56. GenericPropertyNode node = binTable.getProperty( x );
  57. int pageNum = LittleEndian.getInt( node.getBytes() );
  58. int pageOffset = POIFSConstants.SMALLER_BIG_BLOCK_SIZE * pageNum;
  59. PAPFormattedDiskPage pfkp = new PAPFormattedDiskPage(
  60. documentStream, dataStream, pageOffset,
  61. charIndexTranslator );
  62. for ( PAPX papx : pfkp.getPAPXs() )
  63. {
  64. if ( papx != null )
  65. _paragraphs.add( papx );
  66. }
  67. }
  68. }
  69. logger.log( POILogger.DEBUG, "PAPX tables loaded in ",
  70. Long.valueOf( System.currentTimeMillis() - start ), " ms (",
  71. Integer.valueOf( _paragraphs.size() ), " elements)" );
  72. if ( _paragraphs.isEmpty() )
  73. {
  74. logger.log( POILogger.WARN, "PAPX FKPs are empty" );
  75. _paragraphs.add( new PAPX( 0, 0, new SprmBuffer( 2 ) ) );
  76. }
  77. }
  78. public void rebuild( final StringBuilder docText,
  79. ComplexFileTable complexFileTable )
  80. {
  81. rebuild( docText, complexFileTable, _paragraphs );
  82. }
  83. static void rebuild( final StringBuilder docText,
  84. ComplexFileTable complexFileTable, List<PAPX> paragraphs )
  85. {
  86. long start = System.currentTimeMillis();
  87. if ( complexFileTable != null )
  88. {
  89. SprmBuffer[] sprmBuffers = complexFileTable.getGrpprls();
  90. // adding PAPX from fast-saved SPRMs
  91. for ( TextPiece textPiece : complexFileTable.getTextPieceTable()
  92. .getTextPieces() )
  93. {
  94. PropertyModifier prm = textPiece.getPieceDescriptor().getPrm();
  95. if ( !prm.isComplex() )
  96. continue;
  97. int igrpprl = prm.getIgrpprl();
  98. if ( igrpprl < 0 || igrpprl >= sprmBuffers.length )
  99. {
  100. logger.log( POILogger.WARN, textPiece
  101. + "'s PRM references to unknown grpprl" );
  102. continue;
  103. }
  104. boolean hasPap = false;
  105. SprmBuffer sprmBuffer = sprmBuffers[igrpprl];
  106. for ( SprmIterator iterator = sprmBuffer.iterator(); iterator
  107. .hasNext(); )
  108. {
  109. SprmOperation sprmOperation = iterator.next();
  110. if ( sprmOperation.getType() == SprmOperation.TYPE_PAP )
  111. {
  112. hasPap = true;
  113. break;
  114. }
  115. }
  116. if ( hasPap )
  117. {
  118. SprmBuffer newSprmBuffer = new SprmBuffer( 2 );
  119. newSprmBuffer.append( sprmBuffer.toByteArray() );
  120. PAPX papx = new PAPX( textPiece.getStart(),
  121. textPiece.getEnd(), newSprmBuffer );
  122. paragraphs.add( papx );
  123. }
  124. }
  125. logger.log( POILogger.DEBUG,
  126. "Merged (?) with PAPX from complex file table in ",
  127. Long.valueOf( System.currentTimeMillis() - start ),
  128. " ms (", Integer.valueOf( paragraphs.size() ),
  129. " elements in total)" );
  130. start = System.currentTimeMillis();
  131. }
  132. List<PAPX> oldPapxSortedByEndPos = new ArrayList<>(paragraphs);
  133. oldPapxSortedByEndPos.sort(PropertyNode.EndComparator);
  134. logger.log( POILogger.DEBUG, "PAPX sorted by end position in ",
  135. Long.valueOf( System.currentTimeMillis() - start ), " ms" );
  136. start = System.currentTimeMillis();
  137. final Map<PAPX, Integer> papxToFileOrder = new IdentityHashMap<>();
  138. {
  139. int counter = 0;
  140. for ( PAPX papx : paragraphs )
  141. {
  142. papxToFileOrder.put( papx, Integer.valueOf( counter++ ) );
  143. }
  144. }
  145. final Comparator<PAPX> papxFileOrderComparator = new Comparator<PAPX>()
  146. {
  147. public int compare( PAPX o1, PAPX o2 )
  148. {
  149. Integer i1 = papxToFileOrder.get( o1 );
  150. Integer i2 = papxToFileOrder.get( o2 );
  151. return i1.compareTo( i2 );
  152. }
  153. };
  154. logger.log( POILogger.DEBUG, "PAPX's order map created in ",
  155. Long.valueOf( System.currentTimeMillis() - start ), " ms" );
  156. start = System.currentTimeMillis();
  157. List<PAPX> newPapxs = new LinkedList<>();
  158. int lastParStart = 0;
  159. int lastPapxIndex = 0;
  160. for ( int charIndex = 0; charIndex < docText.length(); charIndex++ )
  161. {
  162. final char c = docText.charAt( charIndex );
  163. if ( c != 13 && c != 7 && c != 12 )
  164. continue;
  165. final int startInclusive = lastParStart;
  166. final int endExclusive = charIndex + 1;
  167. boolean broken = false;
  168. List<PAPX> papxs = new LinkedList<>();
  169. for ( int papxIndex = lastPapxIndex; papxIndex < oldPapxSortedByEndPos
  170. .size(); papxIndex++ )
  171. {
  172. broken = false;
  173. PAPX papx = oldPapxSortedByEndPos.get( papxIndex );
  174. assert startInclusive == 0
  175. || papxIndex + 1 == oldPapxSortedByEndPos.size()
  176. || papx.getEnd() > startInclusive;
  177. if ( papx.getEnd() - 1 > charIndex )
  178. {
  179. lastPapxIndex = papxIndex;
  180. broken = true;
  181. break;
  182. }
  183. papxs.add( papx );
  184. }
  185. if ( !broken )
  186. {
  187. lastPapxIndex = oldPapxSortedByEndPos.size() - 1;
  188. }
  189. if ( papxs.size() == 0 )
  190. {
  191. logger.log( POILogger.WARN, "Paragraph [",
  192. Integer.valueOf( startInclusive ), "; ",
  193. Integer.valueOf( endExclusive ),
  194. ") has no PAPX. Creating new one." );
  195. // create it manually
  196. PAPX papx = new PAPX( startInclusive, endExclusive,
  197. new SprmBuffer( 2 ) );
  198. newPapxs.add( papx );
  199. lastParStart = endExclusive;
  200. continue;
  201. }
  202. if ( papxs.size() == 1 )
  203. {
  204. // can we reuse existing?
  205. PAPX existing = papxs.get( 0 );
  206. if ( existing.getStart() == startInclusive
  207. && existing.getEnd() == endExclusive )
  208. {
  209. newPapxs.add( existing );
  210. lastParStart = endExclusive;
  211. continue;
  212. }
  213. }
  214. // restore file order of PAPX
  215. papxs.sort(papxFileOrderComparator);
  216. SprmBuffer sprmBuffer = null;
  217. for ( PAPX papx : papxs )
  218. {
  219. if ( papx.getGrpprl() == null || papx.getGrpprl().length <= 2 )
  220. continue;
  221. if ( sprmBuffer == null ) {
  222. sprmBuffer = papx.getSprmBuf().copy();
  223. } else {
  224. sprmBuffer.append( papx.getGrpprl(), 2 );
  225. }
  226. }
  227. PAPX newPapx = new PAPX( startInclusive, endExclusive, sprmBuffer );
  228. newPapxs.add( newPapx );
  229. lastParStart = endExclusive;
  230. continue;
  231. }
  232. paragraphs.clear();
  233. paragraphs.addAll( newPapxs );
  234. logger.log( POILogger.DEBUG, "PAPX rebuilded from document text in ",
  235. Long.valueOf( System.currentTimeMillis() - start ), " ms (",
  236. Integer.valueOf( paragraphs.size() ), " elements)" );
  237. }
  238. public void insert(int listIndex, int cpStart, SprmBuffer buf)
  239. {
  240. PAPX forInsert = new PAPX(0, 0, buf);
  241. // Ensure character offsets are really characters
  242. forInsert.setStart(cpStart);
  243. forInsert.setEnd(cpStart);
  244. if (listIndex == _paragraphs.size())
  245. {
  246. _paragraphs.add(forInsert);
  247. }
  248. else
  249. {
  250. PAPX currentPap = _paragraphs.get(listIndex);
  251. if (currentPap != null && currentPap.getStart() < cpStart)
  252. {
  253. SprmBuffer clonedBuf = currentPap.getSprmBuf().copy();
  254. // Copy the properties of the one before to afterwards
  255. // Will go:
  256. // Original, until insert at point
  257. // New one
  258. // Clone of original, on to the old end
  259. PAPX clone = new PAPX(0, 0, clonedBuf);
  260. // Again ensure contains character based offsets no matter what
  261. clone.setStart(cpStart);
  262. clone.setEnd(currentPap.getEnd());
  263. currentPap.setEnd(cpStart);
  264. _paragraphs.add(listIndex + 1, forInsert);
  265. _paragraphs.add(listIndex + 2, clone);
  266. }
  267. else
  268. {
  269. _paragraphs.add(listIndex, forInsert);
  270. }
  271. }
  272. }
  273. public void adjustForDelete(int listIndex, int offset, int length)
  274. {
  275. int size = _paragraphs.size();
  276. int endMark = offset + length;
  277. int endIndex = listIndex;
  278. PAPX papx = _paragraphs.get(endIndex);
  279. while (papx.getEnd() < endMark)
  280. {
  281. papx = _paragraphs.get(++endIndex);
  282. }
  283. if (listIndex == endIndex)
  284. {
  285. papx = _paragraphs.get(endIndex);
  286. papx.setEnd((papx.getEnd() - endMark) + offset);
  287. }
  288. else
  289. {
  290. papx = _paragraphs.get(listIndex);
  291. papx.setEnd(offset);
  292. for (int x = listIndex + 1; x < endIndex; x++)
  293. {
  294. papx = _paragraphs.get(x);
  295. papx.setStart(offset);
  296. papx.setEnd(offset);
  297. }
  298. papx = _paragraphs.get(endIndex);
  299. papx.setEnd((papx.getEnd() - endMark) + offset);
  300. }
  301. for (int x = endIndex + 1; x < size; x++)
  302. {
  303. papx = _paragraphs.get(x);
  304. papx.setStart(papx.getStart() - length);
  305. papx.setEnd(papx.getEnd() - length);
  306. }
  307. }
  308. public void adjustForInsert(int listIndex, int length)
  309. {
  310. int size = _paragraphs.size();
  311. PAPX papx = _paragraphs.get(listIndex);
  312. papx.setEnd(papx.getEnd() + length);
  313. for (int x = listIndex + 1; x < size; x++)
  314. {
  315. papx = _paragraphs.get(x);
  316. papx.setStart(papx.getStart() + length);
  317. papx.setEnd(papx.getEnd() + length);
  318. }
  319. }
  320. public ArrayList<PAPX> getParagraphs()
  321. {
  322. return _paragraphs;
  323. }
  324. public void writeTo( ByteArrayOutputStream wordDocumentStream,
  325. ByteArrayOutputStream tableStream, CharIndexTranslator translator )
  326. throws IOException
  327. {
  328. PlexOfCps binTable = new PlexOfCps(4);
  329. // each FKP must start on a 512 byte page.
  330. int docOffset = wordDocumentStream.size();
  331. int mod = docOffset % POIFSConstants.SMALLER_BIG_BLOCK_SIZE;
  332. if (mod != 0)
  333. {
  334. byte[] padding = new byte[POIFSConstants.SMALLER_BIG_BLOCK_SIZE - mod];
  335. wordDocumentStream.write(padding);
  336. }
  337. // get the page number for the first fkp
  338. docOffset = wordDocumentStream.size();
  339. int pageNum = docOffset/POIFSConstants.SMALLER_BIG_BLOCK_SIZE;
  340. // get the ending fc
  341. // int endingFc = _paragraphs.get(_paragraphs.size() - 1).getEnd();
  342. // endingFc += fcMin;
  343. int endingFc = translator.getByteIndex( _paragraphs.get(_paragraphs.size() - 1 ).getEnd() );
  344. ArrayList<PAPX> overflow = _paragraphs;
  345. do
  346. {
  347. PAPX startingProp = overflow.get(0);
  348. // int start = startingProp.getStart() + fcMin;
  349. int start = translator.getByteIndex( startingProp.getStart() );
  350. PAPFormattedDiskPage pfkp = new PAPFormattedDiskPage();
  351. pfkp.fill(overflow);
  352. byte[] bufFkp = pfkp.toByteArray(tableStream, translator);
  353. wordDocumentStream.write(bufFkp);
  354. overflow = pfkp.getOverflow();
  355. int end = endingFc;
  356. if (overflow != null)
  357. {
  358. // end = overflow.get(0).getStart() + fcMin;
  359. end = translator.getByteIndex( overflow.get( 0 ).getStart() );
  360. }
  361. byte[] intHolder = new byte[4];
  362. LittleEndian.putInt(intHolder, 0, pageNum++);
  363. binTable.addProperty(new GenericPropertyNode(start, end, intHolder));
  364. }
  365. while (overflow != null);
  366. tableStream.write(binTable.toByteArray());
  367. }
  368. }