1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.util;
20
21 import org.apache.hadoop.hbase.classification.InterfaceAudience;
22 import org.apache.hadoop.io.DataInputBuffer;
23 import org.apache.hadoop.io.Writable;
24
25 import java.io.ByteArrayInputStream;
26 import java.io.ByteArrayOutputStream;
27 import java.io.DataInputStream;
28 import java.io.DataOutputStream;
29 import java.io.IOException;
30 import java.util.ArrayList;
31 import java.util.List;
32
33
34
35
36 @InterfaceAudience.Private
37 public class Writables {
38
39
40
41
42
43
44
45 public static byte [] getBytes(final Writable w) throws IOException {
46 if (w == null) {
47 throw new IllegalArgumentException("Writable cannot be null");
48 }
49 ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
50 DataOutputStream out = new DataOutputStream(byteStream);
51 try {
52 w.write(out);
53 out.close();
54 out = null;
55 return byteStream.toByteArray();
56 } finally {
57 if (out != null) {
58 out.close();
59 }
60 }
61 }
62
63
64
65
66
67
68
69
70 public static byte [] getBytes(final Writable... ws) throws IOException {
71 List<byte []> bytes = new ArrayList<byte []>();
72 int size = 0;
73 for (Writable w: ws) {
74 byte [] b = getBytes(w);
75 size += b.length;
76 bytes.add(b);
77 }
78 byte [] result = new byte[size];
79 int offset = 0;
80 for (byte [] b: bytes) {
81 System.arraycopy(b, 0, result, offset, b.length);
82 offset += b.length;
83 }
84 return result;
85 }
86
87
88
89
90
91
92
93
94
95
96
97
98
99 public static Writable getWritable(final byte [] bytes, final Writable w)
100 throws IOException {
101 return getWritable(bytes, 0, bytes.length, w);
102 }
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118 public static Writable getWritable(final byte [] bytes, final int offset,
119 final int length, final Writable w)
120 throws IOException {
121 if (bytes == null || length <=0) {
122 throw new IllegalArgumentException("Can't build a writable with empty " +
123 "bytes array");
124 }
125 if (w == null) {
126 throw new IllegalArgumentException("Writable cannot be null");
127 }
128 DataInputBuffer in = new DataInputBuffer();
129 try {
130 in.reset(bytes, offset, length);
131 w.readFields(in);
132 return w;
133 } finally {
134 in.close();
135 }
136 }
137
138
139
140
141
142
143
144
145 public static Writable copyWritable(final Writable src, final Writable tgt)
146 throws IOException {
147 return copyWritable(getBytes(src), tgt);
148 }
149
150
151
152
153
154
155
156
157 public static Writable copyWritable(final byte [] bytes, final Writable tgt)
158 throws IOException {
159 DataInputStream dis = new DataInputStream(new ByteArrayInputStream(bytes));
160 try {
161 tgt.readFields(dis);
162 } finally {
163 dis.close();
164 }
165 return tgt;
166 }
167 }