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

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