1 2 3 4 package net.nutch.io; 5 6 import java.util.*; 7 import java.io.*; 8 9 public class RandomDatum implements WritableComparable { 10 private int length; 11 private byte[] data; 12 13 public RandomDatum() {} 14 15 public RandomDatum(Random random) { 16 length = 10 + random.nextInt(100); 17 data = new byte[length]; 18 random.nextBytes(data); 19 } 20 21 public void write(DataOutput out) throws IOException { 22 out.writeInt(length); 23 out.write(data); 24 } 25 26 public void readFields(DataInput in) throws IOException { 27 length = in.readInt(); 28 if (data == null || length > data.length) 29 data = new byte[length]; 30 in.readFully(data, 0, length); 31 } 32 33 public int compareTo(Object o) { 34 RandomDatum that = (RandomDatum)o; 35 return WritableComparator.compareBytes(this.data, 0, this.length, 36 that.data, 0, that.length); 37 } 38 39 public boolean equals(Object o) { 40 return compareTo(o) == 0; 41 } 42 43 private static final char[] HEX_DIGITS = 44 {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; 45 46 47 public String toString() { 48 StringBuffer buf = new StringBuffer (length*2); 49 for (int i = 0; i < length; i++) { 50 int b = data[i]; 51 buf.append(HEX_DIGITS[(b >> 4) & 0xf]); 52 buf.append(HEX_DIGITS[b & 0xf]); 53 } 54 return buf.toString(); 55 } 56 57 public static class Generator { 58 Random random; 59 60 private RandomDatum key; 61 private RandomDatum value; 62 63 public Generator() { random = new Random(); } 64 public Generator(int seed) { random = new Random(seed); } 65 66 public RandomDatum getKey() { return key; } 67 public RandomDatum getValue() { return value; } 68 69 public void next() { 70 key = new RandomDatum(random); 71 value = new RandomDatum(random); 72 } 73 } 74 75 76 public static class Comparator extends WritableComparator { 77 public Comparator() { 78 super(RandomDatum.class); 79 } 80 81 public int compare(byte[] b1, int s1, int l1, 82 byte[] b2, int s2, int l2) { 83 int n1 = readInt(b1, s1); 84 int n2 = readInt(b2, s2); 85 return compareBytes(b1, s1+4, n1, b2, s2+4, n2); 86 } 87 } 88 89 } 90 | Popular Tags |