1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.apache.hadoop.hbase.client;
22
23 import java.io.DataInput;
24 import java.io.DataOutput;
25 import java.io.IOException;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.Map;
29
30 import org.apache.hadoop.hbase.util.Bytes;
31 import org.apache.hadoop.hbase.util.ClassSize;
32 import org.apache.hadoop.io.WritableUtils;
33
34 public abstract class OperationWithAttributes extends Operation implements Attributes {
35
36 private Map<String, byte[]> attributes;
37
38 public void setAttribute(String name, byte[] value) {
39 if (attributes == null && value == null) {
40 return;
41 }
42
43 if (attributes == null) {
44 attributes = new HashMap<String, byte[]>();
45 }
46
47 if (value == null) {
48 attributes.remove(name);
49 if (attributes.isEmpty()) {
50 this.attributes = null;
51 }
52 } else {
53 attributes.put(name, value);
54 }
55 }
56
57 public byte[] getAttribute(String name) {
58 if (attributes == null) {
59 return null;
60 }
61
62 return attributes.get(name);
63 }
64
65 public Map<String, byte[]> getAttributesMap() {
66 if (attributes == null) {
67 return Collections.emptyMap();
68 }
69 return Collections.unmodifiableMap(attributes);
70 }
71
72 protected long getAttributeSize() {
73 long size = 0;
74 if (attributes != null) {
75 size += ClassSize.align(this.attributes.size() * ClassSize.MAP_ENTRY);
76 for(Map.Entry<String, byte[]> entry : this.attributes.entrySet()) {
77 size += ClassSize.align(ClassSize.STRING + entry.getKey().length());
78 size += ClassSize.align(ClassSize.ARRAY + entry.getValue().length);
79 }
80 }
81 return size;
82 }
83
84 protected void writeAttributes(final DataOutput out) throws IOException {
85 if (this.attributes == null) {
86 out.writeInt(0);
87 } else {
88 out.writeInt(this.attributes.size());
89 for (Map.Entry<String, byte[]> attr : this.attributes.entrySet()) {
90 WritableUtils.writeString(out, attr.getKey());
91 Bytes.writeByteArray(out, attr.getValue());
92 }
93 }
94 }
95
96 protected void readAttributes(final DataInput in) throws IOException {
97 int numAttributes = in.readInt();
98 if (numAttributes > 0) {
99 this.attributes = new HashMap<String, byte[]>();
100 for(int i=0; i<numAttributes; i++) {
101 String name = WritableUtils.readString(in);
102 byte[] value = Bytes.readByteArray(in);
103 this.attributes.put(name, value);
104 }
105 }
106 }
107 }