freehep-util-2.0.2/0000755012010301201030000000000011273054221015067 5ustar mascellanimascellanifreehep-util-2.0.2/src/0000755012010301201030000000000011273054221015656 5ustar mascellanimascellanifreehep-util-2.0.2/src/test/0000755012010301201030000000000011273054221016635 5ustar mascellanimascellanifreehep-util-2.0.2/src/test/java/0000755012010301201030000000000011273054221017556 5ustar mascellanimascellanifreehep-util-2.0.2/src/test/java/org/0000755012010301201030000000000011273054221020345 5ustar mascellanimascellanifreehep-util-2.0.2/src/test/java/org/freehep/0000755012010301201030000000000011273054221021763 5ustar mascellanimascellanifreehep-util-2.0.2/src/test/java/org/freehep/util/0000755012010301201030000000000011273054221022740 5ustar mascellanimascellanifreehep-util-2.0.2/src/test/java/org/freehep/util/template/0000755012010301201030000000000011273054221024553 5ustar mascellanimascellanifreehep-util-2.0.2/src/test/java/org/freehep/util/template/test/0000755012010301201030000000000011273054221025532 5ustar mascellanimascellanifreehep-util-2.0.2/src/test/java/org/freehep/util/template/test/Test.java0000644012010301201030000000241710466735775027347 0ustar mascellanimascellanipackage org.freehep.util.template.test; import java.io.IOException; import java.io.InputStreamReader; import java.io.Reader; import org.freehep.util.template.Template; import org.freehep.util.template.TemplateEngine; /** * * @author tonyj */ public class Test { public static void main(String[] args) throws IOException { Template store = new Template(); store.set("title", "Simple Book Template Example"); store.set("name", "JavaBY"); Template book1 = new Template(); book1.set("author", "Alexey Popov"); book1.set("title", "Patterns of using JavaBY Template Engine."); book1.set("year", "2002"); store.append("book", book1); Template book2 = new Template(); book2.set("author", "Garmash Viacheslav"); book2.set("title", "Creating web shop using JavaBY Template Engine."); book2.set("year", "2002"); store.append("book", book2); TemplateEngine engine = new TemplateEngine(); engine.addValueProvider(store); Reader in = new InputStreamReader(Test.class.getResourceAsStream("test.html")); Reader out = engine.filter(in); for (;;) { int c = out.read(); if (c < 0) break; System.out.print((char) c); } } } freehep-util-2.0.2/src/test/java/org/freehep/util/test/0000755012010301201030000000000011273054221023717 5ustar mascellanimascellanifreehep-util-2.0.2/src/test/java/org/freehep/util/test/VersionComparatorTest.java0000644012010301201030000000275610466735775031140 0ustar mascellanimascellanipackage org.freehep.util.test; import junit.framework.*; import org.freehep.util.VersionComparator; /** * * @author Tony Johnson * @version $Id: VersionComparatorTest.java 8584 2006-08-10 23:06:37Z duns $ */ public class VersionComparatorTest extends TestCase { public VersionComparatorTest(java.lang.String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(VersionComparatorTest.class); return suite; } /** * Test of versionNumberCompare method, of class org.freehep.util.VersionComparator. */ public void testVersionNumberCompare() { VersionComparator v = new VersionComparator(); assertTrue(v.compare("1", "2") < 0); assertTrue(v.compare("2", "1") > 0); assertTrue(v.compare("2", "2") == 0); assertTrue(v.compare("2.1", "2.1") == 0); assertTrue(v.compare("2.....1", "2.1") == 0); assertTrue(v.compare("2.1.0", "2.1") == 0); // Correct? assertTrue(v.compare("2.1.1", "2.1") > 0); assertTrue(v.compare("2.1.1", "2.1.2") < 0); assertTrue(v.compare("2.1.1rc1", "2.1.1") < 0); assertTrue(v.compare("2.1.1rc1", "2.1.1rc2") < 0); assertTrue(v.compare("2.1.1rc1", "2.1.1rc1") == 0); assertTrue(v.compare("2.1.1beta1", "2.1.1rc1") < 0); assertTrue(v.compare("2.1.1alpha1", "2.1.1beta1") < 0); } public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } } freehep-util-2.0.2/src/test/java/org/freehep/util/test/UtilTestSuite.java0000644012010301201030000000150710466735775027403 0ustar mascellanimascellanipackage org.freehep.util.test; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; /** * * @author Tony Johnson * @version $Id: UtilTestSuite.java 8584 2006-08-10 23:06:37Z duns $ * */ public class UtilTestSuite extends TestCase { private TestSuite suite; public UtilTestSuite(java.lang.String testName) { super(testName); suite = (TestSuite) suite(); } protected TestSuite getSuite() { return suite; } public static Test suite() { TestSuite suite = new TestSuite(); // Add all the test suites here suite.addTestSuite( DoubleHashtableTest.class ); suite.addTestSuite( VersionComparatorTest.class ); suite.addTestSuite( ScientificFormatTest.class ); return suite; } } freehep-util-2.0.2/src/test/java/org/freehep/util/test/ScientificFormatTest.java0000644012010301201030000001161510466735775030706 0ustar mascellanimascellanipackage org.freehep.util.test; import java.util.Random; import junit.framework.*; import org.freehep.util.ScientificFormat; import org.freehep.util.DoubleWithError; /** * * @author Mark Donszelmann * @version $Id: ScientificFormatTest.java 8584 2006-08-10 23:06:37Z duns $ */ public class ScientificFormatTest extends TestCase { public ScientificFormatTest(java.lang.String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(ScientificFormatTest.class); return suite; } /** * Test of versionNumberCompare method, of class org.freehep.util.VersionComparator. */ public void testScientificFormatCompare() { ScientificFormat f = new ScientificFormat(); assertEquals("1.0000", f.format(1.0)); assertEquals(".10000", f.format(1E-1)); assertEquals(".010000", f.format(1E-2)); assertEquals(".0010000", f.format(1E-3)); assertEquals("1.0000E-4", f.format(1E-4)); assertEquals("1.0000E-5", f.format(1E-5)); assertEquals("1.0000E-6", f.format(1E-6)); assertEquals("10.000", f.format(1E1)); assertEquals("100.00", f.format(1E2)); assertEquals("1000.0", f.format(1E3)); assertEquals("10000", f.format(1E4)); assertEquals("100000", f.format(1E5)); assertEquals("1000000", f.format(1E6)); assertEquals("10000000", f.format(1E7)); assertEquals("1.0000E8", f.format(1E8)); assertEquals("1000000", f.format(999999)); assertEquals("99999", f.format(99999)); assertEquals("9999.0", f.format(9999)); assertEquals("999.00", f.format(999)); assertEquals("99.000", f.format(99)); assertEquals("9.0000", f.format(9)); assertEquals(".90000", f.format(.9)); assertEquals(".090000", f.format(.09)); assertEquals("1000.0", f.format(999.999)); assertEquals("100000", f.format(100000.000001)); assertEquals("100000", f.format(100000.0000001)); assertEquals("100000", f.format(100000.00000001)); assertEquals("100000", f.format(100000.000000001)); assertEquals("100000", f.format(100000.0000000001)); assertEquals("100000", f.format(100000.00000000001)); assertEquals("-1.0000", f.format(-1.0)); assertEquals("-.10000", f.format(-1E-1)); assertEquals("-.010000", f.format(-1E-2)); assertEquals("-.0010000", f.format(-1E-3)); assertEquals("-1.0000E-4", f.format(-1E-4)); assertEquals("-1.0000E-5", f.format(-1E-5)); assertEquals("-1.0000E-6", f.format(-1E-6)); assertEquals("-10.000", f.format(-1E1)); assertEquals("-100.00", f.format(-1E2)); assertEquals("-1000.0", f.format(-1E3)); assertEquals("-10000", f.format(-1E4)); assertEquals("-100000", f.format(-1E5)); assertEquals("-1000000", f.format(-1E6)); assertEquals("-10000000", f.format(-1E7)); assertEquals("-1.0000E8", f.format(-1E8)); assertEquals("-1000000", f.format(-999999)); assertEquals("-99999", f.format(-99999)); assertEquals("-9999.0", f.format(-9999)); assertEquals("-999.00", f.format(-999)); assertEquals("-99.000", f.format(-99)); assertEquals("-9.0000", f.format(-9)); assertEquals("-.90000", f.format(-.9)); assertEquals("-.090000", f.format(-.09)); assertEquals("-1000.0", f.format(-999.999)); assertEquals("-100000", f.format(-100000.000001)); assertEquals("-100000", f.format(-100000.0000001)); assertEquals("-100000", f.format(-100000.00000001)); assertEquals("-100000", f.format(-100000.000000001)); assertEquals("-100000", f.format(-100000.0000000001)); assertEquals("-100000", f.format(-100000.00000000001)); assertEquals("0.0000", f.format(-0)); Random r = new Random(); for (int i=0; i<10000; i++) { double d = r.nextDouble(); String sd = f.format(d); double d2 = Double.parseDouble(sd); assertEquals(d,d2,d*1e-4); } for (int i=0; i<10000; i++) { long l = r.nextLong(); double d = Double.longBitsToDouble(l); String sd = f.format(d); double d2 = Double.parseDouble(sd); if (Double.isNaN(d)) assertTrue(Double.isNaN(d2)); else if (Double.isInfinite(d)) assertTrue(Double.isInfinite(d2)); else assertEquals(d,d2,Math.abs(d)*1e-4); } } public void testDoubleWitheErrorCompare() { ScientificFormat f = new ScientificFormat(); char plusorminus = '\u00b1'; DoubleWithError de = new DoubleWithError(1,.01); assertEquals("1.0000"+plusorminus+".0100",f.format(de)); } public static void main(java.lang.String[] args) { junit.textui.TestRunner.run(suite()); } } freehep-util-2.0.2/src/test/java/org/freehep/util/test/DoubleHashtableTest.java0000644012010301201030000000454510466735775030507 0ustar mascellanimascellanipackage org.freehep.util.test; import java.util.Enumeration; import java.util.Iterator; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.freehep.util.DoubleHashtable; /** * * @author duns * @version $Id: DoubleHashtableTest.java 8584 2006-08-10 23:06:37Z duns $ */ public class DoubleHashtableTest extends TestCase { public DoubleHashtableTest(java.lang.String testName) { super(testName); } public static Test suite() { TestSuite suite = new TestSuite(DoubleHashtableTest.class); return suite; } public void testTable() { DoubleHashtable table = new DoubleHashtable(); assertTrue(table.isEmpty()); table.put("Donszelmann", "Mark", "CERN"); table.put("Donszelmann", "Mark", "SLAC"); table.put("Donszelmann", "Niels", "Knoworries"); table.put("Johnson", "Tony", "SLAC"); table.put(null, "Mark", "Family"); table.put("Donszelmann", null, "Family"); table.put(null, null, "Family"); table.put("Perl", "Joseph", null); assertFalse(table.isEmpty()); assertNotNull(table.get("Donszelmann")); assertNotNull(table.get("Donszelmann", "Mark")); assertEquals(table.get("Donszelmann", "Mark"),"SLAC"); assertNotNull(table.get("Donszelmann", null)); assertEquals(table.get("Donszelmann", null),"Family"); assertNotNull(table.get(null, null)); assertNotNull(table.get(null, "Mark")); assertTrue(table.containsKey("Perl", "Joseph")); assertNull(table.get("Perl", "Joseph")); table.remove("Johnson", "Tony"); assertNull(table.get("Johnson", "Tony")); int count = 0; for (Enumeration e=table.elements(); e.hasMoreElements(); ) { e.nextElement(); count++; } assertEquals(count,table.size()); for (Iterator i=table.iterator(); i.hasNext(); ) { String value = (String)i.next(); if ((value != null) && value.equals("SLAC")) { i.remove(); } } assertNull(table.get("Donszelmann","Mark")); table.clear(); assertTrue(table.isEmpty()); } public static void main(java.lang.String[] args) { TestRunner.run(suite()); } } freehep-util-2.0.2/src/test/resources/0000755012010301201030000000000011273054221020647 5ustar mascellanimascellanifreehep-util-2.0.2/src/test/resources/org/0000755012010301201030000000000011273054221021436 5ustar mascellanimascellanifreehep-util-2.0.2/src/test/resources/org/freehep/0000755012010301201030000000000011273054221023054 5ustar mascellanimascellanifreehep-util-2.0.2/src/test/resources/org/freehep/util/0000755012010301201030000000000011273054221024031 5ustar mascellanimascellanifreehep-util-2.0.2/src/test/resources/org/freehep/util/template/0000755012010301201030000000000011273054221025644 5ustar mascellanimascellanifreehep-util-2.0.2/src/test/resources/org/freehep/util/template/test/0000755012010301201030000000000011273054221026623 5ustar mascellanimascellanifreehep-util-2.0.2/src/test/resources/org/freehep/util/template/test/test.html0000644012010301201030000000062410470537377030512 0ustar mascellanimascellani {v:title} Welcome {v:name} to Simple Template Example
AuthorTitleYear
{v:author} {v:title} {v:year}
freehep-util-2.0.2/src/site/0000755012010301201030000000000011273054221016622 5ustar mascellanimascellanifreehep-util-2.0.2/src/site/site.xml0000644012010301201030000000315010502105024020277 0ustar mascellanimascellani FreeHEP Util http://java.freehep.org/freehep-util FreeHEP http://java.freehep.org/images/sm-freehep.gif http://java.freehep.org/ freehep-util-2.0.2/src/site/apt/0000755012010301201030000000000011273054221017406 5ustar mascellanimascellanifreehep-util-2.0.2/src/site/apt/index.apt0000644012010301201030000000016710502113066021224 0ustar mascellanimascellani --- FreeHEP Util --- --- Mark Donszelmann --- Introduction General utility classes for FreeHEP. freehep-util-2.0.2/src/main/0000755012010301201030000000000011273054221016602 5ustar mascellanimascellanifreehep-util-2.0.2/src/main/java/0000755012010301201030000000000011273054221017523 5ustar mascellanimascellanifreehep-util-2.0.2/src/main/java/org/0000755012010301201030000000000011273054221020312 5ustar mascellanimascellanifreehep-util-2.0.2/src/main/java/org/freehep/0000755012010301201030000000000011273054221021730 5ustar mascellanimascellanifreehep-util-2.0.2/src/main/java/org/freehep/util/0000755012010301201030000000000011273054221022705 5ustar mascellanimascellanifreehep-util-2.0.2/src/main/java/org/freehep/util/OptionParser.java0000644012010301201030000000134210466735775026224 0ustar mascellanimascellanipackage org.freehep.util; import java.util.Map; import java.util.HashMap; import java.util.StringTokenizer; /** * * @author The FreeHEP team @ SLAC * */ public abstract class OptionParser { public static Map parseOptions( String options ) { Map hashValues = new HashMap(); if (options != null) { StringTokenizer st = new StringTokenizer(options,",;"); while ( st.hasMoreTokens() ) { String tk = st.nextToken().toLowerCase().trim(); int pos = tk.indexOf('='); if (pos < 0) hashValues.put(tk,"true"); else hashValues.put(tk.substring(0,pos).trim(),tk.substring(pos+1).trim()); } } return hashValues; } } freehep-util-2.0.2/src/main/java/org/freehep/util/DoubleWithError.java0000644012010301201030000000407410466735775026664 0ustar mascellanimascellanipackage org.freehep.util; /** * A class that encapsulates a value and its error. * Primarily for use with ScientificFormat * * @see ScientificFormat * * @author Tony Johnson * @author Mark Donszelmann * @version $Id: DoubleWithError.java 8584 2006-08-10 23:06:37Z duns $ */ public class DoubleWithError { public DoubleWithError(double value, double error) { this.value = value; this.error = error; this.asymmetricError = false; } public DoubleWithError(double value, double plusError, double minError) { this.value = value; this.error = plusError; this.minError = minError; this.asymmetricError = true; } public void setError(double error) { this.error = error; this.asymmetricError = false; } public void setError(double plusError, double minError) { this.error = plusError; this.minError = minError; this.asymmetricError = true; } public double getError() { // FIXME: what do we return here if this has an asymmetric error return error; } public double getPlusError() { return error; } public double getMinError() { return (asymmetricError) ? minError : error; } public boolean hasAsymmetricError() { return asymmetricError; } public void setValue(double value) { this.value = value; } public double getValue() { return value; } public String toString() { if (asymmetricError) { return String.valueOf(value)+plus+error+minus+minError; } else { return String.valueOf(value)+plusorminus+error; } } // Not private because used by scientific format final static char plusorminus = '\u00b1'; final static char plus = '+'; final static char minus = '-'; private double value; private double error; private boolean asymmetricError; private double minError; } freehep-util-2.0.2/src/main/java/org/freehep/util/ScientificFormat.java0000644012010301201030000001776410466735775027047 0ustar mascellanimascellanipackage org.freehep.util; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.FieldPosition; import java.text.Format; import java.text.ParsePosition; import java.util.Locale; /** * This code formats numbers in Scientific Notation. The input Number object is returned * as a ScientificFormated string. There are two output styles: Pure and Standard scientific * notation. Pure formatted numbers have precisely the number of digits specified by the * significant digits (sigDig) parameter and always specify a Base 10 Exponential(E). * Standard formated numbers have the number of digits specified by the significant * digits (sigDig) parameter but will not have a Base 10 Exponential(E) if the number of digits * in the mantissa <= maxWidth. * * @author Paul Spence * @author Mark Donszelmann * @version $Id: ScientificFormat.java 8584 2006-08-10 23:06:37Z duns $ */ public class ScientificFormat extends Format { /** * The number of significant digits the number is formatted to is recorded by sigDigit. * The maximum width allowed for the returned String is recorded by MaxWidth */ private int sigDigit = 5; private int maxWidth = 8; private boolean sciNote = false; //set to true for pure Scientific Notation private DecimalFormat decimalFormat; private static final long serialVersionUID = -1182686857248711235L; public ScientificFormat() { } /** * Sets the significant digits, maximum allowable width and number formatting style * (SciNote == true for Pure formatting). */ public ScientificFormat(int sigDigit, int maxWidth, boolean SciNote) { setSigDigits(sigDigit); setMaxWidth(maxWidth); setScientificNotationStyle(SciNote); } /** * Implementation of inherited abstract method. Checks to see if object to be formatted * is of type Number. If so casts the Number object to double and calls the format method. * Returns the result. */ public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { if (obj instanceof Number) { String result = format(((Number) obj).doubleValue()); return toAppendTo.append(result); } else if (obj instanceof DoubleWithError) { DoubleWithError dwe = (DoubleWithError) obj; toAppendTo.append(format(dwe.getValue())); if (dwe.hasAsymmetricError()) { toAppendTo.append(DoubleWithError.plus); int errorSigDigit = resolveErrorSigDigit(dwe.getValue(),dwe.getPlusError()); toAppendTo.append(format(dwe.getPlusError(),errorSigDigit)); toAppendTo.append(DoubleWithError.minus); errorSigDigit = resolveErrorSigDigit(dwe.getValue(),dwe.getMinError()); toAppendTo.append(format(dwe.getMinError(),errorSigDigit)); } else { toAppendTo.append(DoubleWithError.plusorminus); int errorSigDigit = resolveErrorSigDigit(dwe.getValue(),dwe.getError()); toAppendTo.append(format(dwe.getError(),errorSigDigit)); } return toAppendTo; } else throw new IllegalArgumentException("Cannot format given Object as a Number"); } /**Dummy implementation of inherited abstract method. */ public Object parseObject(String source, ParsePosition pos) { return null; } /** * Returns the number of significant digits */ public int getSigDigits() { return sigDigit; } /** * Returns the maximum allowable width of formatted number excluding any exponentials */ public int getMaxWidth() { return maxWidth; } /** * Returns the formatting style: True means Pure scientific formatting, False means standard. */ public boolean getScientificNotationStyle() { return sciNote; } /** * Sets the number of significant digits for the formatted number */ public void setSigDigits(int SigDigit) { if (SigDigit < 1) throw new IllegalArgumentException("sigDigit"); sigDigit = SigDigit; decimalFormat = null; } /** * Sets the maximum allowable length of the formattted number mantissa before exponential notation * is used. */ public void setMaxWidth(int mWidth) { if (mWidth < 3) throw new IllegalArgumentException("maxWidth"); maxWidth = mWidth; } /** * Sets the format style used. * There are two output styles: Pure and Standard scientific * notation. Pure formatted numbers have precisely the number of digits specified by the * significant digits (sigDig) parameter and always specify a Base 10 Exponential(E). * Standard formated numbers have the number of digits specified by the significant * digits (sigDig) parameter but will not have a Base 10 Exponential(E) if the number of digits * in the mantissa <= maxWidth. */ public void setScientificNotationStyle(boolean sciNote) { this.sciNote = sciNote; } //simplify method for taking log base 10 of x private final static double k = 1/Math.log(10); private double Log10(double x) { if (x==0) return 0; else return Math.log(x)*k; } private int resolveErrorSigDigit(double x, double dx) { //dx should never be negative dx = Math.abs(dx); //make x +ve cause negative doesn't effect sigdigits x=Math.abs(x); //these circumstances errorsigdit does equal sigdigit, excluding infinity and Nan which are handled by format if(dx == 0 || Double.isInfinite(dx) || Double.isNaN(dx) || dx >= x) return sigDigit; //fail cases for log, method fails to handle if(x==0||Double.isInfinite(x) || Double.isNaN(x))return sigDigit; //otherwise solve for cases when dxmaxWidth) return preliminaryResult; if (exponent<-maxWidth+sigDig+1) return preliminaryResult; // We need to fix up the result int sign = preliminaryResult.charAt(0)=='-' ? 1 : 0; StringBuffer result = new StringBuffer(preliminaryResult.substring(sign,sign+1)+preliminaryResult.substring(sign+2,ePos)); if (exponent >= sigDig) { for (int i=sigDig; i 0) result.insert(0,'-'); return result.toString(); } // /** // * Format a number plus error using scientific notation // */ // public String formatError(double d,double dx) // { // return format(dx, resolveErrorSigDigit(d, dx)); // } }freehep-util-2.0.2/src/main/java/org/freehep/util/DoubleHashtable.java0000644012010301201030000001707610466735775026640 0ustar mascellanimascellani// Copyright 2002, SLAC, Stanford, U.S.A. package org.freehep.util; import java.io.*; import java.util.*; /** * Stores a hashtable of hashtables, which can be indexed by a key and a subkey. * Keys and Values can be null. * * @author Mark Donszelmann * @version $Id: DoubleHashtable.java 8584 2006-08-10 23:06:37Z duns $ */ public class DoubleHashtable extends AbstractCollection implements Serializable { /** * */ private static final long serialVersionUID = -545653328241864972L; private Hashtable table; /** * creates a hashtable of hashtables */ public DoubleHashtable() { table = new Hashtable(); } /** * removes all entries and sub-tables */ public void clear() { table.clear(); } /** * removes all entries from a subtable */ public void clear(Object key) { Hashtable subtable = get(key); if (subtable != null) { subtable.clear(); } } public Object clone() throws CloneNotSupportedException { throw new CloneNotSupportedException("DoubleHashtable.clone() is not (yet) supported."); } /** * @return true if value exists in some sub-table */ public boolean contains(Object value) { if (value == null) value = this; for (Enumeration e=table.keys(); e.hasMoreElements(); ) { Hashtable subtable = get(e.nextElement()); if (subtable.contains(value)) return true; } return false; } /** * @return true if sub-table exists for key */ public boolean containsKey(Object key) { if (key == null) key = this; return table.containsKey(key); } /** * @return true if value exists for key and subkey */ public boolean containsKey(Object key, Object subKey) { if (subKey == null) subKey = this; Hashtable subtable = get(key); return (subtable != null) ? subtable.containsKey(subKey) : false; } /** * @return enumeration over all values in all sub-tables */ public Enumeration elements() { return new Enumeration() { private Enumeration subtableEnumeration = table.elements(); private Enumeration valueEnumeration; private Object nullValue = DoubleHashtable.this; public boolean hasMoreElements() { if ((valueEnumeration == null) || (!valueEnumeration.hasMoreElements())) { if (!subtableEnumeration.hasMoreElements()) { return false; } valueEnumeration = ((Hashtable)subtableEnumeration.nextElement()).elements(); } return true; } public Object nextElement() { hasMoreElements(); Object value = valueEnumeration.nextElement(); return (value == nullValue) ? null : value; } }; } /** * @return iterator over all values in all sub-tables */ public Iterator iterator() { return new Iterator() { private Iterator subtableIterator = table.entrySet().iterator(); private Map subtable; private Iterator valueIterator; private Object nullValue = DoubleHashtable.this; public boolean hasNext() { if ((valueIterator == null) || (!valueIterator.hasNext())) { if (!subtableIterator.hasNext()) { return false; } Map.Entry entry = (Map.Entry)subtableIterator.next(); subtable = (Map)entry.getValue(); valueIterator = subtable.entrySet().iterator(); } return true; } public Object next() { hasNext(); Map.Entry entry = (Map.Entry)valueIterator.next(); Object value = entry.getValue(); return (value == nullValue) ? null : value; } public void remove() { valueIterator.remove(); if (subtable.isEmpty()) { subtableIterator.remove(); } } }; } /** * @return sub-table for key */ public Hashtable get(Object key) { if (key == null) key = this; return (Hashtable)table.get(key); } /** * @return value for key and subkey, null in non-existent or null value was stored */ public Object get(Object key, Object subKey) { if (subKey == null) subKey = this; Hashtable table = get(key); Object value = (table==null) ? null : table.get(subKey); return (value == this) ? null : value; } /** * @return true if table is empty */ public boolean isEmpty() { return table.isEmpty(); } /** * @return enumeration of keys in table */ public Enumeration keys() { return table.keys(); } /** * @return enumeration in subkeys of sub-table pointed by key, and empty if sub-table does not exist */ public Enumeration keys(Object key) { final Hashtable subtable = get(key); return new Enumeration() { private Enumeration subkeys = (subtable == null) ? null : subtable.keys(); private Object nullKey = DoubleHashtable.this; public boolean hasMoreElements() { return (subkeys == null) ? false : subkeys.hasMoreElements(); } public Object nextElement() { if (subkeys == null) { throw new NoSuchElementException(); } Object subkey = subkeys.nextElement(); return (subkey == nullKey) ? null : subkey; } }; } /** * puts a value in sub-table specified by key and subkey. * * @return previous value */ public Object put(Object key, Object subKey, Object value) { // Make sure there exists a subtable Hashtable subtable = get(key); if (subtable == null) { subtable = new Hashtable(); if (key == null) key = this; table.put(key, subtable); } // add entry and handle nulls if (subKey == null) subKey = this; if (value == null) value = this; Object old = subtable.get(subKey); subtable.put(subKey, value); // return previous entry return (old == this) ? null : old; } /** * removes value from sub-table specified by key and subkey. * * @return previous value */ public Object remove(Object key, Object subKey) { // look for subtable Hashtable subtable = get(key); if (subtable == null) return null; // remove from subtable if (subKey == null) subKey = this; Object old = subtable.remove(subKey); // remove subtable if needed if (subtable.isEmpty()) { if (key == null) key = this; table.remove(key); } // return old value return (old == this) ? null : old; } /** * @return size of all tables */ public int size() { int size =0; for (Enumeration e = table.keys(); e.hasMoreElements(); ) { Object key = e.nextElement(); Hashtable subtable = get(key); size += subtable.size(); } return size; } /** * @return a string representation of the table */ public String toString() { return "DoubleHashtable@"+hashCode(); } } freehep-util-2.0.2/src/main/java/org/freehep/util/Value.java0000644012010301201030000003326110513737007024637 0ustar mascellanimascellani/* * Value.java * * Created on January 4, 2001, 11:37 AM */ package org.freehep.util; import java.lang.reflect.Constructor; import java.util.Date; import java.text.SimpleDateFormat; import java.text.ParseException; /** * A class that can represent any Java object or primitive. Unlike the * built-in primitive proxies (Double, Integer etc) it is mutable. It is * used to allow values to be used without needing overloaded methods for * each primitive type, and without the overhead of object creation/deletion. * * When a value is returned by an Object method it should be assumed to be valid * only until the next method call to that Object. The use of Value should be * avoided in multi-threaded environments. * * @author tonyj * @version $Id: Value.java 9133 2006-10-13 16:25:43Z turri $ */ public class Value { private int intValue; private short shortValue; private long longValue; private float floatValue; private double doubleValue; private boolean boolValue; private byte byteValue; private char charValue; private Object obj; private Class type; public final static Class TYPE_INTEGER = Integer.TYPE; public final static Class TYPE_SHORT = Short.TYPE; public final static Class TYPE_LONG = Long.TYPE; public final static Class TYPE_FLOAT = Float.TYPE; public final static Class TYPE_DOUBLE = Double.TYPE; public final static Class TYPE_BOOLEAN = Boolean.TYPE; public final static Class TYPE_BYTE = Byte.TYPE; public final static Class TYPE_CHAR = Character.TYPE; public final static Class TYPE_STRING = String.class; public final static Class TYPE_DATE = Date.class; public Value() {} public Value( Value v ) { setValue(v); } public Value setValue(Value v) { this.type = v.getType(); this.intValue = v.intValue; this.shortValue = v.shortValue; this.longValue = v.longValue; this.floatValue = v.floatValue; this.doubleValue = v.doubleValue; this.boolValue = v.boolValue; this.byteValue = v.byteValue; this.charValue = v.charValue; this.obj = v.obj; return this; } /** * Get the Value's type * @return The Class of this Value. * */ public Class getType() { return type; } /** * Set the Value's internal value to an integer. * @param val The integer value. * @return The Value object with the given internal value. * */ public Value set(int val) { intValue = val; type = TYPE_INTEGER; return this; } /** * Set the Value's internal value to a short. * @param val The short value. * @return The Value object with the given internal value. * */ public Value set(short val) { shortValue = val; type = TYPE_SHORT; return this; } /** * Set the Value's internal value to a long. * @param val The long value. * @return The Value object with the given internal value. * */ public Value set(long val) { longValue = val; type = TYPE_LONG; return this; } /** * Set the Value's internal value to a float. * @param val The float value. * @return The Value object with the given internal value. * */ public Value set(float val) { floatValue = val; type = TYPE_FLOAT; return this; } /** * Set the Value's internal value to a double. * @param val The double value. * @return The Value object with the given internal value. * */ public Value set(double val) { doubleValue = val; type = TYPE_DOUBLE; return this; } /** * Set the Value's internal value to a boolean. * @param val The boolean value. * @return The Value object with the given internal value. * */ public Value set(boolean val){ boolValue = val; type = TYPE_BOOLEAN; return this; } /** * Set the Value's internal value to a byte. * @param val The byte value. * @return The Value object with the given internal value. * */ public Value set(byte val) { byteValue = val; type = TYPE_BYTE; return this; } /** * Set the Value's internal value to a char. * @param val The char value. * @return The Value object with the given internal value. * */ public Value set(char val) { charValue = val; type = TYPE_CHAR; return this; } /** * Set the Value's internal value to a String. * @param val The String value. * @return The Value object with the given internal value. * */ public Value set(String val) { obj = val; type = TYPE_STRING; return this; } /** * Set the Value's internal value to a Date. * @param val The Date value. * @return The Value object with the given internal value. * */ public Value set(Date val) { obj = val; type = TYPE_DATE; return this; } /** * Set the Value's internal value to an Object. * @param val The Object value. * @return The Value object with the given internal value. * */ public Value set(Object val) { obj = val; type = obj == null ? Object.class : obj.getClass(); return this; } /** * Get the integer value. * @return The int value. * @exception A ClassCastException is thrown if this Value has incompatible type. * */ public int getInt() { if (type == TYPE_INTEGER) return intValue; else if (type == TYPE_SHORT) return shortValue; else if (type == TYPE_BYTE) return byteValue; else throw new ClassCastException( "getInt cannot be called for type "+type.toString()); } /** * Get the short value. * @return The short value. * @exception A ClassCastException is thrown if this Value has incompatible type. * */ public short getShort() { if (type == TYPE_SHORT) return shortValue; else if (type == TYPE_BYTE) return byteValue; else throw new ClassCastException( "getShort cannot be called for type "+type.toString()); } /** * Get the long value. * @return The long value. * @exception A ClassCastException is thrown if this Value has incompatible type. * */ public long getLong() { if (type == TYPE_LONG) return longValue; else if (type == TYPE_INTEGER) return intValue; else if (type == TYPE_SHORT) return shortValue; else if (type == TYPE_BYTE) return byteValue; else throw new ClassCastException( "getLong cannot be called for type "+type.toString()); } /** * Get the float value. * @return The float value. * @exception A ClassCastException is thrown if this Value has incompatible type. * */ public float getFloat() { if (type == TYPE_FLOAT) return floatValue; else if (type == TYPE_INTEGER) return intValue; else if (type == TYPE_SHORT) return shortValue; else if (type == TYPE_LONG) return longValue; else if (type == TYPE_BYTE) return byteValue; else throw new ClassCastException( "getFloat cannot be called for type "+type.toString()); } /** * Get the double value. * @return The double value. * @exception A ClassCastException is thrown if this Value has incompatible type. * */ public double getDouble() { if (type == TYPE_DOUBLE) return doubleValue; else if (type == TYPE_INTEGER) return intValue; else if (type == TYPE_SHORT) return shortValue; else if (type == TYPE_LONG) return longValue; else if (type == TYPE_FLOAT) return floatValue; else if (type == TYPE_BYTE) return byteValue; else if (type == TYPE_DATE) return ((Date)obj).getTime(); else throw new ClassCastException( "getDouble cannot be called for type "+type.toString()); } /** * Get the boolean value. * @return The boolean value. * @exception A ClassCastException is thrown if this Value has incompatible type. * */ public boolean getBoolean() { if (type == TYPE_BOOLEAN) return boolValue; else throw new ClassCastException( "getBoolean cannot be called for type "+type.toString()); } /** * Get the byte value. * @return The byte value. * @exception A ClassCastException is thrown if this Value has incompatible type. * */ public byte getByte() { if (type == TYPE_BYTE) return byteValue; else throw new ClassCastException( "getByte cannot be called for type "+type.toString()); } /** * Get the char value. * @return The char value. * @exception A ClassCastException is thrown if this Value has incompatible type. * */ public char getChar() { if (type == TYPE_CHAR) return charValue; else throw new ClassCastException( "getChar cannot be called for type "+type.toString()); } /** * Get the String value. * @return The String representation of the internal value. * */ public String getString() { if (type == TYPE_STRING) return (String)obj; else if (type == TYPE_INTEGER) return String.valueOf(intValue); else if (type == TYPE_SHORT) return String.valueOf(shortValue); else if (type == TYPE_LONG) return String.valueOf(longValue); else if (type == TYPE_FLOAT) return String.valueOf(floatValue); else if (type == TYPE_DOUBLE) return String.valueOf(doubleValue); else if (type == TYPE_BOOLEAN) return String.valueOf(boolValue); else if (type == TYPE_BYTE) return String.valueOf(byteValue); else if (type == TYPE_CHAR) return String.valueOf(charValue); else if (type == TYPE_DATE) return ((Date)obj).toString(); else return obj != null ? obj.toString(): "null"; } /** * Get the Date value. * @return The Date value. * @exception A ClassCastException is thrown if this Value has incompatible type. * */ public Date getDate() { if (type == TYPE_DATE) return (Date)obj; else throw new ClassCastException( "getDate cannot be called for type "+type.toString()); } /** * Get the Object value. * @return The Object value. * */ public Object getObject() { if (obj != null) return obj; else if (type == TYPE_INTEGER) return new Integer(intValue); else if (type == TYPE_SHORT) return new Short(shortValue); else if (type == TYPE_LONG) return new Long(longValue); else if (type == TYPE_FLOAT) return new Float(floatValue); else if (type == TYPE_DOUBLE) return new Double(doubleValue); else if (type == TYPE_BOOLEAN) return new Boolean(boolValue); else if (type == TYPE_BYTE) return new Byte(byteValue); else if (type == TYPE_CHAR) return new Character(charValue); else return null; } /** * Get the String value. * @return The String representation of the internal value. * */ public String toString() { return getString(); } /** * Returns an external representation of this value */ public String toExternal() { // FIXME, does not work for arrays... return type.getName()+":"+getString(); } /** * Set to value from the external respresentation */ public Value fromExternal(String external) throws IllegalArgumentException { String[] part = external.split(":", 2); if (part.length != 2) throw new IllegalArgumentException(getClass()+": External '"+external+ "'does not contain ':' to separate type from value."); if (part[0].equals(TYPE_STRING.getName())) { return set(part[1]); } else if (part[0].equals(TYPE_SHORT.getName())) { return set(Short.parseShort(part[1])); } else if (part[0].equals(TYPE_LONG.getName())) { return set(Long.parseLong(part[1])); } else if (part[0].equals(TYPE_FLOAT.getName())) { return set(Float.parseFloat(part[1])); } else if (part[0].equals(TYPE_DOUBLE.getName())) { return set(Double.parseDouble(part[1])); } else if (part[0].equals(TYPE_BOOLEAN.getName())) { return set(Boolean.getBoolean(part[1])); } else if (part[0].equals(TYPE_BYTE.getName())) { return set(Byte.parseByte(part[1])); } else if (part[0].equals(TYPE_CHAR.getName())) { return set(part[1].charAt(0)); } else if (part[0].equals(TYPE_INTEGER.getName())) { return set(Integer.parseInt(part[1])); } else if (part[0].equals(TYPE_DATE.getName())) { try { return set(new SimpleDateFormat().parse(part[1])); } catch (ParseException e) { throw new IllegalArgumentException(e.getMessage()); } } else if (part[0].equals(Object.class.getName()) && part[1].equals("null")) { return set((Object)null); } else { // FIXME will not work for arrays, which are encoded as "[Lpackagename.classname;" try { Class cls = Class.forName(part[0]); Constructor ctor = cls.getDeclaredConstructor(new Class[] { String.class }); ctor.setAccessible(true); return set(ctor.newInstance(new Object[] { part[1] })); } catch (Exception e) { throw new IllegalArgumentException(getClass()+": Cannot reconstruct value from type: "+part[0]+", " +"and value "+part[1]+", due to "+e.getMessage()); } } } } freehep-util-2.0.2/src/main/java/org/freehep/util/StringUtilities.java0000644012010301201030000000337710466735775026753 0ustar mascellanimascellani// Copyright Freehep 2006. package org.freehep.util; import java.util.regex.Pattern; /** * * @author Mark Donszelmann * @version $Id: StringUtilities.java 8584 2006-08-10 23:06:37Z duns $ */ public class StringUtilities { private StringUtilities() { // static methods only } public static String replace(CharSequence target, CharSequence replacement, String string) { return Pattern.compile(quote(target.toString()) /* Pattern.LITERAL jdk 1.4 */).matcher( string).replaceAll(/* Matcher. jdk 1.4 */ quoteReplacement(replacement.toString())); } /* for jdk 1.4 */ private static String quote(String s) { int slashEIndex = s.indexOf("\\E"); if (slashEIndex == -1) return "\\Q" + s + "\\E"; StringBuffer sb = new StringBuffer(s.length() * 2); sb.append("\\Q"); slashEIndex = 0; int current = 0; while ((slashEIndex = s.indexOf("\\E", current)) != -1) { sb.append(s.substring(current, slashEIndex)); current = slashEIndex + 2; sb.append("\\E\\\\E\\Q"); } sb.append(s.substring(current, s.length())); sb.append("\\E"); return sb.toString(); } /* for jdk 1.4 */ private static String quoteReplacement(String s) { if ((s.indexOf('\\') == -1) && (s.indexOf('$') == -1)) return s; StringBuffer sb = new StringBuffer(); for (int i=0; i * Example of use: *
 * Hello {v:user.name}
 * 
* @author tonyj * @version $Id: PropertiesValueProvider.java 8584 2006-08-10 23:06:37Z duns $ */ public class PropertiesValueProvider implements ValueProvider { private Properties props; /** Builds a PropertiesValueProvider which takes its values from * the system properties. * @see java.lang.System#getProperties() */ public PropertiesValueProvider() { this(null); } /** Builds a PropertiesValueProvider which takes its values from * the specified Properties object. * @param props The properties to use. */ public PropertiesValueProvider(Properties props) { this.props = props; } public String getValue(String name) { return props == null ? System.getProperty(name) : props.getProperty(name); } public List getValues(String name) { return null; } }freehep-util-2.0.2/src/main/java/org/freehep/util/template/TemplateEngine.java0000644012010301201030000001574610466735775030330 0ustar mascellanimascellanipackage org.freehep.util.template; import java.io.FilterReader; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** A very simple template engine. The template engine takes input and transforms * it by looking for tags in the document, and replacing them with values provided * by a set of ValueProviders. *

* Example of HTML template:

* <html>
* <head>
* <title>{v:title}</title>
* </head>
* <body>
* Welcome {v:name} to Simple Template Example
* <table>
* <tr bgcolor="d0d0d0"><th>Author</th><th>Title</th><th>Year</th></tr>
* <t:book>
* <tr>
* <td><a href="#">{v:author}</a></td>
* <td><a href="#">{v:title}</a></td>
* <td><a href="#">{v:year}</a></td>
* </tr>
* </t:book>
* </table>
* </body>
* </html>
*

* The design (although not the code) was inspired by the JByte template engine * @link {http://javaby.sourceforge.net/}. * @author tonyj * @version $Id: TemplateEngine.java 8584 2006-08-10 23:06:37Z duns $ */ public class TemplateEngine { /** Apply the template to a document. * @param in The Reader from which the document will be read. * @return A Reader from which the filtered document can be read. */ public Reader filter(Reader in) { return new TemplateReader(in,providers); } /** Add a value provider to the set of value providers * @param p The ValueProvider to add */ public void addValueProvider(ValueProvider p) { providers.add(p); } /** Remove a value provider from the list of value providers. * @param p The value provider to remove. */ public void removeValueProvider(ValueProvider p) { providers.remove(p); } private List providers = new ArrayList(); private static class TemplateReader extends FilterReader { TemplateReader(Reader in, List providers) { super(in); this.providers = providers; } public int read() throws IOException { outer: for (;;) { if (subReader != null) { int c = subReader.read(); if (c >= 0) return c; subReader = null; } if (templateIterator != null) { if (templateIterator.hasNext()) { ValueProvider vp = (ValueProvider) templateIterator.next(); subReader = new TemplateReader(new StringReader(buf.toString()),Collections.singletonList(vp)); continue; } else { templateIterator = null; buf.delete(0, buf.length()); } } if (state < 0) { int rc = buf.charAt(buf.length()+state++); if (state == 0) buf.delete(0,buf.length()); return rc; } int c = in.read(); if (c<0) { state = -buf.length(); if (state == 0) return -1; continue; } if (templateMarker > 0) { buf.append((char) c); if (state == 0 && c == '<') state++; else if (state == 1 && c == '/') state++; else if (state > 1 && buf.charAt(state-1) == c) state++; else state = 0; if (state-1 == templateMarker) // Found end of template { String symb = buf.substring(3,templateMarker-1); for (int i=0; i 2 && (template ? c!='>' : c!='}')) { state++; buf.append((char) c); } else if (state > 2) { if (template) { // Everything must go into the string buffer until we // find end of template buf.append((char) c); state++; templateMarker = state; state = 0; } else { String symb = buf.substring(3); for (int i=0; i Template store = new Template(); * * store.set("title", "Simple Book Template Example"); * store.set("name", "JavaBY"); * * Template book1 = new Template(); * book1.set("author", "Alexey Popov"); * book1.set("title", "Patterns of using JavaBY Template Engine."); * book1.set("year", "2002"); * store.append("book", book1); * * Template book2 = new Template(); * book2.set("author", "Garmash Viacheslav"); * book2.set("title", "Creating web shop using JavaBY Template Engine."); * book2.set("year", "2002"); * store.append("book", book2); * * TemplateEngine engine = new TemplateEngine(); * engine.addValueProvider(store); * Reader in = new InputStreamReader(Test.class.getResourceAsStream("test.html")); * Reader out = engine.filter(in); * @author tonyj * @version $Id: Template.java 8584 2006-08-10 23:06:37Z duns $ */ public class Template implements ValueProvider { private Map values = new HashMap(); private Map templates = new HashMap(); /** Create an empty template. */ public Template() { } public String getValue(String name) { return (String) values.get(name); } public List getValues(String name) { return (List) templates.get(name); } /** Set a value. * @param name The name of the value * @param value The value */ public void set(String name, String value) { values.put(name,value); } /** Append a template to this template * @param name The name of the template to add. * @param template The template. */ public void append(String name, Template template) { List l = (List) templates.get(name); if (l == null) { l = new ArrayList(); templates.put(name,l); } l.add(template); } } freehep-util-2.0.2/src/main/java/org/freehep/util/template/package.html0000644012010301201030000000017010470537377027017 0ustar mascellanimascellani

A simple template engine.

@Status Stable.

freehep-util-2.0.2/src/main/java/org/freehep/util/template/ValueProvider.java0000644012010301201030000000141310466735775030200 0ustar mascellanimascellanipackage org.freehep.util.template; import java.util.List; /** An interface to be implemented by anything that wishes * to provide values to the template engine. * @author tonyj * @version $Id: ValueProvider.java 8584 2006-08-10 23:06:37Z duns $ */ public interface ValueProvider { /** Get a single value * @param name The name whose value is to be returned * @return The value, or null if undefined. */ String getValue(String name); /** Get a list of value providers. * Each item in the returned list must itself be a ValueProvider. * @param name The template name of the list to be returned. * @return The list of value providers, or null if no template is defined. */ List getValues(String name); } freehep-util-2.0.2/src/main/java/org/freehep/util/VersionComparator.java0000644012010301201030000000253110466735775027255 0ustar mascellanimascellanipackage org.freehep.util; import java.util.Comparator; /** * * @author Tony Johnson * @version $Id: VersionComparator.java 8584 2006-08-10 23:06:37Z duns $ */ public class VersionComparator implements Comparator { private static String[] special = { "alpha" , "beta", "rc" }; private static String pattern = "\\.+"; /** * Compares two version numbers of the form 1.2.3.4 * @return >0 if v1>v2, <0 if v1The Netbeans Lookup API * @see The service provider mechanism * @author tonyj * @version $Id: FreeHEPLookup.java 8584 2006-08-10 23:06:37Z duns $ */ public class FreeHEPLookup extends Lookup { private static InstanceContent ic = new InstanceContent(); private static AbstractLookup contentLookup = new AbstractLookup(ic); private static FreeHEPLookup theLookup = new FreeHEPLookup(); private MyProxyLookup proxy; private FreeHEPLookup() { proxy = new MyProxyLookup(contentLookup, Lookup.getDefault()); } /** Access a singleton instance of FreeHEPLookup.ProxyLookup * @return The singleton instance of FreeHEPLookup */ public static FreeHEPLookup instance() { return theLookup; } /** Add an instance of an Object to the lookup. * @param instance The object to add. */ public void add(Object instance) { ic.add(instance); } /** Add an instance with an ID. * @param instance The instance to add. * @param id The ID associated with the instance */ public void add(Object instance, String id) { ic.addPair(new DontAsk(instance,id)); } /** Add an instance with multiple IDs. * @param instance The instance to add. * @param ids The IDs associated with the instance. */ public void add(Object instance, String[] ids) { for ( int i = 0; i < ids.length; i++ ) ic.addPair(new DontAsk(instance,ids[i])); } /** Remove an instance from the lookup * @param instance The instance to remove */ public void remove(Object instance) { ic.remove(instance); } /** Remove an instance with a specific ID. * @param instance The instance to remove * @param id The ID of the instance */ public void remove(Object instance, String id) { ic.removePair(new DontAsk(instance,id)); } /** Remove an instance with multiple IDs * @param instance The instance to remove * @param ids The IDs of the instance */ public void remove(Object instance, String[] ids) { for ( int i = 0; i < ids.length; i++ ) ic.removePair(new DontAsk(instance,ids[i])); } /** Sets the ClassLoader used for subsequent service API lookups * @param loader The ClassLoader to use. */ public void setClassLoader(ClassLoader loader) { Lookup serviceLookup = new MetaInfServicesLookup(loader); proxy.setLookups(contentLookup, serviceLookup); } public Lookup.Result lookup(Lookup.Template template) { return proxy.lookup(template); } public Object lookup(Class clazz) { return proxy.lookup(clazz); } private class DontAsk extends Pair { private static final long serialVersionUID = -6621505967094205187L; private Object instance; private String id; DontAsk(Object instance, String id) { this.id = id; this.instance = instance; } protected boolean creatorOf(Object obj) { return obj == instance; } public String getDisplayName() { return instance.toString(); } public String getId() { return id; } public Object getInstance() { return instance; } public Class getType() { return instance.getClass(); } protected boolean instanceOf(Class clazz) { return clazz.isInstance(instance); } public boolean equals(Object xx) { if (xx instanceof DontAsk) { DontAsk other = (DontAsk) xx; return other.instance == this.instance && other.id.equals(this.id); } else return false; } public int hashCode() { return instance.hashCode() + id.hashCode(); } } private class MyProxyLookup extends ProxyLookup { MyProxyLookup(Lookup a, Lookup b) { super(new Lookup[]{a, b}); } private void setLookups(Lookup a, Lookup b) { super.setLookups(new Lookup[]{a, b}); } } } freehep-util-2.0.2/src/main/java/org/freehep/util/DiscreteAngle.java0000644012010301201030000000671410466735775026320 0ustar mascellanimascellani// Copyright 2003, SLAC, Stanford, U.S.A. package org.freehep.util; import java.util.Iterator; import java.util.SortedSet; import java.util.TreeSet; /** * Calculates a discrete angle from an arbitrary angle, based on a set of * given angles. * * The class calculates the angle by dividing 360 degrees into segments * based on the discrete angles. It then will calculate the closest discrete angle * for a given angle. Discrete angles can be added and removed. * * This class can be used to constrain the mouse movement (or its result) if one * wants to draw under certain angles only. * * @author Mark Donszelmann * @version $Id: DiscreteAngle.java 8584 2006-08-10 23:06:37Z duns $ */ public class DiscreteAngle { private SortedSet angles; public DiscreteAngle() { angles = new TreeSet(); } /** * Returns the closest angle to any discrete angle in the set. Returns itself * if the set is empty. Returns the only discrete angle if the set only contains * one angle. */ public double getAngle(double angle) { if (angles.isEmpty()) return angle; Iterator i = angles.iterator(); Double prev = (Double)i.next(); if (!i.hasNext()) return prev.doubleValue(); while (i.hasNext()) { Double cur = (Double)i.next(); double cutoff = (cur.doubleValue() - prev.doubleValue()) / 2.0 + prev.doubleValue(); if (angle <= cutoff) return prev.doubleValue(); prev = cur; } return prev.doubleValue(); } /** * Adds a discrete angle to the set. */ public Double addAngle(double angle) { Double a = new Double(angle); angles.add(a); return a; } /** * Removes a discrete angle from the set. */ public boolean removeAngle(double angle) { for (Iterator i = angles.iterator(); i.hasNext(); ) { Double r = (Double)i.next(); if (r.doubleValue() == angle) { return removeAngle(r); } } return false; } /** * Removes a discrete angle from the set. */ public boolean removeAngle(Double angle) { return (angle != null) ? angles.remove(angle) : false; } public String toString() { StringBuffer s = new StringBuffer(); s.append("Angles: "); for (Iterator i = angles.iterator(); i.hasNext(); ) { Double r = (Double)i.next(); s.append(r.doubleValue()); if (i.hasNext()) s.append(", "); } return s.toString(); } public static void main(String[] args) { DiscreteAngle da = new DiscreteAngle(); da.addAngle(0); da.addAngle(90); da.addAngle(180); da.addAngle(270); da.addAngle(360); da.addAngle(10); da.addAngle(190); System.out.println(" 0 results in "+da.getAngle( 0)); System.out.println(" 1 results in "+da.getAngle( 1)); System.out.println(" 5 results in "+da.getAngle( 5)); System.out.println(" 80 results in "+da.getAngle( 80)); System.out.println(" 90 results in "+da.getAngle( 90)); System.out.println("170 results in "+da.getAngle(170)); System.out.println("185 results in "+da.getAngle(185)); System.out.println("186 results in "+da.getAngle(186)); System.out.println("231 results in "+da.getAngle(231)); System.out.println("359 results in "+da.getAngle(359)); } } freehep-util-2.0.2/src/main/java/org/freehep/util/Factory.java0000644012010301201030000000763510466735775025221 0ustar mascellanimascellani// Copyright 2000-2004, FreeHEP. package org.freehep.util; import java.io.*; import java.util.*; /** * Methods to use factories (a la JAXP). * * @author Mark Donszelmann * @version $Id: Factory.java 8584 2006-08-10 23:06:37Z duns $ */ public class Factory { // static class private Factory() { } /** * Find the correct factory name, based on the following procedure: *
    *
  1. Use the specified system property: factoryName. *
  2. Use the specified property file in JAVA_HOME/lib/ and the * specified property: factoryName. *
  3. Use the Services API (as detailed in the JAR specification) to look * for the classname in META-INF/services/. *
  4. Use the specfied default factory: defaultFactory. *
* * @param factoryName name to be used for lookup * @param factoryFile filename to look for in JAVA_HOME/lib * @param defaultFactory name of the default factory * @return the name of the factory according to the procedure above */ public static String findFactory(String factoryName, String factoryFile, String defaultFactory) { // try System Property String factory = null; try { factory = System.getProperty(factoryName); if (factory != null) { return factory; } } catch(SecurityException securityexception) { } // try JAVA_HOME/lib try { String javaHome = System.getProperty("java.home"); String configFile = javaHome + File.separator + "lib" + File.separator + factoryFile; File file = new File(configFile); if (file.exists()) { Properties props = new Properties(); props.load(new FileInputStream(file)); factory = props.getProperty(factoryName); if (factory != null) { return factory; } } } catch(Exception e) { e.printStackTrace(); } // try Services API String service1 = "meta-inf/services/" + factoryName; String service2 = "META-INF/services/" + factoryName; try { ClassLoader loader = null; try { loader = Class.forName("org.freehep.util.Factory").getClassLoader(); } catch(ClassNotFoundException cnfe) { cnfe.printStackTrace(); } InputStream stream = null; if (loader == null) { stream = ClassLoader.getSystemResourceAsStream(service1); } else { stream = loader.getResourceAsStream(service1); } if (stream == null) { if (loader == null) { stream = ClassLoader.getSystemResourceAsStream(service2); } else { stream = loader.getResourceAsStream(service2); } } if(stream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); factory = reader.readLine(); reader.close(); if (factory != null && !factory.equals("")) { return factory; } } } catch(Exception e) { e.printStackTrace(); } return defaultFactory; } public static Object loadFactory(String name, String file, String defaultImplementation) { String factoryName = findFactory(name, file, defaultImplementation); try { System.out.println("Loading factory: "+factoryName); Class factoryClass = Class.forName(factoryName); return factoryClass.newInstance(); } catch (Exception e) { System.err.println("Unable to load factory: "+factoryName); e.printStackTrace(); } return null; } } freehep-util-2.0.2/src/main/java/org/freehep/util/images/0000755012010301201030000000000011273054221024152 5ustar mascellanimascellanifreehep-util-2.0.2/src/main/java/org/freehep/util/images/ImageUtilities.java0000644012010301201030000001250110555206622027740 0ustar mascellanimascellani// Copyright 2001-2007, FreeHEP. package org.freehep.util.images; import java.awt.Color; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.image.ColorModel; import java.awt.image.ImageObserver; import java.awt.image.Raster; import java.awt.image.RenderedImage; /** * @author Mark Donszelmann * @version $Id: ImageUtilities.java 10366 2007-01-22 19:16:34Z duns $ */ public class ImageUtilities { private ImageUtilities() { } public static RenderedImage createRenderedImage(Image image, ImageObserver observer, Color bkg) { if ((bkg == null) && (image instanceof RenderedImage)) return (RenderedImage)image; BufferedImage bufferedImage = new BufferedImage( image.getWidth(observer), image.getHeight(observer), (bkg == null) ? BufferedImage.TYPE_INT_ARGB : BufferedImage.TYPE_INT_RGB); Graphics g = bufferedImage.getGraphics(); if (bkg == null) { g.drawImage(image, 0, 0, observer); } else { g.drawImage(image, 0, 0, bkg, observer); } return bufferedImage; } public static BufferedImage createBufferedImage(RenderedImage image, ImageObserver observer, Color bkg) { if (image instanceof BufferedImage) return (BufferedImage)image; throw new IllegalArgumentException("not supperted " + image.getClass()); } public static BufferedImage createBufferedImage(Image image, ImageObserver observer, Color bkg) { if ((bkg == null) && (image instanceof BufferedImage)) return (BufferedImage)image; return (BufferedImage) createRenderedImage(image, observer, bkg); } public static RenderedImage createRenderedImage(RenderedImage image, Color bkg) { if (bkg == null) return image; BufferedImage bufferedImage = new BufferedImage( image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = (Graphics2D)bufferedImage.getGraphics(); g.setBackground(bkg); g.clearRect(0, 0, image.getWidth(), image.getHeight()); g.drawRenderedImage(image, new AffineTransform()); return bufferedImage; } public static byte[] getBytes(Image image, Color bkg, String code, int pad, ImageObserver observer) { return getBytes(createRenderedImage(image, observer, bkg), bkg, code, pad); } /** * Returns the bytes of an image. * * @param image to be converted to bytes * @param bkg the color to be used for alpha-multiplication * @param code ARGB, A, or BGR, ... you may also use *ARGB to pre-multiply with alpha * @param pad number of bytes to pad the scanline with (1=byte, 2=short, 4=int, ...) */ public static byte[] getBytes(RenderedImage image, Color bkg, String code, int pad) { if (pad < 1) pad = 1; Raster raster = image.getData(); int width = image.getWidth(); int height = image.getHeight(); boolean preMultiply = (code.charAt(0) == '*'); if (preMultiply) code = code.substring(1); int pixelSize = code.length(); int size = width*height*pixelSize; size += (width % pad)*height; int index = 0; byte[] bytes = new byte[size]; ColorModel colorModel = image.getColorModel(); for (int y=0; y> 24) & 0xFF); int r = ((argb >> 16) & 0xFF); int g = ((argb >> 8) & 0xFF); int b = ((argb >> 0) & 0xFF); // Check the transparancy. If transparent substitute // the background color. if (preMultiply && (a < 0xFF)) { if (bkg == null) bkg = Color.BLACK; double alpha = a/255.0; r = (int)(alpha*r+(1-alpha)*bkg.getRed()); g = (int)(alpha*g+(1-alpha)*bkg.getGreen()); b = (int)(alpha*b+(1-alpha)*bkg.getBlue()); } for (int i=0; i0) offset += rc; else { length += 1000; byte[] newBytes = new byte[length]; System.arraycopy(bytes,0,newBytes,0,offset); bytes = newBytes; } } image = toolkit.createImage(bytes); } finally { in.close(); } } catch (IOException x) { image = brokenImage; } // Note we SHOULD include brokenImage in the cache, otherwise repeated requests for // the same non-existant url will be very slow if (url!=null) imageCache.put(url, image); } return image; } /** * Create the best cursor by reading from a URL, with hotspot (0,0). */ public static Cursor getBestCursor(String name, Class clazz, int width, int height) { return getBestCursor(name, clazz, width, height, 0, 0); } /** * Create the best cursor by reading from a URL, with hotspot (x, y). * The best width and height are inserted into the URL in the spots with %width * and %height. Example: * * getBestCursor("/org/freehep/swing/images/MyIcon%wx%h.png", 32 32); * * @param name URL of the cursor * @param clazz Class to be used for getting resource * @param width suggested width * @param height suggested height * @param x hotspot * @param y hotspot * @return The cursor, the default cursor if custom cursors are not supported * or brokenCursor if the cursor cannot be found */ public static Cursor getBestCursor(String name, Class clazz, int width, int height, int x, int y) { Toolkit toolkit = Toolkit.getDefaultToolkit(); Dimension dimension = toolkit.getBestCursorSize(width, height); if ((dimension.width == 0) && (dimension.height == 0)) return Cursor.getDefaultCursor(); name = name.replaceAll("%w", Integer.toString(dimension.width)); name = name.replaceAll("%h", Integer.toString(dimension.height)); return getCursor(name, clazz, x, y); } /** * Create a cursor by reading from a URL, with hotspot (0,0). * @param url The URL to read * @return The cursor, or brokenCursor if the cursor cannot be found */ public static Cursor getCursor(URL url) { return getCursor(url, 0, 0); } /** * Create a cursor by reading from a URL * @param url The URL to read * @param x x position of hotspot * @param y y position of hotspot * @return The cursor, or brokenCursor if the cursor cannot be found */ public static Cursor getCursor(URL url, int x, int y) { Cursor cursor = (url!=null) ? (Cursor) cursorCache.get(url) : null; if (cursor == null) { Toolkit toolkit = Toolkit.getDefaultToolkit(); Image image = getImage(url); if (image == brokenImage) cursor = brokenCursor; else cursor = toolkit.createCustomCursor(image, new Point(x, y), url.getFile()); if (url != null) cursorCache.put(url, cursor); } return cursor; } /** * Create an Icon by reading from a URL * @param url The URL to read * @return The icon, or brokenIcon if it cannot be loaded */ public static Icon getIcon(URL url) { Icon icon = (url!=null) ? (Icon) iconCache.get(url) : null; if (icon == null) { Image image = getImage(url); if (image == brokenImage) icon = brokenIcon; else icon = new ImageIcon(image,url.getFile()); if (url != null) iconCache.put(url, icon); } return icon; } /** * Convenience routine, equivalent to getImage(clazz.getResource(name)); * As an additional convenience, if the name does not contain an extension (eg .gif) * then a list of common extensions will be tried. * @param name The relative address of the image to load * @param clazz The class from which the address is based * @return The image, or brokenImage if no image is found. */ public static Image getImage(String name, Class clazz) { if (name.indexOf('.') >= 0) return getImage(clazz.getResource(name)); for (int i=0; i= 0) return getCursor(clazz.getResource(name), x, y); for (int i=0; i= 0) return getIcon(clazz.getResource(name)); for (int i=0; i Image handler to (pre-)load images and icons.

@Status Stable.

freehep-util-2.0.2/src/main/java/org/freehep/util/images/TempImageHandler.java0000644012010301201030000001477410466735775030227 0ustar mascellanimascellanipackage org.freehep.util.images; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Hashtable; import javax.swing.Icon; import javax.swing.ImageIcon; public class TempImageHandler { private static Image brokenImage; private static Cursor brokenCursor; private static String[] imageExtensions = { ".gif", ".png" }; private static Hashtable imageCache = new Hashtable(); private static Hashtable cursorCache = new Hashtable(); private static Hashtable iconCache = new Hashtable(); // only static methods protected TempImageHandler() { } static { Toolkit toolkit = Toolkit.getDefaultToolkit(); byte[] brokenImageBytes = getImageBytes("BrokenImage.gif", TempImageHandler.class); if (brokenImageBytes != null) { brokenImage = toolkit.createImage(brokenImageBytes); } if (brokenImage == null) { throw new RuntimeException("Could not load BrokenIcon"); } byte[] brokenCursorBytes = getImageBytes("BrokenCursor.gif", TempImageHandler.class); if (brokenCursorBytes != null) { Image brokenCursorImage = toolkit.createImage(brokenCursorBytes); if (brokenCursorImage != null) { brokenCursor = toolkit.createCustomCursor(brokenCursorImage, new Point(0,0), "BrokenCursor"); } } if (brokenCursor == null) { throw new RuntimeException("Could not load BrokenCursor"); } } public static Image getImage(String name, Class clazz) { Image image = (Image)imageCache.get(name); if (image == null) { Toolkit toolkit = Toolkit.getDefaultToolkit(); int i = 0; while ((image == null) && (i < imageExtensions.length)) { byte[] imageBytes = getImageBytes(name+imageExtensions[i], clazz); if (imageBytes != null) { image = toolkit.createImage(imageBytes); } i++; } if (image != null) { imageCache.put(name, image); } else { image = brokenImage; } } return image; } public static Cursor getCursor(String name, Class clazz) { return getCursor(name, clazz, 0, 0); } public static Cursor getCursor(String name, Class clazz, int x, int y) { Cursor cursor = (Cursor)cursorCache.get(name); if (cursor == null) { Toolkit toolkit = Toolkit.getDefaultToolkit(); Image image = getImage(name, clazz); // Make this into an icon image, so that we don't have to deal // with image observers. ImageIcon icon = new ImageIcon(image); int iconWidth = icon.getIconWidth(); int iconHeight = icon.getIconHeight(); // Get the best size for the cursor. Dimension bestSize = toolkit.getBestCursorSize(icon.getIconWidth(), icon.getIconHeight()); int cursorWidth = bestSize.width; int cursorHeight = bestSize.height; if (cursorWidth0) { ostream.write(buffer,0,bytesRead); bytesRead = stream.read(buffer); } stream.close(); // Convert to a byte array and return it. return ostream.toByteArray(); } catch (IOException x) { return null; } } } freehep-util-2.0.2/src/main/java/org/freehep/util/package.html0000644012010301201030000000011210470537377025200 0ustar mascellanimascellani Generic utility classes for FreeHEP.

@Status Stable.

freehep-util-2.0.2/src/main/java/org/freehep/util/Assert.java0000644012010301201030000000713210466735775025043 0ustar mascellanimascellani// Copyright 2002-2005, FreeHEP. package org.freehep.util; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.IOException; import java.util.zip.GZIPInputStream; import junit.framework.AssertionFailedError; /** * Additional assert methods to the junit.framework.Assert class. * * @author Mark Donszelmann * @version $Id: Assert.java 8584 2006-08-10 23:06:37Z duns $ */ public class Assert extends junit.framework.Assert { /** * static class only */ protected Assert() { } /** * Compares two files. The files may be gzipped, and will then be uncompressed on * the fly. * * @param expected reference file * @param actual file to be tested * @param isBinary when true will do byte-by-byte comparison rather than line by line. * @throws FileNotFoundException if one of the files cannot be found. * @throws IOException if one of the files cannot read. * @throws AssertionFailedError if the files are not equal. */ public static void assertEquals(File expected, File actual, boolean isBinary) throws FileNotFoundException, IOException { InputStream ref = new BufferedInputStream(new FileInputStream(expected)); if (expected.getPath().toLowerCase().endsWith(".gz")) { ref = new GZIPInputStream(ref); } InputStream tst = new BufferedInputStream(new FileInputStream(actual)); if (actual.getPath().toLowerCase().endsWith(".gz")) { tst = new GZIPInputStream(tst); } assertEquals(ref, tst, isBinary, "File "+actual.getPath()); } /** * Compares two streams. * * @param expected reference stream * @param actual stream to be tested * @param filename an prefix for the error message (normally filename associated with the actual stream) * @param isBinary when true will do byte-by-byte comparison rather than line by line (Reader). * @throws IOException if one of the streams cannot read. * @throws AssertionFailedError if the streams are not equal. */ public static void assertEquals(InputStream expected, InputStream actual, boolean isBinary, String filename) throws IOException { int diff; if (isBinary) { diff = diff (expected, actual); if (diff >= 0) throw new AssertionFailedError(filename+": comparison failed at offset "+diff); } else { diff = diff(new BufferedReader(new InputStreamReader(expected)), new BufferedReader(new InputStreamReader(actual))); if (diff >= 0) throw new AssertionFailedError(filename+": comparison failed at line "+diff); } } private static int diff(InputStream ref, InputStream tst) throws IOException { int bRef, bTst; int i = 0; do { bRef = ref.read(); bTst = tst.read(); i++; } while ((bRef >= 0) && (bTst >= 0) && (bRef == bTst)); ref.close(); tst.close(); return (bRef == bTst) ? -1 : i-1; } private static int diff(BufferedReader ref, BufferedReader tst) throws IOException { String bRef, bTst; int i = 1; do { bRef = ref.readLine(); bTst = tst.readLine(); i++; } while ((bRef != null) && (bTst != null) && (bRef.equals(bTst))); ref.close(); tst.close(); return ((bRef == null) && (bTst == null)) ? -1 : i-1; } } freehep-util-2.0.2/src/main/java/org/freehep/util/PackageInfo.java0000644012010301201030000000331610466735775025751 0ustar mascellanimascellani// Copyright 2000, CERN, Geneva, Switzerland and SLAC, Stanford, U.S.A. package org.freehep.util; import java.io.*; import java.util.*; /** * Methods for Package Info (version, name, ...) * * @author Mark Donszelmann * @version $Id: PackageInfo.java 8584 2006-08-10 23:06:37Z duns $ */ public class PackageInfo { // static class private PackageInfo() { } /** * retrieves the name */ public static String getName(Class clazz, String name) { return getInfo(clazz, name, "TITLE"); } /** * retrieves the version */ public static String getVersion(Class clazz, String name) { return getInfo(clazz, name, "VERSION"); } /** * retrieves the info for the package of this class * either from the MANIFEST file or from the given text file * situated at the root of the jar file */ public static String getInfo(Class clazz, String name, String property) { Package p = clazz.getPackage(); String info = null; if (p != null) { if (property.equals("TITLE")) { info = p.getSpecificationTitle(); } else if (property.equals("VERSION")) { info = p.getSpecificationVersion(); } } if (info == null) { try { Properties props = new Properties(); InputStream in = clazz.getResourceAsStream("/"+name+"-version.txt"); props.load(in); in.close(); info = props.getProperty(property); } catch (IOException ioe) { } catch (NullPointerException npe) { } } return info; } } freehep-util-2.0.2/src/main/java/org/freehep/util/Service.java0000644012010301201030000000722210466735775025202 0ustar mascellanimascellani// Copyright 2003, FreeHEP. package org.freehep.util; import java.io.*; import java.net.*; import java.util.*; /** * This class does the same as sun.misc.Service, which may become public * in some java or javax package at some point. See Sun BUG# 4640520. * * @author Mark Donszelmann * @version $Id: Service.java 8584 2006-08-10 23:06:37Z duns $ */ public class Service { private Service() { } public static Collection providers(Class service, ClassLoader loader) { List classList = new ArrayList(); List nameSet = new ArrayList(); String name = "META-INF/services/" + service.getName(); Enumeration services; try { services = (loader == null) ? ClassLoader.getSystemResources(name) : loader.getResources(name); } catch (IOException ioe) { System.err.println("Service: cannot load "+name); return classList; } while (services.hasMoreElements()) { URL url = (URL)services.nextElement(); // System.out.println(url); InputStream input = null; BufferedReader reader = null; try { input = url.openStream(); reader = new BufferedReader(new InputStreamReader(input, "utf-8")); String line = reader.readLine(); while (line != null) { int ci = line.indexOf('#'); if (ci >= 0) line = line.substring(0, ci); line = line.trim(); int si = line.indexOf(' '); if (si >= 0) line = line.substring(0, si); line = line.trim(); if (line.length() > 0) { if (!nameSet.contains(line)) nameSet.add(line); } line = reader.readLine(); } } catch (IOException ioe) { System.err.println("Service: problem with: "+url); } finally { try { if (input != null) input.close(); if (reader != null) reader.close(); } catch (IOException ioe2) { System.err.println("Service: problem with: "+url); } } } Iterator names = nameSet.iterator(); while (names.hasNext()) { String className = (String)names.next(); try { classList.add(Class.forName(className, true, loader).newInstance()); } catch (ClassNotFoundException e) { System.err.println("Service: cannot find class: "+className); } catch (InstantiationException e) { System.err.println("Service: cannot instantiate: "+className); } catch (IllegalAccessException e) { System.err.println("Service: illegal access to: "+className); } catch (NoClassDefFoundError e) { System.err.println("Service: "+e+" for "+className); } catch (Exception e) { System.err.println("Service: exception for: "+className+" "+e); } } return classList; } public static Collection providers(Class service) { ClassLoader loader = Thread.currentThread().getContextClassLoader(); return Service.providers(service, loader); } public static Collection installedProviders(Class service) { ClassLoader loader = ClassLoader.getSystemClassLoader(); ClassLoader previous = null; while (loader != null) { previous = loader; loader = loader.getParent(); } return providers(service, previous); } } freehep-util-2.0.2/src/main/java/org/freehep/util/FastStack.java0000644012010301201030000000144710466735775025470 0ustar mascellanimascellani// Copyright 2002, FreeHEP. package org.freehep.util; import java.util.ArrayList; import java.util.EmptyStackException; /** * Unsynchronized version of a Stack. * * @author Mark Donszelmann */ public class FastStack extends ArrayList { /** * */ private static final long serialVersionUID = -111966774350178793L; public FastStack() { this(10); } public FastStack(int initialCapacity) { super(initialCapacity); } public Object push(Object item) { add(item); return item; } public Object pop() { Object obj = peek(); int len = size(); remove(len - 1); return obj; } public Object peek() { int len = size(); if (len == 0) throw new EmptyStackException(); return get(len - 1); } } freehep-util-2.0.2/src/main/java/org/freehep/util/UserProperties.java0000644012010301201030000002247210466735775026601 0ustar mascellanimascellani// Copyright 2003, FreeHEP. package org.freehep.util; import java.awt.Color; import java.awt.Dimension; import java.awt.Insets; import java.util.ArrayList; import java.util.Collections; import java.awt.Rectangle; import java.util.Enumeration; import java.util.List; import java.util.Properties; /** * Special property class which allows typed properties to be set and * returned. It also allows the hookup of two default property objects * to be searched if this property object does not contain the property. * * FIXME check what org.freehep.application.PropertyUtilities.java * has to offer and merge, or not * * FIXME: This class does not seem general enough to be a "public" utility. Should be * improved and merged with PropertyUtilities, or moved into the graphicsio package (tonyj) * * @author Mark Donszelmann * @version $Id: UserProperties.java 8584 2006-08-10 23:06:37Z duns $ */ public class UserProperties extends Properties { /** * */ private static final long serialVersionUID = 3297483251864528952L; protected Properties altDefaults; public UserProperties() { super(); altDefaults = new Properties(); } public UserProperties(Properties defaults) { super(defaults); altDefaults = new Properties(); } /** * Constructs UserProperties with a defaults and altDefaults table, * which are searched in that order. */ public UserProperties(Properties defaults, Properties altDefaults) { super(defaults); this.altDefaults = altDefaults; } public Enumeration propertyNames() { List list = new ArrayList(); for (Enumeration e = super.propertyNames(); e.hasMoreElements(); ) { list.add(e.nextElement()); } if (altDefaults != null) { for (Enumeration e = altDefaults.propertyNames(); e.hasMoreElements(); ) { list.add(e.nextElement()); } } return Collections.enumeration(list); } /** * Copies properties, including its defaults into this UserProperties */ public void setProperties(Properties properties) { for (Enumeration e=properties.propertyNames(); e.hasMoreElements(); ) { String key = (String)e.nextElement(); setProperty(key, properties.getProperty(key)); } } public Object setProperty(String key, String value) { if (value == null) return super.setProperty(key, "null"); return super.setProperty(key, value); } public Object setProperty(String key, String[] value) { return setProperty(this, key, value); } public static Object setProperty(Properties properties, String key, String[] value) { if (value == null) return properties.setProperty(key, "null"); StringBuffer sb = new StringBuffer(); for (int i=0; i * Subclasses of OutputStream must provide an * implementation for this method. * * @param b the byte. * @exception IOException if an I/O error occurs. * @since JDK1.0 */ public void write(int b) throws IOException { one[0] = (byte) b; write(one, 0, 1); } /** * Writes len bytes from the specified byte array * starting at offset off to this output stream. *

* The write method of OutputStream calls * the write method of one argument on each of the bytes to be * written out. Subclasses are encouraged to override this method and * provide a more efficient implementation. * * @param b the data. * @param off the start offset in the data. * @param len the number of bytes to write. * @exception IOException if an I/O error occurs. * @since JDK1.0 */ public void write(byte b[], int off, int len) throws IOException { try { doc.insertString(doc.getLength(), new String(b, off, len), a); } catch (BadLocationException ble) { throw new IOException(ble.getMessage()); } } private byte[] one = new byte[1]; private javax.swing.text.Document doc; private AttributeSet a; } freehep-util-2.0.2/src/main/resources/0000755012010301201030000000000011273054221020614 5ustar mascellanimascellanifreehep-util-2.0.2/src/main/resources/org/0000755012010301201030000000000011273054221021403 5ustar mascellanimascellanifreehep-util-2.0.2/src/main/resources/org/freehep/0000755012010301201030000000000011273054221023021 5ustar mascellanimascellanifreehep-util-2.0.2/src/main/resources/org/freehep/util/0000755012010301201030000000000011273054221023776 5ustar mascellanimascellanifreehep-util-2.0.2/src/main/resources/org/freehep/util/images/0000755012010301201030000000000011273054221025243 5ustar mascellanimascellanifreehep-util-2.0.2/src/main/resources/org/freehep/util/images/BrokenCursor.gif0000644012010301201030000000036210337474064030364 0ustar mascellanimascellaniGIF89a !, @IY(7(u"(3fznR |@"?A vfcI5+V{%Utݩ;ia{fQqC;zWTU~a: `~_wxG?BhOuE/1vmmLjg+! LViewPro200;freehep-util-2.0.2/src/main/resources/org/freehep/util/images/BrokenImage.gif0000644012010301201030000000024710337474064030133 0ustar mascellanimascellaniGIF89a!,@EI|8:ϴ%Ajx0˜z̰&^)j(/RC*A\[7BD! LViewPro200;freehep-util-2.0.2/pom.xml0000644012010301201030000000240410633617505016415 0ustar mascellanimascellani global org.freehep 8 4.0.0 org.freehep freehep-util 2.0.2 FreeHEP Util FreeHEP Utility Library freehep-maven Maven FreeHEP http://java.freehep.org/maven2 org.netbeans openide-lookup 1.9-patched-1.0 junit junit provided scm:svn:svn://svn.freehep.org/svn/freehep/tags/freehep-util-2.0.2 scm:svn:svn://svn.freehep.org/svn/freehep/tags/freehep-util-2.0.2