View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.hbase.security.access;
20  
21  import java.io.ByteArrayInputStream;
22  import java.io.ByteArrayOutputStream;
23  import java.io.DataInput;
24  import java.io.DataOutput;
25  import java.io.IOException;
26  import java.io.InputStream;
27  import java.io.ObjectInputStream;
28  import java.io.ObjectOutputStream;
29  import java.io.Serializable;
30  import java.lang.reflect.Array;
31  import java.lang.reflect.InvocationTargetException;
32  import java.lang.reflect.Method;
33  import java.util.ArrayList;
34  import java.util.HashMap;
35  import java.util.List;
36  import java.util.Map;
37  import java.util.NavigableSet;
38  
39  import org.apache.commons.logging.Log;
40  import org.apache.commons.logging.LogFactory;
41  import org.apache.hadoop.hbase.classification.InterfaceAudience;
42  import org.apache.hadoop.conf.Configurable;
43  import org.apache.hadoop.conf.Configuration;
44  import org.apache.hadoop.conf.Configured;
45  import org.apache.hadoop.hbase.ClusterStatus;
46  import org.apache.hadoop.hbase.HColumnDescriptor;
47  import org.apache.hadoop.hbase.HConstants;
48  import org.apache.hadoop.hbase.HRegionInfo;
49  import org.apache.hadoop.hbase.HTableDescriptor;
50  import org.apache.hadoop.hbase.KeyValue;
51  import org.apache.hadoop.hbase.client.Action;
52  import org.apache.hadoop.hbase.client.Append;
53  import org.apache.hadoop.hbase.client.Delete;
54  import org.apache.hadoop.hbase.client.Get;
55  import org.apache.hadoop.hbase.client.Increment;
56  import org.apache.hadoop.hbase.client.MultiAction;
57  import org.apache.hadoop.hbase.client.MultiResponse;
58  import org.apache.hadoop.hbase.client.Put;
59  import org.apache.hadoop.hbase.client.Result;
60  import org.apache.hadoop.hbase.client.Row;
61  import org.apache.hadoop.hbase.client.RowMutations;
62  import org.apache.hadoop.hbase.client.Scan;
63  import org.apache.hadoop.hbase.exceptions.DeserializationException;
64  import org.apache.hadoop.hbase.filter.BinaryComparator;
65  import org.apache.hadoop.hbase.filter.BitComparator;
66  import org.apache.hadoop.hbase.filter.ByteArrayComparable;
67  import org.apache.hadoop.hbase.filter.ColumnCountGetFilter;
68  import org.apache.hadoop.hbase.filter.ColumnPrefixFilter;
69  import org.apache.hadoop.hbase.filter.ColumnRangeFilter;
70  import org.apache.hadoop.hbase.filter.CompareFilter;
71  import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
72  import org.apache.hadoop.hbase.filter.DependentColumnFilter;
73  import org.apache.hadoop.hbase.filter.FirstKeyOnlyFilter;
74  import org.apache.hadoop.hbase.filter.InclusiveStopFilter;
75  import org.apache.hadoop.hbase.filter.KeyOnlyFilter;
76  import org.apache.hadoop.hbase.filter.PageFilter;
77  import org.apache.hadoop.hbase.filter.PrefixFilter;
78  import org.apache.hadoop.hbase.filter.QualifierFilter;
79  import org.apache.hadoop.hbase.filter.RandomRowFilter;
80  import org.apache.hadoop.hbase.filter.RowFilter;
81  import org.apache.hadoop.hbase.filter.SingleColumnValueExcludeFilter;
82  import org.apache.hadoop.hbase.filter.SingleColumnValueFilter;
83  import org.apache.hadoop.hbase.filter.SkipFilter;
84  import org.apache.hadoop.hbase.filter.ValueFilter;
85  import org.apache.hadoop.hbase.filter.WhileMatchFilter;
86  import org.apache.hadoop.hbase.io.DataOutputOutputStream;
87  import org.apache.hadoop.hbase.io.WritableWithSize;
88  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
89  import org.apache.hadoop.hbase.protobuf.generated.ClientProtos;
90  import org.apache.hadoop.hbase.regionserver.RegionOpeningState;
91  import org.apache.hadoop.hbase.regionserver.wal.HLog;
92  import org.apache.hadoop.hbase.regionserver.wal.HLogKey;
93  import org.apache.hadoop.hbase.util.Bytes;
94  import org.apache.hadoop.hbase.util.ProtoUtil;
95  import org.apache.hadoop.io.MapWritable;
96  import org.apache.hadoop.io.ObjectWritable;
97  import org.apache.hadoop.io.Text;
98  import org.apache.hadoop.io.Writable;
99  import org.apache.hadoop.io.WritableFactories;
100 import org.apache.hadoop.io.WritableUtils;
101 
102 import com.google.protobuf.Message;
103 import com.google.protobuf.RpcController;
104 
105 /**
106  * <p>This is a customized version of the polymorphic hadoop
107  * {@link ObjectWritable}.  It removes UTF8 (HADOOP-414).
108  * Using {@link Text} intead of UTF-8 saves ~2% CPU between reading and writing
109  * objects running a short sequentialWrite Performance Evaluation test just in
110  * ObjectWritable alone; more when we're doing randomRead-ing.  Other
111  * optimizations include our passing codes for classes instead of the
112  * actual class names themselves.  This makes it so this class needs amendment
113  * if non-Writable classes are introduced -- if passed a Writable for which we
114  * have no code, we just do the old-school passing of the class name, etc. --
115  * but passing codes the  savings are large particularly when cell
116  * data is small (If < a couple of kilobytes, the encoding/decoding of class
117  * name and reflection to instantiate class was costing in excess of the cell
118  * handling).
119  * @deprecated This class is needed migrating TablePermissions written with
120  * Writables.  It is needed to read old permissions written pre-0.96.  This
121  * class is to be removed after HBase 0.96 ships since then all permissions
122  * will have been migrated and written with protobufs.
123  */
124 @Deprecated
125 @InterfaceAudience.Private
126 class HbaseObjectWritableFor96Migration implements Writable, WritableWithSize, Configurable {
127   protected final static Log LOG = LogFactory.getLog(HbaseObjectWritableFor96Migration.class);
128 
129   // Here we maintain two static maps of classes to code and vice versa.
130   // Add new classes+codes as wanted or figure way to auto-generate these
131   // maps.
132   static final Map<Integer, Class<?>> CODE_TO_CLASS =
133     new HashMap<Integer, Class<?>>();
134   static final Map<Class<?>, Integer> CLASS_TO_CODE =
135     new HashMap<Class<?>, Integer>();
136   // Special code that means 'not-encoded'; in this case we do old school
137   // sending of the class name using reflection, etc.
138   private static final byte NOT_ENCODED = 0;
139   //Generic array means that the array type is not one of the pre-defined arrays
140   //in the CLASS_TO_CODE map, but we have to still encode the array since it's
141   //elements are serializable by this class.
142   private static final int GENERIC_ARRAY_CODE;
143   private static final int NEXT_CLASS_CODE;
144   static {
145     ////////////////////////////////////////////////////////////////////////////
146     // WARNING: Please do not insert, remove or swap any line in this static  //
147     // block.  Doing so would change or shift all the codes used to serialize //
148     // objects, which makes backwards compatibility very hard for clients.    //
149     // New codes should always be added at the end. Code removal is           //
150     // discouraged because code is a short now.                               //
151     ////////////////////////////////////////////////////////////////////////////
152 
153     int code = NOT_ENCODED + 1;
154     // Primitive types.
155     addToMap(Boolean.TYPE, code++);
156     addToMap(Byte.TYPE, code++);
157     addToMap(Character.TYPE, code++);
158     addToMap(Short.TYPE, code++);
159     addToMap(Integer.TYPE, code++);
160     addToMap(Long.TYPE, code++);
161     addToMap(Float.TYPE, code++);
162     addToMap(Double.TYPE, code++);
163     addToMap(Void.TYPE, code++);
164 
165     // Other java types
166     addToMap(String.class, code++);
167     addToMap(byte [].class, code++);
168     addToMap(byte [][].class, code++);
169 
170     // Hadoop types
171     addToMap(Text.class, code++);
172     addToMap(Writable.class, code++);
173     addToMap(Writable [].class, code++);
174     code++; // Removed
175     addToMap(NullInstance.class, code++);
176 
177     // Hbase types
178     addToMap(HColumnDescriptor.class, code++);
179     addToMap(HConstants.Modify.class, code++);
180 
181     // We used to have a class named HMsg but its been removed.  Rather than
182     // just axe it, use following random Integer class -- we just chose any
183     // class from java.lang -- instead just so codes that follow stay
184     // in same relative place.
185     addToMap(Integer.class, code++);
186     addToMap(Integer[].class, code++);
187 
188     //HRegion shouldn't be pushed across the wire.
189     code++; //addToMap(HRegion.class, code++);
190     code++; //addToMap(HRegion[].class, code++);
191 
192     addToMap(HRegionInfo.class, code++);
193     addToMap(HRegionInfo[].class, code++);
194     code++; // Removed
195     code++; // Removed
196     addToMap(HTableDescriptor.class, code++);
197     addToMap(MapWritable.class, code++);
198 
199     //
200     // HBASE-880
201     //
202     addToMap(ClusterStatus.class, code++);
203     addToMap(Delete.class, code++);
204     addToMap(Get.class, code++);
205     addToMap(KeyValue.class, code++);
206     addToMap(KeyValue[].class, code++);
207     addToMap(Put.class, code++);
208     addToMap(Put[].class, code++);
209     addToMap(Result.class, code++);
210     addToMap(Result[].class, code++);
211     addToMap(Scan.class, code++);
212 
213     addToMap(WhileMatchFilter.class, code++);
214     addToMap(PrefixFilter.class, code++);
215     addToMap(PageFilter.class, code++);
216     addToMap(InclusiveStopFilter.class, code++);
217     addToMap(ColumnCountGetFilter.class, code++);
218     addToMap(SingleColumnValueFilter.class, code++);
219     addToMap(SingleColumnValueExcludeFilter.class, code++);
220     addToMap(BinaryComparator.class, code++);
221     addToMap(BitComparator.class, code++);
222     addToMap(CompareFilter.class, code++);
223     addToMap(RowFilter.class, code++);
224     addToMap(ValueFilter.class, code++);
225     addToMap(QualifierFilter.class, code++);
226     addToMap(SkipFilter.class, code++);
227     addToMap(ByteArrayComparable.class, code++);
228     addToMap(FirstKeyOnlyFilter.class, code++);
229     addToMap(DependentColumnFilter.class, code++);
230 
231     addToMap(Delete [].class, code++);
232 
233     addToMap(HLog.Entry.class, code++);
234     addToMap(HLog.Entry[].class, code++);
235     addToMap(HLogKey.class, code++);
236 
237     addToMap(List.class, code++);
238 
239     addToMap(NavigableSet.class, code++);
240     addToMap(ColumnPrefixFilter.class, code++);
241 
242     // Multi
243     addToMap(Row.class, code++);
244     addToMap(Action.class, code++);
245     addToMap(MultiAction.class, code++);
246     addToMap(MultiResponse.class, code++);
247 
248     // coprocessor execution
249     // Exec no longer exists --> addToMap(Exec.class, code++);
250     code++;
251     addToMap(Increment.class, code++);
252 
253     addToMap(KeyOnlyFilter.class, code++);
254 
255     // serializable
256     addToMap(Serializable.class, code++);
257 
258     addToMap(RandomRowFilter.class, code++);
259 
260     addToMap(CompareOp.class, code++);
261 
262     addToMap(ColumnRangeFilter.class, code++);
263 
264     // HServerLoad no longer exists; increase code so other classes stay the same.
265     code++;
266     //addToMap(HServerLoad.class, code++);
267 
268     addToMap(RegionOpeningState.class, code++);
269 
270     addToMap(HTableDescriptor[].class, code++);
271 
272     addToMap(Append.class, code++);
273 
274     addToMap(RowMutations.class, code++);
275 
276     addToMap(Message.class, code++);
277 
278     //java.lang.reflect.Array is a placeholder for arrays not defined above
279     GENERIC_ARRAY_CODE = code++;
280     addToMap(Array.class, GENERIC_ARRAY_CODE);
281 
282     addToMap(RpcController.class, code++);
283 
284     // make sure that this is the last statement in this static block
285     NEXT_CLASS_CODE = code;
286   }
287 
288   private Class<?> declaredClass;
289   private Object instance;
290   private Configuration conf;
291 
292   /** default constructor for writable */
293   HbaseObjectWritableFor96Migration() {
294     super();
295   }
296 
297   /**
298    * @param instance
299    */
300   HbaseObjectWritableFor96Migration(Object instance) {
301     set(instance);
302   }
303 
304   /**
305    * @param declaredClass
306    * @param instance
307    */
308   HbaseObjectWritableFor96Migration(Class<?> declaredClass, Object instance) {
309     this.declaredClass = declaredClass;
310     this.instance = instance;
311   }
312 
313   /** @return the instance, or null if none. */
314   Object get() { return instance; }
315 
316   /** @return the class this is meant to be. */
317   Class<?> getDeclaredClass() { return declaredClass; }
318 
319   /**
320    * Reset the instance.
321    * @param instance
322    */
323   void set(Object instance) {
324     this.declaredClass = instance.getClass();
325     this.instance = instance;
326   }
327 
328   /**
329    * @see java.lang.Object#toString()
330    */
331   @Override
332   public String toString() {
333     return "OW[class=" + declaredClass + ",value=" + instance + "]";
334   }
335 
336 
337   public void readFields(DataInput in) throws IOException {
338     readObject(in, this, this.conf);
339   }
340 
341   public void write(DataOutput out) throws IOException {
342     writeObject(out, instance, declaredClass, conf);
343   }
344 
345   public long getWritableSize() {
346     return getWritableSize(instance, declaredClass, conf);
347   }
348 
349   private static class NullInstance extends Configured implements Writable {
350     Class<?> declaredClass;
351     /** default constructor for writable */
352     @SuppressWarnings("unused")
353     public NullInstance() { super(null); }
354 
355     /**
356      * @param declaredClass
357      * @param conf
358      */
359     public NullInstance(Class<?> declaredClass, Configuration conf) {
360       super(conf);
361       this.declaredClass = declaredClass;
362     }
363 
364     public void readFields(DataInput in) throws IOException {
365       this.declaredClass = CODE_TO_CLASS.get(WritableUtils.readVInt(in));
366     }
367 
368     public void write(DataOutput out) throws IOException {
369       writeClassCode(out, this.declaredClass);
370     }
371   }
372 
373   static Integer getClassCode(final Class<?> c)
374   throws IOException {
375     Integer code = CLASS_TO_CODE.get(c);
376     if (code == null ) {
377       if (List.class.isAssignableFrom(c)) {
378         code = CLASS_TO_CODE.get(List.class);
379       } else if (Writable.class.isAssignableFrom(c)) {
380         code = CLASS_TO_CODE.get(Writable.class);
381       } else if (c.isArray()) {
382         code = CLASS_TO_CODE.get(Array.class);
383       } else if (Message.class.isAssignableFrom(c)) {
384         code = CLASS_TO_CODE.get(Message.class);
385       } else if (Serializable.class.isAssignableFrom(c)){
386         code = CLASS_TO_CODE.get(Serializable.class);
387       } else if (Scan.class.isAssignableFrom(c)) {
388         code = CLASS_TO_CODE.get(Scan.class);
389       }
390     }
391     return code;
392   }
393 
394   /**
395    * @return the next object code in the list.  Used in testing to verify that additional fields are not added 
396    */
397   static int getNextClassCode(){
398     return NEXT_CLASS_CODE;
399   }
400 
401   /**
402    * Write out the code for passed Class.
403    * @param out
404    * @param c
405    * @throws IOException
406    */
407   static void writeClassCode(final DataOutput out, final Class<?> c)
408       throws IOException {
409     Integer code = getClassCode(c);
410 
411     if (code == null) {
412       LOG.error("Unsupported type " + c);
413       StackTraceElement[] els = new Exception().getStackTrace();
414       for(StackTraceElement elem : els) {
415         LOG.error(elem.getMethodName());
416       }
417       throw new UnsupportedOperationException("No code for unexpected " + c);
418     }
419     WritableUtils.writeVInt(out, code);
420   }
421 
422   static long getWritableSize(Object instance, Class declaredClass,
423                                      Configuration conf) {
424     return 0L; // no hint is the default.
425   }
426   /**
427    * Write a {@link Writable}, {@link String}, primitive type, or an array of
428    * the preceding.
429    * @param out
430    * @param instance
431    * @param declaredClass
432    * @param conf
433    * @throws IOException
434    */
435   @SuppressWarnings("unchecked")
436   static void writeObject(DataOutput out, Object instance,
437                                  Class declaredClass,
438                                  Configuration conf)
439   throws IOException {
440 
441     Object instanceObj = instance;
442     Class declClass = declaredClass;
443 
444     if (instanceObj == null) {                       // null
445       instanceObj = new NullInstance(declClass, conf);
446       declClass = Writable.class;
447     }
448     writeClassCode(out, declClass);
449     if (declClass.isArray()) {                // array
450       // If bytearray, just dump it out -- avoid the recursion and
451       // byte-at-a-time we were previously doing.
452       if (declClass.equals(byte [].class)) {
453         Bytes.writeByteArray(out, (byte [])instanceObj);
454       } else {
455         //if it is a Generic array, write the element's type
456         if (getClassCode(declaredClass) == GENERIC_ARRAY_CODE) {
457           Class<?> componentType = declaredClass.getComponentType();
458           writeClass(out, componentType);
459         }
460 
461         int length = Array.getLength(instanceObj);
462         out.writeInt(length);
463         for (int i = 0; i < length; i++) {
464           Object item = Array.get(instanceObj, i);
465           writeObject(out, item,
466                     item.getClass(), conf);
467         }
468       }
469     } else if (List.class.isAssignableFrom(declClass)) {
470       List list = (List)instanceObj;
471       int length = list.size();
472       out.writeInt(length);
473       for (int i = 0; i < length; i++) {
474         Object elem = list.get(i);
475         writeObject(out, elem,
476                   elem == null ? Writable.class : elem.getClass(), conf);
477       }
478     } else if (declClass == String.class) {   // String
479       Text.writeString(out, (String)instanceObj);
480     } else if (declClass.isPrimitive()) {     // primitive type
481       if (declClass == Boolean.TYPE) {        // boolean
482         out.writeBoolean(((Boolean)instanceObj).booleanValue());
483       } else if (declClass == Character.TYPE) { // char
484         out.writeChar(((Character)instanceObj).charValue());
485       } else if (declClass == Byte.TYPE) {    // byte
486         out.writeByte(((Byte)instanceObj).byteValue());
487       } else if (declClass == Short.TYPE) {   // short
488         out.writeShort(((Short)instanceObj).shortValue());
489       } else if (declClass == Integer.TYPE) { // int
490         out.writeInt(((Integer)instanceObj).intValue());
491       } else if (declClass == Long.TYPE) {    // long
492         out.writeLong(((Long)instanceObj).longValue());
493       } else if (declClass == Float.TYPE) {   // float
494         out.writeFloat(((Float)instanceObj).floatValue());
495       } else if (declClass == Double.TYPE) {  // double
496         out.writeDouble(((Double)instanceObj).doubleValue());
497       } else if (declClass == Void.TYPE) {    // void
498       } else {
499         throw new IllegalArgumentException("Not a primitive: "+declClass);
500       }
501     } else if (declClass.isEnum()) {         // enum
502       Text.writeString(out, ((Enum)instanceObj).name());
503     } else if (Message.class.isAssignableFrom(declaredClass)) {
504       Text.writeString(out, instanceObj.getClass().getName());
505       ((Message)instance).writeDelimitedTo(
506           DataOutputOutputStream.constructOutputStream(out));
507     } else if (Writable.class.isAssignableFrom(declClass)) { // Writable
508       Class <?> c = instanceObj.getClass();
509       Integer code = CLASS_TO_CODE.get(c);
510       if (code == null) {
511         out.writeByte(NOT_ENCODED);
512         Text.writeString(out, c.getName());
513       } else {
514         writeClassCode(out, c);
515       }
516       ((Writable)instanceObj).write(out);
517     } else if (Serializable.class.isAssignableFrom(declClass)) {
518       if (!conf.getBoolean(HConstants.ALLOW_LEGACY_OBJECT_SERIALIZATION_KEY, false)) {
519         throw new IOException(
520           "Legacy object serialization support is disabled by default." +
521           " Change '" + HConstants.ALLOW_LEGACY_OBJECT_SERIALIZATION_KEY + "' to enable.");
522       }
523       Class <?> c = instanceObj.getClass();
524       Integer code = CLASS_TO_CODE.get(c);
525       if (code == null) {
526         out.writeByte(NOT_ENCODED);
527         Text.writeString(out, c.getName());
528       } else {
529         writeClassCode(out, c);
530       }
531       ByteArrayOutputStream bos = null;
532       ObjectOutputStream oos = null;
533       try{
534         bos = new ByteArrayOutputStream();
535         oos = new ObjectOutputStream(bos);
536         oos.writeObject(instanceObj);
537         byte[] value = bos.toByteArray();
538         out.writeInt(value.length);
539         out.write(value);
540       } finally {
541         if(bos!=null) bos.close();
542         if(oos!=null) oos.close();
543       }
544     } else if (Scan.class.isAssignableFrom(declClass)) {
545       Scan scan = (Scan)instanceObj;
546       byte [] scanBytes = ProtobufUtil.toScan(scan).toByteArray();
547       out.writeInt(scanBytes.length);
548       out.write(scanBytes);
549     } else {
550       throw new IOException("Can't write: "+instanceObj+" as "+declClass);
551     }
552   }
553 
554   /** Writes the encoded class code as defined in CLASS_TO_CODE, or
555    * the whole class name if not defined in the mapping.
556    */
557   static void writeClass(DataOutput out, Class<?> c) throws IOException {
558     Integer code = CLASS_TO_CODE.get(c);
559     if (code == null) {
560       WritableUtils.writeVInt(out, NOT_ENCODED);
561       Text.writeString(out, c.getName());
562     } else {
563       WritableUtils.writeVInt(out, code);
564     }
565   }
566 
567   /** Reads and returns the class as written by {@link #writeClass(DataOutput, Class)} */
568   static Class<?> readClass(Configuration conf, DataInput in) throws IOException {
569     Class<?> instanceClass = null;
570     int b = (byte)WritableUtils.readVInt(in);
571     if (b == NOT_ENCODED) {
572       String className = Text.readString(in);
573       try {
574         instanceClass = getClassByName(conf, className);
575       } catch (ClassNotFoundException e) {
576         LOG.error("Can't find class " + className, e);
577         throw new IOException("Can't find class " + className, e);
578       }
579     } else {
580       instanceClass = CODE_TO_CLASS.get(b);
581     }
582     return instanceClass;
583   }
584 
585   /**
586    * Read a {@link Writable}, {@link String}, primitive type, or an array of
587    * the preceding.
588    * @param in
589    * @param conf
590    * @return the object
591    * @throws IOException
592    */
593   static Object readObject(DataInput in, Configuration conf)
594     throws IOException {
595     return readObject(in, null, conf);
596   }
597 
598   /**
599    * Read a {@link Writable}, {@link String}, primitive type, or an array of
600    * the preceding.
601    * @param in
602    * @param objectWritable
603    * @param conf
604    * @return the object
605    * @throws IOException
606    */
607   @SuppressWarnings("unchecked")
608   static Object readObject(DataInput in,
609       HbaseObjectWritableFor96Migration objectWritable, Configuration conf)
610   throws IOException {
611     Class<?> declaredClass = CODE_TO_CLASS.get(WritableUtils.readVInt(in));
612     Object instance;
613     if (declaredClass.isPrimitive()) {            // primitive types
614       if (declaredClass == Boolean.TYPE) {             // boolean
615         instance = Boolean.valueOf(in.readBoolean());
616       } else if (declaredClass == Character.TYPE) {    // char
617         instance = Character.valueOf(in.readChar());
618       } else if (declaredClass == Byte.TYPE) {         // byte
619         instance = Byte.valueOf(in.readByte());
620       } else if (declaredClass == Short.TYPE) {        // short
621         instance = Short.valueOf(in.readShort());
622       } else if (declaredClass == Integer.TYPE) {      // int
623         instance = Integer.valueOf(in.readInt());
624       } else if (declaredClass == Long.TYPE) {         // long
625         instance = Long.valueOf(in.readLong());
626       } else if (declaredClass == Float.TYPE) {        // float
627         instance = Float.valueOf(in.readFloat());
628       } else if (declaredClass == Double.TYPE) {       // double
629         instance = Double.valueOf(in.readDouble());
630       } else if (declaredClass == Void.TYPE) {         // void
631         instance = null;
632       } else {
633         throw new IllegalArgumentException("Not a primitive: "+declaredClass);
634       }
635     } else if (declaredClass.isArray()) {              // array
636       if (declaredClass.equals(byte [].class)) {
637         instance = Bytes.readByteArray(in);
638       } else {
639         int length = in.readInt();
640         instance = Array.newInstance(declaredClass.getComponentType(), length);
641         for (int i = 0; i < length; i++) {
642           Array.set(instance, i, readObject(in, conf));
643         }
644       }
645     } else if (declaredClass.equals(Array.class)) { //an array not declared in CLASS_TO_CODE
646       Class<?> componentType = readClass(conf, in);
647       int length = in.readInt();
648       instance = Array.newInstance(componentType, length);
649       for (int i = 0; i < length; i++) {
650         Array.set(instance, i, readObject(in, conf));
651       }
652     } else if (List.class.isAssignableFrom(declaredClass)) {            // List
653       int length = in.readInt();
654       instance = new ArrayList(length);
655       for (int i = 0; i < length; i++) {
656         ((ArrayList)instance).add(readObject(in, conf));
657       }
658     } else if (declaredClass == String.class) {        // String
659       instance = Text.readString(in);
660     } else if (declaredClass.isEnum()) {         // enum
661       instance = Enum.valueOf((Class<? extends Enum>) declaredClass,
662         Text.readString(in));
663     } else if (declaredClass == Message.class) {
664       String className = Text.readString(in);
665       try {
666         declaredClass = getClassByName(conf, className);
667         instance = tryInstantiateProtobuf(declaredClass, in);
668       } catch (ClassNotFoundException e) {
669         LOG.error("Can't find class " + className, e);
670         throw new IOException("Can't find class " + className, e);
671       }
672     } else if (Scan.class.isAssignableFrom(declaredClass)) {
673       int length = in.readInt();
674       byte [] scanBytes = new byte[length];
675       in.readFully(scanBytes);
676       ClientProtos.Scan.Builder scanProto = ClientProtos.Scan.newBuilder();
677       ProtobufUtil.mergeFrom(scanProto, scanBytes);
678       instance = ProtobufUtil.toScan(scanProto.build());
679     } else {                                      // Writable or Serializable
680       Class instanceClass = null;
681       int b = (byte)WritableUtils.readVInt(in);
682       if (b == NOT_ENCODED) {
683         String className = Text.readString(in);
684         try {
685           instanceClass = getClassByName(conf, className);
686         } catch (ClassNotFoundException e) {
687           LOG.error("Can't find class " + className, e);
688           throw new IOException("Can't find class " + className, e);
689         }
690       } else {
691         instanceClass = CODE_TO_CLASS.get(b);
692       }
693       if(Writable.class.isAssignableFrom(instanceClass)){
694         Writable writable = WritableFactories.newInstance(instanceClass, conf);
695         try {
696           writable.readFields(in);
697         } catch (Exception e) {
698           LOG.error("Error in readFields", e);
699           throw new IOException("Error in readFields" , e);
700         }
701         instance = writable;
702         if (instanceClass == NullInstance.class) {  // null
703           declaredClass = ((NullInstance)instance).declaredClass;
704           instance = null;
705         }
706       } else {
707         if (!conf.getBoolean(HConstants.ALLOW_LEGACY_OBJECT_SERIALIZATION_KEY, false)) {
708           throw new IOException(
709             "Legacy object deserialization support is disabled by default." +
710             " Change '" + HConstants.ALLOW_LEGACY_OBJECT_SERIALIZATION_KEY + "' to enable.");
711         }
712         int length = in.readInt();
713         byte[] objectBytes = new byte[length];
714         in.readFully(objectBytes);
715         ByteArrayInputStream bis = null;
716         ObjectInputStream ois = null;
717         try {
718           bis = new ByteArrayInputStream(objectBytes);
719           ois = new ObjectInputStream(bis);
720           instance = ois.readObject();
721         } catch (ClassNotFoundException e) {
722           LOG.error("Class not found when attempting to deserialize object", e);
723           throw new IOException("Class not found when attempting to " +
724               "deserialize object", e);
725         } finally {
726           if(bis!=null) bis.close();
727           if(ois!=null) ois.close();
728         }
729       }
730     }
731     if (objectWritable != null) {                 // store values
732       objectWritable.declaredClass = declaredClass;
733       objectWritable.instance = instance;
734     }
735     return instance;
736   }
737 
738   /**
739    * Try to instantiate a protocol buffer of the given message class
740    * from the given input stream.
741    *
742    * @param protoClass the class of the generated protocol buffer
743    * @param dataIn the input stream to read from
744    * @return the instantiated Message instance
745    * @throws IOException if an IO problem occurs
746    */
747   static Message tryInstantiateProtobuf(
748       Class<?> protoClass,
749       DataInput dataIn) throws IOException {
750 
751     try {
752       if (dataIn instanceof InputStream) {
753         // We can use the built-in parseDelimitedFrom and not have to re-copy
754         // the data
755         Method parseMethod = getStaticProtobufMethod(protoClass,
756             "parseDelimitedFrom", InputStream.class);
757         return (Message)parseMethod.invoke(null, (InputStream)dataIn);
758       } else {
759         // Have to read it into a buffer first, since protobuf doesn't deal
760         // with the DataInput interface directly.
761 
762         // Read the size delimiter that writeDelimitedTo writes
763         int size = ProtoUtil.readRawVarint32(dataIn);
764         if (size < 0) {
765           throw new IOException("Invalid size: " + size);
766         }
767 
768         byte[] data = new byte[size];
769         dataIn.readFully(data);
770         Method parseMethod = getStaticProtobufMethod(protoClass,
771             "parseFrom", byte[].class);
772         return (Message)parseMethod.invoke(null, data);
773       }
774     } catch (InvocationTargetException e) {
775 
776       if (e.getCause() instanceof IOException) {
777         throw (IOException)e.getCause();
778       } else {
779         throw new IOException(e.getCause());
780       }
781     } catch (IllegalAccessException iae) {
782       throw new AssertionError("Could not access parse method in " +
783           protoClass);
784     }
785   }
786 
787   static Method getStaticProtobufMethod(Class<?> declaredClass, String method,
788       Class<?> ... args) {
789 
790     try {
791       return declaredClass.getMethod(method, args);
792     } catch (Exception e) {
793       // This is a bug in Hadoop - protobufs should all have this static method
794       throw new AssertionError("Protocol buffer class " + declaredClass +
795           " does not have an accessible parseFrom(InputStream) method!");
796     }
797   }
798 
799   @SuppressWarnings("unchecked")
800   private static Class getClassByName(Configuration conf, String className)
801   throws ClassNotFoundException {
802     if(conf != null) {
803       return conf.getClassByName(className);
804     }
805     ClassLoader cl = Thread.currentThread().getContextClassLoader();
806     if(cl == null) {
807       cl = HbaseObjectWritableFor96Migration.class.getClassLoader();
808     }
809     return Class.forName(className, true, cl);
810   }
811 
812   private static void addToMap(final Class<?> clazz, final int code) {
813     CLASS_TO_CODE.put(clazz, code);
814     CODE_TO_CLASS.put(code, clazz);
815   }
816 
817   public void setConf(Configuration conf) {
818     this.conf = conf;
819   }
820 
821   public Configuration getConf() {
822     return this.conf;
823   }
824 }