View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase;
20  
21  import java.io.DataInput;
22  import java.io.DataOutput;
23  import java.io.IOException;
24  import java.util.Collections;
25  import java.util.HashMap;
26  import java.util.HashSet;
27  import java.util.Map;
28  import java.util.Set;
29  
30  import org.apache.hadoop.hbase.classification.InterfaceAudience;
31  import org.apache.hadoop.hbase.classification.InterfaceStability;
32  import org.apache.hadoop.hbase.exceptions.DeserializationException;
33  import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
34  import org.apache.hadoop.hbase.io.compress.Compression;
35  import org.apache.hadoop.hbase.io.encoding.DataBlockEncoding;
36  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
37  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.BytesBytesPair;
38  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.ColumnFamilySchema;
39  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.NameStringPair;
40  import org.apache.hadoop.hbase.regionserver.BloomType;
41  import org.apache.hadoop.hbase.util.Bytes;
42  import org.apache.hadoop.hbase.util.PrettyPrinter;
43  import org.apache.hadoop.hbase.util.PrettyPrinter.Unit;
44  import org.apache.hadoop.io.Text;
45  import org.apache.hadoop.io.WritableComparable;
46  
47  import com.google.common.base.Preconditions;
48  import org.apache.hadoop.hbase.util.ByteStringer;
49  import com.google.protobuf.InvalidProtocolBufferException;
50  
51  /**
52   * An HColumnDescriptor contains information about a column family such as the
53   * number of versions, compression settings, etc.
54   *
55   * It is used as input when creating a table or adding a column.
56   */
57  @InterfaceAudience.Public
58  @InterfaceStability.Evolving
59  public class HColumnDescriptor implements WritableComparable<HColumnDescriptor> {
60    // For future backward compatibility
61  
62    // Version  3 was when column names become byte arrays and when we picked up
63    // Time-to-live feature.  Version 4 was when we moved to byte arrays, HBASE-82.
64    // Version  5 was when bloom filter descriptors were removed.
65    // Version  6 adds metadata as a map where keys and values are byte[].
66    // Version  7 -- add new compression and hfile blocksize to HColumnDescriptor (HBASE-1217)
67    // Version  8 -- reintroduction of bloom filters, changed from boolean to enum
68    // Version  9 -- add data block encoding
69    // Version 10 -- change metadata to standard type.
70    // Version 11 -- add column family level configuration.
71    private static final byte COLUMN_DESCRIPTOR_VERSION = (byte) 11;
72  
73    // These constants are used as FileInfo keys
74    public static final String COMPRESSION = "COMPRESSION";
75    public static final String COMPRESSION_COMPACT = "COMPRESSION_COMPACT";
76    public static final String ENCODE_ON_DISK = // To be removed, it is not used anymore
77        "ENCODE_ON_DISK";
78    public static final String DATA_BLOCK_ENCODING =
79        "DATA_BLOCK_ENCODING";
80    /**
81     * Key for the BLOCKCACHE attribute.
82     * A more exact name would be CACHE_DATA_ON_READ because this flag sets whether or not we
83     * cache DATA blocks.  We always cache INDEX and BLOOM blocks; caching these blocks cannot be
84     * disabled.
85     */
86    public static final String BLOCKCACHE = "BLOCKCACHE";
87    public static final String CACHE_DATA_ON_WRITE = "CACHE_DATA_ON_WRITE";
88    public static final String CACHE_INDEX_ON_WRITE = "CACHE_INDEX_ON_WRITE";
89    public static final String CACHE_BLOOMS_ON_WRITE = "CACHE_BLOOMS_ON_WRITE";
90    public static final String EVICT_BLOCKS_ON_CLOSE = "EVICT_BLOCKS_ON_CLOSE";
91    /**
92     * Key for cache data into L1 if cache is set up with more than one tier.
93     * To set in the shell, do something like this:
94     * <code>hbase(main):003:0> create 't',
95     *    {NAME => 't', CONFIGURATION => {CACHE_DATA_IN_L1 => 'true'}}</code>
96     */
97    public static final String CACHE_DATA_IN_L1 = "CACHE_DATA_IN_L1";
98  
99    /**
100    * Key for the PREFETCH_BLOCKS_ON_OPEN attribute.
101    * If set, all INDEX, BLOOM, and DATA blocks of HFiles belonging to this
102    * family will be loaded into the cache as soon as the file is opened. These
103    * loads will not count as cache misses.
104    */
105   public static final String PREFETCH_BLOCKS_ON_OPEN = "PREFETCH_BLOCKS_ON_OPEN";
106 
107   /**
108    * Size of storefile/hfile 'blocks'.  Default is {@link #DEFAULT_BLOCKSIZE}.
109    * Use smaller block sizes for faster random-access at expense of larger
110    * indices (more memory consumption).
111    */
112   public static final String BLOCKSIZE = "BLOCKSIZE";
113 
114   public static final String LENGTH = "LENGTH";
115   public static final String TTL = "TTL";
116   public static final String BLOOMFILTER = "BLOOMFILTER";
117   public static final String FOREVER = "FOREVER";
118   public static final String REPLICATION_SCOPE = "REPLICATION_SCOPE";
119   public static final byte[] REPLICATION_SCOPE_BYTES = Bytes.toBytes(REPLICATION_SCOPE);
120   public static final String MIN_VERSIONS = "MIN_VERSIONS";
121   public static final String KEEP_DELETED_CELLS = "KEEP_DELETED_CELLS";
122   public static final String COMPRESS_TAGS = "COMPRESS_TAGS";
123 
124   public static final String ENCRYPTION = "ENCRYPTION";
125   public static final String ENCRYPTION_KEY = "ENCRYPTION_KEY";
126 
127   /**
128    * Default compression type.
129    */
130   public static final String DEFAULT_COMPRESSION =
131     Compression.Algorithm.NONE.getName();
132 
133   /**
134    * Default value of the flag that enables data block encoding on disk, as
135    * opposed to encoding in cache only. We encode blocks everywhere by default,
136    * as long as {@link #DATA_BLOCK_ENCODING} is not NONE.
137    */
138   public static final boolean DEFAULT_ENCODE_ON_DISK = true;
139 
140   /** Default data block encoding algorithm. */
141   public static final String DEFAULT_DATA_BLOCK_ENCODING =
142       DataBlockEncoding.NONE.toString();
143 
144   /**
145    * Default number of versions of a record to keep.
146    */
147   public static final int DEFAULT_VERSIONS = HBaseConfiguration.create().getInt(
148     "hbase.column.max.version", 1);
149 
150   /**
151    * Default is not to keep a minimum of versions.
152    */
153   public static final int DEFAULT_MIN_VERSIONS = 0;
154 
155   /*
156    * Cache here the HCD value.
157    * Question: its OK to cache since when we're reenable, we create a new HCD?
158    */
159   private volatile Integer blocksize = null;
160 
161   /**
162    * Default setting for whether to try and serve this column family from memory or not.
163    */
164   public static final boolean DEFAULT_IN_MEMORY = false;
165 
166   /**
167    * Default setting for preventing deleted from being collected immediately.
168    */
169   public static final KeepDeletedCells DEFAULT_KEEP_DELETED = KeepDeletedCells.FALSE;
170 
171   /**
172    * Default setting for whether to use a block cache or not.
173    */
174   public static final boolean DEFAULT_BLOCKCACHE = true;
175 
176   /**
177    * Default setting for whether to cache data blocks on write if block caching
178    * is enabled.
179    */
180   public static final boolean DEFAULT_CACHE_DATA_ON_WRITE = false;
181 
182   /**
183    * Default setting for whether to cache data blocks in L1 tier.  Only makes sense if more than
184    * one tier in operations: i.e. if we have an L1 and a L2.  This will be the cases if we are
185    * using BucketCache.
186    */
187   public static final boolean DEFAULT_CACHE_DATA_IN_L1 = false;
188 
189   /**
190    * Default setting for whether to cache index blocks on write if block
191    * caching is enabled.
192    */
193   public static final boolean DEFAULT_CACHE_INDEX_ON_WRITE = false;
194 
195   /**
196    * Default size of blocks in files stored to the filesytem (hfiles).
197    */
198   public static final int DEFAULT_BLOCKSIZE = HConstants.DEFAULT_BLOCKSIZE;
199 
200   /**
201    * Default setting for whether or not to use bloomfilters.
202    */
203   public static final String DEFAULT_BLOOMFILTER = BloomType.ROW.toString();
204 
205   /**
206    * Default setting for whether to cache bloom filter blocks on write if block
207    * caching is enabled.
208    */
209   public static final boolean DEFAULT_CACHE_BLOOMS_ON_WRITE = false;
210 
211   /**
212    * Default time to live of cell contents.
213    */
214   public static final int DEFAULT_TTL = HConstants.FOREVER;
215 
216   /**
217    * Default scope.
218    */
219   public static final int DEFAULT_REPLICATION_SCOPE = HConstants.REPLICATION_SCOPE_LOCAL;
220 
221   /**
222    * Default setting for whether to evict cached blocks from the blockcache on
223    * close.
224    */
225   public static final boolean DEFAULT_EVICT_BLOCKS_ON_CLOSE = false;
226 
227   /**
228    * Default compress tags along with any type of DataBlockEncoding.
229    */
230   public static final boolean DEFAULT_COMPRESS_TAGS = true;
231 
232   /*
233    * Default setting for whether to prefetch blocks into the blockcache on open.
234    */
235   public static final boolean DEFAULT_PREFETCH_BLOCKS_ON_OPEN = false;
236 
237   private final static Map<String, String> DEFAULT_VALUES
238     = new HashMap<String, String>();
239   private final static Set<ImmutableBytesWritable> RESERVED_KEYWORDS
240     = new HashSet<ImmutableBytesWritable>();
241   static {
242       DEFAULT_VALUES.put(BLOOMFILTER, DEFAULT_BLOOMFILTER);
243       DEFAULT_VALUES.put(REPLICATION_SCOPE, String.valueOf(DEFAULT_REPLICATION_SCOPE));
244       DEFAULT_VALUES.put(HConstants.VERSIONS, String.valueOf(DEFAULT_VERSIONS));
245       DEFAULT_VALUES.put(MIN_VERSIONS, String.valueOf(DEFAULT_MIN_VERSIONS));
246       DEFAULT_VALUES.put(COMPRESSION, DEFAULT_COMPRESSION);
247       DEFAULT_VALUES.put(TTL, String.valueOf(DEFAULT_TTL));
248       DEFAULT_VALUES.put(BLOCKSIZE, String.valueOf(DEFAULT_BLOCKSIZE));
249       DEFAULT_VALUES.put(HConstants.IN_MEMORY, String.valueOf(DEFAULT_IN_MEMORY));
250       DEFAULT_VALUES.put(BLOCKCACHE, String.valueOf(DEFAULT_BLOCKCACHE));
251       DEFAULT_VALUES.put(KEEP_DELETED_CELLS, String.valueOf(DEFAULT_KEEP_DELETED));
252       DEFAULT_VALUES.put(DATA_BLOCK_ENCODING, String.valueOf(DEFAULT_DATA_BLOCK_ENCODING));
253       DEFAULT_VALUES.put(CACHE_DATA_ON_WRITE, String.valueOf(DEFAULT_CACHE_DATA_ON_WRITE));
254       DEFAULT_VALUES.put(CACHE_DATA_IN_L1, String.valueOf(DEFAULT_CACHE_DATA_IN_L1));
255       DEFAULT_VALUES.put(CACHE_INDEX_ON_WRITE, String.valueOf(DEFAULT_CACHE_INDEX_ON_WRITE));
256       DEFAULT_VALUES.put(CACHE_BLOOMS_ON_WRITE, String.valueOf(DEFAULT_CACHE_BLOOMS_ON_WRITE));
257       DEFAULT_VALUES.put(EVICT_BLOCKS_ON_CLOSE, String.valueOf(DEFAULT_EVICT_BLOCKS_ON_CLOSE));
258       DEFAULT_VALUES.put(PREFETCH_BLOCKS_ON_OPEN, String.valueOf(DEFAULT_PREFETCH_BLOCKS_ON_OPEN));
259       for (String s : DEFAULT_VALUES.keySet()) {
260         RESERVED_KEYWORDS.add(new ImmutableBytesWritable(Bytes.toBytes(s)));
261       }
262       RESERVED_KEYWORDS.add(new ImmutableBytesWritable(Bytes.toBytes(ENCRYPTION)));
263       RESERVED_KEYWORDS.add(new ImmutableBytesWritable(Bytes.toBytes(ENCRYPTION_KEY)));
264   }
265 
266   private static final int UNINITIALIZED = -1;
267 
268   // Column family name
269   private byte [] name;
270 
271   // Column metadata
272   private final Map<ImmutableBytesWritable, ImmutableBytesWritable> values =
273     new HashMap<ImmutableBytesWritable,ImmutableBytesWritable>();
274 
275   /**
276    * A map which holds the configuration specific to the column family.
277    * The keys of the map have the same names as config keys and override the defaults with
278    * cf-specific settings. Example usage may be for compactions, etc.
279    */
280   private final Map<String, String> configuration = new HashMap<String, String>();
281 
282   /*
283    * Cache the max versions rather than calculate it every time.
284    */
285   private int cachedMaxVersions = UNINITIALIZED;
286 
287   /**
288    * Default constructor.
289    * @deprecated As of release 0.96
290    *             (<a href="https://issues.apache.org/jira/browse/HBASE-5453">HBASE-5453</a>).
291    *             This will be made private in HBase 2.0.0.
292    *             Used by Writables and Writables are going away.
293    */
294   @Deprecated
295   // Make this private rather than remove after deprecation period elapses.  Its needed by pb
296   // deserializations.
297   public HColumnDescriptor() {
298     this.name = null;
299   }
300 
301   /**
302    * Construct a column descriptor specifying only the family name
303    * The other attributes are defaulted.
304    *
305    * @param familyName Column family name. Must be 'printable' -- digit or
306    * letter -- and may not contain a <code>:<code>
307    */
308   public HColumnDescriptor(final String familyName) {
309     this(Bytes.toBytes(familyName));
310   }
311 
312   /**
313    * Construct a column descriptor specifying only the family name
314    * The other attributes are defaulted.
315    *
316    * @param familyName Column family name. Must be 'printable' -- digit or
317    * letter -- and may not contain a <code>:<code>
318    */
319   public HColumnDescriptor(final byte [] familyName) {
320     this (familyName == null || familyName.length <= 0?
321       HConstants.EMPTY_BYTE_ARRAY: familyName, DEFAULT_VERSIONS,
322       DEFAULT_COMPRESSION, DEFAULT_IN_MEMORY, DEFAULT_BLOCKCACHE,
323       DEFAULT_TTL, DEFAULT_BLOOMFILTER);
324   }
325 
326   /**
327    * Constructor.
328    * Makes a deep copy of the supplied descriptor.
329    * Can make a modifiable descriptor from an UnmodifyableHColumnDescriptor.
330    * @param desc The descriptor.
331    */
332   public HColumnDescriptor(HColumnDescriptor desc) {
333     super();
334     this.name = desc.name.clone();
335     for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> e:
336         desc.values.entrySet()) {
337       this.values.put(e.getKey(), e.getValue());
338     }
339     for (Map.Entry<String, String> e : desc.configuration.entrySet()) {
340       this.configuration.put(e.getKey(), e.getValue());
341     }
342     setMaxVersions(desc.getMaxVersions());
343   }
344 
345   /**
346    * Constructor
347    * @param familyName Column family name. Must be 'printable' -- digit or
348    * letter -- and may not contain a <code>:<code>
349    * @param maxVersions Maximum number of versions to keep
350    * @param compression Compression type
351    * @param inMemory If true, column data should be kept in an HRegionServer's
352    * cache
353    * @param blockCacheEnabled If true, MapFile blocks should be cached
354    * @param timeToLive Time-to-live of cell contents, in seconds
355    * (use HConstants.FOREVER for unlimited TTL)
356    * @param bloomFilter Bloom filter type for this column
357    *
358    * @throws IllegalArgumentException if passed a family name that is made of
359    * other than 'word' characters: i.e. <code>[a-zA-Z_0-9]</code> or contains
360    * a <code>:</code>
361    * @throws IllegalArgumentException if the number of versions is &lt;= 0
362    * @deprecated As of release 0.96
363    *             (<a href="https://issues.apache.org/jira/browse/HBASE-">HBASE-</a>).
364    *             This will be removed in HBase 2.0.0.
365    *             Use {@link #HColumnDescriptor(String)} and setters.
366    */
367   @Deprecated
368   public HColumnDescriptor(final byte [] familyName, final int maxVersions,
369       final String compression, final boolean inMemory,
370       final boolean blockCacheEnabled,
371       final int timeToLive, final String bloomFilter) {
372     this(familyName, maxVersions, compression, inMemory, blockCacheEnabled,
373       DEFAULT_BLOCKSIZE, timeToLive, bloomFilter, DEFAULT_REPLICATION_SCOPE);
374   }
375 
376   /**
377    * Constructor
378    * @param familyName Column family name. Must be 'printable' -- digit or
379    * letter -- and may not contain a <code>:<code>
380    * @param maxVersions Maximum number of versions to keep
381    * @param compression Compression type
382    * @param inMemory If true, column data should be kept in an HRegionServer's
383    * cache
384    * @param blockCacheEnabled If true, MapFile blocks should be cached
385    * @param blocksize Block size to use when writing out storefiles.  Use
386    * smaller block sizes for faster random-access at expense of larger indices
387    * (more memory consumption).  Default is usually 64k.
388    * @param timeToLive Time-to-live of cell contents, in seconds
389    * (use HConstants.FOREVER for unlimited TTL)
390    * @param bloomFilter Bloom filter type for this column
391    * @param scope The scope tag for this column
392    *
393    * @throws IllegalArgumentException if passed a family name that is made of
394    * other than 'word' characters: i.e. <code>[a-zA-Z_0-9]</code> or contains
395    * a <code>:</code>
396    * @throws IllegalArgumentException if the number of versions is &lt;= 0
397    * @deprecated As of release 0.96
398    *             (<a href="https://issues.apache.org/jira/browse/HBASE-">HBASE-</a>).
399    *             This will be removed in HBase 2.0.0.
400    *             Use {@link #HColumnDescriptor(String)} and setters.
401    */
402   @Deprecated
403   public HColumnDescriptor(final byte [] familyName, final int maxVersions,
404       final String compression, final boolean inMemory,
405       final boolean blockCacheEnabled, final int blocksize,
406       final int timeToLive, final String bloomFilter, final int scope) {
407     this(familyName, DEFAULT_MIN_VERSIONS, maxVersions, DEFAULT_KEEP_DELETED,
408         compression, DEFAULT_ENCODE_ON_DISK, DEFAULT_DATA_BLOCK_ENCODING,
409         inMemory, blockCacheEnabled, blocksize, timeToLive, bloomFilter,
410         scope);
411   }
412 
413   /**
414    * Constructor
415    * @param familyName Column family name. Must be 'printable' -- digit or
416    * letter -- and may not contain a <code>:<code>
417    * @param minVersions Minimum number of versions to keep
418    * @param maxVersions Maximum number of versions to keep
419    * @param keepDeletedCells Whether to retain deleted cells until they expire
420    *        up to maxVersions versions.
421    * @param compression Compression type
422    * @param encodeOnDisk whether to use the specified data block encoding
423    *        on disk. If false, the encoding will be used in cache only.
424    * @param dataBlockEncoding data block encoding
425    * @param inMemory If true, column data should be kept in an HRegionServer's
426    * cache
427    * @param blockCacheEnabled If true, MapFile blocks should be cached
428    * @param blocksize Block size to use when writing out storefiles.  Use
429    * smaller blocksizes for faster random-access at expense of larger indices
430    * (more memory consumption).  Default is usually 64k.
431    * @param timeToLive Time-to-live of cell contents, in seconds
432    * (use HConstants.FOREVER for unlimited TTL)
433    * @param bloomFilter Bloom filter type for this column
434    * @param scope The scope tag for this column
435    *
436    * @throws IllegalArgumentException if passed a family name that is made of
437    * other than 'word' characters: i.e. <code>[a-zA-Z_0-9]</code> or contains
438    * a <code>:</code>
439    * @throws IllegalArgumentException if the number of versions is &lt;= 0
440    * @deprecated As of release 0.96
441    *             (<a href="https://issues.apache.org/jira/browse/HBASE-">HBASE-</a>).
442    *             This will be removed in HBase 2.0.0.
443    *             Use {@link #HColumnDescriptor(String)} and setters.
444    */
445   @Deprecated
446   public HColumnDescriptor(final byte[] familyName, final int minVersions,
447       final int maxVersions, final KeepDeletedCells keepDeletedCells,
448       final String compression, final boolean encodeOnDisk,
449       final String dataBlockEncoding, final boolean inMemory,
450       final boolean blockCacheEnabled, final int blocksize,
451       final int timeToLive, final String bloomFilter, final int scope) {
452     isLegalFamilyName(familyName);
453     this.name = familyName;
454 
455     if (maxVersions <= 0) {
456       // TODO: Allow maxVersion of 0 to be the way you say "Keep all versions".
457       // Until there is support, consider 0 or < 0 -- a configuration error.
458       throw new IllegalArgumentException("Maximum versions must be positive");
459     }
460 
461     if (minVersions > 0) {
462       if (timeToLive == HConstants.FOREVER) {
463         throw new IllegalArgumentException("Minimum versions requires TTL.");
464       }
465       if (minVersions >= maxVersions) {
466         throw new IllegalArgumentException("Minimum versions must be < "
467             + "maximum versions.");
468       }
469     }
470 
471     setMaxVersions(maxVersions);
472     setMinVersions(minVersions);
473     setKeepDeletedCells(keepDeletedCells);
474     setInMemory(inMemory);
475     setBlockCacheEnabled(blockCacheEnabled);
476     setTimeToLive(timeToLive);
477     setCompressionType(Compression.Algorithm.
478       valueOf(compression.toUpperCase()));
479     setDataBlockEncoding(DataBlockEncoding.
480         valueOf(dataBlockEncoding.toUpperCase()));
481     setBloomFilterType(BloomType.
482       valueOf(bloomFilter.toUpperCase()));
483     setBlocksize(blocksize);
484     setScope(scope);
485   }
486 
487   /**
488    * @param b Family name.
489    * @return <code>b</code>
490    * @throws IllegalArgumentException If not null and not a legitimate family
491    * name: i.e. 'printable' and ends in a ':' (Null passes are allowed because
492    * <code>b</code> can be null when deserializing).  Cannot start with a '.'
493    * either. Also Family can not be an empty value or equal "recovered.edits".
494    */
495   public static byte [] isLegalFamilyName(final byte [] b) {
496     if (b == null) {
497       return b;
498     }
499     Preconditions.checkArgument(b.length != 0, "Family name can not be empty");
500     if (b[0] == '.') {
501       throw new IllegalArgumentException("Family names cannot start with a " +
502         "period: " + Bytes.toString(b));
503     }
504     for (int i = 0; i < b.length; i++) {
505       if (Character.isISOControl(b[i]) || b[i] == ':' || b[i] == '\\' || b[i] == '/') {
506         throw new IllegalArgumentException("Illegal character <" + b[i] +
507           ">. Family names cannot contain control characters or colons: " +
508           Bytes.toString(b));
509       }
510     }
511     byte[] recoveredEdit = Bytes.toBytes(HConstants.RECOVERED_EDITS_DIR);
512     if (Bytes.equals(recoveredEdit, b)) {
513       throw new IllegalArgumentException("Family name cannot be: " +
514           HConstants.RECOVERED_EDITS_DIR);
515     }
516     return b;
517   }
518 
519   /**
520    * @return Name of this column family
521    */
522   public byte [] getName() {
523     return name;
524   }
525 
526   /**
527    * @return Name of this column family
528    */
529   public String getNameAsString() {
530     return Bytes.toString(this.name);
531   }
532 
533   /**
534    * @param key The key.
535    * @return The value.
536    */
537   public byte[] getValue(byte[] key) {
538     ImmutableBytesWritable ibw = values.get(new ImmutableBytesWritable(key));
539     if (ibw == null)
540       return null;
541     return ibw.get();
542   }
543 
544   /**
545    * @param key The key.
546    * @return The value as a string.
547    */
548   public String getValue(String key) {
549     byte[] value = getValue(Bytes.toBytes(key));
550     if (value == null)
551       return null;
552     return Bytes.toString(value);
553   }
554 
555   /**
556    * @return All values.
557    */
558   public Map<ImmutableBytesWritable,ImmutableBytesWritable> getValues() {
559     // shallow pointer copy
560     return Collections.unmodifiableMap(values);
561   }
562 
563   /**
564    * @param key The key.
565    * @param value The value.
566    * @return this (for chained invocation)
567    */
568   public HColumnDescriptor setValue(byte[] key, byte[] value) {
569     values.put(new ImmutableBytesWritable(key),
570       new ImmutableBytesWritable(value));
571     return this;
572   }
573 
574   /**
575    * @param key Key whose key and value we're to remove from HCD parameters.
576    */
577   public void remove(final byte [] key) {
578     values.remove(new ImmutableBytesWritable(key));
579   }
580 
581   /**
582    * @param key The key.
583    * @param value The value.
584    * @return this (for chained invocation)
585    */
586   public HColumnDescriptor setValue(String key, String value) {
587     if (value == null) {
588       remove(Bytes.toBytes(key));
589     } else {
590       setValue(Bytes.toBytes(key), Bytes.toBytes(value));
591     }
592     return this;
593   }
594 
595   /** @return compression type being used for the column family */
596   public Compression.Algorithm getCompression() {
597     String n = getValue(COMPRESSION);
598     if (n == null) {
599       return Compression.Algorithm.NONE;
600     }
601     return Compression.Algorithm.valueOf(n.toUpperCase());
602   }
603 
604   /** @return compression type being used for the column family for major
605       compression */
606   public Compression.Algorithm getCompactionCompression() {
607     String n = getValue(COMPRESSION_COMPACT);
608     if (n == null) {
609       return getCompression();
610     }
611     return Compression.Algorithm.valueOf(n.toUpperCase());
612   }
613 
614   /** @return maximum number of versions */
615   public int getMaxVersions() {
616     if (this.cachedMaxVersions == UNINITIALIZED) {
617       String v = getValue(HConstants.VERSIONS);
618       this.cachedMaxVersions = Integer.parseInt(v);
619     }
620     return this.cachedMaxVersions;
621   }
622 
623   /**
624    * @param maxVersions maximum number of versions
625    * @return this (for chained invocation)
626    */
627   public HColumnDescriptor setMaxVersions(int maxVersions) {
628     if (maxVersions <= 0) {
629       // TODO: Allow maxVersion of 0 to be the way you say "Keep all versions".
630       // Until there is support, consider 0 or < 0 -- a configuration error.
631       throw new IllegalArgumentException("Maximum versions must be positive");
632     }
633     if (maxVersions < this.getMinVersions()) {
634         throw new IllegalArgumentException("Set MaxVersion to " + maxVersions
635             + " while minVersion is " + this.getMinVersions()
636             + ". Maximum versions must be >= minimum versions ");
637     }
638     setValue(HConstants.VERSIONS, Integer.toString(maxVersions));
639     cachedMaxVersions = maxVersions;
640     return this;
641   }
642 
643   /**
644    * @return The storefile/hfile blocksize for this column family.
645    */
646   public synchronized int getBlocksize() {
647     if (this.blocksize == null) {
648       String value = getValue(BLOCKSIZE);
649       this.blocksize = (value != null)?
650         Integer.decode(value): Integer.valueOf(DEFAULT_BLOCKSIZE);
651     }
652     return this.blocksize.intValue();
653   }
654 
655   /**
656    * @param s Blocksize to use when writing out storefiles/hfiles on this
657    * column family.
658    * @return this (for chained invocation)
659    */
660   public HColumnDescriptor setBlocksize(int s) {
661     setValue(BLOCKSIZE, Integer.toString(s));
662     this.blocksize = null;
663     return this;
664   }
665 
666   /**
667    * @return Compression type setting.
668    */
669   public Compression.Algorithm getCompressionType() {
670     return getCompression();
671   }
672 
673   /**
674    * Compression types supported in hbase.
675    * LZO is not bundled as part of the hbase distribution.
676    * See <a href="http://wiki.apache.org/hadoop/UsingLzoCompression">LZO Compression</a>
677    * for how to enable it.
678    * @param type Compression type setting.
679    * @return this (for chained invocation)
680    */
681   public HColumnDescriptor setCompressionType(Compression.Algorithm type) {
682     return setValue(COMPRESSION, type.getName().toUpperCase());
683   }
684 
685   /**
686    * @return data block encoding algorithm used on disk
687    * @deprecated As of release 0.98
688    *             (<a href="https://issues.apache.org/jira/browse/HBASE-9870">HBASE-9870</a>).
689    *             This will be removed in HBase 2.0.0. See {@link #getDataBlockEncoding()}}
690    */
691   @Deprecated
692   public DataBlockEncoding getDataBlockEncodingOnDisk() {
693     return getDataBlockEncoding();
694   }
695 
696   /**
697    * This method does nothing now. Flag ENCODE_ON_DISK is not used
698    * any more. Data blocks have the same encoding in cache as on disk.
699    * @return this (for chained invocation)
700    * @deprecated As of release 0.98
701    *             (<a href="https://issues.apache.org/jira/browse/HBASE-9870">HBASE-9870</a>).
702    *             This will be removed in HBase 2.0.0. This method does nothing now.
703    */
704   @Deprecated
705   public HColumnDescriptor setEncodeOnDisk(boolean encodeOnDisk) {
706     return this;
707   }
708 
709   /**
710    * @return the data block encoding algorithm used in block cache and
711    *         optionally on disk
712    */
713   public DataBlockEncoding getDataBlockEncoding() {
714     String type = getValue(DATA_BLOCK_ENCODING);
715     if (type == null) {
716       type = DEFAULT_DATA_BLOCK_ENCODING;
717     }
718     return DataBlockEncoding.valueOf(type);
719   }
720 
721   /**
722    * Set data block encoding algorithm used in block cache.
723    * @param type What kind of data block encoding will be used.
724    * @return this (for chained invocation)
725    */
726   public HColumnDescriptor setDataBlockEncoding(DataBlockEncoding type) {
727     String name;
728     if (type != null) {
729       name = type.toString();
730     } else {
731       name = DataBlockEncoding.NONE.toString();
732     }
733     return setValue(DATA_BLOCK_ENCODING, name);
734   }
735 
736   /**
737    * Set whether the tags should be compressed along with DataBlockEncoding. When no
738    * DataBlockEncoding is been used, this is having no effect.
739    *
740    * @param compressTags
741    * @return this (for chained invocation)
742    */
743   public HColumnDescriptor setCompressTags(boolean compressTags) {
744     return setValue(COMPRESS_TAGS, String.valueOf(compressTags));
745   }
746 
747   /**
748    * @return Whether KV tags should be compressed along with DataBlockEncoding. When no
749    *         DataBlockEncoding is been used, this is having no effect.
750    * @deprecated As of release 1.0.0
751    *             (<a href="https://issues.apache.org/jira/browse/HBASE-10870">HBASE-10870</a>).
752    *             This will be removed in HBase 2.0.0. Use {@link #isCompressTags()} instead.
753    */
754   @Deprecated
755   public boolean shouldCompressTags() {
756     String compressTagsStr = getValue(COMPRESS_TAGS);
757     boolean compressTags = DEFAULT_COMPRESS_TAGS;
758     if (compressTagsStr != null) {
759       compressTags = Boolean.valueOf(compressTagsStr);
760     }
761     return compressTags;
762   }
763 
764   /**
765    * @return Whether KV tags should be compressed along with DataBlockEncoding. When no
766    *         DataBlockEncoding is been used, this is having no effect.
767    */
768   public boolean isCompressTags() {
769     String compressTagsStr = getValue(COMPRESS_TAGS);
770     boolean compressTags = DEFAULT_COMPRESS_TAGS;
771     if (compressTagsStr != null) {
772       compressTags = Boolean.valueOf(compressTagsStr);
773     }
774     return compressTags;
775   }
776 
777   /**
778    * @return Compression type setting.
779    */
780   public Compression.Algorithm getCompactionCompressionType() {
781     return getCompactionCompression();
782   }
783 
784   /**
785    * Compression types supported in hbase.
786    * LZO is not bundled as part of the hbase distribution.
787    * See <a href="http://wiki.apache.org/hadoop/UsingLzoCompression">LZO Compression</a>
788    * for how to enable it.
789    * @param type Compression type setting.
790    * @return this (for chained invocation)
791    */
792   public HColumnDescriptor setCompactionCompressionType(
793       Compression.Algorithm type) {
794     return setValue(COMPRESSION_COMPACT, type.getName().toUpperCase());
795   }
796 
797   /**
798    * @return True if we are to favor keeping all values for this column family in the
799    * HRegionServer cache.
800    */
801   public boolean isInMemory() {
802     String value = getValue(HConstants.IN_MEMORY);
803     if (value != null)
804       return Boolean.valueOf(value).booleanValue();
805     return DEFAULT_IN_MEMORY;
806   }
807 
808   /**
809    * @param inMemory True if we are to favor keeping all values for this column family in the
810    * HRegionServer cache
811    * @return this (for chained invocation)
812    */
813   public HColumnDescriptor setInMemory(boolean inMemory) {
814     return setValue(HConstants.IN_MEMORY, Boolean.toString(inMemory));
815   }
816 
817   public KeepDeletedCells getKeepDeletedCells() {
818     String value = getValue(KEEP_DELETED_CELLS);
819     if (value != null) {
820       // toUpperCase for backwards compatibility
821       return KeepDeletedCells.valueOf(value.toUpperCase());
822     }
823     return DEFAULT_KEEP_DELETED;
824   }
825 
826   /**
827    * @param keepDeletedCells True if deleted rows should not be collected
828    * immediately.
829    * @return this (for chained invocation)
830    * @deprecated As of release 1.0.0
831    *             (<a href="https://issues.apache.org/jira/browse/HBASE-12363">HBASE-12363</a>).
832    *             This will be removed in HBase 2.0.0.
833    *             Use {@link #setKeepDeletedCells(KeepDeletedCells)}.
834    */
835   @Deprecated
836   public HColumnDescriptor setKeepDeletedCells(boolean keepDeletedCells) {
837     return setValue(KEEP_DELETED_CELLS, (keepDeletedCells ? KeepDeletedCells.TRUE
838         : KeepDeletedCells.FALSE).toString());
839   }
840 
841   /**
842    * @param keepDeletedCells True if deleted rows should not be collected
843    * immediately.
844    * @return this (for chained invocation)
845    */
846   public HColumnDescriptor setKeepDeletedCells(KeepDeletedCells keepDeletedCells) {
847     return setValue(KEEP_DELETED_CELLS, keepDeletedCells.toString());
848   }
849 
850   /**
851    * @return Time-to-live of cell contents, in seconds.
852    */
853   public int getTimeToLive() {
854     String value = getValue(TTL);
855     return (value != null)? Integer.valueOf(value).intValue(): DEFAULT_TTL;
856   }
857 
858   /**
859    * @param timeToLive Time-to-live of cell contents, in seconds.
860    * @return this (for chained invocation)
861    */
862   public HColumnDescriptor setTimeToLive(int timeToLive) {
863     return setValue(TTL, Integer.toString(timeToLive));
864   }
865 
866   /**
867    * @return The minimum number of versions to keep.
868    */
869   public int getMinVersions() {
870     String value = getValue(MIN_VERSIONS);
871     return (value != null)? Integer.valueOf(value).intValue(): 0;
872   }
873 
874   /**
875    * @param minVersions The minimum number of versions to keep.
876    * (used when timeToLive is set)
877    * @return this (for chained invocation)
878    */
879   public HColumnDescriptor setMinVersions(int minVersions) {
880     return setValue(MIN_VERSIONS, Integer.toString(minVersions));
881   }
882 
883   /**
884    * @return True if hfile DATA type blocks should be cached (You cannot disable caching of INDEX
885    * and BLOOM type blocks).
886    */
887   public boolean isBlockCacheEnabled() {
888     String value = getValue(BLOCKCACHE);
889     if (value != null)
890       return Boolean.valueOf(value).booleanValue();
891     return DEFAULT_BLOCKCACHE;
892   }
893 
894   /**
895    * @param blockCacheEnabled True if hfile DATA type blocks should be cached (We always cache
896    * INDEX and BLOOM blocks; you cannot turn this off).
897    * @return this (for chained invocation)
898    */
899   public HColumnDescriptor setBlockCacheEnabled(boolean blockCacheEnabled) {
900     return setValue(BLOCKCACHE, Boolean.toString(blockCacheEnabled));
901   }
902 
903   /**
904    * @return bloom filter type used for new StoreFiles in ColumnFamily
905    */
906   public BloomType getBloomFilterType() {
907     String n = getValue(BLOOMFILTER);
908     if (n == null) {
909       n = DEFAULT_BLOOMFILTER;
910     }
911     return BloomType.valueOf(n.toUpperCase());
912   }
913 
914   /**
915    * @param bt bloom filter type
916    * @return this (for chained invocation)
917    */
918   public HColumnDescriptor setBloomFilterType(final BloomType bt) {
919     return setValue(BLOOMFILTER, bt.toString());
920   }
921 
922    /**
923     * @return the scope tag
924     */
925   public int getScope() {
926     byte[] value = getValue(REPLICATION_SCOPE_BYTES);
927     if (value != null) {
928       return Integer.valueOf(Bytes.toString(value));
929     }
930     return DEFAULT_REPLICATION_SCOPE;
931   }
932 
933  /**
934   * @param scope the scope tag
935   * @return this (for chained invocation)
936   */
937   public HColumnDescriptor setScope(int scope) {
938     return setValue(REPLICATION_SCOPE, Integer.toString(scope));
939   }
940 
941   /**
942    * @return true if we should cache data blocks on write
943    * @deprecated As of release 1.0.0
944    *             (<a href="https://issues.apache.org/jira/browse/HBASE-10870">HBASE-10870</a>).
945    *             This will be removed in HBase 2.0.0. Use {@link #isCacheDataOnWrite()}} instead.
946    */
947   @Deprecated
948   public boolean shouldCacheDataOnWrite() {
949     return setAndGetBoolean(CACHE_DATA_ON_WRITE, DEFAULT_CACHE_DATA_ON_WRITE);
950   }
951 
952   /**
953    * @return true if we should cache data blocks on write
954    */
955   public boolean isCacheDataOnWrite() {
956     return setAndGetBoolean(CACHE_DATA_ON_WRITE, DEFAULT_CACHE_DATA_ON_WRITE);
957   }
958 
959   /**
960    * @param value true if we should cache data blocks on write
961    * @return this (for chained invocation)
962    */
963   public HColumnDescriptor setCacheDataOnWrite(boolean value) {
964     return setValue(CACHE_DATA_ON_WRITE, Boolean.toString(value));
965   }
966 
967   /**
968    * @return true if we should cache data blocks in the L1 cache (if block cache deploy
969    * has more than one tier; e.g. we are using CombinedBlockCache).
970    * @deprecated As of release 1.0.0
971    *             (<a href="https://issues.apache.org/jira/browse/HBASE-10870">HBASE-10870</a>).
972    *             This will be removed in HBase 2.0.0. Use {@link #isCacheDataInL1()}} instead.
973    */
974   @Deprecated
975   public boolean shouldCacheDataInL1() {
976     return setAndGetBoolean(CACHE_DATA_IN_L1, DEFAULT_CACHE_DATA_IN_L1);
977   }
978 
979   /**
980    * @return true if we should cache data blocks in the L1 cache (if block cache deploy has more
981    *         than one tier; e.g. we are using CombinedBlockCache).
982    */
983   public boolean isCacheDataInL1() {
984     return setAndGetBoolean(CACHE_DATA_IN_L1, DEFAULT_CACHE_DATA_IN_L1);
985   }
986 
987   /**
988    * @param value true if we should cache data blocks in the L1 cache (if block cache deploy
989    * has more than one tier; e.g. we are using CombinedBlockCache).
990    * @return this (for chained invocation)
991    */
992   public HColumnDescriptor setCacheDataInL1(boolean value) {
993     return setValue(CACHE_DATA_IN_L1, Boolean.toString(value));
994   }
995 
996   private boolean setAndGetBoolean(final String key, final boolean defaultSetting) {
997     String value = getValue(key);
998     if (value != null) return Boolean.valueOf(value).booleanValue();
999     return defaultSetting;
1000   }
1001 
1002   /**
1003    * @return true if we should cache index blocks on write
1004    * @deprecated As of release 1.0.0
1005    *             (<a href="https://issues.apache.org/jira/browse/HBASE-10870">HBASE-10870</a>).
1006    *             This will be removed in HBase 2.0.0.
1007    *             Use {@link #isCacheIndexesOnWrite()} instead.
1008    */
1009   @Deprecated
1010   public boolean shouldCacheIndexesOnWrite() {
1011     return setAndGetBoolean(CACHE_INDEX_ON_WRITE, DEFAULT_CACHE_INDEX_ON_WRITE);
1012   }
1013 
1014   /**
1015    * @return true if we should cache index blocks on write
1016    */
1017   public boolean isCacheIndexesOnWrite() {
1018     return setAndGetBoolean(CACHE_INDEX_ON_WRITE, DEFAULT_CACHE_INDEX_ON_WRITE);
1019   }
1020 
1021   /**
1022    * @param value true if we should cache index blocks on write
1023    * @return this (for chained invocation)
1024    */
1025   public HColumnDescriptor setCacheIndexesOnWrite(boolean value) {
1026     return setValue(CACHE_INDEX_ON_WRITE, Boolean.toString(value));
1027   }
1028 
1029   /**
1030    * @return true if we should cache bloomfilter blocks on write
1031    * @deprecated As of release 1.0.0
1032    *             (<a href="https://issues.apache.org/jira/browse/HBASE-10870">HBASE-10870</a>).
1033    *             This will be removed in HBase 2.0.0.
1034    *             Use {@link #isCacheBloomsOnWrite()}} instead.
1035    */
1036   @Deprecated
1037   public boolean shouldCacheBloomsOnWrite() {
1038     return setAndGetBoolean(CACHE_BLOOMS_ON_WRITE, DEFAULT_CACHE_BLOOMS_ON_WRITE);
1039   }
1040 
1041   /**
1042    * @return true if we should cache bloomfilter blocks on write
1043    */
1044   public boolean isCacheBloomsOnWrite() {
1045     return setAndGetBoolean(CACHE_BLOOMS_ON_WRITE, DEFAULT_CACHE_BLOOMS_ON_WRITE);
1046   }
1047 
1048   /**
1049    * @param value true if we should cache bloomfilter blocks on write
1050    * @return this (for chained invocation)
1051    */
1052   public HColumnDescriptor setCacheBloomsOnWrite(boolean value) {
1053     return setValue(CACHE_BLOOMS_ON_WRITE, Boolean.toString(value));
1054   }
1055 
1056   /**
1057    * @return true if we should evict cached blocks from the blockcache on
1058    * close
1059    * @deprecated As of release 1.0.0
1060    *             (<a href="https://issues.apache.org/jira/browse/HBASE-10870">HBASE-10870</a>).
1061    *             This will be removed in HBase 2.0.0.
1062    *             Use {@link #isEvictBlocksOnClose()}} instead.
1063    */
1064   @Deprecated
1065   public boolean shouldEvictBlocksOnClose() {
1066     return setAndGetBoolean(EVICT_BLOCKS_ON_CLOSE, DEFAULT_EVICT_BLOCKS_ON_CLOSE);
1067   }
1068 
1069   /**
1070    * @return true if we should evict cached blocks from the blockcache on close
1071    */
1072   public boolean isEvictBlocksOnClose() {
1073     return setAndGetBoolean(EVICT_BLOCKS_ON_CLOSE, DEFAULT_EVICT_BLOCKS_ON_CLOSE);
1074   }
1075 
1076   /**
1077    * @param value true if we should evict cached blocks from the blockcache on
1078    * close
1079    * @return this (for chained invocation)
1080    */
1081   public HColumnDescriptor setEvictBlocksOnClose(boolean value) {
1082     return setValue(EVICT_BLOCKS_ON_CLOSE, Boolean.toString(value));
1083   }
1084 
1085   /**
1086    * @return true if we should prefetch blocks into the blockcache on open
1087    * @deprecated As of release 1.0.0
1088    *             (<a href="https://issues.apache.org/jira/browse/HBASE-10870">HBASE-10870</a>).
1089    *             This will be removed in HBase 2.0.0.
1090    *             Use {@link #isPrefetchBlocksOnOpen()}}} instead.
1091    */
1092   @Deprecated
1093   public boolean shouldPrefetchBlocksOnOpen() {
1094     return setAndGetBoolean(PREFETCH_BLOCKS_ON_OPEN, DEFAULT_PREFETCH_BLOCKS_ON_OPEN);
1095   }
1096 
1097   /**
1098    * @return true if we should prefetch blocks into the blockcache on open
1099    */
1100   public boolean isPrefetchBlocksOnOpen() {
1101     return setAndGetBoolean(PREFETCH_BLOCKS_ON_OPEN, DEFAULT_PREFETCH_BLOCKS_ON_OPEN);
1102   }
1103 
1104   /**
1105    * @param value true if we should prefetch blocks into the blockcache on open
1106    * @return this (for chained invocation)
1107    */
1108   public HColumnDescriptor setPrefetchBlocksOnOpen(boolean value) {
1109     return setValue(PREFETCH_BLOCKS_ON_OPEN, Boolean.toString(value));
1110   }
1111 
1112   /**
1113    * @see java.lang.Object#toString()
1114    */
1115   @Override
1116   public String toString() {
1117     StringBuilder s = new StringBuilder();
1118 
1119     s.append('{');
1120     s.append(HConstants.NAME);
1121     s.append(" => '");
1122     s.append(Bytes.toString(name));
1123     s.append("'");
1124     s.append(getValues(true));
1125     s.append('}');
1126     return s.toString();
1127   }
1128 
1129   /**
1130    * @return Column family descriptor with only the customized attributes.
1131    */
1132   public String toStringCustomizedValues() {
1133     StringBuilder s = new StringBuilder();
1134     s.append('{');
1135     s.append(HConstants.NAME);
1136     s.append(" => '");
1137     s.append(Bytes.toString(name));
1138     s.append("'");
1139     s.append(getValues(false));
1140     s.append('}');
1141     return s.toString();
1142   }
1143 
1144   private StringBuilder getValues(boolean printDefaults) {
1145     StringBuilder s = new StringBuilder();
1146 
1147     boolean hasConfigKeys = false;
1148 
1149     // print all reserved keys first
1150     for (ImmutableBytesWritable k : values.keySet()) {
1151       if (!RESERVED_KEYWORDS.contains(k)) {
1152         hasConfigKeys = true;
1153         continue;
1154       }
1155       String key = Bytes.toString(k.get());
1156       String value = Bytes.toStringBinary(values.get(k).get());
1157       if (printDefaults
1158           || !DEFAULT_VALUES.containsKey(key)
1159           || !DEFAULT_VALUES.get(key).equalsIgnoreCase(value)) {
1160         s.append(", ");
1161         s.append(key);
1162         s.append(" => ");
1163         s.append('\'').append(PrettyPrinter.format(value, getUnit(key))).append('\'');
1164       }
1165     }
1166 
1167     // print all non-reserved, advanced config keys as a separate subset
1168     if (hasConfigKeys) {
1169       s.append(", ");
1170       s.append(HConstants.METADATA).append(" => ");
1171       s.append('{');
1172       boolean printComma = false;
1173       for (ImmutableBytesWritable k : values.keySet()) {
1174         if (RESERVED_KEYWORDS.contains(k)) {
1175           continue;
1176         }
1177         String key = Bytes.toString(k.get());
1178         String value = Bytes.toStringBinary(values.get(k).get());
1179         if (printComma) {
1180           s.append(", ");
1181         }
1182         printComma = true;
1183         s.append('\'').append(key).append('\'');
1184         s.append(" => ");
1185         s.append('\'').append(PrettyPrinter.format(value, getUnit(key))).append('\'');
1186       }
1187       s.append('}');
1188     }
1189 
1190     if (!configuration.isEmpty()) {
1191       s.append(", ");
1192       s.append(HConstants.CONFIGURATION).append(" => ");
1193       s.append('{');
1194       boolean printCommaForConfiguration = false;
1195       for (Map.Entry<String, String> e : configuration.entrySet()) {
1196         if (printCommaForConfiguration) s.append(", ");
1197         printCommaForConfiguration = true;
1198         s.append('\'').append(e.getKey()).append('\'');
1199         s.append(" => ");
1200         s.append('\'').append(PrettyPrinter.format(e.getValue(), getUnit(e.getKey()))).append('\'');
1201       }
1202       s.append("}");
1203     }
1204     return s;
1205   }
1206 
1207   public static Unit getUnit(String key) {
1208     Unit unit;
1209       /* TTL for now, we can add more as we neeed */
1210     if (key.equals(HColumnDescriptor.TTL)) {
1211       unit = Unit.TIME_INTERVAL;
1212     } else {
1213       unit = Unit.NONE;
1214     }
1215     return unit;
1216   }
1217 
1218   public static Map<String, String> getDefaultValues() {
1219     return Collections.unmodifiableMap(DEFAULT_VALUES);
1220   }
1221 
1222   /**
1223    * @see java.lang.Object#equals(java.lang.Object)
1224    */
1225   @Override
1226   public boolean equals(Object obj) {
1227     if (this == obj) {
1228       return true;
1229     }
1230     if (obj == null) {
1231       return false;
1232     }
1233     if (!(obj instanceof HColumnDescriptor)) {
1234       return false;
1235     }
1236     return compareTo((HColumnDescriptor)obj) == 0;
1237   }
1238 
1239   /**
1240    * @see java.lang.Object#hashCode()
1241    */
1242   @Override
1243   public int hashCode() {
1244     int result = Bytes.hashCode(this.name);
1245     result ^= Byte.valueOf(COLUMN_DESCRIPTOR_VERSION).hashCode();
1246     result ^= values.hashCode();
1247     result ^= configuration.hashCode();
1248     return result;
1249   }
1250 
1251   /**
1252    * @deprecated Writables are going away.  Use pb {@link #parseFrom(byte[])} instead.
1253    */
1254   @Deprecated
1255   public void readFields(DataInput in) throws IOException {
1256     int version = in.readByte();
1257     if (version < 6) {
1258       if (version <= 2) {
1259         Text t = new Text();
1260         t.readFields(in);
1261         this.name = t.getBytes();
1262 //        if(KeyValue.getFamilyDelimiterIndex(this.name, 0, this.name.length)
1263 //            > 0) {
1264 //          this.name = stripColon(this.name);
1265 //        }
1266       } else {
1267         this.name = Bytes.readByteArray(in);
1268       }
1269       this.values.clear();
1270       setMaxVersions(in.readInt());
1271       int ordinal = in.readInt();
1272       setCompressionType(Compression.Algorithm.values()[ordinal]);
1273       setInMemory(in.readBoolean());
1274       setBloomFilterType(in.readBoolean() ? BloomType.ROW : BloomType.NONE);
1275       if (getBloomFilterType() != BloomType.NONE && version < 5) {
1276         // If a bloomFilter is enabled and the column descriptor is less than
1277         // version 5, we need to skip over it to read the rest of the column
1278         // descriptor. There are no BloomFilterDescriptors written to disk for
1279         // column descriptors with a version number >= 5
1280         throw new UnsupportedClassVersionError(this.getClass().getName() +
1281             " does not support backward compatibility with versions older " +
1282             "than version 5");
1283       }
1284       if (version > 1) {
1285         setBlockCacheEnabled(in.readBoolean());
1286       }
1287       if (version > 2) {
1288        setTimeToLive(in.readInt());
1289       }
1290     } else {
1291       // version 6+
1292       this.name = Bytes.readByteArray(in);
1293       this.values.clear();
1294       int numValues = in.readInt();
1295       for (int i = 0; i < numValues; i++) {
1296         ImmutableBytesWritable key = new ImmutableBytesWritable();
1297         ImmutableBytesWritable value = new ImmutableBytesWritable();
1298         key.readFields(in);
1299         value.readFields(in);
1300 
1301         // in version 8, the BloomFilter setting changed from bool to enum
1302         if (version < 8 && Bytes.toString(key.get()).equals(BLOOMFILTER)) {
1303           value.set(Bytes.toBytes(
1304               Boolean.getBoolean(Bytes.toString(value.get()))
1305                 ? BloomType.ROW.toString()
1306                 : BloomType.NONE.toString()));
1307         }
1308 
1309         values.put(key, value);
1310       }
1311       if (version == 6) {
1312         // Convert old values.
1313         setValue(COMPRESSION, Compression.Algorithm.NONE.getName());
1314       }
1315       String value = getValue(HConstants.VERSIONS);
1316       this.cachedMaxVersions = (value != null)?
1317           Integer.valueOf(value).intValue(): DEFAULT_VERSIONS;
1318       if (version > 10) {
1319         configuration.clear();
1320         int numConfigs = in.readInt();
1321         for (int i = 0; i < numConfigs; i++) {
1322           ImmutableBytesWritable key = new ImmutableBytesWritable();
1323           ImmutableBytesWritable val = new ImmutableBytesWritable();
1324           key.readFields(in);
1325           val.readFields(in);
1326           configuration.put(
1327             Bytes.toString(key.get(), key.getOffset(), key.getLength()),
1328             Bytes.toString(val.get(), val.getOffset(), val.getLength()));
1329         }
1330       }
1331     }
1332   }
1333 
1334   /**
1335    * @deprecated Writables are going away.  Use {@link #toByteArray()} instead.
1336    */
1337   @Deprecated
1338   public void write(DataOutput out) throws IOException {
1339     out.writeByte(COLUMN_DESCRIPTOR_VERSION);
1340     Bytes.writeByteArray(out, this.name);
1341     out.writeInt(values.size());
1342     for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> e:
1343         values.entrySet()) {
1344       e.getKey().write(out);
1345       e.getValue().write(out);
1346     }
1347     out.writeInt(configuration.size());
1348     for (Map.Entry<String, String> e : configuration.entrySet()) {
1349       new ImmutableBytesWritable(Bytes.toBytes(e.getKey())).write(out);
1350       new ImmutableBytesWritable(Bytes.toBytes(e.getValue())).write(out);
1351     }
1352   }
1353 
1354   // Comparable
1355   @Override
1356   public int compareTo(HColumnDescriptor o) {
1357     int result = Bytes.compareTo(this.name, o.getName());
1358     if (result == 0) {
1359       // punt on comparison for ordering, just calculate difference
1360       result = this.values.hashCode() - o.values.hashCode();
1361       if (result < 0)
1362         result = -1;
1363       else if (result > 0)
1364         result = 1;
1365     }
1366     if (result == 0) {
1367       result = this.configuration.hashCode() - o.configuration.hashCode();
1368       if (result < 0)
1369         result = -1;
1370       else if (result > 0)
1371         result = 1;
1372     }
1373     return result;
1374   }
1375 
1376   /**
1377    * @return This instance serialized with pb with pb magic prefix
1378    * @see #parseFrom(byte[])
1379    */
1380   public byte [] toByteArray() {
1381     return ProtobufUtil.prependPBMagic(convert().toByteArray());
1382   }
1383 
1384   /**
1385    * @param bytes A pb serialized {@link HColumnDescriptor} instance with pb magic prefix
1386    * @return An instance of {@link HColumnDescriptor} made from <code>bytes</code>
1387    * @throws DeserializationException
1388    * @see #toByteArray()
1389    */
1390   public static HColumnDescriptor parseFrom(final byte [] bytes) throws DeserializationException {
1391     if (!ProtobufUtil.isPBMagicPrefix(bytes)) throw new DeserializationException("No magic");
1392     int pblen = ProtobufUtil.lengthOfPBMagic();
1393     ColumnFamilySchema.Builder builder = ColumnFamilySchema.newBuilder();
1394     ColumnFamilySchema cfs = null;
1395     try {
1396       cfs = builder.mergeFrom(bytes, pblen, bytes.length - pblen).build();
1397     } catch (InvalidProtocolBufferException e) {
1398       throw new DeserializationException(e);
1399     }
1400     return convert(cfs);
1401   }
1402 
1403   /**
1404    * @param cfs
1405    * @return An {@link HColumnDescriptor} made from the passed in <code>cfs</code>
1406    */
1407   public static HColumnDescriptor convert(final ColumnFamilySchema cfs) {
1408     // Use the empty constructor so we preserve the initial values set on construction for things
1409     // like maxVersion.  Otherwise, we pick up wrong values on deserialization which makes for
1410     // unrelated-looking test failures that are hard to trace back to here.
1411     HColumnDescriptor hcd = new HColumnDescriptor();
1412     hcd.name = cfs.getName().toByteArray();
1413     for (BytesBytesPair a: cfs.getAttributesList()) {
1414       hcd.setValue(a.getFirst().toByteArray(), a.getSecond().toByteArray());
1415     }
1416     for (NameStringPair a: cfs.getConfigurationList()) {
1417       hcd.setConfiguration(a.getName(), a.getValue());
1418     }
1419     return hcd;
1420   }
1421 
1422   /**
1423    * @return Convert this instance to a the pb column family type
1424    */
1425   public ColumnFamilySchema convert() {
1426     ColumnFamilySchema.Builder builder = ColumnFamilySchema.newBuilder();
1427     builder.setName(ByteStringer.wrap(getName()));
1428     for (Map.Entry<ImmutableBytesWritable, ImmutableBytesWritable> e: this.values.entrySet()) {
1429       BytesBytesPair.Builder aBuilder = BytesBytesPair.newBuilder();
1430       aBuilder.setFirst(ByteStringer.wrap(e.getKey().get()));
1431       aBuilder.setSecond(ByteStringer.wrap(e.getValue().get()));
1432       builder.addAttributes(aBuilder.build());
1433     }
1434     for (Map.Entry<String, String> e : this.configuration.entrySet()) {
1435       NameStringPair.Builder aBuilder = NameStringPair.newBuilder();
1436       aBuilder.setName(e.getKey());
1437       aBuilder.setValue(e.getValue());
1438       builder.addConfiguration(aBuilder.build());
1439     }
1440     return builder.build();
1441   }
1442 
1443   /**
1444    * Getter for accessing the configuration value by key.
1445    */
1446   public String getConfigurationValue(String key) {
1447     return configuration.get(key);
1448   }
1449 
1450   /**
1451    * Getter for fetching an unmodifiable {@link #configuration} map.
1452    */
1453   public Map<String, String> getConfiguration() {
1454     // shallow pointer copy
1455     return Collections.unmodifiableMap(configuration);
1456   }
1457 
1458   /**
1459    * Setter for storing a configuration setting in {@link #configuration} map.
1460    * @param key Config key. Same as XML config key e.g. hbase.something.or.other.
1461    * @param value String value. If null, removes the configuration.
1462    */
1463   public HColumnDescriptor setConfiguration(String key, String value) {
1464     if (value == null) {
1465       removeConfiguration(key);
1466     } else {
1467       configuration.put(key, value);
1468     }
1469     return this;
1470   }
1471 
1472   /**
1473    * Remove a configuration setting represented by the key from the {@link #configuration} map.
1474    */
1475   public void removeConfiguration(final String key) {
1476     configuration.remove(key);
1477   }
1478 
1479   /**
1480    * Return the encryption algorithm in use by this family
1481    */
1482   public String getEncryptionType() {
1483     return getValue(ENCRYPTION);
1484   }
1485 
1486   /**
1487    * Set the encryption algorithm for use with this family
1488    * @param algorithm
1489    */
1490   public HColumnDescriptor setEncryptionType(String algorithm) {
1491     setValue(ENCRYPTION, algorithm);
1492     return this;
1493   }
1494 
1495   /** Return the raw crypto key attribute for the family, or null if not set  */
1496   public byte[] getEncryptionKey() {
1497     return getValue(Bytes.toBytes(ENCRYPTION_KEY));
1498   }
1499 
1500   /** Set the raw crypto key attribute for the family */
1501   public HColumnDescriptor setEncryptionKey(byte[] keyBytes) {
1502     setValue(Bytes.toBytes(ENCRYPTION_KEY), keyBytes);
1503     return this;
1504   }
1505 }