aboutsummaryrefslogtreecommitdiffstats
path: root/src/main/java/com/healthmarketscience/jackcess/impl/PropertyMaps.java
blob: e545574bac7ccfb42a42ac0f3c69fd049ae54344 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
/*
Copyright (c) 2011 James Ahlborn

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package com.healthmarketscience.jackcess.impl;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.healthmarketscience.jackcess.DataType;
import com.healthmarketscience.jackcess.PropertyMap;

/**
 * Collection of PropertyMap instances read from a single property data block.
 *
 * @author James Ahlborn
 */
public class PropertyMaps implements Iterable<PropertyMapImpl>
{
  /** the name of the "default" properties for a PropertyMaps instance */
  public static final String DEFAULT_NAME = "";

  private static final short PROPERTY_NAME_LIST = 0x80;
  private static final short DEFAULT_PROPERTY_VALUE_LIST = 0x00;
  private static final short COLUMN_PROPERTY_VALUE_LIST = 0x01;

  /** maps the PropertyMap name (case-insensitive) to the PropertyMap
      instance */
  private final Map<String,PropertyMapImpl> _maps =
    new LinkedHashMap<String,PropertyMapImpl>();
  private final int _objectId;
  private final RowIdImpl _rowId;
  private final Handler _handler;
  private final Owner _owner;

  public PropertyMaps(int objectId, RowIdImpl rowId, Handler handler,
                      Owner owner) {
    _objectId = objectId;
    _rowId = rowId;
    _handler = handler;
    _owner = owner;
  }

  public int getObjectId() {
    return _objectId;
  }

  public int getSize() {
    return _maps.size();
  }

  public boolean isEmpty() {
    return _maps.isEmpty();
  }

  /**
   * @return the unnamed "default" PropertyMap in this group, creating if
   *         necessary.
   */
  public PropertyMapImpl getDefault() {
    return get(DEFAULT_NAME, DEFAULT_PROPERTY_VALUE_LIST);
  }

  /**
   * @return the PropertyMap with the given name in this group, creating if
   *         necessary
   */
  public PropertyMapImpl get(String name) {
    return get(name, COLUMN_PROPERTY_VALUE_LIST);
  }

  /**
   * @return the PropertyMap with the given name and type in this group,
   *         creating if necessary
   */
  private PropertyMapImpl get(String name, short type) {
    String lookupName = DatabaseImpl.toLookupName(name);
    PropertyMapImpl map = _maps.get(lookupName);
    if(map == null) {
      map = new PropertyMapImpl(name, type, this);
      _maps.put(lookupName, map);
    }
    return map;
  }

  @Override
  public Iterator<PropertyMapImpl> iterator() {
    return _maps.values().iterator();
  }

  public byte[] write() throws IOException {
    return _handler.write(this);
  }

  public void save() throws IOException {
    _handler.save(this);
    if(_owner != null) {
      _owner.propertiesUpdated();
    }
  }

  @Override
  public String toString() {
    return CustomToStringStyle.builder(this)
      .append(null, _maps.values())
      .toString();
  }

  public static String getTrimmedStringProperty(
      PropertyMap props, String propName)
  {
    return DatabaseImpl.trimToNull((String)props.getValue(propName));
  }

  /**
   * Utility class for reading/writing property blocks.
   */
  static final class Handler
  {
    /** the current database */
    private final DatabaseImpl _database;
    /** the system table "property" column */
    private final ColumnImpl _propCol;
    /** cache of PropColumns used to read/write property values */
    private final Map<DataType,PropColumn> _columns =
      new HashMap<DataType,PropColumn>();

    Handler(DatabaseImpl database) {
      _database = database;
      _propCol = _database.getSystemCatalog().getColumn(
          DatabaseImpl.CAT_COL_PROPS);
    }

    /**
     * @return a PropertyMaps instance decoded from the given bytes (always
     *         returns non-{@code null} result).
     */
    public PropertyMaps read(byte[] propBytes, int objectId,
                             RowIdImpl rowId, Owner owner)
      throws IOException
    {
      PropertyMaps maps = new PropertyMaps(objectId, rowId, this, owner);
      if((propBytes == null) || (propBytes.length == 0)) {
        return maps;
      }

      ByteBuffer bb = PageChannel.wrap(propBytes);

      // check for known header
      boolean knownType = false;
      for(byte[] tmpType : JetFormat.PROPERTY_MAP_TYPES) {
        if(ByteUtil.matchesRange(bb, bb.position(), tmpType)) {
          ByteUtil.forward(bb, tmpType.length);
          knownType = true;
          break;
        }
      }

      if(!knownType) {
        throw new IOException("Unknown property map type " +
                              ByteUtil.toHexString(bb, 4));
      }

      // parse each data "chunk"
      List<String> propNames = null;
      while(bb.hasRemaining()) {

        int len = bb.getInt();
        short type = bb.getShort();
        int endPos = bb.position() + len - 6;

        ByteBuffer bbBlock = PageChannel.narrowBuffer(bb, bb.position(),
                                                      endPos);

        if(type == PROPERTY_NAME_LIST) {
          propNames = readPropertyNames(bbBlock);
        } else {
          readPropertyValues(bbBlock, propNames, type, maps);
        }

        bb.position(endPos);
      }

      return maps;
    }

    /**
     * @return a byte[] encoded from the given PropertyMaps instance
     */
    public byte[] write(PropertyMaps maps)
      throws IOException
    {
      if(maps == null) {
        return null;
      }

      ByteArrayBuilder bab = new ByteArrayBuilder();

      bab.put(_database.getFormat().PROPERTY_MAP_TYPE);

      // grab the property names from all the maps
      Set<String> propNames = new LinkedHashSet<String>();
      for(PropertyMapImpl propMap : maps) {
        for(PropertyMap.Property prop : propMap) {
          propNames.add(prop.getName());
        }
      }

      if(propNames.isEmpty()) {
        return null;
      }

      // write the full set of property names
      writeBlock(null, propNames, PROPERTY_NAME_LIST, bab);

      // write all the map values
      for(PropertyMapImpl propMap : maps) {
        if(!propMap.isEmpty()) {
          writeBlock(propMap, propNames, propMap.getType(), bab);
        }
      }

      return bab.toArray();
    }

    /**
     * Saves PropertyMaps instance to the db.
     */
    public void save(PropertyMaps maps) throws IOException
    {
      RowIdImpl rowId = maps._rowId;
      if(rowId == null) {
        throw new IllegalStateException(
            "PropertyMaps cannot be saved without a row id");
      }

      byte[] mapsBytes = write(maps);

      // for now assume all properties come from system catalog table
      _propCol.getTable().updateValue(_propCol, rowId, mapsBytes);
    }

    private void writeBlock(
        PropertyMapImpl propMap, Set<String> propNames,
        short blockType, ByteArrayBuilder bab)
      throws IOException
    {
      int blockStartPos = bab.position();
      bab.reserveInt()
        .putShort(blockType);

      if(blockType == PROPERTY_NAME_LIST) {
        writePropertyNames(propNames, bab);
      } else {
        writePropertyValues(propMap, propNames, bab);
      }

      int len = bab.position() - blockStartPos;
      bab.putInt(blockStartPos, len);
    }

    /**
     * @return the property names parsed from the given data chunk
     */
    private List<String> readPropertyNames(ByteBuffer bbBlock) {
      List<String> names = new ArrayList<String>();
      while(bbBlock.hasRemaining()) {
        names.add(readPropName(bbBlock));
      }
      return names;
    }

    private void writePropertyNames(Set<String> propNames,
                                    ByteArrayBuilder bab) {
      for(String propName : propNames) {
        writePropName(propName, bab);
      }
    }

    /**
     * @return the PropertyMap created from the values parsed from the given
     *         data chunk combined with the given property names
     */
    private PropertyMapImpl readPropertyValues(
        ByteBuffer bbBlock, List<String> propNames, short blockType,
        PropertyMaps maps)
      throws IOException
    {
      String mapName = DEFAULT_NAME;

      if(bbBlock.hasRemaining()) {

        // read the map name, if any
        int nameBlockLen = bbBlock.getInt();
        int endPos = bbBlock.position() + nameBlockLen - 4;
        if(nameBlockLen > 6) {
          mapName = readPropName(bbBlock);
        }
        bbBlock.position(endPos);
      }

      PropertyMapImpl map = maps.get(mapName, blockType);

      // read the values
      while(bbBlock.hasRemaining()) {

        int valLen = bbBlock.getShort();
        int endPos = bbBlock.position() + valLen - 2;
        boolean isDdl = (bbBlock.get() != 0);
        DataType dataType = DataType.fromByte(bbBlock.get());
        int nameIdx = bbBlock.getShort();
        int dataSize = bbBlock.getShort();

        String propName = propNames.get(nameIdx);
        PropColumn col = getColumn(dataType, propName, dataSize, null);

        byte[] data = ByteUtil.getBytes(bbBlock, dataSize);
        Object value = col.read(data);

        map.put(propName, dataType, value, isDdl);

        bbBlock.position(endPos);
      }

      return map;
    }

    private void writePropertyValues(
        PropertyMapImpl propMap, Set<String> propNames, ByteArrayBuilder bab)
      throws IOException
    {
      // write the map name, if any
      String mapName = propMap.getName();
      int blockStartPos = bab.position();
      bab.reserveInt();
      writePropName(mapName, bab);
      int len = bab.position() - blockStartPos;
      bab.putInt(blockStartPos, len);

      // write the map values
      int nameIdx = 0;
      for(String propName : propNames) {

        PropertyMapImpl.PropertyImpl prop = (PropertyMapImpl.PropertyImpl)
          propMap.get(propName);

        if(prop != null) {

          Object value = prop.getValue();
          if(value != null) {

            int valStartPos = bab.position();
            bab.reserveShort();

            byte ddlFlag = (byte)(prop.isDdl() ? 1 : 0);
            bab.put(ddlFlag);
            bab.put(prop.getType().getValue());
            bab.putShort((short)nameIdx);

            PropColumn col = getColumn(prop.getType(), propName, -1, value);

            ByteBuffer data = col.write(
                value, _database.getFormat().MAX_ROW_SIZE);

            bab.putShort((short)data.remaining());
            bab.put(data);

            len = bab.position() - valStartPos;
            bab.putShort(valStartPos, (short)len);
          }
        }

        ++nameIdx;
      }
    }

    /**
     * Reads a property name from the given data block
     */
    private String readPropName(ByteBuffer buffer) {
      int nameLength = buffer.getShort();
      byte[] nameBytes = ByteUtil.getBytes(buffer, nameLength);
      return ColumnImpl.decodeUncompressedText(nameBytes, _database.getCharset());
    }

    /**
     * Writes a property name to the given data block
     */
    private void writePropName(String propName, ByteArrayBuilder bab) {
      ByteBuffer textBuf = ColumnImpl.encodeUncompressedText(
          propName, _database.getCharset());
      bab.putShort((short)textBuf.remaining());
      bab.put(textBuf);
    }

    /**
     * Gets a PropColumn capable of reading/writing a property of the given
     * DataType
     */
    private PropColumn getColumn(DataType dataType, String propName,
                                 int dataSize, Object value)
      throws IOException
    {

      if(isPseudoGuidColumn(dataType, propName, dataSize, value)) {
        dataType = DataType.GUID;
      }

      PropColumn col = _columns.get(dataType);

      if(col == null) {

        // translate long value types into simple types
        DataType colType = dataType;
        if(dataType == DataType.MEMO) {
          colType = DataType.TEXT;
        } else if(dataType == DataType.OLE) {
          colType = DataType.BINARY;
        }

        // create column with ability to read/write the given data type
        col = ((colType == DataType.BOOLEAN) ?
               new BooleanPropColumn() : new PropColumn(colType));

        _columns.put(dataType, col);
      }

      return col;
    }

    private static boolean isPseudoGuidColumn(
        DataType dataType, String propName, int dataSize, Object value)
      throws IOException
    {
      // guids seem to be marked as "binary" fields
      return((dataType == DataType.BINARY) &&
             ((dataSize == DataType.GUID.getFixedSize()) ||
              ((dataSize == -1) && ColumnImpl.isGUIDValue(value))) &&
             PropertyMap.GUID_PROP.equalsIgnoreCase(propName));
    }

    /**
     * Column adapted to work w/out a Table.
     */
    private class PropColumn extends ColumnImpl
    {
      private PropColumn(DataType type) {
        super(null, null, type, 0, 0, 0);
      }

      @Override
      public DatabaseImpl getDatabase() {
        return _database;
      }
    }

    /**
     * Normal boolean columns do not write into the actual row data, so we
     * need to do a little extra work.
     */
    private final class BooleanPropColumn extends PropColumn
    {
      private BooleanPropColumn() {
        super(DataType.BOOLEAN);
      }

      @Override
      public Object read(byte[] data) throws IOException {
        return ((data[0] != 0) ? Boolean.TRUE : Boolean.FALSE);
      }

      @Override
      public ByteBuffer write(Object obj, int remainingRowLength)
        throws IOException
      {
        ByteBuffer buffer = PageChannel.createBuffer(1);
        buffer.put(((Number)booleanToInteger(obj)).byteValue());
        buffer.flip();
        return buffer;
      }
    }
  }

  /**
   * Utility interface for the object which owns the PropertyMaps
   */
  static interface Owner {

    /**
     * Invoked when new properties are saved.
     */
    public void propertiesUpdated() throws IOException;
  }
}