Update of /cvsroot/pyxida/Util-PRP/src/edu/harvard/syrah/prp In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv17572/src/edu/harvard/syrah/prp Added Files: PrimitiveArray.java PUtil.java Stat2.java LongArray.java Triple.java Debug.java SortedList.java BitArray.java Log.java IntIntArray.java LogFormatter.java ByteArray.java UnknownPropertyException.java ByteArrayClassLoader.java Stat.java PTimer.java ANSI.java NetUtil.java IntArray.java POut.java PError.java RateCalc.java Pair.java TypedMap.java Log Message: Initial checkin --- NEW FILE: PUtil.java --- /* * Created on Apr 28, 2004 */ package edu.harvard.syrah.prp; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.InvalidMarkException; import java.util.*; /** * Useful static utility methods. * * @author prp */ public abstract class PUtil { static Log log = new Log(PUtil.class); private static final long GARBAGE_COLLECTION_DELAY = 1 * 1000; private static Random random = new Random(); public static void sleep(long time) { if (time == 0) return; try { Thread.sleep(time); } catch (InterruptedException e2) { /* ignore */ } } public static long getRandomLong() { return random.nextLong(); } public static int getRandomInt() { return random.nextInt(); } public static long getRandomPosLong() { return Math.abs(random.nextLong()); } public static int getRandomPosInt(int maxInt) { return random.nextInt(maxInt); } public static int getRandomPosInt() { return Math.abs(random.nextInt()); } public static String getRandomString(int minLength, int maxLength) { int start = 'a'; int end = 'z'; StringBuffer sb = new StringBuffer(); for (int i = 0; i < random.nextInt(maxLength - minLength) + minLength; i++) { sb.append((char) (random.nextInt(end - start) + start)); } return sb.toString(); } public static <T> T getRandomObject(Collection<T> collection) { // Is this set empty? if (collection.isEmpty()) return null; Iterator<T> objIt = collection.iterator(); int index = getRandomPosInt(collection.size()) + 1; T obj = null; for (int i = 0; i < index; i++) { obj = objIt.next(); } return obj; } public static Random getRandom() { return random; } public static double getMax(double[] array) { double max = 0; for (int i=0; i < array.length; i++) { if (array[i] > max) max = array[i]; } return max; } public static int getMax(int[] array) { int max = 0; for (int i=0; i < array.length; i++) { if (array[i] > max) max = array[i]; } return max; } public static double getLength(double[] vector) { double length = 0; for (int i = 0; i < vector.length; i++) length += vector[i] * vector[i]; length = Math.sqrt(length); return length; } public static void block() { while (!Thread.currentThread().isInterrupted()) { try { Thread.sleep(100000); } catch (InterruptedException e) { /* ignore */ } } } public static void gc() { System.gc(); System.runFinalization(); System.gc(); try { Thread.sleep(GARBAGE_COLLECTION_DELAY); } catch (InterruptedException e) { POut.abort("Util.gc(): Garbage Collection interrupted."); } } public static void delay(double seconds) { Object dummy = new Object(); synchronized (dummy) { try { dummy.wait(Math.round(seconds * 1000)); } catch (InterruptedException e) { /* ignore */ } } } public static InputStream createInputStream(final ByteBuffer buffer) { return new InputStream() { public synchronized int read() throws IOException { if (!buffer.hasRemaining()) return -1; return buffer.get(); } public synchronized int read(byte[] bytes, int off, int len) throws IOException { if (!buffer.hasRemaining()) return -1; len = Math.min(len, buffer.remaining()); buffer.get(bytes, off, len); return len; } }; } public static byte[] convertInputStreamToByteArray(InputStream is) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[1000]; int read = -1; try { while ((read = is.read(buf, 0, buf.length)) != -1) { baos.write(buf, 0, read); } } catch (IOException e) { log.error("Error converting byte array from stream: " + e); } return baos.toByteArray(); } /** * This methods extends a buffer to a new size by copying it. * * @param oldBuffer * @param newSize * @return */ public static ByteBuffer extendByteBuffer(ByteBuffer oldBuffer, int newSize) { int currentPosition = oldBuffer.position(); int limitPosition = oldBuffer.limit(); int markPosition = 0; try { oldBuffer.reset(); markPosition = oldBuffer.position(); } catch (InvalidMarkException e) { // No mark has been set yet } oldBuffer.position(0); ByteBuffer newBuffer = ByteBuffer.allocate(newSize); newBuffer.put(oldBuffer); newBuffer.position(markPosition); newBuffer.mark(); newBuffer.position(currentPosition); newBuffer.limit(limitPosition); return newBuffer; } public static String getDiffTimeStr(long time1, long time2) { long diff = (time2 - time1) / 1000; int days = (int) (diff / (3600 * 24)); diff -= days * 3600 * 24; int hours = (int) (diff / 3600); diff -= (hours * 3600); int mins = (int) (diff / 60); diff -= mins * 60; int secs = (int) diff; StringBuffer sb = new StringBuffer(); if (days > 1) sb.append(days + " days "); if (days == 1) sb.append(days + " day "); if (hours > 1) sb.append(hours + " hours "); if (hours == 1) sb.append(hours + " hour "); if (mins > 1) sb.append(mins + " mins "); if (mins == 1) sb.append(mins + " min "); if (secs > 1) sb.append(secs + " secs "); if (secs == 1) sb.append(secs + " sec "); if (sb.length() > 0) sb.deleteCharAt(sb.length() - 1); return sb.toString(); } public static final void main(String[] args) { Set<String> set = new HashSet<String>(); set.add("One"); set.add("Two"); set.add("Three"); set.add("Four"); set.add("Five"); for (int i = 0; i < 10; i++) { POut.p((String) getRandomObject(set)); } } } --- NEW FILE: BitArray.java --- /* * Title: ByteArray * Description: Implements a variable size byte array.<p> * Copyright: Copyright (c) 2001 <p> * Company: Computer Laboratory, Cambridge University <p> * @author Peter Pietzuch <pr...@cl...> * @version 1.0 * * (C) Copyright 2001-2003 Peter R Pietzuch * * This file is part of Util. * * Util is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Util is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with DSSim; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package edu.harvard.syrah.prp; public class BitArray extends PrimitiveArray { private boolean[] a; public BitArray() { super(); } public BitArray (int initialSize, int growStep) { super(initialSize, growStep); } public BitArray(int initialSize) { super(initialSize); } protected void init(int initialSize) { a = new boolean[initialSize]; } /** * Adds a new byte value to the array. The array is extended if necessary by doubling its size. * * @param byte Byte to be added. */ public void add(boolean b) { if ((len + 1) > a.length) { if (growthStep == 0) multiplySize(2); else resize(a.length + growthStep); } a[len++] = b; } /** * Adds an byte array to the variable size array. All the values are copied. * * @param b Byte array to be copied. * @param size Size of b to be copied. */ public void addAll(boolean[] b, int size) { if (size == 0) return; if ((len + size) > a.length) { if (growthStep == 0) multiplySize(((len + size) / a.length) + 1); else { int factor = ((len + size - a.length) / growthStep) + 1; resize ((factor * growthStep) + a.length); } } for (int i = 0; i < size; i++) a[len++] = b[i]; } /** * Returns the byte value at a particular index. * * @param index Index * @return Byte value */ public boolean get(int index) { if (index >= len) throw new IndexOutOfBoundsException(); return a[index]; } /** * Sets a value in the array to a new value. The index must exist. * * @param value New value * @param index Index */ public void set(boolean value, int index) { if (index >= len) throw new IndexOutOfBoundsException(); a[index] = value; } /** * Returns a new byte array which has the optimal size. This is done by copying. * * @return Byte Array */ public boolean[] getArrayCopy() { boolean[] retA = new boolean[len]; for (int i = 0; i < len; i++) retA[i] = a[i]; return retA; } public boolean[] getArray() { return a; } protected void resize(int newSize) { boolean[] newA = new boolean[newSize]; for (int i = 0; i < a.length; i++) newA[i] = a[i]; a = newA; } public int capacity() { return a.length; } public static void main(String[] args) { Debug.p("hello"); BitArray a1 = new BitArray(100, 100); boolean[] ba = {true, false, true, true, false}; for (int i = 0; i < 1000; i++) { a1.addAll(ba, ba.length); } System.out.println("a1.size() = " + a1.size()); //for (int i = 0; i < a1.size(); i++) //System.out.print(a1.elementAt(i) + " "); System.out.println(); } } --- NEW FILE: PTimer.java --- /* * @author Last modified by $Author: prp $ * @version $Revision: 1.1 $ on $Date: 2007/11/19 17:50:10 $ * @since Feb 2, 2005 */ package edu.harvard.syrah.prp; import edu.harvard.syrah.prp.ANSI.Color; /** * */ public class PTimer { private static long hardLimit = Long.MAX_VALUE; private long startTime; private boolean isStarted = false; public PTimer() { this(true); } public PTimer(boolean start) { if (start) { startTime = System.nanoTime(); isStarted = true; } } public static void setHardLimit(long newHardLimit) { if (newHardLimit > 0) { hardLimit = newHardLimit; } } public void start() { startTime = System.nanoTime(); isStarted = true; } public boolean isStarted() { return isStarted; } public double stop() { isStarted = false; return (System.nanoTime() - startTime) / 1000000d; } public void setBack(double value) { startTime += (value * 1000000d); } public double lap() { long currentTime = System.nanoTime(); double runningTime = (currentTime - startTime) /1000000d; startTime = currentTime; return runningTime; } public void lap(Log log, String what) { double runningTime = (System.nanoTime() - startTime) / 1000000d; String output = "Lap : " + what + " " + ANSI.color(Color.GREEN, POut.toString(runningTime)) + " ms"; log.main(output); if (hardLimit < runningTime) { log.info(ANSI.color(Color.LIGHTRED, "Timer hit hard limit of " + hardLimit + " ms: " + output)); } } public void stop(Log log, String what) { isStarted = false; double runningTime = (System.nanoTime() - startTime) / 1000000d; String output = "Stop: " + what + " " + ANSI.color(Color.GREEN, POut.toString(runningTime)) + " ms"; log.main(output); if (hardLimit < runningTime) { log.info(ANSI.color(Color.LIGHTRED, "Timer hit hard limit of " + hardLimit + " ms: " + output)); } } public double getTime() { return (System.nanoTime() - startTime) / 1000000d; } public String toString() { return POut.toString(getTime()) + " ms"; } } --- NEW FILE: ByteArrayClassLoader.java --- /* * SBON * * @author Last modified by $Author: prp $ * @version $Revision: 1.1 $ on $Date: 2007/11/19 17:50:10 $ * @since Jan 17, 2005 */ package edu.harvard.syrah.prp; import java.util.HashMap; import java.util.Map; import edu.harvard.syrah.prp.Log; /** * * This is an implementation of a Java class loader that loads a class from a byte array. * */ public class ByteArrayClassLoader extends ClassLoader { private static final Log log = new Log(ByteArrayClassLoader.class); private Map<String, byte[]> classByteCodeTable = new HashMap<String, byte[]>(); public void addClassByteCode(String className, byte[] byteCode) { classByteCodeTable.put(className, byteCode); } public synchronized Class< ? > loadClass(String name, boolean resolve) throws ClassNotFoundException { log.debug("Trying to load the className=" + name + " dynamically."); Class<?> newClass = findLoadedClass(name); if (newClass != null) return newClass; SecurityManager sm = System.getSecurityManager(); if (sm != null) { int i = name.lastIndexOf('.'); if (i >= 0) sm.checkPackageAccess(name.substring(0, i)); } if (sm != null) { int i = name.lastIndexOf('.'); if (i >= 0) sm.checkPackageDefinition(name.substring(0, i)); } try { //if (parent != null) // newClass = parent.loadClass(name, resolve); //else // Call this method in both 1.1 and 1.2 newClass = findSystemClass(name); if (newClass != null) return newClass; } catch (ClassNotFoundException e) { // Not a system class, simply continue } log.debug("Considering byte code cache."); byte[] byteCode = classByteCodeTable.get(name); //log.debug("byteCode=" + Util.toString(byteCode)); newClass = defineClass(null, byteCode, 0, byteCode.length); log.debug("newClass=" + newClass); if (resolve) resolveClass(newClass); return newClass; } } --- NEW FILE: SortedList.java --- /* * @author Last modified by $Author: prp $ * @version $Revision: 1.1 $ on $Date: 2007/11/19 17:50:10 $ * @since Sep 8, 2005 */ package edu.harvard.syrah.prp; import java.io.Serializable; import java.util.*; public class SortedList<T> implements List<T>, Serializable { private static final Log log = new Log(SortedList.class); static final long serialVersionUID = 1000000000L; private int maxSize; private Comparator<? super T> comp; private List<T> list = new LinkedList<T>(); public SortedList(Comparator<? super T> comp) { this(0, comp); } public SortedList(int maxSize, Comparator<? super T> comp) { this.maxSize = maxSize; this.comp = comp; } public int size() { return list.size(); } public boolean isEmpty() { return list.isEmpty(); } public boolean contains(Object o) { return list.contains(o); } public Iterator<T> iterator() { return list.iterator(); } public Object[] toArray() { return list.toArray(); } public <U> U[] toArray(U[] a) { return list.toArray(a); } public boolean add(T o) { list.add(o); Collections.sort(list, comp); if (maxSize != 0 && list.size() > maxSize) { list.remove(list.size() - 1); } return true; } public boolean remove(Object o) { return list.remove(o); } public boolean containsAll(Collection< ? > c) { return list.containsAll(c); } public boolean addAll(Collection< ? extends T> c) { return list.addAll(c); } public boolean addAll(int index, Collection< ? extends T> c) { return list.addAll(index, c); } public boolean removeAll(Collection< ? > c) { return list.removeAll(c); } public boolean retainAll(Collection< ? > c) { return list.retainAll(c); } public void clear() { list.clear(); } public T get(int index) { return list.get(index); } public T set(int index, T element) { return list.set(index, element); } public void add(int index, T element) { list.add(index, element); } public T remove(int index) { return list.remove(index); } public int indexOf(Object o) { return list.indexOf(o); } public int lastIndexOf(Object o) { return list.lastIndexOf(o); } public ListIterator<T> listIterator() { return list.listIterator(); } public ListIterator<T> listIterator(int index) { return listIterator(index); } public List<T> subList(int fromIndex, int toIndex) { return list.subList(fromIndex, toIndex); } } --- NEW FILE: POut.java --- /* * @author Last modified by $Author: prp $ * @version $Revision: 1.1 $ on $Date: 2007/11/19 17:50:10 $ * @since Aug 16, 2005 */ package edu.harvard.syrah.prp; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.ByteBuffer; import java.text.NumberFormat; import java.util.Collection; import java.util.Iterator; import java.util.Map; public class POut { private static final Log log = new Log(POut.class); public static final String NL = System.getProperty("line.separator"); private static final int VSPACE_LINES = 3; private static boolean debugState = true; private static NumberFormat fpFormat = NumberFormat.getNumberInstance(); private static NumberFormat intFormat = NumberFormat.getIntegerInstance(); static { fpFormat.setMaximumFractionDigits(2); fpFormat.setMinimumFractionDigits(2); fpFormat.setGroupingUsed(false); intFormat.setGroupingUsed(false); intFormat.setMinimumFractionDigits(0); intFormat.setMaximumFractionDigits(0); } public static String toString(double[] vector, String sep) { StringBuffer sb = new StringBuffer(); sb.append("("); if (vector != null) { for (int i = 0; i < vector.length; i++) { sb.append(fpFormat.format(vector[i])); if (i < (vector.length - 1)) sb.append(sep); } } else sb.append("null"); sb.append(")"); return sb.toString(); } public static String toString(long[] vector, String sep) { StringBuffer sb = new StringBuffer(); sb.append("("); if (vector != null) { for (int i = 0; i < vector.length; i++) { sb.append(intFormat.format(vector[i])); if (i < (vector.length - 1)) sb.append(sep); } } else sb.append("null"); sb.append(")"); return sb.toString(); } public static String toString(Object[] vector) { return toString(vector, " "); } public static String toString(Object[] vector, String sep) { StringBuffer sb = new StringBuffer(); if (vector != null) { for (int i = 0; i < vector.length; i++) { sb.append(vector[i]); if (i < (vector.length - 1)) sb.append(sep); } } return sb.toString(); } public static String toString(double[] vector) { return toString(vector, " "); } public static String toString(long[] vector) { return toString(vector, " "); } public static String toString(byte[] vector, String sep) { StringBuffer sb = new StringBuffer(); sb.append("("); if (vector != null) { for (int i = 0; i < vector.length; i++) { sb.append(vector[i]); if (i < (vector.length - 1)) sb.append(sep); } } sb.append(")"); return sb.toString(); } public static String toString(byte[] vector) { return toString(vector, " "); } public static String toString(int[] vector, String sep) { StringBuffer sb = new StringBuffer(); sb.append("("); if (vector != null) { for (int i = 0; i < vector.length; i++) { sb.append(vector[i]); if (i < (vector.length - 1)) sb.append(sep); } } sb.append(")"); return sb.toString(); } public static String toString(double[][] matrix) { StringBuffer str = new StringBuffer(); str.append("("); if (matrix != null) { for (int i = 0; i < matrix.length; i++) { str.append(toString(matrix[i], ",")); if (i != (matrix.length - 1)) str.append(" "); } } else { str.append("null"); } str.append(")"); return str.toString(); } public static String toString(int[] vector) { return toString(vector, " "); } public static String toString(int[][] matrix, int space) { StringBuffer str = new StringBuffer(); str.append("\n"); if (matrix.length == 0) { str.append("empty"); } else { for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { for (int k = (new Integer(matrix[i][j])).toString().length(); k < space; k++) str.append(" "); str.append(matrix[i][j] + " "); } if (i != matrix.length - 1) str.append("\n"); } } //str.append("\n"); return str.toString(); } public static String toString(int[][] matrix) { return toString(matrix, 2); } public static String toString(Object[][] matrix, int space) { StringBuffer str = new StringBuffer(); str.append("\n\n"); for (int i = 0; i < matrix.length; i++) { for (int j = 0; j < matrix[i].length; j++) { if (matrix[i][j] == null) { for (int k = 0; k < space; k++) str.append ("-"); str.append(" "); } else { for (int k = matrix[i][j].toString().length(); k < space; k++) str.append(" "); str.append(matrix[i][j] + " "); } } str.append("\n"); } str.append("\n"); return str.toString(); } @SuppressWarnings("unchecked") public static String toString(Iterator it) { return toString(it, ","); } @SuppressWarnings("unchecked") public static String toString(Iterator it, String sep) { StringBuffer strBuffer = new StringBuffer(); while (it.hasNext()) { strBuffer.append(it.next()); if (it.hasNext()) strBuffer.append(sep); } return strBuffer.toString(); } public static String toString(Object[][] matrix) { return toString(matrix, 2); } @SuppressWarnings("unchecked") public static String toString(Map m) { StringBuffer strBuffer = new StringBuffer(); strBuffer.append("{"); for (Iterator it = m.keySet().iterator(); it.hasNext();) { Object key = it.next(); Object value = m.get(key); strBuffer.append("("); strBuffer.append(key != null ? key.toString() : "null"); strBuffer.append(","); strBuffer.append(value != null ? value.toString() : "null"); strBuffer.append(")"); if (it.hasNext()) strBuffer.append(", "); } strBuffer.append("}"); return strBuffer.toString(); } @SuppressWarnings("unchecked") public static String toString(Collection c) { return toString(c, ","); } @SuppressWarnings("unchecked") public static String toString(Collection c, String sep) { if (c != null) return toString(c.iterator(), sep); else return "null"; } public static String toString(double d) { return fpFormat.format(d); } public static String toString(int i, int digits) { return prependFixedLength(String.valueOf(i), digits); } public static void p() { System.out.println(); } public static void p(String what) { System.out.println(what); } public static void pStart(String what) { POut.pStart(what, false); } public static void pStart(String what, boolean newline) { if (newline) System.out.println("[" + what + "... "); else System.out.print("[" + what + "... "); } public static void pDone() { System.out.println("Done.]\n"); } public static void waitForReturn(String descr) { System.out.println("Press Return " + descr + "..."); try { (new BufferedReader (new InputStreamReader (System.in))).readLine(); } catch (IOException e) { /* ignore */ } } public static void waitForReturn() { waitForReturn("to continue"); } /** * Pads a string with whitspace or truncates it before adding it to a StringBuffer * @param sb * @param appendString * @param desiredLength */ public static void appendFixedLength(StringBuffer sb, String appendString, int desiredLength) { int currentLength = appendString.length(); if (currentLength < desiredLength) { sb.append(appendString); for (int i = 0; i < (desiredLength - currentLength); i++) sb.append(" "); } else { sb.append(appendString.substring(0, desiredLength)); } } public static String appendFixedLength(String what, int desiredLength) { StringBuffer padding = new StringBuffer(); for (int i = 0; i < desiredLength - what.length(); i++) { padding.append(" "); } return what + padding.toString(); } public static String prependFixedLength(String what, int desiredLength) { StringBuffer padding = new StringBuffer(); for (int i = 0; i < desiredLength - what.length(); i++) { padding.append(" "); } return padding.toString() + what; } public static String prependFL(String what, int desiredLength) { return prependFixedLength(what, desiredLength); } public static String prependFL(int i, int desiredLength) { return prependFixedLength(String.valueOf(i), desiredLength); } public static String print(ByteBuffer byteBuffer) { byteBuffer.rewind(); StringBuffer sB = new StringBuffer(); for (int i = 0; i < byteBuffer.limit(); i++) { sB.append(byteBuffer.get()); sB.append(" "); } byteBuffer.rewind(); return "{" + sB.toString() + "}"; } public static String printChar(ByteBuffer byteBuffer) { int pos = byteBuffer.position(); byteBuffer.rewind(); StringBuffer sB = new StringBuffer(); while (byteBuffer.remaining() > 0) { sB.append((char) byteBuffer.get()); } byteBuffer.position(pos); return "{" + sB.toString() + "}"; } public static void vspace() { for (int i = 0; i < VSPACE_LINES; i++) System.out.println(); } public static String ws(int length) { StringBuffer sb = new StringBuffer(); for (int i = 0; i < length; i++) { sb.append(" "); } return sb.toString(); } public static void appendWS(StringBuffer sb, int length) { for (int i = 0; i < length; i++) { sb.append(" "); } } public static void debug(String msg) { if (debugState) PUtil.log.debug(msg); //System.out.println("Debug: " + msg); } // TODO should use log.config to do this sort of thing. public static void setDebugState(boolean state) { debugState = state; } public static void abort() { POut.abort("Program abort."); } public static void abort(String msg) { //System.out.println("Abort: " + msg); PUtil.log.error(msg); Thread.dumpStack(); System.exit(-1); } public static void main(String[] args) { String split[] = "imperial, university".split("\\,\\s"); System.out.println(split[0] + "/" + split[1] + "/"); } } --- NEW FILE: PrimitiveArray.java --- /* * @author Last modified by $Author: prp $ * @version $Revision: 1.1 $ on $Date: 2007/11/19 17:50:10 $ * @since Jul 25, 2006 */ package edu.harvard.syrah.prp; public abstract class PrimitiveArray { protected int len = 0; protected int growthStep = 0; /** * The default initial size of the array. */ protected static final int DEFAULT_INITIAL_SIZE = 128; /** * Creates a new array. */ protected PrimitiveArray() { this(DEFAULT_INITIAL_SIZE); } /** * If this constructor is used, the array starts with an initial size and grows by stepSize. * * @param growthStep Step size */ protected PrimitiveArray(int initialSize, int growthStep) { this(initialSize); this.growthStep = growthStep; } /** * Creates a new array. * * @param initialSize The initial size of the array. */ protected PrimitiveArray(int initialSize) { init(initialSize); } protected abstract void init(int initialSize); /** * Returns the number of bytes stored in the array. * * @return Size of the array data. */ public int size() { return len; } /** * Sets the steps that are used for growing the array. * * @param growStep Step size. */ public void setGrowStep(int growStep) { this.growthStep = growStep; } public boolean isEmpty() { return len == 0; } public abstract int capacity(); /** * Makes the array at least this big. * * @param minCapacity Minimal capicity required. */ public void ensureCapacity(int minCapacity) { if (capacity() < minCapacity) resize(minCapacity); } public void fill(int length) { ensureCapacity(length); this.len = length; } protected void multiplySize(int factor) { resize(capacity() == 0 ? factor : factor * capacity()); } protected abstract void resize(int minCapacity); } --- NEW FILE: IntArray.java --- /* * Title: ByteArray * Description: Implements a variable size byte array.<p> * Copyright: Copyright (c) 2001 <p> * Company: Computer Laboratory, Cambridge University <p> * @author Peter Pietzuch <pr...@cl...> * @version 1.0 * * (C) Copyright 2001-2003 Peter R Pietzuch * * This file is part of Util. * * Util is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Util is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with DSSim; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package edu.harvard.syrah.prp; public class IntArray extends PrimitiveArray{ private int[] a; public IntArray() { super(); } public IntArray (int initialSize, int growStep) { super(initialSize, growStep); } public IntArray(int initialSize) { super(initialSize); } protected void init(int initialSize) { a = new int[initialSize]; } /** * Adds a new byte value to the array. The array is extended if necessary by doubling its size. * * @param byte Byte to be added. */ public void add(int b) { if ((len + 1) > a.length) { if (growthStep == 0) multiplySize(2); else resize(a.length + growthStep); } a[len++] = b; } /** * Adds an byte array to the variable size array. All the values are copied. * * @param b Byte array to be copied. * @param size Size of b to be copied. */ public void addAll(int[] b, int size) { if (size == 0) return; if ((len + size) > a.length) { if (growthStep == 0) multiplySize(((len + size) / a.length) + 1); else { int factor = ((len + size - a.length) / growthStep) + 1; resize ((factor * growthStep) + a.length); } } for (int i = 0; i < size; i++) a[len++] = b[i]; } /** * Returns the byte value at a particular index. * * @param index Index * @return Byte value */ public int get(int index) { if (index >= len) throw new IndexOutOfBoundsException(); return a[index]; } /** * Sets a value in the array to a new value. The index must exist. * * @param value New value * @param index Index */ public void set(int value, int index) { if (index >= len) throw new IndexOutOfBoundsException(); a[index] = value; } /** * Returns a new byte array which has the optimal size. This is done by copying. * * @return Byte Array */ public int[] getArrayCopy() { int[] retA = new int[len]; for (int i = 0; i < len; i++) retA[i] = a[i]; return retA; } protected void resize(int newSize) { int[] newA = new int[newSize]; for (int i = 0; i < a.length; i++) newA[i] = a[i]; a = newA; } public int capacity() { return a.length; } public static void main(String[] args) { Debug.p("hello"); //IntArray a1 = new IntArray(100, 100); IntArray a1 = new IntArray(); int[] ba = {23, 42, 314, 16, 3}; for (int i = 0; i < 1000; i++) { a1.addAll(ba, ba.length); } System.out.println("a1.size() = " + a1.size()); //for (int i = 0; i < a1.size(); i++) //System.out.print(a1.elementAt(i) + " "); System.out.println(); } } --- NEW FILE: PError.java --- /* * Title: PError * Description: Error class <p> * Copyright: Copyright (c) 2001 <p> * Company: Computer Laboratory, Cambridge University <p> * @author Peter Pietzuch <pr...@cl...> * @version 1.0 * * (C) Copyright 2001-2003 Peter R Pietzuch * * This file is part of Util. * * Util is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Util is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with DSSim; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package edu.harvard.syrah.prp; /** * This class is deprecated and should not be used anymore. * */ public class PError { /** * This method aborts the program and prints out an error message. * * @param where Name of class/method in which the error occurred. * @param what Description of the error condition */ public static void abort(String where, String what) { System.err.println("Error: [" + where + "] " + what); Thread.dumpStack(); System.exit(-1); } public static void abort(String where, String what, Exception e) { System.err.println("Error: [" + where + "] " + what + " : " + e.toString()); e.printStackTrace(); System.exit(-1); } public static void error(String where, String what) { System.err.println("Error: [" + where + "] " + what); System.err.flush(); } public static void warn(String where, String what) { warning(where, what); } public static void warning(String where, String what) { System.err.println("Warning: [" + where + "] " + what); } } --- NEW FILE: Debug.java --- /* * Title: Debug <p> * Description: This class contains Debug aids. <p> * Copyright: Copyright (c) 2001 <p> * Company: Computer Laboratory, Cambridge University <p> * @author Peter Pietzuch <pr...@cl...> * @version 1.0 * * (C) Copyright 2001-2003 Peter R Pietzuch * * This file is part of Util. * * Util is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Util is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with DSSim; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package edu.harvard.syrah.prp; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.io.PrintStream; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; import java.util.Vector; public class Debug { private static final String DEBUG_SYSTEM_PROPERTY = "PDEBUG_CLASSES"; private static final int TRACE_DEPTH = 3; private static final int INDENT = 45; private static boolean debugState = true; private static Set<String> debugClasses; private static Set<String> noDebugClasses; static { debugClasses = new HashSet<String>(); noDebugClasses = new HashSet<String>(); String debugClassEnv = System.getProperty(DEBUG_SYSTEM_PROPERTY); //Util.p("debugClassEnv = " + debugClassEnv); if ((debugClassEnv != null) && (debugClassEnv.length() != 0)) addDebugClass(debugClassEnv); } @SuppressWarnings("deprecation") static Context getContext (int level) { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream pout = new PrintStream(out); new Exception().printStackTrace(pout); DataInputStream din = new DataInputStream(new ByteArrayInputStream(out.toByteArray())); String targetLine = " at CLASS.METHOD(FILE.java:0000)"; // ??? try { for (int i = 0; i < level; i++) { if (i == 1) { String line = din.readLine(); if (line.indexOf("Throwable") != -1) level = level + 2; } else din.readLine(); } targetLine = din.readLine(); } catch (IOException e) { /* empty */ } StringTokenizer tk = new StringTokenizer(targetLine, " \n\t.():"); Vector<String> tokens = new Vector<String>(); for (int i = 0; tk.hasMoreTokens(); i++) { tokens.add(tk.nextToken()); } int tokenSize = tokens.size(); Context context = new Context(); //context.lineNumber = Integer.parseInt((String) tokens.elementAt(tokenSize - 1)); String ext = (String) tokens.elementAt(tokenSize - 2); String file = (String) tokens.elementAt(tokenSize - 3); context.sourceFile = file + "." + ext; context.methodName = (String) tokens.elementAt(tokenSize - 4); context.className = (String) tokens.elementAt(tokenSize - 5); StringBuffer packages = new StringBuffer(); for (int i = 1; i < tokenSize - 5; i++) { packages.append(tokens.elementAt(i)); if (i < tokenSize - 6) packages.append("."); } context.packageName = packages.toString(); return context; } public static void p(String what) { if (!debugState == true) return; Context c = getContext(TRACE_DEPTH); String origName = c.packageName + "." + c.className; String className = new String(origName); while (className.indexOf(".") != -1) { if (noDebugClasses.contains(className)) return; className = className.substring(0, className.lastIndexOf(".")); } className = origName; while (true) { if (debugClasses.contains(className)) { System.out.print(" #Debug: (" + c + ") : "); for (int i = 0; i < INDENT - c.toString().length(); i++) System.out.print(" "); System.out.println(what); return; } if (className.indexOf(".") != -1) className = className.substring(0, className.lastIndexOf(".")); else return; } } public static void p(long what) { p(Long.toString(what)); } public static void p(String where, String what, int p) { p(what); } public static void p(String where, String what) { p(what); } @SuppressWarnings("unchecked") public static void addDebugClass(Class newClass) { System.out.println(newClass.getName()); debugClasses.add(newClass.getName()); } public static void addDebugClass(String newClass) { debugClasses.add(newClass); } public static void addNoDebugClass(String newClass) { noDebugClasses.add(newClass); } public static void setLevel(int l) { /* empty */ } public static void setDebugState(boolean newState) { debugState = newState; } } class Context { public String packageName; public String className; public String methodName; public String sourceFile; public int lineNumber; public String toString () { //return "[" + packageName + "." + className + ", " + methodName + "(...), " + sourceFile + ", " + lineNumber + "]"; return "[" + className + "." + methodName + "]"; } } --- NEW FILE: Stat.java --- /* * * @author Last modified by $Author: prp $ * @version $Revision: 1.1 $ on $Date: 2007/11/19 17:50:10 $ * @since Sep 3, 2004 */ package edu.harvard.syrah.prp; import java.util.Arrays; /** * * This class gathers various statistics. * */ public class Stat { //private static final Log log = new Log(Stat.class); private static final int DEFAULT_CDF_BUCKET_NUM = 100; private static final double DEFAULT_BUCKET_SIZE = 1.0; private double[] data; private double[][] dataXY; private double[] sortedData; private double[] distribution; private double[][] histogram; private int index = 0; private boolean dataExists = false; private double max = Double.NaN; private double min = Double.NaN; private double sum = Double.NaN; private double avg = Double.NaN; public Stat(double[] data) { this.data = data; if (data.length > 0) this.dataExists = true; } public Stat(int[] data) { this.data = new double[data.length]; for (int i = 0; i < data.length; i++) this.data[i] = data[i]; if (data.length > 0) this.dataExists = true; } public Stat(int dataSize) { this.data = new double[dataSize]; this.dataXY = new double[dataSize][2]; } public void addData(double dataItem) { data[index] = dataItem; this.dataExists = true; index++; } public void addData(double x, double y) { this.dataXY[index][0] = x; this.dataXY[index++][1] = y; this.dataExists = true; } public void divideBy(double d) { for (int i = 0; i < data.length; i++) data[i] = data[i] / d; } public void calculate() { calculate(DEFAULT_CDF_BUCKET_NUM, DEFAULT_BUCKET_SIZE); } public void calculate(double bucketSize) { calculate(DEFAULT_CDF_BUCKET_NUM, bucketSize); } public void calculate(int cdfBucketNum, double bucketSize) { if (!dataExists) return; // Calculate the distribution function calculateCDF(cdfBucketNum); // Calculate the maximum value max = sortedData[data.length - 1]; min = sortedData[0]; // Calculate the histogram int bucketNum = (int) Math.ceil(max / bucketSize); histogram = new double[bucketNum + 1][2]; int index = 0; for (int i = 0; i < bucketNum; i++) { histogram[i + 1][0] = (i + 1) * bucketSize; while (index < sortedData.length && sortedData[index] <= ((i + 1) * bucketSize)) { histogram[i + 1][1]++; index++; } } sum = 0; for (int i = 0; i < data.length; i++) sum += data[i]; avg = sum / data.length; } private void calculateCDF(int numBuckets) { distribution = new double[numBuckets]; sortedData = new double[data.length]; System.arraycopy(data, 0, sortedData, 0, data.length); Arrays.sort(sortedData); for (int i = 0; i < numBuckets; i++) { double bucketIndex = (double) sortedData.length * (i + 1) / numBuckets; int arrayIndex = ((int) Math.ceil(bucketIndex)) - 1; //log.debug("arrayIndex=" + arrayIndex); if (i < distribution.length / data.length) distribution[i] = Double.NaN; else distribution[i] = sortedData[arrayIndex]; } } public double[] getData() { if (!dataExists) return null; double[] dataArray = new double[index]; System.arraycopy(data, 0, dataArray, 0, index); return dataArray; } public double[][] getDataXY() { return dataExists ? dataXY : null; } public double[] getCDF() { return dataExists ? distribution : null; } public double getCDFValue(int bucket) { return dataExists ? distribution[bucket - 1] : Double.NaN; } public double[][] getHistogram() { return dataExists ? histogram : null; } public double getMax() { return dataExists ? max : Double.NaN; } public double getMin() { return dataExists ? min : Double.NaN; } public double getSum() { return dataExists ? sum : Double.NaN; } public double getAverage() { return dataExists ? avg : Double.NaN; } public static void main(String[] argv) { double[] data = new double[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; //double[] data = new double[] {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; //double[] data = new double[] {-2, 7, 7, 4, 18, -5}; //double[] data = new double[1000]; //double[] data2 = new double[1000]; for (int i = 0; i < data.length; i++) { //data[i] = Util.getRandom().nextGaussian(); //data[i] = Util.getRandomPosInt(1000); //data2[i] = Util.getRandom().nextDouble(); } POut.p("data=" + POut.toString(data)); Stat stat = new Stat(data); stat.calculate(100, 1.0); POut.p("max=" + stat.getMax()); double[] distribution = stat.getCDF(); POut.p("distribution=" + POut.toString(distribution)); double[][] histogram = stat.getHistogram(); POut.p("histogram=" + POut.toString(histogram)); POut.p("50th percentile=" + stat.getCDFValue(50)); /* Stat stat2 = new Stat(data2); stat2.calculateCDF(1000); distribution = stat2.getCDF(); Util.p("distribution2=" + Util.toString(distribution)); */ } } --- NEW FILE: Pair.java --- /* * @author Last modified by $Author: prp $ * @version $Revision: 1.1 $ on $Date: 2007/11/19 17:50:10 $ * @since Jan 11, 2005 */ package edu.harvard.syrah.prp; import java.io.Serializable; /** * Simple implementation of a Pair with generics. * * TODO: * - ensure that T and U are serializable */ @SuppressWarnings("unchecked") public class Pair<T, U> implements Comparable, Serializable { private static final Log log = new Log(Pair.class); static final long serialVersionUID = 1000000001L; public T first; public U second; public Pair() { this(null, null); } public Pair(T first, U second) { this.first = first; this.second = second; } public String toString() { return "(" + (first != null ? first.toString() : "null") + "," + (second != null ? second.toString() : "null") + ")"; } @Override public int hashCode() { int hc = 0; if (first != null) hc += first.hashCode(); if (second != null) hc += second.hashCode(); return hc; } @Override public boolean equals(Object obj) { if (!(obj instanceof Pair)) log.error("Cannot compare Pair to non-Pair."); // Consider the first element Pair cmpPair = (Pair) obj; if (!cmpPair.first.equals(first)) return false; if (second != null) { if (cmpPair.second != null) { if (!cmpPair.second.equals(second)) return false; } else return false; } return true; } /* * @see java.lang.Comparable#compareTo(java.lang.Object) */ @SuppressWarnings("unchecked") public int compareTo(Object o) { if (!(o instanceof Pair)) log.error("Cannot compare Pair to non-Pair."); // Consider the first element Pair cmpPair = (Pair) o; if (!(first instanceof Comparable)) log.error("first is not comparable."); Comparable c1 = (Comparable) first; if (!(cmpPair.first instanceof Comparable)) log.error("cmpPair.first is not comparable."); Comparable c2 = (Comparable) cmpPair.first; int result = c1.compareTo(c2); if (result != 0) return result; // Consider the second element if (!(second instanceof Comparable)) return 0; Comparable d1 = (Comparable) second; if (!(cmpPair.second instanceof Comparable)) return 0; Comparable d2 = (Comparable) cmpPair.second; result = d1.compareTo(d2); return result; } } --- NEW FILE: NetUtil.java --- /* * @author Last modified by $Author: prp $ * @version $Revision: 1.1 $ on $Date: 2007/11/19 17:50:10 $ * @since Jul 5, 2005 */ package edu.harvard.syrah.prp; import java.io.*; import java.net.*; public class NetUtil { protected static final Log log = new Log(NetUtil.class); public static final byte[] HTTP_NEWLINE = NetUtil.toHTTPBytes("\r\n"); public static void checkHttpURL(String urlString) throws IOException { URL url = new URL(urlString); URLConnection connection = url.openConnection(); log.debug("URLConnection opened=" + connection); if (connection instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) connection; httpConnection.connect(); log.debug("HttpURLConnection connected=" + httpConnection); int response = httpConnection.getResponseCode(); if (response != 200 && response != 301 && response != 302) { throw new IOException("Could not access HTTP URL. Reponse=" + response); } } } /** * @param message * @return */ public static byte[] serializeObject(Object obj) { // Serialize a Java object and put it in a byte array ByteArrayOutputStream baOS = new ByteArrayOutputStream(); ObjectOutputStream objOS; try { objOS = new ObjectOutputStream(baOS); objOS.writeObject(obj); objOS.close(); baOS.close(); } catch (IOException e) { log.error("Could not serialize java object: " + e); } return baOS.toByteArray(); } /* public static byte[] serializeObjects(Object obj) { return serializeObjects(new Object[] {obj}); } public static byte[] serializeObjects(Object[] objs) { // Serialize a Java object and put it in a byte array ByteArrayOutputStream baOS = new ByteArrayOutputStream(); ObjectOutputStream objOS; try { objOS = new ObjectOutputStream(baOS); for (Object obj : objs) { objOS.writeObject(obj); } objOS.close(); baOS.close(); } catch (IOException e) { log.error("Could not serialize java object: " + e); } return baOS.toByteArray(); } */ public static Object deserializeObject(byte[] data) { return deserializeObject(data, ClassLoader.getSystemClassLoader()); } /** * @param data * @return */ public static Object deserializeObject(byte[] data, final ClassLoader classLoader) { // Deserialise a byte array into a Java object ByteArrayInputStream baIS = new ByteArrayInputStream(data); ObjectInputStream objIS; Object obj = null; try { objIS = new ObjectInputStream(baIS) { @SuppressWarnings("unchecked") @Override protected Class< ? > resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { //log.info("called with desc=" + desc); Class newClass = classLoader.loadClass(desc.getName()); //log.info("newClass=" + newClass); return newClass; } }; obj = objIS.readObject(); objIS.close(); baIS.close(); } catch (IOException e) { log.warn("Could not deserialize java object: " + e); obj = null; } catch (ClassNotFoundException e) { log.warn("Could not deserialize object: " + e); obj = null; } return obj; } /* public static Object[] deserializeObjects(byte[] data) { return deserializeObjects(data, ClassLoader.getSystemClassLoader()); } public static Object[] deserializeObjects(byte[] data, final ClassLoader classLoader) { Vector<Object> objectVector = new Vector<Object>(); ByteArrayInputStream baIS = new ByteArrayInputStream(data); ObjectInputStream objIS; try { objIS = new ObjectInputStream(baIS) { @Override protected Class< ? > resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { //log.info("called with desc=" + desc); Class newClass = classLoader.loadClass(desc.getName()); //Class newClass = NetUtil.loadClassFromURL(desc.getName(), jarURL, true); //log.info("newClass=" + newClass); return newClass; } }; while (baIS.available() > 0) { Object obj = objIS.readObject(); objectVector.add(obj); } objIS.close(); baIS.close(); } catch (IOException e) { log.error("Could not deserialize java object: " + e); } catch (ClassNotFoundException e) { log.error("Could not deserialize java object and local object: " + e); } return objectVector.toArray(); } */ public static Object deserializeObject(byte[] data, final String jarURL) { return deserializeObject(data, jarURL, ClassLoader.getSystemClassLoader()); } public static Object deserializeObject(byte[] data, final String jarURL, final ClassLoader classLoader) { // Deserialise a byte array into a Java object ByteArrayInputStream baIS = new ByteArrayInputStream(data); ObjectInputStream objIS; Object obj = null; try { objIS = new ObjectInputStream(baIS) { @SuppressWarnings("unchecked") @Override protected Class< ? > resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { //log.info("called with desc=" + desc); Class newClass = NetUtil.loadClassFromURL(desc.getName(), jarURL, classLoader); //log.info("newClass=" + newClass); return newClass; } }; obj = objIS.readObject(); objIS.close(); baIS.close(); } catch (IOException e) { log.warn("Could not deserialize java object: " + e); obj = null; } catch (ClassNotFoundException e) { log.warn("Could not deserialize java object and local object: " + e); obj = null; } return obj; } @SuppressWarnings("unchecked") public static Class loadClassFromURL(String className, String classURL, ClassLoader classLoader) throws MalformedURLException, ClassNotFoundException { Class newClass = null; try { if (classLoader != null) { newClass = classLoader.loadClass(className); } else { throw new ClassNotFoundException("Forcing fresh retrieval"); } } catch (ClassNotFoundException e1) { // Did we get an actual URL? if (classURL.length() > 0) { URL url = null; try { url = new URL(classURL); } catch (MalformedURLException e) { log.warn("Bad URL received: " + e); throw e; } URLClassLoader urlClassLoader = new URLClassLoader(new URL[] {url}); log.debug("Loading class=" + className); log.debug(" from url=" + url); try { newClass = urlClassLoader.loadClass(className); } catch (ClassNotFoundException e) { log.warn("Could not find class (bad URL?): " + e); throw e; } } else { log.warn("Could not locate class=" + className); throw new ClassNotFoundException("Could not locate class=" + className); } } return newClass; } public static String byteIPAddrToString(byte[] byteIPAddr) { StringBuffer sb = new StringBuffer(); sb.append(byteIPAddr[0] & 0Xff).append("."); sb.append(byteIPAddr[1] & 0xff).append("."); sb.append(byteIPAddr[2] & 0xff).append("."); sb.append(byteIPAddr[3] & 0xff); return sb.toString(); } public static String reverseByteIPAddrToString(byte[] byteIPAddr) { StringBuffer sb = new StringBuffer(); sb.append(byteIPAddr[3] & 0Xff).append("."); sb.append(byteIPAddr[2] & 0xff).append("."); sb.append(byteIPAddr[1] & 0xff).append("."); sb.append(byteIPAddr[0] & 0xff); return sb.toString(); } public static int byteIPToIntIP(byte[] byteIPAddr) { return ((byteIPAddr[0] & 0xff) << 24) + ((byteIPAddr[1] & 0xff) << 16) + ((byteIPAddr[2] & 0xff) << 8) + (byteIPAddr[3] & 0xff); } public static byte[] intIPToByteIP(Integer intIPAddr) { byte[] byteIPAddr = new byte[] { (byte) ((intIPAddr >> 24) & 0xff), (byte) ((intIPAddr >> 16) & 0xff), (byte) ((intIPAddr >> 8) & 0xff), (byte) (intIPAddr & 0xff)}; return byteIPAddr; } public static String intIPToString(Integer intIPAddr) { StringBuffer sb = new StringBuffer(); sb.append((byte) ((intIPAddr >> 24) & 0xff)).append("."); sb.append((byte) ((intIPAddr >> 16) & 0xff)).append("."); sb.append((byte) ((intIPAddr >> 8) & 0xff)).append("."); sb.append((byte) (intIPAddr & 0xff)); return sb.toString(); } public static byte[] stringIPToByteIP(String strIP) { String[] octetStr = strIP.split("\\."); byte [] byteIPAddr = new byte[] {(byte) (Integer.valueOf(octetStr[0]).intValue() & 0xff), (byte) (Integer.valueOf(octetStr[1]).intValue() & 0xff), (byte) (Integer.valueOf(octetStr[2]).intValue() & 0xff), (byte) (Integer.valueOf(octetStr[3]).intValue() & 0xff)}; return byteIPAddr; } /** * Returns the US-ASCII encoded byte representation of text for HTTP use (as * per section 2.2 of RFC 2068). */ public static final byte[] toHTTPBytes(String text) { try { return text.getBytes("US-ASCII"); } catch (UnsupportedEncodingException e) { log.error("HTTP requires US-ASCII encoding: " + e); return null; } } public static String toBase64(byte[] data) { // Convert a byte array to base64 string String s = new sun.misc.BASE64Encoder().encode(data); return s; } public static byte[] fromBase64(String base64) { byte[] data = null; try { // Convert base64 string to a byte array data = new sun.misc.BASE64Decoder().decodeBuffer(base64); } catch (IOException e) { log.error(e.toString()); } return data; } public static void main(String[] args) { byte[] byteArray = serializeObject(new Object[] {"Hello", "hello2", 42, 3.444}); Object[] objs = (Object[]) deserializeObject(byteArray); for (Object obj : objs) { POut.p("obj=" + obj.toString()); } } } --- NEW FILE: UnknownPropertyException.java --- /* * @author Last modified by $Author: prp $ * @version $Revision: 1.1 $ on $Date: 2007/11/19 17:50:10 $ * @since Sep 29, 2005 */ package edu.harvard.syrah.prp; public class UnknownPropertyException extends Exception { static final long serialVersionUID = 1000000001L; public UnknownPropertyException(String what) { super(what); } } --- NEW FILE: LongArray.java --- /* * Title: ByteArray * Description: Implements a variable size byte array.<p> * Copyright: Copyright (c) 2001 <p> * Company: Computer Laboratory, Cambridge University <p> * @author Peter Pietzuch <pr...@cl...> * @version 1.0 * * (C) Copyright 2001-2003 Peter R Pietzuch * * This file is part of Util. * * Util is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Util is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with DSSim; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package edu.harvard.syrah.prp; public class LongArray extends PrimitiveArray { private long[] a; public LongArray() { super(); } public LongArray (int initialSize, int growStep) { super(initialSize, growStep); } public LongArray(int initialSize) { super(initialSize); } protected void init(int initialSize) { a = new long[initialSize]; } /** * Adds a new byte value to the array. The array is extended if necessary by doubling its size. * * @param byte Byte to be added. */ public void add(long b) { if ((len + 1) > a.length) { if (growthStep == 0) multiplySize(2); else resize(a.length + growthStep); } a[len++] = b; } public void addAll(long[] b) { addAll(b, b.length); } public void addAll(LongArray longArray) { addAll(longArray.getArray(), longArray.size()); } /** * Adds an byte array to the variable size array. All the values are copied. * * @param b Byte array to be copied. * @param size Size of b to be copied. */ public void addAll(long[] b, int size) { if (size == 0) return; if ((len + size) > a.length) { if (growthStep == 0) multiplySize(((len + size) / a.length) + 1); else { int factor = ((len + size - a.length) / growthStep) + 1; resize ((factor * growthStep) + a.length); } } for (int i = 0; i < size; i++) a[len++] = b[i]; } /** * Returns the byte value at a particular index. * * @param index Index * @return Byte value */ public long get(int index) { if (index >= len) throw new IndexOutOfBoundsException(); return a[index]; } /** * Sets a value in the array to a new value. The index must exist. * * @param value New value * @param index Index */ public void set(long value, int index) { if (index >= len) throw new IndexOutOfBoundsException(); a[index] = value; } /** * Returns a new byte array which has the optimal size. This is done by copying. * * @return Byte Array */ public long[] getArrayCopy() { long[] retA = new long[len]; for (int i = 0; i < len; i++) retA[i] = a[i]; return retA; } public long[] getArray() { return a; } protected void resize(int newSize) { long[] newA = new long[newSize]; for (int i = 0; i < a.length; i++) newA[i] = a[i]; a = newA; } public int capacity() { return a.length; } public String toString() { return POut.toString(getArrayCopy()); } public static void main(String[] args) { Debug.p("hello"); //IntArray a1 = new IntArray(100, 100); LongArray a1 = new LongArray(); long[] ba = {23, 42, 314, 16, 3}; for (int i = 0; i < ... [truncated message content] |