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