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

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