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.

PropertyMaps.java 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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;
  14. import java.io.IOException;
  15. import java.nio.ByteBuffer;
  16. import java.util.ArrayList;
  17. import java.util.HashMap;
  18. import java.util.Iterator;
  19. import java.util.LinkedHashMap;
  20. import java.util.LinkedHashSet;
  21. import java.util.List;
  22. import java.util.Map;
  23. import java.util.Set;
  24. import com.healthmarketscience.jackcess.DataType;
  25. import com.healthmarketscience.jackcess.PropertyMap;
  26. /**
  27. * Collection of PropertyMap instances read from a single property data block.
  28. *
  29. * @author James Ahlborn
  30. */
  31. public class PropertyMaps implements Iterable<PropertyMapImpl>
  32. {
  33. /** the name of the "default" properties for a PropertyMaps instance */
  34. public static final String DEFAULT_NAME = "";
  35. private static final short PROPERTY_NAME_LIST = 0x80;
  36. private static final short DEFAULT_PROPERTY_VALUE_LIST = 0x00;
  37. private static final short COLUMN_PROPERTY_VALUE_LIST = 0x01;
  38. /** maps the PropertyMap name (case-insensitive) to the PropertyMap
  39. instance */
  40. private final Map<String,PropertyMapImpl> _maps =
  41. new LinkedHashMap<String,PropertyMapImpl>();
  42. private final int _objectId;
  43. private final RowIdImpl _rowId;
  44. private final Handler _handler;
  45. public PropertyMaps(int objectId, RowIdImpl rowId, Handler handler) {
  46. _objectId = objectId;
  47. _rowId = rowId;
  48. _handler = handler;
  49. }
  50. public int getObjectId() {
  51. return _objectId;
  52. }
  53. public int getSize() {
  54. return _maps.size();
  55. }
  56. public boolean isEmpty() {
  57. return _maps.isEmpty();
  58. }
  59. /**
  60. * @return the unnamed "default" PropertyMap in this group, creating if
  61. * necessary.
  62. */
  63. public PropertyMapImpl getDefault() {
  64. return get(DEFAULT_NAME, DEFAULT_PROPERTY_VALUE_LIST);
  65. }
  66. /**
  67. * @return the PropertyMap with the given name in this group, creating if
  68. * necessary
  69. */
  70. public PropertyMapImpl get(String name) {
  71. return get(name, COLUMN_PROPERTY_VALUE_LIST);
  72. }
  73. /**
  74. * @return the PropertyMap with the given name and type in this group,
  75. * creating if necessary
  76. */
  77. private PropertyMapImpl get(String name, short type) {
  78. String lookupName = DatabaseImpl.toLookupName(name);
  79. PropertyMapImpl map = _maps.get(lookupName);
  80. if(map == null) {
  81. map = new PropertyMapImpl(name, type, this);
  82. _maps.put(lookupName, map);
  83. }
  84. return map;
  85. }
  86. public Iterator<PropertyMapImpl> iterator() {
  87. return _maps.values().iterator();
  88. }
  89. public byte[] write() throws IOException {
  90. return _handler.write(this);
  91. }
  92. public void save() throws IOException {
  93. _handler.save(this);
  94. }
  95. @Override
  96. public String toString() {
  97. return CustomToStringStyle.builder(this)
  98. .append(null, _maps.values())
  99. .toString();
  100. }
  101. /**
  102. * Utility class for reading/writing property blocks.
  103. */
  104. static final class Handler
  105. {
  106. /** the current database */
  107. private final DatabaseImpl _database;
  108. /** the system table "property" column */
  109. private final ColumnImpl _propCol;
  110. /** cache of PropColumns used to read/write property values */
  111. private final Map<DataType,PropColumn> _columns =
  112. new HashMap<DataType,PropColumn>();
  113. Handler(DatabaseImpl database) {
  114. _database = database;
  115. _propCol = _database.getSystemCatalog().getColumn(
  116. DatabaseImpl.CAT_COL_PROPS);
  117. }
  118. /**
  119. * @return a PropertyMaps instance decoded from the given bytes (always
  120. * returns non-{@code null} result).
  121. */
  122. public PropertyMaps read(byte[] propBytes, int objectId,
  123. RowIdImpl rowId)
  124. throws IOException
  125. {
  126. PropertyMaps maps = new PropertyMaps(objectId, rowId, this);
  127. if((propBytes == null) || (propBytes.length == 0)) {
  128. return maps;
  129. }
  130. ByteBuffer bb = PageChannel.wrap(propBytes);
  131. // check for known header
  132. boolean knownType = false;
  133. for(byte[] tmpType : JetFormat.PROPERTY_MAP_TYPES) {
  134. if(ByteUtil.matchesRange(bb, bb.position(), tmpType)) {
  135. ByteUtil.forward(bb, tmpType.length);
  136. knownType = true;
  137. break;
  138. }
  139. }
  140. if(!knownType) {
  141. throw new IOException("Unknown property map type " +
  142. ByteUtil.toHexString(bb, 4));
  143. }
  144. // parse each data "chunk"
  145. List<String> propNames = null;
  146. while(bb.hasRemaining()) {
  147. int len = bb.getInt();
  148. short type = bb.getShort();
  149. int endPos = bb.position() + len - 6;
  150. ByteBuffer bbBlock = PageChannel.narrowBuffer(bb, bb.position(),
  151. endPos);
  152. if(type == PROPERTY_NAME_LIST) {
  153. propNames = readPropertyNames(bbBlock);
  154. } else {
  155. readPropertyValues(bbBlock, propNames, type, maps);
  156. }
  157. bb.position(endPos);
  158. }
  159. return maps;
  160. }
  161. /**
  162. * @return a byte[] encoded from the given PropertyMaps instance
  163. */
  164. public byte[] write(PropertyMaps maps)
  165. throws IOException
  166. {
  167. if(maps == null) {
  168. return null;
  169. }
  170. ByteArrayBuilder bab = new ByteArrayBuilder();
  171. bab.put(_database.getFormat().PROPERTY_MAP_TYPE);
  172. // grab the property names from all the maps
  173. Set<String> propNames = new LinkedHashSet<String>();
  174. for(PropertyMapImpl propMap : maps) {
  175. for(PropertyMap.Property prop : propMap) {
  176. propNames.add(prop.getName());
  177. }
  178. }
  179. // write the full set of property names
  180. writeBlock(null, propNames, PROPERTY_NAME_LIST, bab);
  181. // write all the map values
  182. for(PropertyMapImpl propMap : maps) {
  183. writeBlock(propMap, propNames, propMap.getType(), bab);
  184. }
  185. return bab.toArray();
  186. }
  187. /**
  188. * Saves PropertyMaps instance to the db.
  189. */
  190. public void save(PropertyMaps maps) throws IOException
  191. {
  192. RowIdImpl rowId = maps._rowId;
  193. if(rowId == null) {
  194. throw new IllegalStateException(
  195. "PropertyMaps cannot be saved without a row id");
  196. }
  197. byte[] mapsBytes = write(maps);
  198. // for now assume all properties come from system catalog table
  199. _propCol.getTable().updateValue(_propCol, rowId, mapsBytes);
  200. }
  201. private void writeBlock(
  202. PropertyMapImpl propMap, Set<String> propNames,
  203. short blockType, ByteArrayBuilder bab)
  204. throws IOException
  205. {
  206. int blockStartPos = bab.position();
  207. bab.reserveInt()
  208. .putShort(blockType);
  209. if(blockType == PROPERTY_NAME_LIST) {
  210. writePropertyNames(propNames, bab);
  211. } else {
  212. writePropertyValues(propMap, propNames, bab);
  213. }
  214. int len = bab.position() - blockStartPos;
  215. bab.putInt(blockStartPos, len);
  216. }
  217. /**
  218. * @return the property names parsed from the given data chunk
  219. */
  220. private List<String> readPropertyNames(ByteBuffer bbBlock) {
  221. List<String> names = new ArrayList<String>();
  222. while(bbBlock.hasRemaining()) {
  223. names.add(readPropName(bbBlock));
  224. }
  225. return names;
  226. }
  227. private void writePropertyNames(Set<String> propNames,
  228. ByteArrayBuilder bab) {
  229. for(String propName : propNames) {
  230. writePropName(propName, bab);
  231. }
  232. }
  233. /**
  234. * @return the PropertyMap created from the values parsed from the given
  235. * data chunk combined with the given property names
  236. */
  237. private PropertyMapImpl readPropertyValues(
  238. ByteBuffer bbBlock, List<String> propNames, short blockType,
  239. PropertyMaps maps)
  240. throws IOException
  241. {
  242. String mapName = DEFAULT_NAME;
  243. if(bbBlock.hasRemaining()) {
  244. // read the map name, if any
  245. int nameBlockLen = bbBlock.getInt();
  246. int endPos = bbBlock.position() + nameBlockLen - 4;
  247. if(nameBlockLen > 6) {
  248. mapName = readPropName(bbBlock);
  249. }
  250. bbBlock.position(endPos);
  251. }
  252. PropertyMapImpl map = maps.get(mapName, blockType);
  253. // read the values
  254. while(bbBlock.hasRemaining()) {
  255. int valLen = bbBlock.getShort();
  256. int endPos = bbBlock.position() + valLen - 2;
  257. byte flag = bbBlock.get();
  258. DataType dataType = DataType.fromByte(bbBlock.get());
  259. int nameIdx = bbBlock.getShort();
  260. int dataSize = bbBlock.getShort();
  261. String propName = propNames.get(nameIdx);
  262. PropColumn col = getColumn(dataType, propName, dataSize, null);
  263. byte[] data = ByteUtil.getBytes(bbBlock, dataSize);
  264. Object value = col.read(data);
  265. map.put(propName, dataType, flag, value);
  266. bbBlock.position(endPos);
  267. }
  268. return map;
  269. }
  270. private void writePropertyValues(
  271. PropertyMapImpl propMap, Set<String> propNames, ByteArrayBuilder bab)
  272. throws IOException
  273. {
  274. // write the map name, if any
  275. String mapName = propMap.getName();
  276. int blockStartPos = bab.position();
  277. bab.reserveInt();
  278. writePropName(mapName, bab);
  279. int len = bab.position() - blockStartPos;
  280. bab.putInt(blockStartPos, len);
  281. // write the map values
  282. int nameIdx = 0;
  283. for(String propName : propNames) {
  284. PropertyMapImpl.PropertyImpl prop = (PropertyMapImpl.PropertyImpl)
  285. propMap.get(propName);
  286. if(prop != null) {
  287. Object value = prop.getValue();
  288. if(value != null) {
  289. int valStartPos = bab.position();
  290. bab.reserveShort();
  291. bab.put(prop.getFlag());
  292. bab.put(prop.getType().getValue());
  293. bab.putShort((short)nameIdx);
  294. PropColumn col = getColumn(prop.getType(), propName, -1, value);
  295. ByteBuffer data = col.write(
  296. value, _database.getFormat().MAX_ROW_SIZE);
  297. bab.putShort((short)data.remaining());
  298. bab.put(data);
  299. len = bab.position() - valStartPos;
  300. bab.putShort(valStartPos, (short)len);
  301. }
  302. }
  303. ++nameIdx;
  304. }
  305. }
  306. /**
  307. * Reads a property name from the given data block
  308. */
  309. private String readPropName(ByteBuffer buffer) {
  310. int nameLength = buffer.getShort();
  311. byte[] nameBytes = ByteUtil.getBytes(buffer, nameLength);
  312. return ColumnImpl.decodeUncompressedText(nameBytes, _database.getCharset());
  313. }
  314. /**
  315. * Writes a property name to the given data block
  316. */
  317. private void writePropName(String propName, ByteArrayBuilder bab) {
  318. ByteBuffer textBuf = ColumnImpl.encodeUncompressedText(
  319. propName, _database.getCharset());
  320. bab.putShort((short)textBuf.remaining());
  321. bab.put(textBuf);
  322. }
  323. /**
  324. * Gets a PropColumn capable of reading/writing a property of the given
  325. * DataType
  326. */
  327. private PropColumn getColumn(DataType dataType, String propName,
  328. int dataSize, Object value)
  329. throws IOException
  330. {
  331. if(isPseudoGuidColumn(dataType, propName, dataSize, value)) {
  332. dataType = DataType.GUID;
  333. }
  334. PropColumn col = _columns.get(dataType);
  335. if(col == null) {
  336. // translate long value types into simple types
  337. DataType colType = dataType;
  338. if(dataType == DataType.MEMO) {
  339. colType = DataType.TEXT;
  340. } else if(dataType == DataType.OLE) {
  341. colType = DataType.BINARY;
  342. }
  343. // create column with ability to read/write the given data type
  344. col = ((colType == DataType.BOOLEAN) ?
  345. new BooleanPropColumn() : new PropColumn(colType));
  346. _columns.put(dataType, col);
  347. }
  348. return col;
  349. }
  350. private static boolean isPseudoGuidColumn(
  351. DataType dataType, String propName, int dataSize, Object value)
  352. throws IOException
  353. {
  354. // guids seem to be marked as "binary" fields
  355. return((dataType == DataType.BINARY) &&
  356. ((dataSize == DataType.GUID.getFixedSize()) ||
  357. ((dataSize == -1) && ColumnImpl.isGUIDValue(value))) &&
  358. PropertyMap.GUID_PROP.equalsIgnoreCase(propName));
  359. }
  360. /**
  361. * Column adapted to work w/out a Table.
  362. */
  363. private class PropColumn extends ColumnImpl
  364. {
  365. private PropColumn(DataType type) {
  366. super(null, null, type, 0, 0, 0);
  367. }
  368. @Override
  369. public DatabaseImpl getDatabase() {
  370. return _database;
  371. }
  372. }
  373. /**
  374. * Normal boolean columns do not write into the actual row data, so we
  375. * need to do a little extra work.
  376. */
  377. private final class BooleanPropColumn extends PropColumn
  378. {
  379. private BooleanPropColumn() {
  380. super(DataType.BOOLEAN);
  381. }
  382. @Override
  383. public Object read(byte[] data) throws IOException {
  384. return ((data[0] != 0) ? Boolean.TRUE : Boolean.FALSE);
  385. }
  386. @Override
  387. public ByteBuffer write(Object obj, int remainingRowLength)
  388. throws IOException
  389. {
  390. ByteBuffer buffer = PageChannel.createBuffer(1);
  391. buffer.put(((Number)booleanToInteger(obj)).byteValue());
  392. buffer.flip();
  393. return buffer;
  394. }
  395. }
  396. }
  397. }