Skip to content

Instantly share code, notes, and snippets.

@kjunine
Created May 10, 2013 06:53
Show Gist options
  • Select an option

  • Save kjunine/5552823 to your computer and use it in GitHub Desktop.

Select an option

Save kjunine/5552823 to your computer and use it in GitHub Desktop.
BytesBuilder to make row key for HBase.
package iadb.data.utils;
import static org.apache.hadoop.hbase.util.Bytes.*;
import java.math.BigDecimal;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
public class BytesBuilder {
private int size = 0;
private List<byte[]> list = new ArrayList<byte[]>();
public BytesBuilder add(boolean b) {
return add(toBytes(b));
}
public BytesBuilder add(byte b) {
return add(new byte[] { b });
}
public BytesBuilder add(char c) {
return add(new byte[] { (byte) c });
}
public BytesBuilder add(short s) {
return add(toBytes(s));
}
public BytesBuilder add(int i) {
return add(toBytes(i));
}
public BytesBuilder add(long l) {
return add(toBytes(l));
}
public BytesBuilder add(float f) {
return add(toBytes(f));
}
public BytesBuilder add(double d) {
return add(toBytes(d));
}
public BytesBuilder add(BigDecimal val) {
return add(toBytes(val));
}
public BytesBuilder add(String s) {
return add(toBytes(s));
}
public BytesBuilder add(ByteBuffer bb) {
return add(toBytes(bb));
}
public BytesBuilder add(byte[] bs) {
size += bs.length;
list.add(bs);
return this;
}
public BytesBuilder add(Object o) {
if (o instanceof Boolean) {
add(((Boolean) o).booleanValue());
} else if (o instanceof Byte) {
add(((Byte) o).byteValue());
} else if (o instanceof Character) {
add(((Character) o).charValue());
} else if (o instanceof Short) {
add(((Short) o).shortValue());
} else if (o instanceof Integer) {
add(((Integer) o).intValue());
} else if (o instanceof Long) {
add(((Long) o).longValue());
} else if (o instanceof Float) {
add(((Float) o).floatValue());
} else if (o instanceof Double) {
add(((Double) o).doubleValue());
} else if (o instanceof BigDecimal) {
add((BigDecimal) o);
} else if (o instanceof String) {
add((String) o);
} else if (o instanceof ByteBuffer) {
add((ByteBuffer) o);
} else if (o instanceof byte[]) {
add((byte[]) o);
} else {
throw new IllegalArgumentException("Object '" + o
+ "' is not a valid type.");
}
return this;
}
public BytesBuilder add(Object... os) {
for (Object o : os) {
add(o);
}
return this;
}
/**
* Returns the combined byte array.
*
* @return the combined byte array
*/
public byte[] build() {
byte[] bytes = new byte[size];
int offset = 0;
for (byte[] src : list) {
offset = putBytes(bytes, offset, src, 0, src.length);
}
return bytes;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment