incubator-hama-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From tomm...@apache.org
Subject svn commit: r1152788 [6/9] - in /incubator/hama/trunk: ./ bin/ conf/ core/ core/bin/ core/conf/ core/src/ core/src/main/ core/src/main/java/ core/src/main/java/org/ core/src/main/java/org/apache/ core/src/main/java/org/apache/hama/ core/src/main/java/o...
Date Mon, 01 Aug 2011 14:12:56 GMT
Added: incubator/hama/trunk/core/src/main/java/org/apache/hama/util/Bytes.java
URL: http://svn.apache.org/viewvc/incubator/hama/trunk/core/src/main/java/org/apache/hama/util/Bytes.java?rev=1152788&view=auto
==============================================================================
--- incubator/hama/trunk/core/src/main/java/org/apache/hama/util/Bytes.java (added)
+++ incubator/hama/trunk/core/src/main/java/org/apache/hama/util/Bytes.java Mon Aug  1 14:12:46 2011
@@ -0,0 +1,1226 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hama.util;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.util.Comparator;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.io.RawComparator;
+import org.apache.hadoop.io.WritableComparator;
+import org.apache.hadoop.io.WritableUtils;
+import org.apache.hama.Constants;
+
+/**
+ * Utility class that handles byte arrays, conversions to/from other types,
+ * comparisons, hash code generation, manufacturing keys for HashMaps or
+ * HashSets, etc.
+ */
+public class Bytes {
+
+  private static final Log LOG = LogFactory.getLog(Bytes.class);
+
+  /**
+   * Size of boolean in bytes
+   */
+  public static final int SIZEOF_BOOLEAN = Byte.SIZE / Byte.SIZE;
+
+  /**
+   * Size of byte in bytes
+   */
+  public static final int SIZEOF_BYTE = SIZEOF_BOOLEAN;
+
+  /**
+   * Size of char in bytes
+   */
+  public static final int SIZEOF_CHAR = Character.SIZE / Byte.SIZE;
+
+  /**
+   * Size of double in bytes
+   */
+  public static final int SIZEOF_DOUBLE = Double.SIZE / Byte.SIZE;
+
+  /**
+   * Size of float in bytes
+   */
+  public static final int SIZEOF_FLOAT = Float.SIZE / Byte.SIZE;
+
+  /**
+   * Size of int in bytes
+   */
+  public static final int SIZEOF_INT = Integer.SIZE / Byte.SIZE;
+
+  /**
+   * Size of long in bytes
+   */
+  public static final int SIZEOF_LONG = Long.SIZE / Byte.SIZE;
+
+  /**
+   * Size of short in bytes
+   */
+  public static final int SIZEOF_SHORT = Short.SIZE / Byte.SIZE;
+
+  /**
+   * Estimate of size cost to pay beyond payload in jvm for instance of byte [].
+   * Estimate based on study of jhat and jprofiler numbers.
+   */
+  // JHat says BU is 56 bytes.
+  // SizeOf which uses java.lang.instrument says 24 bytes. (3 longs?)
+  public static final int ESTIMATED_HEAP_TAX = 16;
+
+  /**
+   * Byte array comparator class.
+   */
+  public static class ByteArrayComparator implements RawComparator<byte[]> {
+    /**
+     * Constructor
+     */
+    public ByteArrayComparator() {
+      super();
+    }
+
+    public int compare(byte[] left, byte[] right) {
+      return compareTo(left, right);
+    }
+
+    public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
+      return compareTo(b1, s1, l1, b2, s2, l2);
+    }
+  }
+
+  /**
+   * Pass this to TreeMaps where byte [] are keys.
+   */
+  public static Comparator<byte[]> BYTES_COMPARATOR = new ByteArrayComparator();
+
+  /**
+   * Use comparing byte arrays, byte-by-byte
+   */
+  public static RawComparator<byte[]> BYTES_RAWCOMPARATOR = new ByteArrayComparator();
+
+  /**
+   * Read byte-array written with a WritableableUtils.vint prefix.
+   * 
+   * @param in Input to read from.
+   * @return byte array read off <code>in</code>
+   * @throws IOException e
+   */
+  public static byte[] readByteArray(final DataInput in) throws IOException {
+    int len = WritableUtils.readVInt(in);
+    if (len < 0) {
+      throw new NegativeArraySizeException(Integer.toString(len));
+    }
+    byte[] result = new byte[len];
+    in.readFully(result, 0, len);
+    return result;
+  }
+
+  /**
+   * Read byte-array written with a WritableableUtils.vint prefix. IOException
+   * is converted to a RuntimeException.
+   * 
+   * @param in Input to read from.
+   * @return byte array read off <code>in</code>
+   */
+  public static byte[] readByteArrayThrowsRuntime(final DataInput in) {
+    try {
+      return readByteArray(in);
+    } catch (Exception e) {
+      throw new RuntimeException(e);
+    }
+  }
+
+  /**
+   * Write byte-array with a WritableableUtils.vint prefix.
+   * 
+   * @param out output stream to be written to
+   * @param b array to write
+   * @throws IOException e
+   */
+  public static void writeByteArray(final DataOutput out, final byte[] b)
+      throws IOException {
+    if (b == null) {
+      WritableUtils.writeVInt(out, 0);
+    } else {
+      writeByteArray(out, b, 0, b.length);
+    }
+  }
+
+  /**
+   * Write byte-array to out with a vint length prefix.
+   * 
+   * @param out output stream
+   * @param b array
+   * @param offset offset into array
+   * @param length length past offset
+   * @throws IOException e
+   */
+  public static void writeByteArray(final DataOutput out, final byte[] b,
+      final int offset, final int length) throws IOException {
+    WritableUtils.writeVInt(out, length);
+    out.write(b, offset, length);
+  }
+
+  /**
+   * Write byte-array from src to tgt with a vint length prefix.
+   * 
+   * @param tgt target array
+   * @param tgtOffset offset into target array
+   * @param src source array
+   * @param srcOffset source offset
+   * @param srcLength source length
+   * @return New offset in src array.
+   */
+  public static int writeByteArray(final byte[] tgt, final int tgtOffset,
+      final byte[] src, final int srcOffset, final int srcLength) {
+    byte[] vint = vintToBytes(srcLength);
+    System.arraycopy(vint, 0, tgt, tgtOffset, vint.length);
+    int offset = tgtOffset + vint.length;
+    System.arraycopy(src, srcOffset, tgt, offset, srcLength);
+    return offset + srcLength;
+  }
+
+  /**
+   * Put bytes at the specified byte array position.
+   * 
+   * @param tgtBytes the byte array
+   * @param tgtOffset position in the array
+   * @param srcBytes array to write out
+   * @param srcOffset source offset
+   * @param srcLength source length
+   * @return incremented offset
+   */
+  public static int putBytes(byte[] tgtBytes, int tgtOffset, byte[] srcBytes,
+      int srcOffset, int srcLength) {
+    System.arraycopy(srcBytes, srcOffset, tgtBytes, tgtOffset, srcLength);
+    return tgtOffset + srcLength;
+  }
+
+  /**
+   * Write a single byte out to the specified byte array position.
+   * 
+   * @param bytes the byte array
+   * @param offset position in the array
+   * @param b byte to write out
+   * @return incremented offset
+   */
+  public static int putByte(byte[] bytes, int offset, byte b) {
+    bytes[offset] = b;
+    return offset + 1;
+  }
+
+  /**
+   * Returns a new byte array, copied from the passed ByteBuffer.
+   * 
+   * @param bb A ByteBuffer
+   * @return the byte array
+   */
+  public static byte[] toBytes(ByteBuffer bb) {
+    int length = bb.limit();
+    byte[] result = new byte[length];
+    System.arraycopy(bb.array(), bb.arrayOffset(), result, 0, length);
+    return result;
+  }
+
+  /**
+   * @param b Presumed UTF-8 encoded byte array.
+   * @return String made from <code>b</code>
+   */
+  public static String toString(final byte[] b) {
+    if (b == null) {
+      return null;
+    }
+    return toString(b, 0, b.length);
+  }
+
+  /**
+   * Joins two byte arrays together using a separator.
+   * 
+   * @param b1 The first byte array.
+   * @param sep The separator to use.
+   * @param b2 The second byte array.
+   */
+  public static String toString(final byte[] b1, String sep, final byte[] b2) {
+    return toString(b1, 0, b1.length) + sep + toString(b2, 0, b2.length);
+  }
+
+  /**
+   * This method will convert utf8 encoded bytes into a string. If an
+   * UnsupportedEncodingException occurs, this method will eat it and return
+   * null instead.
+   * 
+   * @param b Presumed UTF-8 encoded byte array.
+   * @param off offset into array
+   * @param len length of utf-8 sequence
+   * @return String made from <code>b</code> or null
+   */
+  public static String toString(final byte[] b, int off, int len) {
+    if (b == null) {
+      return null;
+    }
+    if (len == 0) {
+      return "";
+    }
+    try {
+      return new String(b, off, len, Constants.UTF8_ENCODING);
+    } catch (UnsupportedEncodingException e) {
+      LOG.error("UTF-8 not supported?", e);
+      return null;
+    }
+  }
+
+  /**
+   * Write a printable representation of a byte array.
+   * 
+   * @param b byte array
+   * @return string
+   * @see #toStringBinary(byte[], int, int)
+   */
+  public static String toStringBinary(final byte[] b) {
+    return toStringBinary(b, 0, b.length);
+  }
+
+  /**
+   * Write a printable representation of a byte array. Non-printable characters
+   * are hex escaped in the format \\x%02X, eg: \x00 \x05 etc
+   * 
+   * @param b array to write out
+   * @param off offset to start at
+   * @param len length to write
+   * @return string output
+   */
+  public static String toStringBinary(final byte[] b, int off, int len) {
+    StringBuilder result = new StringBuilder();
+    try {
+      String first = new String(b, off, len, "ISO-8859-1");
+      for (int i = 0; i < first.length(); ++i) {
+        int ch = first.charAt(i) & 0xFF;
+        if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z')
+            || (ch >= 'a' && ch <= 'z') || ch == ',' || ch == '_' || ch == '-'
+            || ch == ':' || ch == ' ' || ch == '<' || ch == '>' || ch == '='
+            || ch == '/' || ch == '.') {
+          result.append(first.charAt(i));
+        } else {
+          result.append(String.format("\\x%02X", ch));
+        }
+      }
+    } catch (UnsupportedEncodingException e) {
+      LOG.error("ISO-8859-1 not supported?", e);
+    }
+    return result.toString();
+  }
+
+  private static boolean isHexDigit(char c) {
+    return (c >= 'A' && c <= 'F') || (c >= '0' && c <= '9');
+  }
+
+  /**
+   * Takes a ASCII digit in the range A-F0-9 and returns the corresponding
+   * integer/ordinal value.
+   * 
+   * @param ch The hex digit.
+   * @return The converted hex value as a byte.
+   */
+  public static byte toBinaryFromHex(byte ch) {
+    if (ch >= 'A' && ch <= 'F')
+      return (byte) ((byte) 10 + (byte) (ch - 'A'));
+    // else
+    return (byte) (ch - '0');
+  }
+
+  public static byte[] toBytesBinary(String in) {
+    // this may be bigger than we need, but lets be safe.
+    byte[] b = new byte[in.length()];
+    int size = 0;
+    for (int i = 0; i < in.length(); ++i) {
+      char ch = in.charAt(i);
+      if (ch == '\\') {
+        // begin hex escape:
+        char next = in.charAt(i + 1);
+        if (next != 'x') {
+          // invalid escape sequence, ignore this one.
+          b[size++] = (byte) ch;
+          continue;
+        }
+        // ok, take next 2 hex digits.
+        char hd1 = in.charAt(i + 2);
+        char hd2 = in.charAt(i + 3);
+
+        // they need to be A-F0-9:
+        if (!isHexDigit(hd1) || !isHexDigit(hd2)) {
+          // bogus escape code, ignore:
+          continue;
+        }
+        // turn hex ASCII digit -> number
+        byte d = (byte) ((toBinaryFromHex((byte) hd1) << 4) + toBinaryFromHex((byte) hd2));
+
+        b[size++] = d;
+        i += 3; // skip 3
+      } else {
+        b[size++] = (byte) ch;
+      }
+    }
+    // resize:
+    byte[] b2 = new byte[size];
+    System.arraycopy(b, 0, b2, 0, size);
+    return b2;
+  }
+
+  /**
+   * Converts a string to a UTF-8 byte array.
+   * 
+   * @param s string
+   * @return the byte array
+   */
+  public static byte[] toBytes(String s) {
+    try {
+      return s.getBytes(Constants.UTF8_ENCODING);
+    } catch (UnsupportedEncodingException e) {
+      LOG.error("UTF-8 not supported?", e);
+      return null;
+    }
+  }
+
+  /**
+   * Convert a boolean to a byte array. True becomes -1 and false becomes 0.
+   * 
+   * @param b value
+   * @return <code>b</code> encoded in a byte array.
+   */
+  public static byte[] toBytes(final boolean b) {
+    return new byte[] { b ? (byte) -1 : (byte) 0 };
+  }
+
+  /**
+   * Reverses {@link #toBytes(boolean)}
+   * 
+   * @param b array
+   * @return True or false.
+   */
+  public static boolean toBoolean(final byte[] b) {
+    if (b.length != 1) {
+      throw new IllegalArgumentException("Array has wrong size: " + b.length);
+    }
+    return b[0] != (byte) 0;
+  }
+
+  /**
+   * Convert a long value to a byte array using big-endian.
+   * 
+   * @param val value to convert
+   * @return the byte array
+   */
+  public static byte[] toBytes(long val) {
+    byte[] b = new byte[8];
+    for (int i = 7; i > 0; i--) {
+      b[i] = (byte) val;
+      val >>>= 8;
+    }
+    b[0] = (byte) val;
+    return b;
+  }
+
+  /**
+   * Converts a byte array to a long value. Reverses {@link #toBytes(long)}
+   * 
+   * @param bytes array
+   * @return the long value
+   */
+  public static long toLong(byte[] bytes) {
+    return toLong(bytes, 0, SIZEOF_LONG);
+  }
+
+  /**
+   * Converts a byte array to a long value. Assumes there will be
+   * {@link #SIZEOF_LONG} bytes available.
+   * 
+   * @param bytes bytes
+   * @param offset offset
+   * @return the long value
+   */
+  public static long toLong(byte[] bytes, int offset) {
+    return toLong(bytes, offset, SIZEOF_LONG);
+  }
+
+  /**
+   * Converts a byte array to a long value.
+   * 
+   * @param bytes array of bytes
+   * @param offset offset into array
+   * @param length length of data (must be {@link #SIZEOF_LONG})
+   * @return the long value
+   * @throws IllegalArgumentException if length is not {@link #SIZEOF_LONG} or
+   *           if there's not enough room in the array at the offset indicated.
+   */
+  public static long toLong(byte[] bytes, int offset, final int length) {
+    if (length != SIZEOF_LONG || offset + length > bytes.length) {
+      throw explainWrongLengthOrOffset(bytes, offset, length, SIZEOF_LONG);
+    }
+    long l = 0;
+    for (int i = offset; i < offset + length; i++) {
+      l <<= 8;
+      l ^= bytes[i] & 0xFF;
+    }
+    return l;
+  }
+
+  private static IllegalArgumentException explainWrongLengthOrOffset(
+      final byte[] bytes, final int offset, final int length,
+      final int expectedLength) {
+    String reason;
+    if (length != expectedLength) {
+      reason = "Wrong length: " + length + ", expected " + expectedLength;
+    } else {
+      reason = "offset (" + offset + ") + length (" + length + ") exceed the"
+          + " capacity of the array: " + bytes.length;
+    }
+    return new IllegalArgumentException(reason);
+  }
+
+  /**
+   * Put a long value out to the specified byte array position.
+   * 
+   * @param bytes the byte array
+   * @param offset position in the array
+   * @param val long to write out
+   * @return incremented offset
+   * @throws IllegalArgumentException if the byte array given doesn't have
+   *           enough room at the offset specified.
+   */
+  public static int putLong(byte[] bytes, int offset, long val) {
+    if (bytes.length - offset < SIZEOF_LONG) {
+      throw new IllegalArgumentException("Not enough room to put a long at"
+          + " offset " + offset + " in a " + bytes.length + " byte array");
+    }
+    for (int i = offset + 7; i > offset; i--) {
+      bytes[i] = (byte) val;
+      val >>>= 8;
+    }
+    bytes[offset] = (byte) val;
+    return offset + SIZEOF_LONG;
+  }
+
+  /**
+   * Presumes float encoded as IEEE 754 floating-point "single format"
+   * 
+   * @param bytes byte array
+   * @return Float made from passed byte array.
+   */
+  public static float toFloat(byte[] bytes) {
+    return toFloat(bytes, 0);
+  }
+
+  /**
+   * Presumes float encoded as IEEE 754 floating-point "single format"
+   * 
+   * @param bytes array to convert
+   * @param offset offset into array
+   * @return Float made from passed byte array.
+   */
+  public static float toFloat(byte[] bytes, int offset) {
+    return Float.intBitsToFloat(toInt(bytes, offset, SIZEOF_INT));
+  }
+
+  /**
+   * @param bytes byte array
+   * @param offset offset to write to
+   * @param f float value
+   * @return New offset in <code>bytes</code>
+   */
+  public static int putFloat(byte[] bytes, int offset, float f) {
+    return putInt(bytes, offset, Float.floatToRawIntBits(f));
+  }
+
+  /**
+   * @param f float value
+   * @return the float represented as byte []
+   */
+  public static byte[] toBytes(final float f) {
+    // Encode it as int
+    return Bytes.toBytes(Float.floatToRawIntBits(f));
+  }
+
+  /**
+   * @param bytes byte array
+   * @return Return double made from passed bytes.
+   */
+  public static double toDouble(final byte[] bytes) {
+    return toDouble(bytes, 0);
+  }
+
+  /**
+   * @param bytes byte array
+   * @param offset offset where double is
+   * @return Return double made from passed bytes.
+   */
+  public static double toDouble(final byte[] bytes, final int offset) {
+    return Double.longBitsToDouble(toLong(bytes, offset, SIZEOF_LONG));
+  }
+
+  /**
+   * @param bytes byte array
+   * @param offset offset to write to
+   * @param d value
+   * @return New offset into array <code>bytes</code>
+   */
+  public static int putDouble(byte[] bytes, int offset, double d) {
+    return putLong(bytes, offset, Double.doubleToLongBits(d));
+  }
+
+  /**
+   * Serialize a double as the IEEE 754 double format output. The resultant
+   * array will be 8 bytes long.
+   * 
+   * @param d value
+   * @return the double represented as byte []
+   */
+  public static byte[] toBytes(final double d) {
+    // Encode it as a long
+    return Bytes.toBytes(Double.doubleToRawLongBits(d));
+  }
+
+  /**
+   * Convert an int value to a byte array
+   * 
+   * @param val value
+   * @return the byte array
+   */
+  public static byte[] toBytes(int val) {
+    byte[] b = new byte[4];
+    for (int i = 3; i > 0; i--) {
+      b[i] = (byte) val;
+      val >>>= 8;
+    }
+    b[0] = (byte) val;
+    return b;
+  }
+
+  /**
+   * Converts a byte array to an int value
+   * 
+   * @param bytes byte array
+   * @return the int value
+   */
+  public static int toInt(byte[] bytes) {
+    return toInt(bytes, 0, SIZEOF_INT);
+  }
+
+  /**
+   * Converts a byte array to an int value
+   * 
+   * @param bytes byte array
+   * @param offset offset into array
+   * @return the int value
+   */
+  public static int toInt(byte[] bytes, int offset) {
+    return toInt(bytes, offset, SIZEOF_INT);
+  }
+
+  /**
+   * Converts a byte array to an int value
+   * 
+   * @param bytes byte array
+   * @param offset offset into array
+   * @param length length of int (has to be {@link #SIZEOF_INT})
+   * @return the int value
+   * @throws IllegalArgumentException if length is not {@link #SIZEOF_INT} or if
+   *           there's not enough room in the array at the offset indicated.
+   */
+  public static int toInt(byte[] bytes, int offset, final int length) {
+    if (length != SIZEOF_INT || offset + length > bytes.length) {
+      throw explainWrongLengthOrOffset(bytes, offset, length, SIZEOF_INT);
+    }
+    int n = 0;
+    for (int i = offset; i < (offset + length); i++) {
+      n <<= 8;
+      n ^= bytes[i] & 0xFF;
+    }
+    return n;
+  }
+
+  /**
+   * Put an int value out to the specified byte array position.
+   * 
+   * @param bytes the byte array
+   * @param offset position in the array
+   * @param val int to write out
+   * @return incremented offset
+   * @throws IllegalArgumentException if the byte array given doesn't have
+   *           enough room at the offset specified.
+   */
+  public static int putInt(byte[] bytes, int offset, int val) {
+    if (bytes.length - offset < SIZEOF_INT) {
+      throw new IllegalArgumentException("Not enough room to put an int at"
+          + " offset " + offset + " in a " + bytes.length + " byte array");
+    }
+    for (int i = offset + 3; i > offset; i--) {
+      bytes[i] = (byte) val;
+      val >>>= 8;
+    }
+    bytes[offset] = (byte) val;
+    return offset + SIZEOF_INT;
+  }
+
+  /**
+   * Convert a short value to a byte array of {@link #SIZEOF_SHORT} bytes long.
+   * 
+   * @param val value
+   * @return the byte array
+   */
+  public static byte[] toBytes(short val) {
+    byte[] b = new byte[SIZEOF_SHORT];
+    b[1] = (byte) val;
+    val >>= 8;
+    b[0] = (byte) val;
+    return b;
+  }
+
+  /**
+   * Converts a byte array to a short value
+   * 
+   * @param bytes byte array
+   * @return the short value
+   */
+  public static short toShort(byte[] bytes) {
+    return toShort(bytes, 0, SIZEOF_SHORT);
+  }
+
+  /**
+   * Converts a byte array to a short value
+   * 
+   * @param bytes byte array
+   * @param offset offset into array
+   * @return the short value
+   */
+  public static short toShort(byte[] bytes, int offset) {
+    return toShort(bytes, offset, SIZEOF_SHORT);
+  }
+
+  /**
+   * Converts a byte array to a short value
+   * 
+   * @param bytes byte array
+   * @param offset offset into array
+   * @param length length, has to be {@link #SIZEOF_SHORT}
+   * @return the short value
+   * @throws IllegalArgumentException if length is not {@link #SIZEOF_SHORT} or
+   *           if there's not enough room in the array at the offset indicated.
+   */
+  public static short toShort(byte[] bytes, int offset, final int length) {
+    if (length != SIZEOF_SHORT || offset + length > bytes.length) {
+      throw explainWrongLengthOrOffset(bytes, offset, length, SIZEOF_SHORT);
+    }
+    short n = 0;
+    n ^= bytes[offset] & 0xFF;
+    n <<= 8;
+    n ^= bytes[offset + 1] & 0xFF;
+    return n;
+  }
+
+  /**
+   * Put a short value out to the specified byte array position.
+   * 
+   * @param bytes the byte array
+   * @param offset position in the array
+   * @param val short to write out
+   * @return incremented offset
+   * @throws IllegalArgumentException if the byte array given doesn't have
+   *           enough room at the offset specified.
+   */
+  public static int putShort(byte[] bytes, int offset, short val) {
+    if (bytes.length - offset < SIZEOF_SHORT) {
+      throw new IllegalArgumentException("Not enough room to put a short at"
+          + " offset " + offset + " in a " + bytes.length + " byte array");
+    }
+    bytes[offset + 1] = (byte) val;
+    val >>= 8;
+    bytes[offset] = (byte) val;
+    return offset + SIZEOF_SHORT;
+  }
+
+  /**
+   * @param vint Integer to make a vint of.
+   * @return Vint as bytes array.
+   */
+  public static byte[] vintToBytes(final long vint) {
+    long i = vint;
+    int size = WritableUtils.getVIntSize(i);
+    byte[] result = new byte[size];
+    int offset = 0;
+    if (i >= -112 && i <= 127) {
+      result[offset] = (byte) i;
+      return result;
+    }
+
+    int len = -112;
+    if (i < 0) {
+      i ^= -1L; // take one's complement'
+      len = -120;
+    }
+
+    long tmp = i;
+    while (tmp != 0) {
+      tmp = tmp >> 8;
+      len--;
+    }
+
+    result[offset++] = (byte) len;
+
+    len = (len < -120) ? -(len + 120) : -(len + 112);
+
+    for (int idx = len; idx != 0; idx--) {
+      int shiftbits = (idx - 1) * 8;
+      long mask = 0xFFL << shiftbits;
+      result[offset++] = (byte) ((i & mask) >> shiftbits);
+    }
+    return result;
+  }
+
+  /**
+   * @param buffer buffer to convert
+   * @return vint bytes as an integer.
+   */
+  public static long bytesToVint(final byte[] buffer) {
+    int offset = 0;
+    byte firstByte = buffer[offset++];
+    int len = WritableUtils.decodeVIntSize(firstByte);
+    if (len == 1) {
+      return firstByte;
+    }
+    long i = 0;
+    for (int idx = 0; idx < len - 1; idx++) {
+      byte b = buffer[offset++];
+      i = i << 8;
+      i = i | (b & 0xFF);
+    }
+    return (WritableUtils.isNegativeVInt(firstByte) ? ~i : i);
+  }
+
+  /**
+   * Reads a zero-compressed encoded long from input stream and returns it.
+   * 
+   * @param buffer Binary array
+   * @param offset Offset into array at which vint begins.
+   * @throws java.io.IOException e
+   * @return deserialized long from stream.
+   */
+  public static long readVLong(final byte[] buffer, final int offset)
+      throws IOException {
+    byte firstByte = buffer[offset];
+    int len = WritableUtils.decodeVIntSize(firstByte);
+    if (len == 1) {
+      return firstByte;
+    }
+    long i = 0;
+    for (int idx = 0; idx < len - 1; idx++) {
+      byte b = buffer[offset + 1 + idx];
+      i = i << 8;
+      i = i | (b & 0xFF);
+    }
+    return (WritableUtils.isNegativeVInt(firstByte) ? ~i : i);
+  }
+
+  /**
+   * @param left left operand
+   * @param right right operand
+   * @return 0 if equal, < 0 if left is less than right, etc.
+   */
+  public static int compareTo(final byte[] left, final byte[] right) {
+    return compareTo(left, 0, left.length, right, 0, right.length);
+  }
+
+  /**
+   * Lexographically compare two arrays.
+   * 
+   * @param b1 left operand
+   * @param b2 right operand
+   * @param s1 Where to start comparing in the left buffer
+   * @param s2 Where to start comparing in the right buffer
+   * @param l1 How much to compare from the left buffer
+   * @param l2 How much to compare from the right buffer
+   * @return 0 if equal, < 0 if left is less than right, etc.
+   */
+  public static int compareTo(byte[] b1, int s1, int l1, byte[] b2, int s2,
+      int l2) {
+    // Bring WritableComparator code local
+    int end1 = s1 + l1;
+    int end2 = s2 + l2;
+    for (int i = s1, j = s2; i < end1 && j < end2; i++, j++) {
+      int a = (b1[i] & 0xff);
+      int b = (b2[j] & 0xff);
+      if (a != b) {
+        return a - b;
+      }
+    }
+    return l1 - l2;
+  }
+
+  /**
+   * @param left left operand
+   * @param right right operand
+   * @return True if equal
+   */
+  public static boolean equals(final byte[] left, final byte[] right) {
+    // Could use Arrays.equals?
+    // noinspection SimplifiableConditionalExpression
+    if (left == null && right == null) {
+      return true;
+    }
+    return (left == null || right == null || (left.length != right.length) ? false
+        : compareTo(left, right) == 0);
+  }
+
+  /**
+   * @param b bytes to hash
+   * @return Runs {@link WritableComparator#hashBytes(byte[], int)} on the
+   *         passed in array. This method is what
+   *         {@link org.apache.hadoop.io.Text} use calculating hash code.
+   */
+  public static int hashCode(final byte[] b) {
+    return hashCode(b, b.length);
+  }
+
+  /**
+   * @param b value
+   * @param length length of the value
+   * @return Runs {@link WritableComparator#hashBytes(byte[], int)} on the
+   *         passed in array. This method is what
+   *         {@link org.apache.hadoop.io.Text} use calculating hash code.
+   */
+  public static int hashCode(final byte[] b, final int length) {
+    return WritableComparator.hashBytes(b, length);
+  }
+
+  /**
+   * @param b bytes to hash
+   * @return A hash of <code>b</code> as an Integer that can be used as key in
+   *         Maps.
+   */
+  public static Integer mapKey(final byte[] b) {
+    return hashCode(b);
+  }
+
+  /**
+   * @param b bytes to hash
+   * @param length length to hash
+   * @return A hash of <code>b</code> as an Integer that can be used as key in
+   *         Maps.
+   */
+  public static Integer mapKey(final byte[] b, final int length) {
+    return hashCode(b, length);
+  }
+
+  /**
+   * @param a lower half
+   * @param b upper half
+   * @return New array that has a in lower half and b in upper half.
+   */
+  public static byte[] add(final byte[] a, final byte[] b) {
+    return add(a, b, Constants.EMPTY_BYTE_ARRAY);
+  }
+
+  /**
+   * @param a first third
+   * @param b second third
+   * @param c third third
+   * @return New array made from a, b and c
+   */
+  public static byte[] add(final byte[] a, final byte[] b, final byte[] c) {
+    byte[] result = new byte[a.length + b.length + c.length];
+    System.arraycopy(a, 0, result, 0, a.length);
+    System.arraycopy(b, 0, result, a.length, b.length);
+    System.arraycopy(c, 0, result, a.length + b.length, c.length);
+    return result;
+  }
+
+  /**
+   * @param a array
+   * @param length amount of bytes to grab
+   * @return First <code>length</code> bytes from <code>a</code>
+   */
+  public static byte[] head(final byte[] a, final int length) {
+    if (a.length < length) {
+      return null;
+    }
+    byte[] result = new byte[length];
+    System.arraycopy(a, 0, result, 0, length);
+    return result;
+  }
+
+  /**
+   * @param a array
+   * @param length amount of bytes to snarf
+   * @return Last <code>length</code> bytes from <code>a</code>
+   */
+  public static byte[] tail(final byte[] a, final int length) {
+    if (a.length < length) {
+      return null;
+    }
+    byte[] result = new byte[length];
+    System.arraycopy(a, a.length - length, result, 0, length);
+    return result;
+  }
+
+  /**
+   * @param a array
+   * @param length new array size
+   * @return Value in <code>a</code> plus <code>length</code> prepended 0 bytes
+   */
+  public static byte[] padHead(final byte[] a, final int length) {
+    byte[] padding = new byte[length];
+    for (int i = 0; i < length; i++) {
+      padding[i] = 0;
+    }
+    return add(padding, a);
+  }
+
+  /**
+   * @param a array
+   * @param length new array size
+   * @return Value in <code>a</code> plus <code>length</code> appended 0 bytes
+   */
+  public static byte[] padTail(final byte[] a, final int length) {
+    byte[] padding = new byte[length];
+    for (int i = 0; i < length; i++) {
+      padding[i] = 0;
+    }
+    return add(a, padding);
+  }
+
+  /**
+   * Split passed range. Expensive operation relatively. Uses BigInteger math.
+   * Useful splitting ranges for MapReduce jobs.
+   * 
+   * @param a Beginning of range
+   * @param b End of range
+   * @param num Number of times to split range. Pass 1 if you want to split the
+   *          range in two; i.e. one split.
+   * @return Array of dividing values
+   */
+  public static byte[][] split(final byte[] a, final byte[] b, final int num) {
+    byte[] aPadded;
+    byte[] bPadded;
+    if (a.length < b.length) {
+      aPadded = padTail(a, b.length - a.length);
+      bPadded = b;
+    } else if (b.length < a.length) {
+      aPadded = a;
+      bPadded = padTail(b, a.length - b.length);
+    } else {
+      aPadded = a;
+      bPadded = b;
+    }
+    if (compareTo(aPadded, bPadded) >= 0) {
+      throw new IllegalArgumentException("b <= a");
+    }
+    if (num <= 0) {
+      throw new IllegalArgumentException("num cannot be < 0");
+    }
+    byte[] prependHeader = { 1, 0 };
+    BigInteger startBI = new BigInteger(add(prependHeader, aPadded));
+    BigInteger stopBI = new BigInteger(add(prependHeader, bPadded));
+    BigInteger diffBI = stopBI.subtract(startBI);
+    BigInteger splitsBI = BigInteger.valueOf(num + 1);
+    if (diffBI.compareTo(splitsBI) < 0) {
+      return null;
+    }
+    BigInteger intervalBI;
+    try {
+      intervalBI = diffBI.divide(splitsBI);
+    } catch (Exception e) {
+      LOG.error("Exception caught during division", e);
+      return null;
+    }
+
+    byte[][] result = new byte[num + 2][];
+    result[0] = a;
+
+    for (int i = 1; i <= num; i++) {
+      BigInteger curBI = startBI
+          .add(intervalBI.multiply(BigInteger.valueOf(i)));
+      byte[] padded = curBI.toByteArray();
+      if (padded[1] == 0)
+        padded = tail(padded, padded.length - 2);
+      else
+        padded = tail(padded, padded.length - 1);
+      result[i] = padded;
+    }
+    result[num + 1] = b;
+    return result;
+  }
+
+  /**
+   * @param t operands
+   * @return Array of byte arrays made from passed array of Text
+   */
+  public static byte[][] toByteArrays(final String[] t) {
+    byte[][] result = new byte[t.length][];
+    for (int i = 0; i < t.length; i++) {
+      result[i] = Bytes.toBytes(t[i]);
+    }
+    return result;
+  }
+
+  /**
+   * @param column operand
+   * @return A byte array of a byte array where first and only entry is
+   *         <code>column</code>
+   */
+  public static byte[][] toByteArrays(final String column) {
+    return toByteArrays(toBytes(column));
+  }
+
+  /**
+   * @param column operand
+   * @return A byte array of a byte array where first and only entry is
+   *         <code>column</code>
+   */
+  public static byte[][] toByteArrays(final byte[] column) {
+    byte[][] result = new byte[1][];
+    result[0] = column;
+    return result;
+  }
+
+  /**
+   * Binary search for keys in indexes.
+   * 
+   * @param arr array of byte arrays to search for
+   * @param key the key you want to find
+   * @param offset the offset in the key you want to find
+   * @param length the length of the key
+   * @param comparator a comparator to compare.
+   * @return index of key
+   */
+  public static int binarySearch(byte[][] arr, byte[] key, int offset,
+      int length, RawComparator<byte[]> comparator) {
+    int low = 0;
+    int high = arr.length - 1;
+
+    while (low <= high) {
+      int mid = (low + high) >>> 1;
+      // we have to compare in this order, because the comparator order
+      // has special logic when the 'left side' is a special key.
+      int cmp = comparator.compare(key, offset, length, arr[mid], 0,
+          arr[mid].length);
+      // key lives above the midpoint
+      if (cmp > 0)
+        low = mid + 1;
+      // key lives below the midpoint
+      else if (cmp < 0)
+        high = mid - 1;
+      // BAM. how often does this really happen?
+      else
+        return mid;
+    }
+    return -(low + 1);
+  }
+
+  /**
+   * Bytewise binary increment/deincrement of long contained in byte array on
+   * given amount.
+   * 
+   * @param value - array of bytes containing long (length <= SIZEOF_LONG)
+   * @param amount value will be incremented on (deincremented if negative)
+   * @return array of bytes containing incremented long (length == SIZEOF_LONG)
+   * @throws IOException - if value.length > SIZEOF_LONG
+   */
+  public static byte[] incrementBytes(byte[] value, long amount)
+      throws IOException {
+    byte[] val = value;
+    if (val.length < SIZEOF_LONG) {
+      // Hopefully this doesn't happen too often.
+      byte[] newvalue;
+      if (val[0] < 0) {
+        newvalue = new byte[] { -1, -1, -1, -1, -1, -1, -1, -1 };
+      } else {
+        newvalue = new byte[SIZEOF_LONG];
+      }
+      System.arraycopy(val, 0, newvalue, newvalue.length - val.length,
+          val.length);
+      val = newvalue;
+    } else if (val.length > SIZEOF_LONG) {
+      throw new IllegalArgumentException("Increment Bytes - value too big: "
+          + val.length);
+    }
+    if (amount == 0)
+      return val;
+    if (val[0] < 0) {
+      return binaryIncrementNeg(val, amount);
+    }
+    return binaryIncrementPos(val, amount);
+  }
+
+  /* increment/deincrement for positive value */
+  private static byte[] binaryIncrementPos(byte[] value, long amount) {
+    long amo = amount;
+    int sign = 1;
+    if (amount < 0) {
+      amo = -amount;
+      sign = -1;
+    }
+    for (int i = 0; i < value.length; i++) {
+      int cur = ((int) amo % 256) * sign;
+      amo = (amo >> 8);
+      int val = value[value.length - i - 1] & 0x0ff;
+      int total = val + cur;
+      if (total > 255) {
+        amo += sign;
+        total %= 256;
+      } else if (total < 0) {
+        amo -= sign;
+      }
+      value[value.length - i - 1] = (byte) total;
+      if (amo == 0)
+        return value;
+    }
+    return value;
+  }
+
+  /* increment/deincrement for negative value */
+  private static byte[] binaryIncrementNeg(byte[] value, long amount) {
+    long amo = amount;
+    int sign = 1;
+    if (amount < 0) {
+      amo = -amount;
+      sign = -1;
+    }
+    for (int i = 0; i < value.length; i++) {
+      int cur = ((int) amo % 256) * sign;
+      amo = (amo >> 8);
+      int val = ((~value[value.length - i - 1]) & 0x0ff) + 1;
+      int total = cur - val;
+      if (total >= 0) {
+        amo += sign;
+      } else if (total < -256) {
+        amo -= sign;
+        total %= 256;
+      }
+      value[value.length - i - 1] = (byte) total;
+      if (amo == 0)
+        return value;
+    }
+    return value;
+  }
+
+}

Added: incubator/hama/trunk/core/src/main/java/org/apache/hama/util/ClusterUtil.java
URL: http://svn.apache.org/viewvc/incubator/hama/trunk/core/src/main/java/org/apache/hama/util/ClusterUtil.java?rev=1152788&view=auto
==============================================================================
--- incubator/hama/trunk/core/src/main/java/org/apache/hama/util/ClusterUtil.java (added)
+++ incubator/hama/trunk/core/src/main/java/org/apache/hama/util/ClusterUtil.java Mon Aug  1 14:12:46 2011
@@ -0,0 +1,116 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hama.util;
+
+import java.io.IOException;
+import java.util.List;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hama.HamaConfiguration;
+import org.apache.hama.bsp.BSPMaster;
+import org.apache.hama.bsp.GroomServer;
+
+public class ClusterUtil {
+  private static final Log LOG = LogFactory.getLog(ClusterUtil.class);
+  
+  /**
+   * Data Structure to hold GroomServer Thread and GroomServer instance
+   */
+  public static class GroomServerThread extends Thread {
+    private final GroomServer groomServer;
+
+    public GroomServerThread(final GroomServer r, final int index) {
+      super(r, "GroomServer:" + index);
+      this.groomServer = r;
+    }
+
+    /** @return the groom server */
+    public GroomServer getGroomServer() {
+      return this.groomServer;
+    }
+
+    /**
+     * Block until the groom server has come online, indicating it is ready
+     * to be used.
+     */
+    public void waitForServerOnline() {
+      while (!groomServer.isRunning()) {
+        try {
+          Thread.sleep(1000);
+        } catch (InterruptedException e) {
+          // continue waiting
+        }
+      }
+    }
+  }
+
+  /**
+   * Creates a {@link GroomServerThread}.
+   * Call 'start' on the returned thread to make it run.
+   * @param c Configuration to use.
+   * @param hrsc Class to create.
+   * @param index Used distingushing the object returned.
+   * @throws IOException
+   * @return Groom server added.
+   */
+  public static ClusterUtil.GroomServerThread createGroomServerThread(final Configuration c,
+    final Class<? extends GroomServer> hrsc, final int index)
+  throws IOException {
+    GroomServer server;
+      try {
+        server = hrsc.getConstructor(Configuration.class).newInstance(c);
+      } catch (Exception e) {
+        IOException ioe = new IOException();
+        ioe.initCause(e);
+        throw ioe;
+      }
+      return new ClusterUtil.GroomServerThread(server, index);
+  }
+
+  /**
+   * Start the cluster.
+   * @param m
+   * @param conf 
+   * @param groomservers
+   * @return Address to use contacting master.
+   * @throws InterruptedException 
+   * @throws IOException 
+   */
+  public static String startup(final BSPMaster m,
+      final List<ClusterUtil.GroomServerThread> groomservers, Configuration conf) throws IOException, InterruptedException {
+    if (m != null) {
+      BSPMaster.startMaster((HamaConfiguration) conf);
+    }
+
+    if (groomservers != null) {
+      for (ClusterUtil.GroomServerThread t: groomservers) {
+        t.start();
+      }
+    }
+    
+    return m == null? null: BSPMaster.getAddress(conf).getHostName();
+  }
+
+  public static void shutdown(BSPMaster master,
+      List<GroomServerThread> groomThreads, Configuration conf) {
+    LOG.debug("Shutting down HAMA Cluster");
+    // TODO: 
+  }
+}

Added: incubator/hama/trunk/core/src/main/java/org/apache/hama/util/RandomVariable.java
URL: http://svn.apache.org/viewvc/incubator/hama/trunk/core/src/main/java/org/apache/hama/util/RandomVariable.java?rev=1152788&view=auto
==============================================================================
--- incubator/hama/trunk/core/src/main/java/org/apache/hama/util/RandomVariable.java (added)
+++ incubator/hama/trunk/core/src/main/java/org/apache/hama/util/RandomVariable.java Mon Aug  1 14:12:46 2011
@@ -0,0 +1,227 @@
+/**
+ * Copyright 2007 The Apache Software Foundation
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hama.util;
+
+/**
+ * The RandomVaraibale Class provides static methods for generating random
+ * numbers.
+ */
+public class RandomVariable {
+  
+  /**
+   * Generate a random number between 0 and 1.
+   * 
+   * @return a double between 0 and 1.
+   */
+  public static double rand() {
+    double x = Math.random();
+    return x;
+  }
+
+  /**
+   * Generate a random integer.
+   * 
+   * @param i0 min of the random variable.
+   * @param i1 max of the random variable.
+   * @return an int between i0 and i1.
+   */
+  public static int randInt(int i0, int i1) {
+    double x = rand();
+    int i = i0 + (int) Math.floor((i1 - i0 + 1) * x);
+    return i;
+  }
+  
+  /**
+    * Generate a random string using the specified prefix and a fixed length. 
+    * @param prefix
+    *        the specified string prefix.
+    * @param length
+    *        the length of the string to be appended.
+    * @return random string.
+    */
+  public static String randString(String prefix, int length) {
+    StringBuilder result = new StringBuilder(prefix);
+    for (int i = 0; i < length; i++) {
+      char ch = (char) ((Math.random() * 26) + 97);
+      result.append(ch);
+    }
+      
+    return result.toString();
+  }
+
+  /**
+   * Generate a random number from a uniform random variable.
+   * 
+   * @param min min of the random variable.
+   * @param max max of the random variable.
+   * @return a double.
+   */
+  public static double uniform(double min, double max) {
+    double x = min + (max - min) * rand();
+    return x;
+  }
+
+  /**
+   * Generate a random number from a discrete random variable.
+   * 
+   * @param values discrete values.
+   * @param prob probability of each value.
+   * @return a double.
+   */
+  public static double dirac(double[] values, double[] prob) {
+    double[] prob_cumul = new double[values.length];
+    prob_cumul[0] = prob[0];
+    for (int i = 1; i < values.length; i++) {
+      prob_cumul[i] = prob_cumul[i - 1] + prob[i];
+    }
+    double y = rand();
+    double x = 0;
+    for (int i = 0; i < values.length - 1; i++) {
+      if ((y > prob_cumul[i]) && (y < prob_cumul[i + 1])) {
+        x = values[i];
+      }
+    }
+    return x;
+  }
+
+  /**
+   * Generate a random number from a Gaussian (Normal) random variable.
+   * 
+   * @param mu mean of the random variable.
+   * @param sigma standard deviation of the random variable.
+   * @return a double.
+   */
+  public static double normal(double mu, double sigma) {
+    double x = mu + sigma * Math.cos(2 * Math.PI * rand())
+        * Math.sqrt(-2 * Math.log(rand()));
+    return x;
+  }
+
+  /**
+   * Generate a random number from a Chi-2 random variable.
+   * 
+   * @param n degrees of freedom of the chi2 random variable.
+   * @return a double.
+   */
+  public static double chi2(int n) {
+    double x = 0;
+    for (int i = 0; i < n; i++) {
+      double norm = normal(0, 1);
+      x += norm * norm;
+    }
+    return x;
+  }
+
+  /**
+   * Generate a random number from a LogNormal random variable.
+   * 
+   * @param mu mean of the Normal random variable.
+   * @param sigma standard deviation of the Normal random variable.
+   * @return a double.
+   */
+  public static double logNormal(double mu, double sigma) {
+    double x = mu + sigma * Math.cos(2 * Math.PI * rand())
+        * Math.sqrt(-2 * Math.log(rand()));
+    return x;
+  }
+
+  /**
+   * Generate a random number from an exponantial random variable (Mean =
+   * 1/lambda, variance = 1/lambda^2).
+   * 
+   * @param lambda parmaeter of the exponential random variable.
+   * @return a double.
+   */
+  public static double exponential(double lambda) {
+    double x = -1 / lambda * Math.log(rand());
+    return x;
+  }
+
+  /**
+   * Generate a random number from a symetric triangular random variable.
+   * 
+   * @param min min of the random variable.
+   * @param max max of the random variable.
+   * @return a double.
+   */
+  public static double triangular(double min, double max) {
+    double x = min / 2 + (max - min) * rand() / 2 + min / 2 + (max - min)
+        * rand() / 2;
+    return x;
+  }
+
+  /**
+   * Generate a random number from a non-symetric triangular random variable.
+   * 
+   * @param min min of the random variable.
+   * @param med value of the random variable with max density.
+   * @param max max of the random variable.
+   * @return a double.
+   */
+  public static double triangular(double min, double med, double max) {
+    double y = rand();
+    double x = (y < ((med - min) / (max - min))) ? (min + Math.sqrt(y
+        * (max - min) * (med - min))) : (max - Math.sqrt((1 - y) * (max - min)
+        * (max - med)));
+    return x;
+  }
+
+  /**
+   * Generate a random number from a beta random variable.
+   * 
+   * @param a first parameter of the Beta random variable.
+   * @param b second parameter of the Beta random variable.
+   * @return a double.
+   */
+  public static double beta(double a, double b) {
+    double try_x;
+    double try_y;
+    do {
+      try_x = Math.pow(rand(), 1 / a);
+      try_y = Math.pow(rand(), 1 / b);
+    } while ((try_x + try_y) > 1);
+    return try_x / (try_x + try_y);
+  }
+
+  /**
+   * Generate a random number from a Cauchy random variable (Mean = Inf, and
+   * Variance = Inf).
+   * 
+   * @param mu median of the Weibull random variable
+   * @param sigma second parameter of the Cauchy random variable.
+   * @return a double.
+   */
+  public static double cauchy(double mu, double sigma) {
+    double x = sigma * Math.tan(Math.PI * (rand() - 0.5)) + mu;
+    return x;
+  }
+
+  /**
+   * Generate a random number from a Weibull random variable.
+   * 
+   * @param lambda first parameter of the Weibull random variable.
+   * @param c second parameter of the Weibull random variable.
+   * @return a double.
+   */
+  public static double weibull(double lambda, double c) {
+    double x = Math.pow(-Math.log(1 - rand()), 1 / c) / lambda;
+    return x;
+  }
+}

Added: incubator/hama/trunk/core/src/main/java/org/apache/hama/util/RunJar.java
URL: http://svn.apache.org/viewvc/incubator/hama/trunk/core/src/main/java/org/apache/hama/util/RunJar.java?rev=1152788&view=auto
==============================================================================
--- incubator/hama/trunk/core/src/main/java/org/apache/hama/util/RunJar.java (added)
+++ incubator/hama/trunk/core/src/main/java/org/apache/hama/util/RunJar.java Mon Aug  1 14:12:46 2011
@@ -0,0 +1,151 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hama.util;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.lang.reflect.Array;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
+
+import org.apache.hadoop.fs.FileUtil;
+
+/**
+ * Run a Hama job jar.
+ */
+public class RunJar {
+
+  /** Unpack a jar file into a directory. */
+  public static void unJar(File jarFile, File toDir) throws IOException {
+    JarFile jar = new JarFile(jarFile);
+    try {
+      Enumeration<JarEntry> entries = jar.entries();
+      while (entries.hasMoreElements()) {
+        JarEntry entry = (JarEntry) entries.nextElement();
+        if (!entry.isDirectory()) {
+          InputStream in = jar.getInputStream(entry);
+          try {
+            File file = new File(toDir, entry.getName());
+            file.getParentFile().mkdirs();
+            OutputStream out = new FileOutputStream(file);
+            try {
+              byte[] buffer = new byte[8192];
+              int i;
+              while ((i = in.read(buffer)) != -1) {
+                out.write(buffer, 0, i);
+              }
+            } finally {
+              out.close();
+            }
+          } finally {
+            in.close();
+          }
+        }
+      }
+    } finally {
+      jar.close();
+    }
+  }
+
+  /**
+   * Run a Hama job jar. If the main class is not in the jar's manifest, then
+   * it must be provided on the command line.
+   */
+  public static void main(String[] args) throws Throwable {
+    String usage = "Usage: hama jar <jar> [mainClass] args...";
+
+    if (args.length < 1) {
+      System.err.println(usage);
+      System.exit(-1);
+    }
+
+    int firstArg = 0;
+    String fileName = args[firstArg++];
+    File file = new File(fileName);
+    String mainClassName = null;
+
+    JarFile jarFile = new JarFile(fileName);
+    Manifest manifest = jarFile.getManifest();
+    if (manifest != null) {
+      mainClassName = manifest.getMainAttributes().getValue("Main-Class");
+    }
+    jarFile.close();
+
+    if (mainClassName == null) {
+      if (args.length < 2) {
+        System.err.println(usage);
+        System.exit(-1);
+      }
+      mainClassName = args[firstArg++];
+    }
+    mainClassName = mainClassName.replaceAll("/", ".");
+
+    final File workDir = File.createTempFile("hama-unjar", "");
+    workDir.delete();
+    workDir.mkdirs();
+
+    Runtime.getRuntime().addShutdownHook(new Thread() {
+      public void run() {
+        try {
+          FileUtil.fullyDelete(workDir);
+        } catch (IOException e) {
+        }
+      }
+    });
+
+    unJar(file, workDir);
+
+    List<URL> classPath = new ArrayList<URL>();
+    classPath.add(new File(workDir + "/").toURI().toURL());
+    classPath.add(file.toURI().toURL());
+    classPath.add(new File(workDir, "classes/").toURI().toURL());
+    File[] libs = new File(workDir, "lib").listFiles();
+    if (libs != null) {
+      for (int i = 0; i < libs.length; i++) {
+        classPath.add(libs[i].toURI().toURL());
+      }
+    }
+    ClassLoader loader = new URLClassLoader((URL[]) classPath
+        .toArray(new URL[0]));
+
+    Thread.currentThread().setContextClassLoader(loader);
+    Class<?> mainClass = loader.loadClass(mainClassName);
+    Method main = mainClass.getMethod("main", new Class[] { Array.newInstance(
+        String.class, 0).getClass() });
+    String[] newArgs = (String[]) Arrays.asList(args).subList(firstArg,
+        args.length).toArray(new String[0]);
+    try {
+      main.invoke(null, new Object[] { newArgs });
+    } catch (InvocationTargetException e) {
+      throw e.getTargetException();
+    }
+  }
+
+}

Added: incubator/hama/trunk/core/src/main/java/org/apache/hama/util/VersionInfo.java
URL: http://svn.apache.org/viewvc/incubator/hama/trunk/core/src/main/java/org/apache/hama/util/VersionInfo.java?rev=1152788&view=auto
==============================================================================
--- incubator/hama/trunk/core/src/main/java/org/apache/hama/util/VersionInfo.java (added)
+++ incubator/hama/trunk/core/src/main/java/org/apache/hama/util/VersionInfo.java Mon Aug  1 14:12:46 2011
@@ -0,0 +1,28 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hama.util;
+
+/**
+ * A version information class.
+ */
+public class VersionInfo {
+
+  public static void main(String[] args) {
+    System.out.println("Apache Hama - 0.4");
+  }
+}

Added: incubator/hama/trunk/core/src/main/java/org/apache/hama/util/package.html
URL: http://svn.apache.org/viewvc/incubator/hama/trunk/core/src/main/java/org/apache/hama/util/package.html?rev=1152788&view=auto
==============================================================================
--- incubator/hama/trunk/core/src/main/java/org/apache/hama/util/package.html (added)
+++ incubator/hama/trunk/core/src/main/java/org/apache/hama/util/package.html Mon Aug  1 14:12:46 2011
@@ -0,0 +1,23 @@
+<html>
+
+<!--
+   Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  See the NOTICE file distributed with
+   this work for additional information regarding copyright ownership.
+   The ASF licenses this file to You under the Apache License, Version 2.0
+   (the "License"); you may not use this file except in compliance with
+   the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+-->
+
+<body>
+Common utilities. 
+</body>
+</html>

Added: incubator/hama/trunk/core/src/main/java/org/apache/hama/zookeeper/QuorumPeer.java
URL: http://svn.apache.org/viewvc/incubator/hama/trunk/core/src/main/java/org/apache/hama/zookeeper/QuorumPeer.java?rev=1152788&view=auto
==============================================================================
--- incubator/hama/trunk/core/src/main/java/org/apache/hama/zookeeper/QuorumPeer.java (added)
+++ incubator/hama/trunk/core/src/main/java/org/apache/hama/zookeeper/QuorumPeer.java Mon Aug  1 14:12:46 2011
@@ -0,0 +1,354 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hama.zookeeper;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.PrintWriter;
+import java.net.InetAddress;
+import java.net.NetworkInterface;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Properties;
+import java.util.Map.Entry;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.net.DNS;
+import org.apache.hadoop.util.StringUtils;
+import org.apache.hama.Constants;
+import org.apache.hama.HamaConfiguration;
+import org.apache.zookeeper.server.ServerConfig;
+import org.apache.zookeeper.server.ZooKeeperServerMain;
+import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
+import org.apache.zookeeper.server.quorum.QuorumPeerMain;
+
+/**
+ * This class starts and runs the QuorumPeers
+ */
+public class QuorumPeer implements Constants {
+  private static final Log LOG = LogFactory.getLog(QuorumPeer.class);
+
+  private static final String VARIABLE_START = "${";
+  private static final int VARIABLE_START_LENGTH = VARIABLE_START.length();
+  private static final String VARIABLE_END = "}";
+  private static final int VARIABLE_END_LENGTH = VARIABLE_END.length();
+
+  private static final String ZK_CFG_PROPERTY = "hama.zookeeper.property.";
+  private static final int ZK_CFG_PROPERTY_SIZE = ZK_CFG_PROPERTY.length();
+
+  /**
+   * Parse ZooKeeper configuration from Hama XML config and run a QuorumPeer.
+   * @param baseConf Hadoop Configuration.
+   */
+  public static void run(Configuration baseConf) {
+    Configuration conf = new HamaConfiguration(baseConf);
+    try {
+      Properties zkProperties = makeZKProps(conf);
+      writeMyID(zkProperties);
+      QuorumPeerConfig zkConfig = new QuorumPeerConfig();
+      zkConfig.parseProperties(zkProperties);
+      runZKServer(zkConfig);
+    } catch (Exception e) {
+      LOG.error("Exception during ZooKeeper startup - exiting...",e);
+      System.exit(-1);
+    }
+  }
+
+  private static void runZKServer(QuorumPeerConfig zkConfig) throws UnknownHostException, IOException {
+    if (zkConfig.isDistributed()) {
+      QuorumPeerMain qp = new QuorumPeerMain();
+      qp.runFromConfig(zkConfig);
+    } else {
+      ZooKeeperServerMain zk = new ZooKeeperServerMain();
+      ServerConfig serverConfig = new ServerConfig();
+      serverConfig.readFrom(zkConfig);
+      zk.runFromConfig(serverConfig);
+    }
+  }
+
+  private static boolean addressIsLocalHost(String address) {
+    return address.equals("localhost") || address.equals("127.0.0.1");
+  }
+
+  private static void writeMyID(Properties properties) throws IOException {
+    long myId = -1;
+
+    Configuration conf = new HamaConfiguration();
+    String myAddress = DNS.getDefaultHost(
+        conf.get("hama.zookeeper.dns.interface","default"),
+        conf.get("hama.zookeeper.dns.nameserver","default"));
+
+    List<String> ips = new ArrayList<String>();
+
+    // Add what could be the best (configured) match
+    ips.add(myAddress.contains(".") ?
+        myAddress :
+        StringUtils.simpleHostname(myAddress));
+
+    // For all nics get all hostnames and IPs
+    Enumeration<?> nics = NetworkInterface.getNetworkInterfaces();
+    while(nics.hasMoreElements()) {
+      Enumeration<?> rawAdrs =
+          ((NetworkInterface)nics.nextElement()).getInetAddresses();
+      while(rawAdrs.hasMoreElements()) {
+        InetAddress inet = (InetAddress) rawAdrs.nextElement();
+        ips.add(StringUtils.simpleHostname(inet.getHostName()));
+        ips.add(inet.getHostAddress());
+      }
+    }
+
+    for (Entry<Object, Object> entry : properties.entrySet()) {
+      String key = entry.getKey().toString().trim();
+      String value = entry.getValue().toString().trim();
+ 
+      if (key.startsWith("server.")) {
+        int dot = key.indexOf('.');
+        long id = Long.parseLong(key.substring(dot + 1));
+        String[] parts = value.split(":");
+        String address = parts[0];
+        if (addressIsLocalHost(address) || ips.contains(address)) {
+          myId = id;
+          break;
+        }
+      }
+    }
+
+    if (myId == -1) {
+      throw new IOException("Could not find my address: " + myAddress +
+                            " in list of ZooKeeper quorum servers");
+    }
+
+    String dataDirStr = properties.get("dataDir").toString().trim();
+    File dataDir = new File(dataDirStr);
+    if (!dataDir.isDirectory()) {
+      if (!dataDir.mkdirs()) {
+        throw new IOException("Unable to create data dir " + dataDir);
+      }
+    }
+
+    File myIdFile = new File(dataDir, "myid");
+    PrintWriter w = new PrintWriter(myIdFile);
+    w.println(myId);
+    w.close();
+  }
+
+  /**
+   * Make a Properties object holding ZooKeeper config equivalent to zoo.cfg.
+   * If there is a zoo.cfg in the classpath, simply read it in. Otherwise parse
+   * the corresponding config options from the Hama XML configs and generate
+   * the appropriate ZooKeeper properties.
+   * @param conf Configuration to read from.
+   * @return Properties holding mappings representing ZooKeeper zoo.cfg file.
+   */
+  public static Properties makeZKProps(Configuration conf) {
+    // First check if there is a zoo.cfg in the CLASSPATH. If so, simply read
+    // it and grab its configuration properties.
+    ClassLoader cl = QuorumPeer.class.getClassLoader();
+    InputStream inputStream = cl.getResourceAsStream(ZOOKEEPER_CONFIG_NAME);
+    if (inputStream != null) {
+      try {
+        return parseZooCfg(conf, inputStream);
+      } catch (IOException e) {
+        LOG.warn("Cannot read " + ZOOKEEPER_CONFIG_NAME +
+                 ", loading from XML files", e);
+      }
+    }
+
+    // Otherwise, use the configuration options from Hama's XML files.
+    Properties zkProperties = new Properties();
+
+    // Set the max session timeout from the provided client-side timeout
+    zkProperties.setProperty("maxSessionTimeout",
+        conf.get(Constants.ZOOKEEPER_SESSION_TIMEOUT, "1200000"));
+    
+    // Directly map all of the hama.zookeeper.property.KEY properties.
+    for (Entry<String, String> entry : conf) {
+      String key = entry.getKey();
+      if (key.startsWith(ZK_CFG_PROPERTY)) {
+        String zkKey = key.substring(ZK_CFG_PROPERTY_SIZE);
+        String value = entry.getValue();
+        // If the value has variables substitutions, need to do a get.
+        if (value.contains(VARIABLE_START)) {
+          value = conf.get(key);
+        }
+        zkProperties.put(zkKey, value);
+      }
+    }
+
+    // If clientPort is not set, assign the default
+    if (zkProperties.getProperty(ZOOKEEPER_CLIENT_PORT) == null) {
+      zkProperties.put(ZOOKEEPER_CLIENT_PORT, DEFAULT_ZOOKEEPER_CLIENT_PORT);
+    }
+
+    // Create the server.X properties.
+    int peerPort = conf.getInt("hama.zookeeper.peerport", 2888);
+    int leaderPort = conf.getInt("hama.zookeeper.leaderport", 3888);
+
+    String[] serverHosts = conf.getStrings(ZOOKEEPER_QUORUM, "localhost");
+    for (int i = 0; i < serverHosts.length; ++i) {
+      String serverHost = serverHosts[i];
+      String address = serverHost + ":" + peerPort + ":" + leaderPort;
+      String key = "server." + i;
+      zkProperties.put(key, address);
+    }
+
+    return zkProperties;
+  }
+
+  /**
+   * Parse ZooKeeper's zoo.cfg, injecting Hama Configuration variables in.
+   * This method is used for testing so we can pass our own InputStream.
+   * @param conf Configuration to use for injecting variables.
+   * @param inputStream InputStream to read from.
+   * @return Properties parsed from config stream with variables substituted.
+   * @throws IOException if anything goes wrong parsing config
+   */
+  public static Properties parseZooCfg(Configuration conf,
+      InputStream inputStream) throws IOException {
+    Properties properties = new Properties();
+    try {
+      properties.load(inputStream);
+    } catch (IOException e) {
+      String msg = "fail to read properties from " + ZOOKEEPER_CONFIG_NAME;
+      LOG.fatal(msg);
+      throw new IOException(msg, e);
+    }
+    for (Entry<Object, Object> entry : properties.entrySet()) {
+      String value = entry.getValue().toString().trim();
+      String key = entry.getKey().toString().trim();
+      StringBuilder newValue = new StringBuilder();
+      int varStart = value.indexOf(VARIABLE_START);
+      int varEnd = 0;
+      while (varStart != -1) {
+        varEnd = value.indexOf(VARIABLE_END, varStart);
+        if (varEnd == -1) {
+          String msg = "variable at " + varStart + " has no end marker";
+          LOG.fatal(msg);
+          throw new IOException(msg);
+        }
+        String variable = value.substring(varStart + VARIABLE_START_LENGTH, varEnd);
+
+        String substituteValue = System.getProperty(variable);
+        if (substituteValue == null) {
+          substituteValue = conf.get(variable);
+        }
+        if (substituteValue == null) {
+          String msg = "variable " + variable + " not set in system property "
+                     + "or hama configs";
+          LOG.fatal(msg);
+          throw new IOException(msg);
+        }
+
+        newValue.append(substituteValue);
+
+        varEnd += VARIABLE_END_LENGTH;
+        varStart = value.indexOf(VARIABLE_START, varEnd);
+      }
+      // Special case for 'hama.cluster.distributed' property being 'true'
+      if (key.startsWith("server.")) {
+        if (conf.get(CLUSTER_DISTRIBUTED).equals(CLUSTER_IS_DISTRIBUTED) &&
+            value.startsWith("localhost")) {
+          String msg = "The server in zoo.cfg cannot be set to localhost " +
+              "in a fully-distributed setup because it won't be reachable. " +
+              "See \"Getting Started\" for more information.";
+          LOG.fatal(msg);
+          throw new IOException(msg);
+        }
+      }
+      newValue.append(value.substring(varEnd));
+      properties.setProperty(key, newValue.toString());
+    }
+    return properties;
+  }
+  
+  /**
+   * Return the ZK Quorum servers string given zk properties returned by
+   * makeZKProps
+   * @param properties
+   * @return Quorum servers String
+   */
+  public static String getZKQuorumServersString(Properties properties) {
+    String clientPort = null;
+    List<String> servers = new ArrayList<String>();
+
+    // The clientPort option may come after the server.X hosts, so we need to
+    // grab everything and then create the final host:port comma separated list.
+    boolean anyValid = false;
+    for (Entry<Object,Object> property : properties.entrySet()) {
+      String key = property.getKey().toString().trim();
+      String value = property.getValue().toString().trim();
+      if (key.equals("clientPort")) {
+        clientPort = value;
+      }
+      else if (key.startsWith("server.")) {
+        String host = value.substring(0, value.indexOf(':'));
+        servers.add(host);
+        try {
+          //noinspection ResultOfMethodCallIgnored
+          InetAddress.getByName(host);
+          anyValid = true;
+        } catch (UnknownHostException e) {
+          LOG.warn(StringUtils.stringifyException(e));
+        }
+      }
+    }
+
+    if (!anyValid) {
+      LOG.error("no valid quorum servers found in " + Constants.ZOOKEEPER_CONFIG_NAME);
+      return null;
+    }
+
+    if (clientPort == null) {
+      LOG.error("no clientPort found in " + Constants.ZOOKEEPER_CONFIG_NAME);
+      return null;
+    }
+
+    if (servers.isEmpty()) {
+      LOG.fatal("No server.X lines found in conf/zoo.cfg. Hama must have a " +
+                "ZooKeeper cluster configured for its operation.");
+      return null;
+    }
+
+    StringBuilder hostPortBuilder = new StringBuilder();
+    for (int i = 0; i < servers.size(); ++i) {
+      String host = servers.get(i);
+      if (i > 0) {
+        hostPortBuilder.append(',');
+      }
+      hostPortBuilder.append(host);
+      hostPortBuilder.append(':');
+      hostPortBuilder.append(clientPort);
+    }
+
+    return hostPortBuilder.toString();
+  }
+  
+  /**
+   * Return the ZK Quorum servers string given the specified configuration.
+   * @param conf
+   * @return Quorum servers
+   */
+  public static String getZKQuorumServersString(Configuration conf) {
+    return getZKQuorumServersString(makeZKProps(conf));
+  }
+}

Added: incubator/hama/trunk/core/src/main/java/org/apache/hama/zookeeper/ZKServerTool.java
URL: http://svn.apache.org/viewvc/incubator/hama/trunk/core/src/main/java/org/apache/hama/zookeeper/ZKServerTool.java?rev=1152788&view=auto
==============================================================================
--- incubator/hama/trunk/core/src/main/java/org/apache/hama/zookeeper/ZKServerTool.java (added)
+++ incubator/hama/trunk/core/src/main/java/org/apache/hama/zookeeper/ZKServerTool.java Mon Aug  1 14:12:46 2011
@@ -0,0 +1,51 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.hama.zookeeper;
+
+import java.util.Properties;
+import java.util.Map.Entry;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hama.HamaConfiguration;
+
+/**
+ * A tool class for Zookeeper use.
+ */
+public class ZKServerTool {
+  
+  /**
+   * Run the tool.
+   * 
+   * @param args Command line arguments. First arg is path to zookeepers file.
+   */
+  public static void main(String args[]) {
+    Configuration conf = new HamaConfiguration();
+    // Note that we do not simply grab the property ZOOKEEPER_QUORUM from
+    // the HamaConfiguration because the user may be using a zoo.cfg file.
+    Properties zkProps = QuorumPeer.makeZKProps(conf);
+    for (Entry<Object, Object> entry : zkProps.entrySet()) {
+      String key = entry.getKey().toString().trim();
+      String value = entry.getValue().toString().trim();
+      if (key.startsWith("server.")) {
+        String[] parts = value.split(":");
+        String host = parts[0];
+        System.out.println(host);
+      }
+    }
+  }
+}

Added: incubator/hama/trunk/core/src/main/java/org/apache/hama/zookeeper/package.html
URL: http://svn.apache.org/viewvc/incubator/hama/trunk/core/src/main/java/org/apache/hama/zookeeper/package.html?rev=1152788&view=auto
==============================================================================
--- incubator/hama/trunk/core/src/main/java/org/apache/hama/zookeeper/package.html (added)
+++ incubator/hama/trunk/core/src/main/java/org/apache/hama/zookeeper/package.html Mon Aug  1 14:12:46 2011
@@ -0,0 +1,23 @@
+<html>
+
+<!--
+   Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  See the NOTICE file distributed with
+   this work for additional information regarding copyright ownership.
+   The ASF licenses this file to You under the Apache License, Version 2.0
+   (the "License"); you may not use this file except in compliance with
+   the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+-->
+
+<body>
+Tools to start the ZooKeeper server and quorum peers.
+</body>
+</html>

Added: incubator/hama/trunk/core/src/main/java/org/apache/overview.html
URL: http://svn.apache.org/viewvc/incubator/hama/trunk/core/src/main/java/org/apache/overview.html?rev=1152788&view=auto
==============================================================================
--- incubator/hama/trunk/core/src/main/java/org/apache/overview.html (added)
+++ incubator/hama/trunk/core/src/main/java/org/apache/overview.html Mon Aug  1 14:12:46 2011
@@ -0,0 +1,152 @@
+<html>
+
+<!--
+   Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  See the NOTICE file distributed with
+   this work for additional information regarding copyright ownership.
+   The ASF licenses this file to You under the Apache License, Version 2.0
+   (the "License"); you may not use this file except in compliance with
+   the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+-->
+
+<head>
+   <title>Hama</title>
+</head>
+<body>
+Hama is a distributed computing framework based on BSP (Bulk Synchronous Parallel) computing techniques for massive scientific computations.
+
+<h2 id="Requirements">Requirements</h2>
+<ul>
+<li>hadoop-0.20.x for HDFS</li>
+<li>Sun Java JDK 1.6.x or higher version</li>
+</ul>
+
+<h2 id="Startup_script">Startup script</h2>
+The <i>$HAMA_HOME/bin</i> directory contains some script used to start up the Hama daemons.
+<ul>
+<li>
+<i>start-bspd.sh</i> - Starts all Hama daemons, the BSPMaster, GroomServers and Zookeeper.
+</li>
+</ul>
+
+<h2 id="Configuration_files">Configuration files</h2>
+
+The <i>$HAMA_HOME/conf</i> directory contains some configuration files for Hama. These are:
+<ul>
+<li>
+<i>hama-env.sh</i> - This file contains some environment variable settings used by Hama. You can use these to affect some aspects of Hama daemon behavior, 
+such as where log files are stored, the maximum amount of heap used etc. The only variable you should need to change in this file is JAVA_HOME, 
+which specifies the path to the Java 1.5.x installation used by Hama.
+</li>
+<li>
+<i>groomservers</i> - This file lists the hosts, one per line, where the GroomServer daemons will run. By default this contains the single entry localhost.</li>
+<li>
+<i>hama-default.xml</i> - This file contains generic default settings for Hama daemons.&nbsp;<strong>Do not modify this file</strong>.
+</li>
+<li>
+<i>hama-site.xml</i> - This file contains site specific settings for all Hama daemons and BSP jobs. 
+This file is empty by default. Settings in this file override those in hama-default.xml. 
+This file should contain settings that must be respected by all servers and clients in a Hama installation.
+</li>
+</ul>
+
+<h2 id="Setting_up_Hama">Setting up Hama</h2>
+This section describes how to get started by setting up a Hama cluster.
+<ul>
+<li>
+<strong>BSPMaster and Zookeeper settings</strong> - Figure out where to run your HDFS namenode and BSPMaster. 
+Set the variable <i>bsp.master.address</i> to the BSPMaster's intended host:port. 
+Set the variable <i>fs.default.name</i> to the HDFS Namenode's intended host:port.
+</li>
+</ul>
+
+An example of a hama-site.xml file:
+<pre style="background-color: #f3f5f7; border-bottom-color: rgb(174, 189, 204); border-bottom-style: solid; border-bottom-width: 1pt; border-left-color: rgb(174, 189, 204); border-left-style: solid; border-left-width: 1pt; border-right-color: rgb(174, 189, 204); border-right-style: solid; border-right-width: 1pt; border-top-color: rgb(174, 189, 204); border-top-style: solid; border-top-width: 1pt; font-family: courier, monospace; padding-bottom: 5pt; padding-left: 5pt; padding-right: 5pt; padding-top: 5pt; white-space: pre-wrap; word-wrap: break-word;">
+&lt;!--?xml version="1.0"?--&gt;
+&lt;!--?xml-stylesheet type="text/xsl" href="configuration.xsl"?--&gt;
+&lt;configuration&gt;
+  &lt;property&gt;
+    &lt;name&gt;bsp.master.address&lt;/name&gt;
+    &lt;value&gt;host1.mydomain.com:40000&lt;/value&gt;
+    &lt;description&gt;The address of the bsp master server. Either the
+    literal string "local" or a host:port for distributed mode
+    &lt;/description&gt;
+  &lt;/property&gt;
+  
+  &lt;property&gt;
+    &lt;name&gt;fs.default.name&lt;/name&gt;
+    &lt;value&gt;hdfs://host1.mydomain.com:9000/&lt;/value&gt;
+    &lt;description&gt;
+      The name of the default file system. Either the literal string
+      "local" or a host:port for HDFS.
+    &lt;/description&gt;
+  &lt;/property&gt;
+  
+  &lt;property&gt;
+    &lt;name&gt;hama.zookeeper.quorum&lt;/name&gt;
+    &lt;value&gt;host1.mydomain.com&lt;/value&gt;
+    &lt;description&gt;Comma separated list of servers in the ZooKeeper Quorum.
+    For example, "host1.mydomain.com,host2.mydomain.com,host3.mydomain.com".
+    By default this is set to localhost for local and pseudo-distributed modes
+    of operation. For a fully-distributed setup, this should be set to a full
+    list of ZooKeeper quorum servers. If HAMA_MANAGES_ZK is set in hama-env.sh
+    this is the list of servers which we will start/stop zookeeper on.
+    &lt;/description&gt;
+  &lt;/property&gt;
+&lt;/configuration&gt;
+</pre>
+
+If you are managing your own ZooKeeper, you have to specify the port number as below:
+
+<pre style="background-color: #f3f5f7; border-bottom-color: rgb(174, 189, 204); border-bottom-style: solid; border-bottom-width: 1pt; border-left-color: rgb(174, 189, 204); border-left-style: solid; border-left-width: 1pt; border-right-color: rgb(174, 189, 204); border-right-style: solid; border-right-width: 1pt; border-top-color: rgb(174, 189, 204); border-top-style: solid; border-top-width: 1pt; font-family: courier, monospace; padding-bottom: 5pt; padding-left: 5pt; padding-right: 5pt; padding-top: 5pt; white-space: pre-wrap; word-wrap: break-word;">
+  &lt;property&gt;
+    &lt;name&gt;hama.zookeeper.property.clientPort&lt;/name&gt;
+    &lt;value&gt;2181&lt;/value&gt;
+  &lt;/property&gt;
+</pre>
+
+<ul>
+<li>See also <a href="http://wiki.apache.org/hama/GettingStarted/Properties">Configuration Properties</a></li>
+</ul>
+
+<h3 id="Starting_a_Hama_cluster">Starting a Hama cluster</h3>
+
+Run the command:
+<pre style="background-color: #f3f5f7; border-bottom-color: rgb(174, 189, 204); border-bottom-style: solid; border-bottom-width: 1pt; border-left-color: rgb(174, 189, 204); border-left-style: solid; border-left-width: 1pt; border-right-color: rgb(174, 189, 204); border-right-style: solid; border-right-width: 1pt; border-top-color: rgb(174, 189, 204); border-top-style: solid; border-top-width: 1pt; font-family: courier, monospace; padding-bottom: 5pt; padding-left: 5pt; padding-right: 5pt; padding-top: 5pt; white-space: pre-wrap; word-wrap: break-word;">
+% $HAMA_HOME/bin/start-bspd.sh
+</pre>
+
+This will startup a BSPMaster, GroomServers and Zookeeper on your machine.
+
+<h3 id="Stopping_a_Hama_cluster">Stopping a Hama cluster</h3>
+
+Run the command:
+<pre style="background-color: #f3f5f7; border-bottom-color: rgb(174, 189, 204); border-bottom-style: solid; border-bottom-width: 1pt; border-left-color: rgb(174, 189, 204); border-left-style: solid; border-left-width: 1pt; border-right-color: rgb(174, 189, 204); border-right-style: solid; border-right-width: 1pt; border-top-color: rgb(174, 189, 204); border-top-style: solid; border-top-width: 1pt; font-family: courier, monospace; padding-bottom: 5pt; padding-left: 5pt; padding-right: 5pt; padding-top: 5pt; white-space: pre-wrap; word-wrap: break-word;">
+% $HAMA_HOME/bin/stop-bspd.sh
+</pre>
+
+to stop all the daemons running on your cluster.
+
+<h2 id="Run_the_BSP_Examples">Run the BSP Examples</h2>
+Run the command:
+<pre style="background-color: #f3f5f7; border-bottom-color: rgb(174, 189, 204); border-bottom-style: solid; border-bottom-width: 1pt; border-left-color: rgb(174, 189, 204); border-left-style: solid; border-left-width: 1pt; border-right-color: rgb(174, 189, 204); border-right-style: solid; border-right-width: 1pt; border-top-color: rgb(174, 189, 204); border-top-style: solid; border-top-width: 1pt; font-family: courier, monospace; padding-bottom: 5pt; padding-left: 5pt; padding-right: 5pt; padding-top: 5pt; white-space: pre-wrap; word-wrap: break-word;">
+% $HAMA_HOME/bin/hama jar hama-examples-0.x.0-incubating.jar
+</pre>
+
+<h2 id="Hama_Web_Interfaces">Hama Web Interfaces</h2>
+
+The web UI provides information about BSP job statistics of the Hama cluster, running/completed/failed jobs.
+<br/><br/>
+By default, it’s available at http://localhost:40013
+
+</body>
+</html>
+

Added: incubator/hama/trunk/core/src/main/webapp/bspmaster/bspjob.jsp
URL: http://svn.apache.org/viewvc/incubator/hama/trunk/core/src/main/webapp/bspmaster/bspjob.jsp?rev=1152788&view=auto
==============================================================================
--- incubator/hama/trunk/core/src/main/webapp/bspmaster/bspjob.jsp (added)
+++ incubator/hama/trunk/core/src/main/webapp/bspmaster/bspjob.jsp Mon Aug  1 14:12:46 2011
@@ -0,0 +1,66 @@
+<!--
+   Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  See the NOTICE file distributed with
+   this work for additional information regarding copyright ownership.
+   The ASF licenses this file to You under the Apache License, Version 2.0
+   (the "License"); you may not use this file except in compliance with
+   the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+-->
+<%@ page contentType="text/html; charset=UTF-8" import="javax.servlet.*"
+	import="javax.servlet.http.*" import="java.io.*" import="java.util.*"
+	import="java.text.DecimalFormat" import="org.apache.hama.bsp.*"
+	import="org.apache.hama.util.*"%>
+<%!private static final long serialVersionUID = 1L;%>
+<%
+  BSPMaster tracker = (BSPMaster) application
+      .getAttribute("bsp.master");
+  String idString = request.getParameter("jobid");
+  JobStatus status = tracker.getJobStatus(BSPJobID.forName(idString));
+  JobStatus.State state = status.getState();
+%>
+
+<html>
+
+<title>Hama BSP Job Summary</title>
+
+<body>
+  <h1><%=status.getName()%></h1>
+
+  <b>State: </b>  <%=state.toString() %> 
+  
+  <br/> <br/>
+  <table border="1" cellpadding="5" cellspacing="0">
+    <tr>
+      <th>Name</th>
+      <th>User</th>
+      <th>SuperStep</th>
+      <th>StartTime</th>
+      <th>FinishTime</th>
+    </tr>
+
+    <tr>
+      <td><%=status.getName() %></td>
+      <td><%=status.getUsername() %></td>
+      <td><%=status.getSuperstepCount() %></td>
+      <td><%=new Date(status.getStartTime()).toString() %></td>
+      <td>
+        <% if(status.getFinishTime() != 0L) {out.write(new Date(status.getFinishTime()).toString());} %>
+      </td>
+    </tr>
+
+  </table>
+  
+  <hr>
+  <a href="bspmaster.jsp">Back to BSPMaster</a>
+
+  <%
+    out.println(BSPServletUtil.htmlFooter());
+  %>
\ No newline at end of file

Added: incubator/hama/trunk/core/src/main/webapp/bspmaster/bspmaster.jsp
URL: http://svn.apache.org/viewvc/incubator/hama/trunk/core/src/main/webapp/bspmaster/bspmaster.jsp?rev=1152788&view=auto
==============================================================================
--- incubator/hama/trunk/core/src/main/webapp/bspmaster/bspmaster.jsp (added)
+++ incubator/hama/trunk/core/src/main/webapp/bspmaster/bspmaster.jsp Mon Aug  1 14:12:46 2011
@@ -0,0 +1,82 @@
+<!--
+   Licensed to the Apache Software Foundation (ASF) under one or more
+   contributor license agreements.  See the NOTICE file distributed with
+   this work for additional information regarding copyright ownership.
+   The ASF licenses this file to You under the Apache License, Version 2.0
+   (the "License"); you may not use this file except in compliance with
+   the License.  You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+-->
+<%@ page contentType="text/html; charset=UTF-8" import="javax.servlet.*"
+	import="javax.servlet.http.*" import="java.io.*" import="java.util.*"
+	import="java.text.DecimalFormat" import="org.apache.hama.bsp.*"
+	import="org.apache.hama.util.*"%>
+<%!private static final long serialVersionUID = 1L;%>
+<%
+  BSPMaster tracker = (BSPMaster) application
+      .getAttribute("bsp.master");
+  ClusterStatus status = tracker.getClusterStatus(true);
+  String trackerName = tracker.getBSPMasterName();
+  JobStatus[] runningJobs = tracker.jobsToComplete();
+  JobStatus[] allJobs = tracker.getAllJobs();
+%>
+<%!private static DecimalFormat percentFormat = new DecimalFormat("##0.00");
+ 
+  public void generateSummaryTable(JspWriter out, ClusterStatus status,
+      BSPMaster tracker) throws IOException {
+    String tasksPerNode = status.getGroomServers() > 0 ? percentFormat
+        .format(((double) (status.getMaxTasks()) / status
+            .getGroomServers())) : "-";
+    out.print("<table border=\"1\" cellpadding=\"5\" cellspacing=\"0\">\n"
+        + "<tr>" + "<th>Groom Servers</th><th>BSP Task Capacity</th>"
+        + "<th>Avg. Tasks/Node</th>"
+        + "<th>Blacklisted Nodes</th></tr>\n");
+    out.print("<tr><td><a href=\"machines.jsp?type=active\">"
+        + status.getActiveGroomNames().size() + "</a></td><td>"
+        + status.getMaxTasks() + "</td><td>" + tasksPerNode
+        + "</td><td><a href=\"machines.jsp?type=blacklisted\">" + 0
+        + "</a>" + "</td></tr></table>\n");
+
+    out.print("<br>");
+  }%>
+
+
+<html>
+<head>
+<title><%=trackerName%> Hama BSP Administration</title>
+<!--  <link rel="stylesheet" type="text/css" href="/static/hadoop.css">-->
+</head>
+<body>
+
+<h1><%=trackerName%> Hama BSP Administration</h1>
+
+<b>State:</b>
+<%=status.getBSPMasterState()%><br>
+<b>Started:</b>
+<%=new Date(tracker.getStartTime())%><br>
+<b>Identifier:</b>
+<%=tracker.getBSPMasterIdentifier()%><br>
+
+<hr>
+<%
+  generateSummaryTable(out, status, tracker);
+%>
+<hr />
+
+<h2 id="running_jobs">Running Jobs</h2>
+<%=BSPServletUtil.generateJobTable("Running", runningJobs,
+          30, 0)%>
+<hr> 
+<h2 id="running_jobs">All Jobs History</h2>
+<%=BSPServletUtil.generateJobTable("All", allJobs,
+          30, 0)%>
+<%
+  out.println(BSPServletUtil.htmlFooter());
+%>
\ No newline at end of file



Mime
View raw message