BucketExtractionFn: Implement hashCode, fix toString. (#3656)

This commit is contained in:
Gian Merlino 2016-11-04 11:24:02 -07:00 committed by Fangjin Yang
parent 8b3c86f41f
commit 600bbd4a17
2 changed files with 42 additions and 8 deletions

View File

@ -36,10 +36,8 @@ public class BucketExtractionFn implements ExtractionFn
@JsonCreator @JsonCreator
public BucketExtractionFn( public BucketExtractionFn(
@Nullable @Nullable @JsonProperty("size") Double size,
@JsonProperty("size") Double size, @Nullable @JsonProperty("offset") Double offset
@Nullable
@JsonProperty("offset") Double offset
) )
{ {
this.size = size == null ? 1 : size; this.size = size == null ? 1 : size;
@ -74,7 +72,8 @@ public class BucketExtractionFn implements ExtractionFn
{ {
try { try {
return bucket(Double.parseDouble(value)); return bucket(Double.parseDouble(value));
} catch (NumberFormatException | NullPointerException ex) { }
catch (NumberFormatException | NullPointerException ex) {
return null; return null;
} }
} }
@ -85,9 +84,10 @@ public class BucketExtractionFn implements ExtractionFn
return bucket(value); return bucket(value);
} }
private String bucket(double value) { private String bucket(double value)
{
double ret = Math.floor((value - offset) / size) * size + offset; double ret = Math.floor((value - offset) / size) * size + offset;
return ret == (long)ret ? String.valueOf((long)ret) : String.valueOf(ret); return ret == (long) ret ? String.valueOf((long) ret) : String.valueOf(ret);
} }
@Override @Override
@ -124,7 +124,28 @@ public class BucketExtractionFn implements ExtractionFn
BucketExtractionFn that = (BucketExtractionFn) o; BucketExtractionFn that = (BucketExtractionFn) o;
return size == that.size && offset == that.offset; if (Double.compare(that.size, size) != 0) {
return false;
}
return Double.compare(that.offset, offset) == 0;
} }
@Override
public int hashCode()
{
int result;
long temp;
temp = Double.doubleToLongBits(size);
result = (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(offset);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public String toString()
{
return String.format("bucket(%f, %f)", size, offset);
}
} }

View File

@ -52,6 +52,19 @@ public class BucketExtractionFnTest
Assert.assertEquals("71", extractionFn2.apply("7.1e1")); Assert.assertEquals("71", extractionFn2.apply("7.1e1"));
} }
@Test
public void testEqualsAndHashCode()
{
BucketExtractionFn extractionFn1 = new BucketExtractionFn(100.0, 0.5);
BucketExtractionFn extractionFn2 = new BucketExtractionFn(3.0, 2.0);
BucketExtractionFn extractionFn3 = new BucketExtractionFn(3.0, 2.0);
Assert.assertNotEquals(extractionFn1, extractionFn2);
Assert.assertNotEquals(extractionFn1.hashCode(), extractionFn2.hashCode());
Assert.assertEquals(extractionFn2, extractionFn3);
Assert.assertEquals(extractionFn2.hashCode(), extractionFn3.hashCode());
}
@Test @Test
public void testSerde() throws Exception public void testSerde() throws Exception
{ {