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
39 static public String ID_ATRIBUTE = "_operation.attributes.id";
40
41 public void setAttribute(String name, byte[] value) {
42 if (attributes == null && value == null) {
43 return;
44 }
45
46 if (attributes == null) {
47 attributes = new HashMap<String, byte[]>();
48 }
49
50 if (value == null) {
51 attributes.remove(name);
52 if (attributes.isEmpty()) {
53 this.attributes = null;
54 }
55 } else {
56 attributes.put(name, value);
57 }
58 }
59
60 public byte[] getAttribute(String name) {
61 if (attributes == null) {
62 return null;
63 }
64
65 return attributes.get(name);
66 }
67
68 public Map<String, byte[]> getAttributesMap() {
69 if (attributes == null) {
70 return Collections.emptyMap();
71 }
72 return Collections.unmodifiableMap(attributes);
73 }
74
75 protected long getAttributeSize() {
76 long size = 0;
77 if (attributes != null) {
78 size += ClassSize.align(this.attributes.size() * ClassSize.MAP_ENTRY);
79 for(Map.Entry<String, byte[]> entry : this.attributes.entrySet()) {
80 size += ClassSize.align(ClassSize.STRING + entry.getKey().length());
81 size += ClassSize.align(ClassSize.ARRAY + entry.getValue().length);
82 }
83 }
84 return size;
85 }
86
87 protected void writeAttributes(final DataOutput out) throws IOException {
88 if (this.attributes == null) {
89 out.writeInt(0);
90 } else {
91 out.writeInt(this.attributes.size());
92 for (Map.Entry<String, byte[]> attr : this.attributes.entrySet()) {
93 WritableUtils.writeString(out, attr.getKey());
94 Bytes.writeByteArray(out, attr.getValue());
95 }
96 }
97 }
98
99 protected void readAttributes(final DataInput in) throws IOException {
100 int numAttributes = in.readInt();
101 if (numAttributes > 0) {
102 this.attributes = new HashMap<String, byte[]>(numAttributes);
103 for(int i=0; i<numAttributes; i++) {
104 String name = WritableUtils.readString(in);
105 byte[] value = Bytes.readByteArray(in);
106 this.attributes.put(name, value);
107 }
108 }
109 }
110
111
112
113
114
115
116
117
118
119
120 public void setId(String id) {
121 setAttribute(ID_ATRIBUTE, Bytes.toBytes(id));
122 }
123
124
125
126
127
128
129 public String getId() {
130 byte[] attr = getAttribute(ID_ATRIBUTE);
131 return attr == null? null: Bytes.toString(attr);
132 }
133 }