選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

PropertyMaps.java 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. if(propNames.isEmpty()) {
  180. return null;
  181. }
  182. // write the full set of property names
  183. writeBlock(null, propNames, PROPERTY_NAME_LIST, bab);
  184. // write all the map values
  185. for(PropertyMapImpl propMap : maps) {
  186. if(!propMap.isEmpty()) {
  187. writeBlock(propMap, propNames, propMap.getType(), bab);
  188. }
  189. }
  190. return bab.toArray();
  191. }
  192. /**
  193. * Saves PropertyMaps instance to the db.
  194. */
  195. public void save(PropertyMaps maps) throws IOException
  196. {
  197. RowIdImpl rowId = maps._rowId;
  198. if(rowId == null) {
  199. throw new IllegalStateException(
  200. "PropertyMaps cannot be saved without a row id");
  201. }
  202. byte[] mapsBytes = write(maps);
  203. // for now assume all properties come from system catalog table
  204. _propCol.getTable().updateValue(_propCol, rowId, mapsBytes);
  205. }
  206. private void writeBlock(
  207. PropertyMapImpl propMap, Set<String> propNames,
  208. short blockType, ByteArrayBuilder bab)
  209. throws IOException
  210. {
  211. int blockStartPos = bab.position();
  212. bab.reserveInt()
  213. .putShort(blockType);
  214. if(blockType == PROPERTY_NAME_LIST) {
  215. writePropertyNames(propNames, bab);
  216. } else {
  217. writePropertyValues(propMap, propNames, bab);
  218. }
  219. int len = bab.position() - blockStartPos;
  220. bab.putInt(blockStartPos, len);
  221. }
  222. /**
  223. * @return the property names parsed from the given data chunk
  224. */
  225. private List<String> readPropertyNames(ByteBuffer bbBlock) {
  226. List<String> names = new ArrayList<String>();
  227. while(bbBlock.hasRemaining()) {
  228. names.add(readPropName(bbBlock));
  229. }
  230. return names;
  231. }
  232. private void writePropertyNames(Set<String> propNames,
  233. ByteArrayBuilder bab) {
  234. for(String propName : propNames) {
  235. writePropName(propName, bab);
  236. }
  237. }
  238. /**
  239. * @return the PropertyMap created from the values parsed from the given
  240. * data chunk combined with the given property names
  241. */
  242. private PropertyMapImpl readPropertyValues(
  243. ByteBuffer bbBlock, List<String> propNames, short blockType,
  244. PropertyMaps maps)
  245. throws IOException
  246. {
  247. String mapName = DEFAULT_NAME;
  248. if(bbBlock.hasRemaining()) {
  249. // read the map name, if any
  250. int nameBlockLen = bbBlock.getInt();
  251. int endPos = bbBlock.position() + nameBlockLen - 4;
  252. if(nameBlockLen > 6) {
  253. mapName = readPropName(bbBlock);
  254. }
  255. bbBlock.position(endPos);
  256. }
  257. PropertyMapImpl map = maps.get(mapName, blockType);
  258. // read the values
  259. while(bbBlock.hasRemaining()) {
  260. int valLen = bbBlock.getShort();
  261. int endPos = bbBlock.position() + valLen - 2;
  262. boolean isDdl = (bbBlock.get() != 0);
  263. DataType dataType = DataType.fromByte(bbBlock.get());
  264. int nameIdx = bbBlock.getShort();
  265. int dataSize = bbBlock.getShort();
  266. String propName = propNames.get(nameIdx);
  267. PropColumn col = getColumn(dataType, propName, dataSize, null);
  268. byte[] data = ByteUtil.getBytes(bbBlock, dataSize);
  269. Object value = col.read(data);
  270. map.put(propName, dataType, value, isDdl);
  271. bbBlock.position(endPos);
  272. }
  273. return map;
  274. }
  275. private void writePropertyValues(
  276. PropertyMapImpl propMap, Set<String> propNames, ByteArrayBuilder bab)
  277. throws IOException
  278. {
  279. // write the map name, if any
  280. String mapName = propMap.getName();
  281. int blockStartPos = bab.position();
  282. bab.reserveInt();
  283. writePropName(mapName, bab);
  284. int len = bab.position() - blockStartPos;
  285. bab.putInt(blockStartPos, len);
  286. // write the map values
  287. int nameIdx = 0;
  288. for(String propName : propNames) {
  289. PropertyMapImpl.PropertyImpl prop = (PropertyMapImpl.PropertyImpl)
  290. propMap.get(propName);
  291. if(prop != null) {
  292. Object value = prop.getValue();
  293. if(value != null) {
  294. int valStartPos = bab.position();
  295. bab.reserveShort();
  296. byte ddlFlag = (byte)(prop.isDdl() ? 1 : 0);
  297. bab.put(ddlFlag);
  298. bab.put(prop.getType().getValue());
  299. bab.putShort((short)nameIdx);
  300. PropColumn col = getColumn(prop.getType(), propName, -1, value);
  301. ByteBuffer data = col.write(
  302. value, _database.getFormat().MAX_ROW_SIZE);
  303. bab.putShort((short)data.remaining());
  304. bab.put(data);
  305. len = bab.position() - valStartPos;
  306. bab.putShort(valStartPos, (short)len);
  307. }
  308. }
  309. ++nameIdx;
  310. }
  311. }
  312. /**
  313. * Reads a property name from the given data block
  314. */
  315. private String readPropName(ByteBuffer buffer) {
  316. int nameLength = buffer.getShort();
  317. byte[] nameBytes = ByteUtil.getBytes(buffer, nameLength);
  318. return ColumnImpl.decodeUncompressedText(nameBytes, _database.getCharset());
  319. }
  320. /**
  321. * Writes a property name to the given data block
  322. */
  323. private void writePropName(String propName, ByteArrayBuilder bab) {
  324. ByteBuffer textBuf = ColumnImpl.encodeUncompressedText(
  325. propName, _database.getCharset());
  326. bab.putShort((short)textBuf.remaining());
  327. bab.put(textBuf);
  328. }
  329. /**
  330. * Gets a PropColumn capable of reading/writing a property of the given
  331. * DataType
  332. */
  333. private PropColumn getColumn(DataType dataType, String propName,
  334. int dataSize, Object value)
  335. throws IOException
  336. {
  337. if(isPseudoGuidColumn(dataType, propName, dataSize, value)) {
  338. dataType = DataType.GUID;
  339. }
  340. PropColumn col = _columns.get(dataType);
  341. if(col == null) {
  342. // translate long value types into simple types
  343. DataType colType = dataType;
  344. if(dataType == DataType.MEMO) {
  345. colType = DataType.TEXT;
  346. } else if(dataType == DataType.OLE) {
  347. colType = DataType.BINARY;
  348. }
  349. // create column with ability to read/write the given data type
  350. col = ((colType == DataType.BOOLEAN) ?
  351. new BooleanPropColumn() : new PropColumn(colType));
  352. _columns.put(dataType, col);
  353. }
  354. return col;
  355. }
  356. private static boolean isPseudoGuidColumn(
  357. DataType dataType, String propName, int dataSize, Object value)
  358. throws IOException
  359. {
  360. // guids seem to be marked as "binary" fields
  361. return((dataType == DataType.BINARY) &&
  362. ((dataSize == DataType.GUID.getFixedSize()) ||
  363. ((dataSize == -1) && ColumnImpl.isGUIDValue(value))) &&
  364. PropertyMap.GUID_PROP.equalsIgnoreCase(propName));
  365. }
  366. /**
  367. * Column adapted to work w/out a Table.
  368. */
  369. private class PropColumn extends ColumnImpl
  370. {
  371. private PropColumn(DataType type) {
  372. super(null, null, type, 0, 0, 0);
  373. }
  374. @Override
  375. public DatabaseImpl getDatabase() {
  376. return _database;
  377. }
  378. }
  379. /**
  380. * Normal boolean columns do not write into the actual row data, so we
  381. * need to do a little extra work.
  382. */
  383. private final class BooleanPropColumn extends PropColumn
  384. {
  385. private BooleanPropColumn() {
  386. super(DataType.BOOLEAN);
  387. }
  388. @Override
  389. public Object read(byte[] data) throws IOException {
  390. return ((data[0] != 0) ? Boolean.TRUE : Boolean.FALSE);
  391. }
  392. @Override
  393. public ByteBuffer write(Object obj, int remainingRowLength)
  394. throws IOException
  395. {
  396. ByteBuffer buffer = PageChannel.createBuffer(1);
  397. buffer.put(((Number)booleanToInteger(obj)).byteValue());
  398. buffer.flip();
  399. return buffer;
  400. }
  401. }
  402. }
  403. }