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.

RecordFactory.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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;
  16. import java.io.InputStream;
  17. import java.lang.reflect.Constructor;
  18. import java.lang.reflect.InvocationTargetException;
  19. import java.lang.reflect.Modifier;
  20. import java.util.*;
  21. import org.apache.poi.hssf.record.chart.*;
  22. import org.apache.poi.hssf.record.pivottable.*;
  23. /**
  24. * Title: Record Factory<P>
  25. * Description: Takes a stream and outputs an array of Record objects.<P>
  26. *
  27. * @see org.apache.poi.hssf.eventmodel.EventRecordFactory
  28. * @author Andrew C. Oliver (acoliver at apache dot org)
  29. * @author Marc Johnson (mjohnson at apache dot org)
  30. * @author Glen Stampoultzis (glens at apache.org)
  31. * @author Csaba Nagy (ncsaba at yahoo dot com)
  32. */
  33. public final class RecordFactory {
  34. private static final int NUM_RECORDS = 512;
  35. private interface I_RecordCreator {
  36. Record create(RecordInputStream in);
  37. Class<? extends Record> getRecordClass();
  38. }
  39. private static final class ReflectionRecordCreator implements I_RecordCreator {
  40. private final Constructor<? extends Record> _c;
  41. public ReflectionRecordCreator(Constructor<? extends Record> c) {
  42. _c = c;
  43. }
  44. public Record create(RecordInputStream in) {
  45. Object[] args = { in, };
  46. try {
  47. return _c.newInstance(args);
  48. } catch (IllegalArgumentException e) {
  49. throw new RuntimeException(e);
  50. } catch (InstantiationException e) {
  51. throw new RuntimeException(e);
  52. } catch (IllegalAccessException e) {
  53. throw new RuntimeException(e);
  54. } catch (InvocationTargetException e) {
  55. throw new RecordFormatException("Unable to construct record instance" , e.getTargetException());
  56. }
  57. }
  58. public Class<? extends Record> getRecordClass() {
  59. return _c.getDeclaringClass();
  60. }
  61. }
  62. private static final Class<?>[] CONSTRUCTOR_ARGS = { RecordInputStream.class, };
  63. /**
  64. * contains the classes for all the records we want to parse.<br/>
  65. * Note - this most but not *every* subclass of Record.
  66. */
  67. @SuppressWarnings("unchecked")
  68. private static final Class<? extends Record>[] recordClasses = new Class[] {
  69. ArrayRecord.class,
  70. BackupRecord.class,
  71. BlankRecord.class,
  72. BOFRecord.class,
  73. BookBoolRecord.class,
  74. BoolErrRecord.class,
  75. BottomMarginRecord.class,
  76. BoundSheetRecord.class,
  77. CalcCountRecord.class,
  78. CalcModeRecord.class,
  79. CFHeaderRecord.class,
  80. CFRuleRecord.class,
  81. ChartRecord.class,
  82. ChartTitleFormatRecord.class,
  83. CodepageRecord.class,
  84. ColumnInfoRecord.class,
  85. ContinueRecord.class,
  86. CountryRecord.class,
  87. CRNCountRecord.class,
  88. CRNRecord.class,
  89. DateWindow1904Record.class,
  90. DBCellRecord.class,
  91. DefaultColWidthRecord.class,
  92. DefaultRowHeightRecord.class,
  93. DeltaRecord.class,
  94. DimensionsRecord.class,
  95. DrawingGroupRecord.class,
  96. DrawingRecord.class,
  97. DrawingSelectionRecord.class,
  98. DSFRecord.class,
  99. DVALRecord.class,
  100. DVRecord.class,
  101. EOFRecord.class,
  102. ExtendedFormatRecord.class,
  103. ExternalNameRecord.class,
  104. ExternSheetRecord.class,
  105. ExtSSTRecord.class,
  106. FilePassRecord.class,
  107. FileSharingRecord.class,
  108. FnGroupCountRecord.class,
  109. FontRecord.class,
  110. FooterRecord.class,
  111. FormatRecord.class,
  112. FormulaRecord.class,
  113. GridsetRecord.class,
  114. GutsRecord.class,
  115. HCenterRecord.class,
  116. HeaderRecord.class,
  117. HideObjRecord.class,
  118. HorizontalPageBreakRecord.class,
  119. HyperlinkRecord.class,
  120. IndexRecord.class,
  121. InterfaceEndRecord.class,
  122. InterfaceHdrRecord.class,
  123. IterationRecord.class,
  124. LabelRecord.class,
  125. LabelSSTRecord.class,
  126. LeftMarginRecord.class,
  127. LegendRecord.class,
  128. MergeCellsRecord.class,
  129. MMSRecord.class,
  130. MulBlankRecord.class,
  131. MulRKRecord.class,
  132. NameRecord.class,
  133. NoteRecord.class,
  134. NumberRecord.class,
  135. ObjectProtectRecord.class,
  136. ObjRecord.class,
  137. PaletteRecord.class,
  138. PaneRecord.class,
  139. PasswordRecord.class,
  140. PasswordRev4Record.class,
  141. PrecisionRecord.class,
  142. PrintGridlinesRecord.class,
  143. PrintHeadersRecord.class,
  144. PrintSetupRecord.class,
  145. ProtectionRev4Record.class,
  146. ProtectRecord.class,
  147. RecalcIdRecord.class,
  148. RefModeRecord.class,
  149. RefreshAllRecord.class,
  150. RightMarginRecord.class,
  151. RKRecord.class,
  152. RowRecord.class,
  153. SaveRecalcRecord.class,
  154. ScenarioProtectRecord.class,
  155. SelectionRecord.class,
  156. SeriesRecord.class,
  157. SeriesTextRecord.class,
  158. SharedFormulaRecord.class,
  159. SSTRecord.class,
  160. StringRecord.class,
  161. StyleRecord.class,
  162. SupBookRecord.class,
  163. TabIdRecord.class,
  164. TableRecord.class,
  165. TableStylesRecord.class,
  166. TextObjectRecord.class,
  167. TopMarginRecord.class,
  168. UncalcedRecord.class,
  169. UseSelFSRecord.class,
  170. VCenterRecord.class,
  171. VerticalPageBreakRecord.class,
  172. WindowOneRecord.class,
  173. WindowProtectRecord.class,
  174. WindowTwoRecord.class,
  175. WriteAccessRecord.class,
  176. WriteProtectRecord.class,
  177. WSBoolRecord.class,
  178. // chart records
  179. BeginRecord.class,
  180. ChartFRTInfoRecord.class,
  181. ChartStartBlockRecord.class,
  182. ChartEndBlockRecord.class,
  183. // TODO ChartFormatRecord.class,
  184. ChartStartObjectRecord.class,
  185. ChartEndObjectRecord.class,
  186. CatLabRecord.class,
  187. EndRecord.class,
  188. LinkedDataRecord.class,
  189. SeriesToChartGroupRecord.class,
  190. // pivot table records
  191. DataItemRecord.class,
  192. ExtendedPivotTableViewFieldsRecord.class,
  193. PageItemRecord.class,
  194. StreamIDRecord.class,
  195. ViewDefinitionRecord.class,
  196. ViewFieldsRecord.class,
  197. ViewSourceRecord.class,
  198. };
  199. /**
  200. * cache of the recordsToMap();
  201. */
  202. private static final Map<Integer, I_RecordCreator> _recordCreatorsById = recordsToMap(recordClasses);
  203. private static short[] _allKnownRecordSIDs;
  204. /**
  205. * Debug / diagnosis method<br/>
  206. * Gets the POI implementation class for a given <tt>sid</tt>. Only a subset of the any BIFF
  207. * records are actually interpreted by POI. A few others are known but not interpreted
  208. * (see {@link UnknownRecord#getBiffName(int)}).
  209. * @return the POI implementation class for the specified record <tt>sid</tt>.
  210. * <code>null</code> if the specified record is not interpreted by POI.
  211. */
  212. public static Class<? extends Record> getRecordClass(int sid) {
  213. I_RecordCreator rc = _recordCreatorsById.get(Integer.valueOf(sid));
  214. if (rc == null) {
  215. return null;
  216. }
  217. return rc.getRecordClass();
  218. }
  219. /**
  220. * create a record, if there are MUL records than multiple records
  221. * are returned digested into the non-mul form.
  222. */
  223. public static Record [] createRecord(RecordInputStream in) {
  224. Record record = createSingleRecord(in);
  225. if (record instanceof DBCellRecord) {
  226. // Not needed by POI. Regenerated from scratch by POI when spreadsheet is written
  227. return new Record[] { null, };
  228. }
  229. if (record instanceof RKRecord) {
  230. return new Record[] { convertToNumberRecord((RKRecord) record), };
  231. }
  232. if (record instanceof MulRKRecord) {
  233. return convertRKRecords((MulRKRecord)record);
  234. }
  235. return new Record[] { record, };
  236. }
  237. public static Record createSingleRecord(RecordInputStream in) {
  238. I_RecordCreator constructor = _recordCreatorsById.get(Integer.valueOf(in.getSid()));
  239. if (constructor == null) {
  240. return new UnknownRecord(in);
  241. }
  242. return constructor.create(in);
  243. }
  244. /**
  245. * RK record is a slightly smaller alternative to NumberRecord
  246. * POI likes NumberRecord better
  247. */
  248. public static NumberRecord convertToNumberRecord(RKRecord rk) {
  249. NumberRecord num = new NumberRecord();
  250. num.setColumn(rk.getColumn());
  251. num.setRow(rk.getRow());
  252. num.setXFIndex(rk.getXFIndex());
  253. num.setValue(rk.getRKNumber());
  254. return num;
  255. }
  256. /**
  257. * Converts a {@link MulRKRecord} into an equivalent array of {@link NumberRecord}s
  258. */
  259. public static NumberRecord[] convertRKRecords(MulRKRecord mrk) {
  260. NumberRecord[] mulRecs = new NumberRecord[mrk.getNumColumns()];
  261. for (int k = 0; k < mrk.getNumColumns(); k++) {
  262. NumberRecord nr = new NumberRecord();
  263. nr.setColumn((short) (k + mrk.getFirstColumn()));
  264. nr.setRow(mrk.getRow());
  265. nr.setXFIndex(mrk.getXFAt(k));
  266. nr.setValue(mrk.getRKNumberAt(k));
  267. mulRecs[k] = nr;
  268. }
  269. return mulRecs;
  270. }
  271. /**
  272. * Converts a {@link MulBlankRecord} into an equivalent array of {@link BlankRecord}s
  273. */
  274. public static BlankRecord[] convertBlankRecords(MulBlankRecord mbk) {
  275. BlankRecord[] mulRecs = new BlankRecord[mbk.getNumColumns()];
  276. for (int k = 0; k < mbk.getNumColumns(); k++) {
  277. BlankRecord br = new BlankRecord();
  278. br.setColumn((short) (k + mbk.getFirstColumn()));
  279. br.setRow(mbk.getRow());
  280. br.setXFIndex(mbk.getXFAt(k));
  281. mulRecs[k] = br;
  282. }
  283. return mulRecs;
  284. }
  285. /**
  286. * @return an array of all the SIDS for all known records
  287. */
  288. public static short[] getAllKnownRecordSIDs() {
  289. if (_allKnownRecordSIDs == null) {
  290. short[] results = new short[ _recordCreatorsById.size() ];
  291. int i = 0;
  292. for (Iterator<Integer> iterator = _recordCreatorsById.keySet().iterator(); iterator.hasNext(); ) {
  293. Integer sid = iterator.next();
  294. results[i++] = sid.shortValue();
  295. }
  296. Arrays.sort(results);
  297. _allKnownRecordSIDs = results;
  298. }
  299. return _allKnownRecordSIDs.clone();
  300. }
  301. /**
  302. * gets the record constructors and sticks them in the map by SID
  303. * @return map of SIDs to short,short,byte[] constructors for Record classes
  304. * most of org.apache.poi.hssf.record.*
  305. */
  306. private static Map<Integer, I_RecordCreator> recordsToMap(Class<? extends Record> [] records) {
  307. Map<Integer, I_RecordCreator> result = new HashMap<Integer, I_RecordCreator>();
  308. Set<Class<?>> uniqueRecClasses = new HashSet<Class<?>>(records.length * 3 / 2);
  309. for (int i = 0; i < records.length; i++) {
  310. Class<? extends Record> recClass = records[ i ];
  311. if(!Record.class.isAssignableFrom(recClass)) {
  312. throw new RuntimeException("Invalid record sub-class (" + recClass.getName() + ")");
  313. }
  314. if(Modifier.isAbstract(recClass.getModifiers())) {
  315. throw new RuntimeException("Invalid record class (" + recClass.getName() + ") - must not be abstract");
  316. }
  317. if(!uniqueRecClasses.add(recClass)) {
  318. throw new RuntimeException("duplicate record class (" + recClass.getName() + ")");
  319. }
  320. short sid;
  321. Constructor<? extends Record> constructor;
  322. try {
  323. sid = recClass.getField("sid").getShort(null);
  324. constructor = recClass.getConstructor(CONSTRUCTOR_ARGS);
  325. } catch (Exception illegalArgumentException) {
  326. throw new RecordFormatException(
  327. "Unable to determine record types");
  328. }
  329. Integer key = Integer.valueOf(sid);
  330. if (result.containsKey(key)) {
  331. Class<?> prevClass = result.get(key).getRecordClass();
  332. throw new RuntimeException("duplicate record sid 0x" + Integer.toHexString(sid).toUpperCase()
  333. + " for classes (" + recClass.getName() + ") and (" + prevClass.getName() + ")");
  334. }
  335. result.put(key, new ReflectionRecordCreator(constructor));
  336. }
  337. // result.put(Integer.valueOf(0x0406), result.get(Integer.valueOf(0x06)));
  338. return result;
  339. }
  340. /**
  341. * Create an array of records from an input stream
  342. *
  343. * @param in the InputStream from which the records will be obtained
  344. *
  345. * @return an array of Records created from the InputStream
  346. *
  347. * @exception RecordFormatException on error processing the InputStream
  348. */
  349. public static List<Record> createRecords(InputStream in) throws RecordFormatException {
  350. List<Record> records = new ArrayList<Record>(NUM_RECORDS);
  351. RecordFactoryInputStream recStream = new RecordFactoryInputStream(in, true);
  352. Record record;
  353. while ((record = recStream.nextRecord())!=null) {
  354. records.add(record);
  355. }
  356. return records;
  357. }
  358. }