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

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