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 public boolean hasFilterRow() {
95 return true;
96 }
97
98 @Override
99 public boolean filterRowKey(byte[] buffer, int offset, int length) {
100 if (chance < 0) {
101
102 filterOutRow = true;
103 } else if (chance > 1) {
104
105 filterOutRow = false;
106 } else {
107
108 filterOutRow = !(random.nextFloat() < chance);
109 }
110 return filterOutRow;
111 }
112
113 @Override
114 public void reset() {
115 filterOutRow = false;
116 }
117
118
119
120
121 public byte [] toByteArray() {
122 FilterProtos.RandomRowFilter.Builder builder =
123 FilterProtos.RandomRowFilter.newBuilder();
124 builder.setChance(this.chance);
125 return builder.build().toByteArray();
126 }
127
128
129
130
131
132
133
134 public static RandomRowFilter parseFrom(final byte [] pbBytes)
135 throws DeserializationException {
136 FilterProtos.RandomRowFilter proto;
137 try {
138 proto = FilterProtos.RandomRowFilter.parseFrom(pbBytes);
139 } catch (InvalidProtocolBufferException e) {
140 throw new DeserializationException(e);
141 }
142 return new RandomRowFilter(proto.getChance());
143 }
144
145
146
147
148
149
150 boolean areSerializedFieldsEqual(Filter o) {
151 if (o == this) return true;
152 if (!(o instanceof RandomRowFilter)) return false;
153
154 RandomRowFilter other = (RandomRowFilter)o;
155 return this.getChance() == other.getChance();
156 }
157 }