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.

AttachmentColumnInfoImpl.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500
  1. /*
  2. Copyright (c) 2011 James Ahlborn
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package com.healthmarketscience.jackcess.impl.complex;
  14. import java.io.ByteArrayInputStream;
  15. import java.io.DataInputStream;
  16. import java.io.IOException;
  17. import java.io.InputStream;
  18. import java.io.OutputStream;
  19. import java.nio.ByteBuffer;
  20. import java.time.LocalDateTime;
  21. import java.util.Arrays;
  22. import java.util.Date;
  23. import java.util.HashSet;
  24. import java.util.Set;
  25. import java.util.zip.Deflater;
  26. import java.util.zip.DeflaterOutputStream;
  27. import java.util.zip.InflaterInputStream;
  28. import com.healthmarketscience.jackcess.Column;
  29. import com.healthmarketscience.jackcess.Row;
  30. import com.healthmarketscience.jackcess.Table;
  31. import com.healthmarketscience.jackcess.complex.Attachment;
  32. import com.healthmarketscience.jackcess.complex.AttachmentColumnInfo;
  33. import com.healthmarketscience.jackcess.complex.ComplexDataType;
  34. import com.healthmarketscience.jackcess.complex.ComplexValue;
  35. import com.healthmarketscience.jackcess.complex.ComplexValueForeignKey;
  36. import com.healthmarketscience.jackcess.impl.ByteUtil;
  37. import com.healthmarketscience.jackcess.impl.ColumnImpl;
  38. import com.healthmarketscience.jackcess.impl.JetFormat;
  39. import com.healthmarketscience.jackcess.impl.PageChannel;
  40. /**
  41. * Complex column info for a column holding 0 or more attachments per row.
  42. *
  43. * @author James Ahlborn
  44. */
  45. public class AttachmentColumnInfoImpl extends ComplexColumnInfoImpl<Attachment>
  46. implements AttachmentColumnInfo
  47. {
  48. /** some file formats which may not be worth re-compressing */
  49. private static final Set<String> COMPRESSED_FORMATS = new HashSet<String>(
  50. Arrays.asList("jpg", "zip", "gz", "bz2", "z", "7z", "cab", "rar",
  51. "mp3", "mpg"));
  52. private static final String FILE_NAME_COL_NAME = "FileName";
  53. private static final String FILE_TYPE_COL_NAME = "FileType";
  54. private static final int DATA_TYPE_RAW = 0;
  55. private static final int DATA_TYPE_COMPRESSED = 1;
  56. private static final int UNKNOWN_HEADER_VAL = 1;
  57. private static final int WRAPPER_HEADER_SIZE = 8;
  58. private static final int CONTENT_HEADER_SIZE = 12;
  59. private final Column _fileUrlCol;
  60. private final Column _fileNameCol;
  61. private final Column _fileTypeCol;
  62. private final Column _fileDataCol;
  63. private final Column _fileTimeStampCol;
  64. private final Column _fileFlagsCol;
  65. public AttachmentColumnInfoImpl(Column column, int complexId,
  66. Table typeObjTable, Table flatTable)
  67. throws IOException
  68. {
  69. super(column, complexId, typeObjTable, flatTable);
  70. Column fileUrlCol = null;
  71. Column fileNameCol = null;
  72. Column fileTypeCol = null;
  73. Column fileDataCol = null;
  74. Column fileTimeStampCol = null;
  75. Column fileFlagsCol = null;
  76. for(Column col : getTypeColumns()) {
  77. switch(col.getType()) {
  78. case TEXT:
  79. if(FILE_NAME_COL_NAME.equalsIgnoreCase(col.getName())) {
  80. fileNameCol = col;
  81. } else if(FILE_TYPE_COL_NAME.equalsIgnoreCase(col.getName())) {
  82. fileTypeCol = col;
  83. } else {
  84. // if names don't match, assign in order: name, type
  85. if(fileNameCol == null) {
  86. fileNameCol = col;
  87. } else if(fileTypeCol == null) {
  88. fileTypeCol = col;
  89. }
  90. }
  91. break;
  92. case LONG:
  93. fileFlagsCol = col;
  94. break;
  95. case SHORT_DATE_TIME:
  96. fileTimeStampCol = col;
  97. break;
  98. case OLE:
  99. fileDataCol = col;
  100. break;
  101. case MEMO:
  102. fileUrlCol = col;
  103. break;
  104. default:
  105. // ignore
  106. }
  107. }
  108. _fileUrlCol = fileUrlCol;
  109. _fileNameCol = fileNameCol;
  110. _fileTypeCol = fileTypeCol;
  111. _fileDataCol = fileDataCol;
  112. _fileTimeStampCol = fileTimeStampCol;
  113. _fileFlagsCol = fileFlagsCol;
  114. }
  115. public Column getFileUrlColumn() {
  116. return _fileUrlCol;
  117. }
  118. public Column getFileNameColumn() {
  119. return _fileNameCol;
  120. }
  121. public Column getFileTypeColumn() {
  122. return _fileTypeCol;
  123. }
  124. public Column getFileDataColumn() {
  125. return _fileDataCol;
  126. }
  127. public Column getFileTimeStampColumn() {
  128. return _fileTimeStampCol;
  129. }
  130. public Column getFileFlagsColumn() {
  131. return _fileFlagsCol;
  132. }
  133. @Override
  134. public ComplexDataType getType()
  135. {
  136. return ComplexDataType.ATTACHMENT;
  137. }
  138. @Override
  139. protected AttachmentImpl toValue(ComplexValueForeignKey complexValueFk,
  140. Row rawValue) {
  141. ComplexValue.Id id = getValueId(rawValue);
  142. String url = (String)getFileUrlColumn().getRowValue(rawValue);
  143. String name = (String)getFileNameColumn().getRowValue(rawValue);
  144. String type = (String)getFileTypeColumn().getRowValue(rawValue);
  145. Integer flags = (Integer)getFileFlagsColumn().getRowValue(rawValue);
  146. Object ts = getFileTimeStampColumn().getRowValue(rawValue);
  147. byte[] data = (byte[])getFileDataColumn().getRowValue(rawValue);
  148. return new AttachmentImpl(id, complexValueFk, url, name, type, null,
  149. ts, flags, data);
  150. }
  151. @Override
  152. protected Object[] asRow(Object[] row, Attachment attachment)
  153. throws IOException
  154. {
  155. super.asRow(row, attachment);
  156. getFileUrlColumn().setRowValue(row, attachment.getFileUrl());
  157. getFileNameColumn().setRowValue(row, attachment.getFileName());
  158. getFileTypeColumn().setRowValue(row, attachment.getFileType());
  159. getFileFlagsColumn().setRowValue(row, attachment.getFileFlags());
  160. getFileTimeStampColumn().setRowValue(row, attachment.getFileTimeStampObject());
  161. getFileDataColumn().setRowValue(row, attachment.getEncodedFileData());
  162. return row;
  163. }
  164. public static Attachment newAttachment(byte[] data) {
  165. return newAttachment(INVALID_FK, data);
  166. }
  167. public static Attachment newAttachment(ComplexValueForeignKey complexValueFk,
  168. byte[] data) {
  169. return newAttachment(complexValueFk, null, null, null, data, null, null);
  170. }
  171. public static Attachment newAttachment(
  172. String url, String name, String type, byte[] data,
  173. Object timeStamp, Integer flags)
  174. {
  175. return newAttachment(INVALID_FK, url, name, type, data,
  176. timeStamp, flags);
  177. }
  178. public static Attachment newAttachment(
  179. ComplexValueForeignKey complexValueFk, String url, String name,
  180. String type, byte[] data, Object timeStamp, Integer flags)
  181. {
  182. return new AttachmentImpl(INVALID_ID, complexValueFk, url, name, type,
  183. data, timeStamp, flags, null);
  184. }
  185. public static Attachment newEncodedAttachment(byte[] encodedData) {
  186. return newEncodedAttachment(INVALID_FK, encodedData);
  187. }
  188. public static Attachment newEncodedAttachment(
  189. ComplexValueForeignKey complexValueFk, byte[] encodedData) {
  190. return newEncodedAttachment(complexValueFk, null, null, null, encodedData,
  191. null, null);
  192. }
  193. public static Attachment newEncodedAttachment(
  194. String url, String name, String type, byte[] encodedData,
  195. Object timeStamp, Integer flags)
  196. {
  197. return newEncodedAttachment(INVALID_FK, url, name, type,
  198. encodedData, timeStamp, flags);
  199. }
  200. public static Attachment newEncodedAttachment(
  201. ComplexValueForeignKey complexValueFk, String url, String name,
  202. String type, byte[] encodedData, Object timeStamp, Integer flags)
  203. {
  204. return new AttachmentImpl(INVALID_ID, complexValueFk, url, name, type,
  205. null, timeStamp, flags, encodedData);
  206. }
  207. @SuppressWarnings("deprecation")
  208. private static class AttachmentImpl extends ComplexValueImpl
  209. implements Attachment
  210. {
  211. private String _url;
  212. private String _name;
  213. private String _type;
  214. private byte[] _data;
  215. private Object _timeStamp;
  216. private Integer _flags;
  217. private byte[] _encodedData;
  218. private AttachmentImpl(Id id, ComplexValueForeignKey complexValueFk,
  219. String url, String name, String type, byte[] data,
  220. Object timeStamp, Integer flags, byte[] encodedData)
  221. {
  222. super(id, complexValueFk);
  223. _url = url;
  224. _name = name;
  225. _type = type;
  226. _data = data;
  227. _timeStamp = timeStamp;
  228. _flags = flags;
  229. _encodedData = encodedData;
  230. }
  231. @Override
  232. public byte[] getFileData() throws IOException {
  233. if((_data == null) && (_encodedData != null)) {
  234. _data = decodeData();
  235. }
  236. return _data;
  237. }
  238. @Override
  239. public void setFileData(byte[] data) {
  240. _data = data;
  241. _encodedData = null;
  242. }
  243. @Override
  244. public byte[] getEncodedFileData() throws IOException {
  245. if((_encodedData == null) && (_data != null)) {
  246. _encodedData = encodeData();
  247. }
  248. return _encodedData;
  249. }
  250. @Override
  251. public void setEncodedFileData(byte[] data) {
  252. _encodedData = data;
  253. _data = null;
  254. }
  255. @Override
  256. public String getFileName() {
  257. return _name;
  258. }
  259. @Override
  260. public void setFileName(String fileName) {
  261. _name = fileName;
  262. }
  263. @Override
  264. public String getFileUrl() {
  265. return _url;
  266. }
  267. @Override
  268. public void setFileUrl(String fileUrl) {
  269. _url = fileUrl;
  270. }
  271. @Override
  272. public String getFileType() {
  273. return _type;
  274. }
  275. @Override
  276. public void setFileType(String fileType) {
  277. _type = fileType;
  278. }
  279. @Override
  280. public Date getFileTimeStamp() {
  281. return (Date)_timeStamp;
  282. }
  283. @Override
  284. public void setFileTimeStamp(Date fileTimeStamp) {
  285. _timeStamp = fileTimeStamp;
  286. }
  287. @Override
  288. public LocalDateTime getFileLocalTimeStamp() {
  289. return (LocalDateTime)_timeStamp;
  290. }
  291. @Override
  292. public void setFileLocalTimeStamp(LocalDateTime fileTimeStamp) {
  293. _timeStamp = fileTimeStamp;
  294. }
  295. @Override
  296. public Object getFileTimeStampObject() {
  297. return _timeStamp;
  298. }
  299. @Override
  300. public Integer getFileFlags() {
  301. return _flags;
  302. }
  303. @Override
  304. public void setFileFlags(Integer fileFlags) {
  305. _flags = fileFlags;
  306. }
  307. @Override
  308. public void update() throws IOException {
  309. getComplexValueForeignKey().updateAttachment(this);
  310. }
  311. @Override
  312. public void delete() throws IOException {
  313. getComplexValueForeignKey().deleteAttachment(this);
  314. }
  315. @Override
  316. public String toString() {
  317. String dataStr = null;
  318. try {
  319. dataStr = ByteUtil.toHexString(getFileData());
  320. } catch(IOException e) {
  321. dataStr = e.toString();
  322. }
  323. return "Attachment(" + getComplexValueForeignKey() + "," + getId() +
  324. ") " + getFileUrl() + ", " + getFileName() + ", " + getFileType()
  325. + ", " + getFileTimeStampObject() + ", " + getFileFlags() + ", " +
  326. dataStr;
  327. }
  328. /**
  329. * Decodes the raw attachment file data to get the _actual_ content.
  330. */
  331. private byte[] decodeData() throws IOException {
  332. if(_encodedData.length < WRAPPER_HEADER_SIZE) {
  333. // nothing we can do
  334. throw new IOException("Unknown encoded attachment data format");
  335. }
  336. // read initial header info
  337. ByteBuffer bb = PageChannel.wrap(_encodedData);
  338. int typeFlag = bb.getInt();
  339. int dataLen = bb.getInt();
  340. DataInputStream contentStream = null;
  341. try {
  342. InputStream bin = new ByteArrayInputStream(
  343. _encodedData, WRAPPER_HEADER_SIZE,
  344. _encodedData.length - WRAPPER_HEADER_SIZE);
  345. if(typeFlag == DATA_TYPE_RAW) {
  346. // nothing else to do
  347. } else if(typeFlag == DATA_TYPE_COMPRESSED) {
  348. // actual content is deflate compressed
  349. bin = new InflaterInputStream(bin);
  350. } else {
  351. throw new IOException(
  352. "Unknown encoded attachment data type " + typeFlag);
  353. }
  354. contentStream = new DataInputStream(bin);
  355. // header is an unknown flag followed by the "file extension" of the
  356. // data (no clue why we need that again since it's already a separate
  357. // field in the attachment table). just skip all of it
  358. byte[] tmpBytes = new byte[4];
  359. contentStream.readFully(tmpBytes);
  360. int headerLen = PageChannel.wrap(tmpBytes).getInt();
  361. ByteUtil.skipFully(contentStream, headerLen - 4);
  362. // calculate actual data length and read it (note, header length
  363. // includes the bytes for the length)
  364. tmpBytes = new byte[dataLen - headerLen];
  365. contentStream.readFully(tmpBytes);
  366. return tmpBytes;
  367. } finally {
  368. ByteUtil.closeQuietly(contentStream);
  369. }
  370. }
  371. /**
  372. * Encodes the actual attachment file data to get the raw, stored format.
  373. */
  374. private byte[] encodeData() throws IOException {
  375. // possibly compress data based on file type
  376. String type = ((_type != null) ? _type.toLowerCase() : "");
  377. boolean shouldCompress = !COMPRESSED_FORMATS.contains(type);
  378. // encode extension, which ends w/ a null byte
  379. type += '\0';
  380. ByteBuffer typeBytes = ColumnImpl.encodeUncompressedText(
  381. type, JetFormat.VERSION_12.CHARSET);
  382. int headerLen = typeBytes.remaining() + CONTENT_HEADER_SIZE;
  383. int dataLen = _data.length;
  384. ByteUtil.ByteStream dataStream = new ByteUtil.ByteStream(
  385. WRAPPER_HEADER_SIZE + headerLen + dataLen);
  386. // write the wrapper header info
  387. ByteBuffer bb = PageChannel.wrap(dataStream.getBytes());
  388. bb.putInt(shouldCompress ? DATA_TYPE_COMPRESSED : DATA_TYPE_RAW);
  389. bb.putInt(dataLen + headerLen);
  390. dataStream.skip(WRAPPER_HEADER_SIZE);
  391. OutputStream contentStream = dataStream;
  392. Deflater deflater = null;
  393. try {
  394. if(shouldCompress) {
  395. contentStream = new DeflaterOutputStream(
  396. contentStream, deflater = new Deflater(3));
  397. }
  398. // write the header w/ the file extension
  399. byte[] tmpBytes = new byte[CONTENT_HEADER_SIZE];
  400. PageChannel.wrap(tmpBytes)
  401. .putInt(headerLen)
  402. .putInt(UNKNOWN_HEADER_VAL)
  403. .putInt(type.length());
  404. contentStream.write(tmpBytes);
  405. contentStream.write(typeBytes.array(), 0, typeBytes.remaining());
  406. // write the _actual_ contents
  407. contentStream.write(_data);
  408. contentStream.close();
  409. contentStream = null;
  410. return dataStream.toByteArray();
  411. } finally {
  412. ByteUtil.closeQuietly(contentStream);
  413. if(deflater != null) {
  414. deflater.end();
  415. }
  416. }
  417. }
  418. }
  419. }