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