Skip to content

Instantly share code, notes, and snippets.

@tdunning
Created March 4, 2014 01:30
Show Gist options
  • Save tdunning/9338520 to your computer and use it in GitHub Desktop.
Save tdunning/9338520 to your computer and use it in GitHub Desktop.
Quick and dirty (very dirty) big decimal writable. This is much uglier than it needs to be because Hadoop's API causes an extra copy to be required.
public static class BigDecimalWritable implements Writable {
private BigDecimal value;
public BigDecimalWritable(BigDecimal value) {
this.value = value;
}
public BigDecimal value() {
return value;
}
@Override
public void write(DataOutput dataOutput) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bos);
out.writeObject(value);
out.close();
byte[] bytes = bos.toByteArray();
dataOutput.write(bytes.length);
dataOutput.write(bytes);
}
@Override
public void readFields(DataInput dataInput) throws IOException {
int n = dataInput.readInt();
if (n < 0 || n > 1000) {
throw new IllegalArgumentException("Invalid representation for BigDecimal ... length is " + n);
}
byte[] bytes = new byte[n];
dataInput.readFully(bytes);
try {
value = (BigDecimal) new ObjectInputStream(new ByteArrayInputStream(bytes)).readObject();
} catch (ClassNotFoundException e) {
throw new RuntimeException("Unable to read serialized BigDecimal value, can't happen", e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment