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 14KB

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