1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.hadoop.hbase.filter;
21
22 import java.util.Random;
23
24 import org.apache.hadoop.hbase.classification.InterfaceAudience;
25 import org.apache.hadoop.hbase.classification.InterfaceStability;
26 import org.apache.hadoop.hbase.Cell;
27 import org.apache.hadoop.hbase.exceptions.DeserializationException;
28 import org.apache.hadoop.hbase.protobuf.generated.FilterProtos;
29
30 import com.google.protobuf.InvalidProtocolBufferException;
31
32
33
34
35
36 @InterfaceAudience.Public
37 @InterfaceStability.Stable
38 public class RandomRowFilter extends FilterBase {
39 protected static final Random random = new Random();
40
41 protected float chance;
42 protected boolean filterOutRow;
43
44
45
46
47
48
49 public RandomRowFilter(float chance) {
50 this.chance = chance;
51 }
52
53
54
55
56 public float getChance() {
57 return chance;
58 }
59
60
61
62
63
64
65 public void setChance(float chance) {
66 this.chance = chance;
67 }
68
69 @Override
70 public boolean filterAllRemaining() {
71 return false;
72 }
73
74 @Override
75 public ReturnCode filterKeyValue(Cell v) {
76 if (filterOutRow) {
77 return ReturnCode.NEXT_ROW;
78 }
79 return ReturnCode.INCLUDE;
80 }
81
82
83
84 @Override
85 public Cell transformCell(Cell v) {
86 return v;
87 }
88
89 @Override
90 public boolean filterRow() {
91 return filterOutRow;
92 }
93
94 @Override
95 public boolean hasFilterRow() {
96 return true;
97 }
98
99 @Override
100 public boolean filterRowKey(byte[] buffer, int offset, int length) {
101 if (chance < 0) {
102
103 filterOutRow = true;
104 } else if (chance > 1) {
105
106 filterOutRow = false;
107 } else {
108
109 filterOutRow = !(random.nextFloat() < chance);
110 }
111 return filterOutRow;
112 }
113
114 @Override
115 public void reset() {
116 filterOutRow = false;
117 }
118
119
120
121
122 @Override
123 public byte [] toByteArray() {
124 FilterProtos.RandomRowFilter.Builder builder =
125 FilterProtos.RandomRowFilter.newBuilder();
126 builder.setChance(this.chance);
127 return builder.build().toByteArray();
128 }
129
130
131
132
133
134
135
136 public static RandomRowFilter parseFrom(final byte [] pbBytes)
137 throws DeserializationException {
138 FilterProtos.RandomRowFilter proto;
139 try {
140 proto = FilterProtos.RandomRowFilter.parseFrom(pbBytes);
141 } catch (InvalidProtocolBufferException e) {
142 throw new DeserializationException(e);
143 }
144 return new RandomRowFilter(proto.getChance());
145 }
146
147
148
149
150
151
152 @Override
153 boolean areSerializedFieldsEqual(Filter o) {
154 if (o == this) return true;
155 if (!(o instanceof RandomRowFilter)) return false;
156
157 RandomRowFilter other = (RandomRowFilter)o;
158 return this.getChance() == other.getChance();
159 }
160 }