1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.hadoop.hbase.codec;
19
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.io.OutputStream;
23
24 import org.apache.commons.io.IOUtils;
25 import org.apache.hadoop.hbase.Cell;
26 import org.apache.hadoop.hbase.CellUtil;
27 import org.apache.hadoop.hbase.util.Bytes;
28
29
30
31
32
33
34 public class CellCodec implements Codec {
35 static class CellEncoder extends BaseEncoder {
36 CellEncoder(final OutputStream out) {
37 super(out);
38 }
39
40 @Override
41 public void write(Cell cell) throws IOException {
42 checkFlushed();
43 try {
44
45 write(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
46
47 write(cell.getFamilyArray(), cell.getFamilyOffset(), cell.getFamilyLength());
48
49 write(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength());
50
51 this.out.write(Bytes.toBytes(cell.getTimestamp()));
52
53 this.out.write(cell.getTypeByte());
54
55 write(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
56 } catch (IOException e) {
57 throw new CodecException(e);
58 }
59 }
60
61
62
63
64
65
66
67
68 private void write(final byte [] bytes, final int offset, final int length)
69 throws IOException {
70 this.out.write(Bytes.toBytes(length));
71 this.out.write(bytes, offset, length);
72 }
73 }
74
75 static class CellDecoder extends BaseDecoder {
76 public CellDecoder(final InputStream in) {
77 super(in);
78 }
79
80 protected Cell parseCell() throws IOException {
81 byte [] row = readByteArray(this.in);
82 byte [] family = readByteArray(in);
83 byte [] qualifier = readByteArray(in);
84 byte [] longArray = new byte[Bytes.SIZEOF_LONG];
85 IOUtils.readFully(this.in, longArray);
86 long timestamp = Bytes.toLong(longArray);
87 byte type = (byte) this.in.read();
88 byte [] value = readByteArray(in);
89 return CellUtil.createCell(row, family, qualifier, timestamp, type, value);
90 }
91
92
93
94
95
96 private byte [] readByteArray(final InputStream in) throws IOException {
97 byte [] intArray = new byte[Bytes.SIZEOF_INT];
98 IOUtils.readFully(in, intArray);
99 int length = Bytes.toInt(intArray);
100 byte [] bytes = new byte [length];
101 IOUtils.readFully(in, bytes);
102 return bytes;
103 }
104 }
105
106 @Override
107 public Decoder getDecoder(InputStream is) {
108 return new CellDecoder(is);
109 }
110
111 @Override
112 public Encoder getEncoder(OutputStream os) {
113 return new CellEncoder(os);
114 }
115 }