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

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