From: <res...@us...> - 2010-09-21 18:45:47
|
Revision: 3606 http://bigdata.svn.sourceforge.net/bigdata/?rev=3606&view=rev Author: resendes Date: 2010-09-21 18:45:41 +0000 (Tue, 21 Sep 2010) Log Message: ----------- Test coverage for BootStateUtil Modified Paths: -------------- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/BootStateUtil.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java Added Paths: ----------- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestBootStateUtil.java Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/BootStateUtil.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/BootStateUtil.java 2010-09-21 16:47:18 UTC (rev 3605) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/BootStateUtil.java 2010-09-21 18:45:41 UTC (rev 3606) @@ -45,7 +45,6 @@ import com.sun.jini.config.Config; import net.jini.config.Configuration; import net.jini.config.ConfigurationException; -import net.jini.config.NoSuchEntryException; import net.jini.core.lookup.ServiceID; /** @@ -80,7 +79,7 @@ private File persistenceDir = null; private UUID proxyId = null; private ServiceID serviceId = null; - private String stateKey = null; + private String stateKey = null; //TODO -- not used? public BootStateUtil(final Configuration config, final String componentName, @@ -128,22 +127,6 @@ recoverBootState(defaultServiceId); } - - public BootStateUtil(File persistenceDir, - Class entityImplType, - ServiceID defaultServiceId) - throws IOException, ClassNotFoundException - { - if(entityImplType == null) { - throw new NullPointerException("entityImplType null"); - } - this.entityImplType = entityImplType; - this.logger = Logger.getLogger(this.getClass()); - this.persistenceDir = persistenceDir; - - recoverBootState(defaultServiceId); - } - /** * Returns the entity's unique <i>proxy id</i> that is generated/recoverd * as part of the boot state maintained by this class. @@ -161,44 +144,6 @@ return serviceId; } - /** - * Returns the <code>String</code> representing the path of the - * directory in which the entity's <i>boot state</i> is located. - * If the value returned is <code>null</code>, then the entity - * was configured to run in <i>transient</i> mode. - */ - public String getPersistenceDirectory() { - return (persistenceDir != null) ? persistenceDir.toString() : null; - } - - /** - * Returns the <code>true</code> if the entity was configured to - * run in <i>persistent</i> mode; <code>false</code> otherwise. - */ - public boolean isPersistent() { - return (persistenceDir != null); - } - - /** - * If the entity is currently configured to run in <i>persistent</i> - * mode, returns the name-based key under which an entity's (non-boot) - * state was persisted during previous runs of the entity. If the - * entity is currently configured to run in <i>transient</i> mode, - * a non-<code>null</code>, randomly-generated key value is returned. - */ - public String getStateKey() { - return stateKey; - } - - /** - * Returns the <code>Class</code> type of the entity whose boot state - * is associated with the current instance of this utility. - */ - public Class getType() { - return entityImplType; - } - - /* Performs the actual retrieval of the entity's boot state. This * method is called only once, in this utility's constructor. * It recovers the entity's boot state from local persistence storage, @@ -338,6 +283,7 @@ /** * @see java.io.ObjectInputStream#resolveClass */ + @Override protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { @@ -354,7 +300,7 @@ * An interface is specified here to support evolution of new * versions of BootState. */ - interface BootState { + private interface BootState { Class getType(); UUID getProxyId(); String getKey(); Modified: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java 2010-09-21 16:47:18 UTC (rev 3605) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java 2010-09-21 18:45:41 UTC (rev 3606) @@ -76,7 +76,7 @@ suite.addTestSuite(TestByteBufferBitVector.class); suite.addTestSuite( TestCSVReader.class ); - + suite.addTestSuite( TestBootStateUtil.class ); return suite; } Added: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestBootStateUtil.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestBootStateUtil.java (rev 0) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestBootStateUtil.java 2010-09-21 18:45:41 UTC (rev 3606) @@ -0,0 +1,354 @@ +package com.bigdata.util; + +import java.io.File; +import java.io.IOException; +import java.io.RandomAccessFile; +import java.io.StreamCorruptedException; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.UUID; + +import net.jini.config.Configuration; +import net.jini.config.ConfigurationFile; +import net.jini.config.EmptyConfiguration; +import net.jini.config.ConfigurationException; +import net.jini.config.NoSuchEntryException; +import net.jini.core.lookup.ServiceID; + +import org.apache.log4j.Logger; + +import junit.framework.TestCase; +import junit.framework.TestCase2; + +public class TestBootStateUtil extends TestCase2 { + + public TestBootStateUtil(String name) { + super(name); + } + + public void testBootStateUtilNullConsArgs() throws SecurityException, NoSuchMethodException { + Configuration dummyConfiguration = EmptyConfiguration.INSTANCE; + String dummyString = "dummy"; + Class<? extends TestBootStateUtil> dummyClass = this.getClass(); + Logger dummyLogger = Logger.getLogger(dummyClass); + + // Command lines with a null in first three args are invalid + Object [][] badCommandLines = { + {null, null, null, null}, + {null, null, null, dummyLogger}, + {null, null, dummyClass, null}, + {null, null, dummyClass, dummyLogger}, + {null, dummyString, null, null}, + {null, dummyString, null, dummyLogger}, + {null, dummyString, dummyClass, null}, + {null, dummyString, dummyClass, dummyLogger}, + {dummyConfiguration, null, null, null}, + {dummyConfiguration, null, null, dummyLogger}, + {dummyConfiguration, null, dummyClass, null}, + {dummyConfiguration, null, dummyClass, dummyLogger}, + {dummyConfiguration, dummyString, null, null}, + {dummyConfiguration, dummyString, null, dummyLogger}, + }; + + Constructor cons = + BootStateUtil.class.getConstructor(Configuration.class, + String.class, Class.class, Logger.class); + for (int i=0; i < badCommandLines.length; i++) { + try { + cons.newInstance(badCommandLines[i]); + fail("Successfully called constructor with null arg: " + + Arrays.asList(badCommandLines[i])); + } catch (IllegalArgumentException e) { + fail("unexpected exception: " + e.toString()); + } catch (InstantiationException e) { + fail("unexpected exception: " + e.toString()); + } catch (IllegalAccessException e) { + fail("unexpected exception: " + e.toString()); + } catch (InvocationTargetException e) { + if (! (e.getCause() instanceof NullPointerException)){ + fail("unexpected exception: " + e.getCause().toString()); + } + //Otherwise ignore -- expected + } + } + } + + public void testBootStateUtilGoodConsArgs() throws SecurityException, NoSuchMethodException { + Configuration dummyConfiguration = EmptyConfiguration.INSTANCE; + String dummyString = "dummy"; + Class<? extends TestBootStateUtil> dummyClass = this.getClass(); + Logger dummyLogger = Logger.getLogger(dummyClass); + + // Command lines with a non-null in first three args are valid + Object [][] goodCommandLines = { + {dummyConfiguration, dummyString, dummyClass, null}, + {dummyConfiguration, dummyString, dummyClass, dummyLogger}, + }; + + testGoodConsArgs(goodCommandLines); + } + + public void testBootStateUtilNoEntries() + throws SecurityException, NoSuchMethodException, IOException, + ConfigurationException, ClassNotFoundException + { + Class<? extends TestBootStateUtil> dummyClass = this.getClass(); + String className = dummyClass.getName(); + ConfigurationBuilder builder = new ConfigurationBuilder(); + Configuration dummyConfiguration = builder.buildConfiguration(); + Logger dummyLogger = Logger.getLogger(className); + + BootStateUtil bsu = + new BootStateUtil(dummyConfiguration, className, dummyClass, null); + + assertTrue(bsu.getProxyId() != null); + assertTrue(bsu.getServiceId() != null); + + } + + public void testBootStateUtilNonExistentPersistenceDir() + throws SecurityException, NoSuchMethodException, IOException, ConfigurationException + { + Class<? extends TestBootStateUtil> dummyClass = this.getClass(); + String className = dummyClass.getName(); + File persistenceDir = File.createTempFile(className, ".tmp"); + persistenceDir.delete(); + ConfigurationBuilder builder = new ConfigurationBuilder(); + builder.setComponentName(className); + builder.setPersistenceDir(persistenceDir); + Configuration dummyConfiguration = builder.buildConfiguration(); + Logger dummyLogger = Logger.getLogger(className); + + // Command lines with a non-null in first three args are valid + Object [][] goodCommandLines = { + {dummyConfiguration, className, dummyClass, null}, + {dummyConfiguration, className, dummyClass, dummyLogger}, + }; + testGoodConsArgs(goodCommandLines); + + assertTrue(persistenceDir.exists()); + persistenceDir.delete(); + } + + public void testBootStateUtilExistentPersistenceDir() + throws SecurityException, NoSuchMethodException, IOException, ConfigurationException + { + Class<? extends TestBootStateUtil> dummyClass = this.getClass(); + String className = dummyClass.getName(); + File persistenceDir = File.createTempFile(className, ".tmp"); + persistenceDir.delete(); + assertTrue(persistenceDir.mkdirs()); + persistenceDir.deleteOnExit(); + ConfigurationBuilder builder = new ConfigurationBuilder(); + builder.setComponentName(className); + builder.setPersistenceDir(persistenceDir); + Configuration dummyConfiguration = builder.buildConfiguration(); + Logger dummyLogger = Logger.getLogger(className); + + // Command lines with a non-null in first three args are valid + Object [][] goodCommandLines = { + {dummyConfiguration, className, dummyClass, null}, + {dummyConfiguration, className, dummyClass, dummyLogger}, + }; + testGoodConsArgs(goodCommandLines); + persistenceDir.delete(); + } + + public void testBootStateUtilWithEmptyBootState() + throws SecurityException, NoSuchMethodException, IOException, + ConfigurationException, ClassNotFoundException + { + Class<? extends TestBootStateUtil> dummyClass = this.getClass(); + String className = dummyClass.getName(); + File persistenceDir = File.createTempFile(className, ".tmp"); + persistenceDir.delete(); + assertTrue(persistenceDir.mkdirs()); + persistenceDir.deleteOnExit(); + ConfigurationBuilder builder = new ConfigurationBuilder(); + builder.setComponentName(className); + builder.setPersistenceDir(persistenceDir); + File bootStateFile = new File(persistenceDir, "boot.state"); + bootStateFile.createNewFile(); + Configuration dummyConfiguration = builder.buildConfiguration(); + + try { + BootStateUtil bsu = + new BootStateUtil(dummyConfiguration, className, dummyClass, null); + fail("Created boot state instance with emtpy state information file"); + } catch (IOException e) { + //ignore -- expected + } + + } + + public void testBootStateUtilWithInvalidBootState() + throws SecurityException, NoSuchMethodException, IOException, + ConfigurationException, ClassNotFoundException + { + //Create boot state dir/file with default information + Class<? extends TestBootStateUtil> dummyClass = this.getClass(); + String className = dummyClass.getName(); + File persistenceDir = File.createTempFile(className, ".tmp"); + persistenceDir.delete(); + assertTrue(persistenceDir.mkdirs()); + persistenceDir.deleteOnExit(); + ConfigurationBuilder builder = new ConfigurationBuilder(); + builder.setComponentName(className); + builder.setPersistenceDir(persistenceDir); + Configuration dummyConfiguration = builder.buildConfiguration(); + new BootStateUtil(dummyConfiguration, className, dummyClass, null); + // Mangle boot state file by writing junk into the beginning of the file + File bootStateFile = new File(persistenceDir, "boot.state"); + RandomAccessFile raf = new RandomAccessFile(bootStateFile, "rws"); + raf.seek(0); + raf.writeUTF("Bogus data"); + raf.close(); + + //Try to recover from bogus data + try { + new BootStateUtil(dummyConfiguration, className, dummyClass, null); + } catch (StreamCorruptedException e) { + //ignore -- expected + } + } + + public void testBootStateUtilConsWithDefaultServiceId() + throws SecurityException, NoSuchMethodException, IOException, + ConfigurationException, ClassNotFoundException + { + Class<? extends TestBootStateUtil> dummyClass = this.getClass(); + String className = dummyClass.getName(); + File persistenceDir = File.createTempFile(className, ".tmp"); + persistenceDir.delete(); + ConfigurationBuilder builder = new ConfigurationBuilder(); + builder.setComponentName(className); + ServiceID defaultServiceId = new ServiceID(1L, 2L); + builder.setDefaultServiceId(defaultServiceId); + Configuration dummyConfiguration = builder.buildConfiguration(); + Logger dummyLogger = Logger.getLogger(className); + + BootStateUtil bsu = + new BootStateUtil(dummyConfiguration, className, dummyClass, null); + assertTrue(bsu.getServiceId().equals(defaultServiceId)); + UUID defaultProxyID = + new UUID( + defaultServiceId.getMostSignificantBits(), + defaultServiceId.getLeastSignificantBits()); + assertTrue(bsu.getProxyId().equals(defaultProxyID)); + } + + public void testBootStateUtilDefaultServiceId() + throws SecurityException, NoSuchMethodException, IOException, + ConfigurationException, ClassNotFoundException + { + Class<? extends TestBootStateUtil> dummyClass = this.getClass(); + String className = dummyClass.getName(); + File persistenceDir = File.createTempFile(className, ".tmp"); + persistenceDir.delete(); + ConfigurationBuilder builder = new ConfigurationBuilder(); + builder.setComponentName(className); + ServiceID defaultServiceID = new ServiceID(1L, 1L); + builder.setDefaultServiceId(defaultServiceID); + Configuration dummyConfiguration = builder.buildConfiguration(); + + BootStateUtil bsu = + new BootStateUtil(dummyConfiguration, className, dummyClass, null); + assertTrue(bsu.getServiceId().equals(defaultServiceID)); + UUID proxyID = bsu.getProxyId(); + assertTrue(proxyID.getLeastSignificantBits() == defaultServiceID.getLeastSignificantBits()); + assertTrue(proxyID.getMostSignificantBits() == defaultServiceID.getMostSignificantBits()); + } + + public void testBootStateUtilBadPersistenceDir() + throws SecurityException, NoSuchMethodException, IOException, ConfigurationException, ClassNotFoundException + { + Class<? extends TestBootStateUtil> dummyClass = this.getClass(); + String className = dummyClass.getName(); + //create temp file -- should fail dir creation, below + File persistenceDir = File.createTempFile(className, ".tmp"); + ConfigurationBuilder builder = new ConfigurationBuilder(); + builder.setComponentName(className); + builder.setPersistenceDir(persistenceDir); + Configuration dummyConfiguration = builder.buildConfiguration(); + + try { + new BootStateUtil(dummyConfiguration, className, dummyClass, null); + fail("Created BootStateUtil with bad dir file: " + + persistenceDir.getAbsolutePath()); + } catch (IOException e) { + //ignore -- expected + } + } + + + private static void testGoodConsArgs(Object[][] goodCommandLines) + throws SecurityException, NoSuchMethodException + { + Constructor<BootStateUtil> cons = + BootStateUtil.class.getConstructor(Configuration.class, + String.class, Class.class, Logger.class); + for (int i=0; i < goodCommandLines.length; i++) { + try { + cons.newInstance(goodCommandLines[i]); + } catch (IllegalArgumentException e) { + fail("unexpected exception: " + e.toString()); + } catch (InstantiationException e) { + fail("unexpected exception: " + e.toString()); + } catch (IllegalAccessException e) { + fail("unexpected exception: " + e.toString()); + } catch (InvocationTargetException e) { + fail("unexpected exception: " + e.getCause().toString()); + } + } + } + + private static class ConfigurationBuilder { + private String componentName = null; + private File persistenceDir = null; + private ServiceID defaultServiceId = null; + + ConfigurationBuilder() { + + } + + void setComponentName(String componentName) { + this.componentName = componentName; + } + + void setPersistenceDir(File persistenceDirFile) { + this.persistenceDir = persistenceDirFile; + } + + void setDefaultServiceId(ServiceID defaultServiceId) { + this.defaultServiceId = defaultServiceId; + } + + Configuration buildConfiguration() throws ConfigurationException { + List<String> args = new ArrayList<String>(); + args.add("-"); + if(persistenceDir != null) { + args.add( + componentName + ".persistenceDirectory=" + + "\"" + persistenceDir.getAbsolutePath().replace("\\", "\\\\") + + "\""); + } + if (defaultServiceId != null){ + args.add( + componentName + ".defaultServiceId=" + + "new net.jini.core.lookup.ServiceID(" + + defaultServiceId.getMostSignificantBits() + + ", " + + defaultServiceId.getLeastSignificantBits() + + ")"); + } + ConfigurationFile dummyConfiguration = + new ConfigurationFile(args.toArray(new String[0])); + return dummyConfiguration; + + } + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <res...@us...> - 2010-09-24 18:26:15
|
Revision: 3628 http://bigdata.svn.sourceforge.net/bigdata/?rev=3628&view=rev Author: resendes Date: 2010-09-24 18:26:07 +0000 (Fri, 24 Sep 2010) Log Message: ----------- - Continued clean-up of com.bigdata.util.* - Removed unreferenced/unused classes - Added tests and support classes for CSVReader Modified Paths: -------------- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/CSVReader.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestCSVReader.java Added Paths: ----------- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/CSVReaderBuilder.java Removed Paths: ------------- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/ByteBufferBitVector.java branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/ChecksumError.java branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/ClassLoaderUtil.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestByteBufferBitVector.java Deleted: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/ByteBufferBitVector.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/ByteBufferBitVector.java 2010-09-24 17:46:05 UTC (rev 3627) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/ByteBufferBitVector.java 2010-09-24 18:26:07 UTC (rev 3628) @@ -1,167 +0,0 @@ -/* - -Copyright (C) SYSTAP, LLC 2006-2008. All rights reserved. - -Contact: - SYSTAP, LLC - 4501 Tower Road - Greensboro, NC 27410 - lic...@bi... - -This program 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; version 2 of the License. - -This program 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 this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ -/* - * Created on Aug 6, 2009 - */ - -package com.bigdata.util; - -import it.unimi.dsi.bits.AbstractBitVector; - -import java.nio.ByteBuffer; - -import cern.colt.bitvector.BitVector; - -/** - * Wraps a {@link ByteBuffer} as a read-only {@link BitVector}. - * - * @author <a href="mailto:tho...@us...">Bryan Thompson</a> - * @version $Id$ - */ -public class ByteBufferBitVector extends AbstractBitVector { - - /** - * The {@link ByteBuffer} containing the backing data. - */ - final private ByteBuffer b; - - /** - * The #of bits in the vector. - */ - private final long len; - - /** - * The bit offset into the {@link ByteBuffer} of the first bit in the - * vector. - */ - private final long off; - - final public long length() { - - return len; - - } - - /** - * Ctor assumes that all bits in the buffer are used. - * - * @param b - * The buffer. - */ - public ByteBufferBitVector(final ByteBuffer b) { - - this(b, 0/* offset */, b == null ? 0 : b.capacity() * 8/* len */); - - } - - /** - * - * @param b - * The buffer. - * @param off - * The offset from the start of the buffer for the view. - * @param len - * The #of bits which will be included in the view. - */ - public ByteBufferBitVector(final ByteBuffer b, final long off, - final long len) { - - if (b == null) - throw new IllegalArgumentException(); - - if (len < 0) - throw new IllegalArgumentException(); - - if (len < 0) - throw new IllegalArgumentException(); - - if (off + len > b.capacity() * 8L) - throw new IllegalArgumentException(); - - this.b = b; - - this.len = len; - - this.off = off; - - } - - /** - * Return the index of the byte in which the bit with the given index is - * encoded. - * - * @param bitIndex - * The bit index. - * - * @return The byte index. - */ - final protected int byteIndexForBit(final long bitIndex) { - - return ((int) ((bitIndex + off) / 8)); - - } - - /** - * Return the offset within the byte in which the bit is coded of the bit - * (this is just the remainder <code>bitIndex % 8</code>). - * - * @param bitIndex - * The bit index into the byte[]. - * - * @return The offset of the bit in the appropriate byte. - */ - final protected int withinByteIndexForBit(final long bitIndex) { - - return (int) ((bitIndex + off) % 8); - - } - - /** - * Extract and return a bit coded flag. - * - * @param offset - * The offset in the buffer of the start of the byte[] sequence - * in which the bit coded flags are stored. - * @param index - * The index of the bit. - * - * @return The value of the bit. - */ - public boolean getBoolean(final long index) { - - if (index < 0 || index >= len) - throw new IndexOutOfBoundsException(); - - return (b.get(byteIndexForBit(index)) & (1 << withinByteIndexForBit(index))) != 0; - - } - -// // @todo override for mutation. -// public boolean set(final long index, final boolean value) { -// -// throw new UnsupportedOperationException(); -// -// } - -} Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/CSVReader.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/CSVReader.java 2010-09-24 17:46:05 UTC (rev 3627) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/CSVReader.java 2010-09-24 18:26:07 UTC (rev 3628) @@ -93,10 +93,8 @@ private final String name; - public String getName() { - - return name; - + public String getName() { + return name; } /** @@ -227,25 +225,29 @@ } /** - * Equal if the headers have the same data. + * Equal if the headers have the same name. */ - public boolean equals(Header o) { + @Override + public boolean equals(Object o) { + if (!(o instanceof Header)) + return false; + + Header h = (Header)o; - if(this==o) return true; - - return name.equals(o.name); - + return name.equals(h.name); } /** * Based on the header name. */ + @Override public int hashCode() { return name.hashCode(); } + @Override public String toString() { return name; @@ -324,54 +326,54 @@ } - public boolean setSkipCommentLines(boolean skipCommentLines) { +// public boolean setSkipCommentLines(boolean skipCommentLines) { +// +// boolean tmp = this.skipCommentLines; +// +// this.skipCommentLines = skipCommentLines; +// +// return tmp; +// +// } +// +// public boolean getSkipCommentLines() { +// +// return skipCommentLines; +// +// } - boolean tmp = this.skipCommentLines; +// public boolean setSkipBlankLines(boolean skipBlankLines) { +// +// boolean tmp = this.skipBlankLines; +// +// this.skipBlankLines = skipBlankLines; +// +// return tmp; +// +// } +// +// public boolean getSkipBlankLines() { +// +// return skipBlankLines; +// +// } - this.skipCommentLines = skipCommentLines; +// public boolean setTrimWhitespace(boolean trimWhitespace) { +// +// boolean tmp = this.trimWhitespace; +// +// this.trimWhitespace = trimWhitespace; +// +// return tmp; +// +// } +// +// public boolean getTrimWhitespace() { +// +// return trimWhitespace; +// +// } - return tmp; - - } - - public boolean getSkipCommentLines() { - - return skipCommentLines; - - } - - public boolean setSkipBlankLines(boolean skipBlankLines) { - - boolean tmp = this.skipBlankLines; - - this.skipBlankLines = skipBlankLines; - - return tmp; - - } - - public boolean getSkipBlankLines() { - - return skipBlankLines; - - } - - public boolean setTrimWhitespace(boolean trimWhitespace) { - - boolean tmp = this.trimWhitespace; - - this.trimWhitespace = trimWhitespace; - - return tmp; - - } - - public boolean getTrimWhitespace() { - - return trimWhitespace; - - } - /** * The #of milliseconds that the {@link CSVReader} should wait before * attempting to read another line from the source (when reading from @@ -505,8 +507,7 @@ } /** - * Trim whitespace and optional quotes from each value iff - * {@link #getTrimWhitespace()} is true. + * Trim whitespace and optional quotes. * * @param cols * The column values. @@ -651,7 +652,7 @@ */ public Header[] getHeaders() { - return headers.clone(); + return ((headers==null)? null : headers.clone()); } @@ -679,7 +680,7 @@ */ public void setHeader(int index,Header header) { - if (index < 0 || index > headers.length) + if (index < 0 || index >= headers.length) throw new IndexOutOfBoundsException(); if (header == null) @@ -688,7 +689,7 @@ headers[index] = header; } - + /** * Unsupported operation. */ Deleted: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/ChecksumError.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/ChecksumError.java 2010-09-24 17:46:05 UTC (rev 3627) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/ChecksumError.java 2010-09-24 18:26:07 UTC (rev 3628) @@ -1,46 +0,0 @@ -/** - -Copyright (C) SYSTAP, LLC 2006-2007. All rights reserved. - -Contact: - SYSTAP, LLC - 4501 Tower Road - Greensboro, NC 27410 - lic...@bi... - -This program 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; version 2 of the License. - -This program 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 this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ -/* - * Created on Nov 5, 2006 - */ - -package com.bigdata.util; - -/** - * Exception thrown when the checksum field does not match the checksum computed - * for the data being read. This is a serious error and indicates bad logic - * and/or corrupt data. - * - * @author <a href="mailto:tho...@us...">Bryan Thompson</a> - * @version $Id$ - */ -public class ChecksumError extends RuntimeException { - - private static final long serialVersionUID = -9067118459184074756L; - - public ChecksumError(String msg) { - super( msg ); - } - -} \ No newline at end of file Deleted: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/ClassLoaderUtil.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/ClassLoaderUtil.java 2010-09-24 17:46:05 UTC (rev 3627) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/ClassLoaderUtil.java 2010-09-24 18:26:07 UTC (rev 3628) @@ -1,328 +0,0 @@ -/* - -Copyright (C) SYSTAP, LLC 2006-2008. All rights reserved. - -Contact: - SYSTAP, LLC - 4501 Tower Road - Greensboro, NC 27410 - lic...@bi... - -This program 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; version 2 of the License. - -This program 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 this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - -*/ - -package com.bigdata.util; - -import com.bigdata.util.config.LogUtil; - -import org.apache.log4j.Level; -import org.apache.log4j.Logger; - -import java.io.File; -import java.io.IOException; -import java.io.Serializable; - -import java.lang.reflect.Method; - -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLClassLoader; - -import java.rmi.Remote; -import java.rmi.RemoteException; -import java.rmi.activation.ActivationException; -import java.rmi.activation.ActivationID; - -import java.security.SecureClassLoader; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.StringTokenizer; - -import net.jini.io.MarshalledInstance; -import net.jini.loader.ClassAnnotation; - -/** - * This class provides useful utilities for creating and manipulating - * class loaders. Although it can be used for other purposes, it is - * generally intended for debugging. - */ -public class ClassLoaderUtil { - - /** Configure logger */ - private static Logger logger = - LogUtil.getLog4jLogger(ClassLoaderUtil.class); - - // Private constructor to prevent instantiation - private ClassLoaderUtil() { } - - /** - * Utility method that converts the components of a <code>String</code> - * representing a classpath into file <code>URL</code>(s). - * - * @param classpath <code>String</code> containing components separated - * by path separators that represent the components - * making up a classpath - * - * @return a <code>URL[]</code> where - * each element of the array corresponds to one of the components - * in the <code>classpath</code> parameter. The path components - * are (potentially) expanded via - * <code>File.getCanonicalFile()</code> before converting to a - * <code>URL</code> format. - * - * @throws java.net.MalformedURLException - * If the path cannot be parsed as a URL - * @throws java.net.IOException - * If an I/O error occurs, - * which is possible because the construction of - * the canonical pathname may require filesystem queries - */ - public static URL[] getClasspathURLs(String classpath) - throws IOException, MalformedURLException - { - StringTokenizer st = new StringTokenizer(classpath,File.pathSeparator); - URL[] urls = new URL[st.countTokens()]; - for (int i=0; st.hasMoreTokens(); i++) { - urls[i] = - new File(st.nextToken()).getCanonicalFile().toURI().toURL(); - } - return urls; - } - - /** - * Utility method that converts the components of a <code>String</code> - * representing a codebase into standard <code>URL</code>(s). - * - * @param codebase <code>String</code> containing components separated - * by spaces in which each component is in - * <code>URL</code> format. - * - * @return a <code>URL[]</code> where - * each element of the array corresponds to one of the components - * in the <code>codebase</code> parameter - * - * @throws java.net.MalformedURLException - */ - public static URL[] getCodebaseURLs(String codebase) - throws MalformedURLException - { - StringTokenizer st = new StringTokenizer(codebase); - URL[] urls = new URL[st.countTokens()]; - for (int i=0; st.hasMoreTokens(); i++) { - urls[i] = new URL(st.nextToken()); - } - return urls; - } - - /** - * Utility method that converts the components of a <code>String</code> - * representing a codebase or classpath into <code>URL</code>(s). - * - * @param importCodebase <code>String</code> assumed (in order) to be - * either - * 1) a space delimited set of <code>URL</code>(s) - * representing a codebase or - * 2) a <code>File.pathSeparator</code> delimited set - * of class paths. - * - * @return a <code>URL[]</code> where - * each element of the array corresponds to one of the components - * in the <code>importCodebase</code> parameter - * - * @throws java.net.MalformedURLException - * If the path cannot be parsed as a URL - * @throws java.net.IOException - * If an I/O error occurs, - * which is possible because the construction of - * the canonical pathname may require filesystem queries - */ - public static URL[] getImportCodebaseURLs(String importCodebase) - throws IOException, MalformedURLException - { - try { - return getCodebaseURLs(importCodebase); - } catch (MalformedURLException me) { - return getClasspathURLs(importCodebase); - } - } - - /** - * Utility method that retrieves the components making up the class loader - * delegation tree for the current context class loader and returns each - * in an <code>ArrayList</code>. - * - * @return an <code>ArrayList</code> instance in which each element of the - * list is one of the components making up the current delegation - * tree. - */ - private static ArrayList getContextClassLoaderTree() { - Thread curThread = Thread.currentThread(); - ClassLoader curClassLoader = curThread.getContextClassLoader(); - return getClassLoaderTree(curClassLoader); - } - - /** - * Utility method that retrieves the components making up the class loader - * delegation tree for the given <code>classloader</code> parameter and - * returns them via an <code>ArrayList</code>. - * - * @param classloader <code>ClassLoader</code> instance whose delegation - * tree is to be retrieved and returned - * - * @return an <code>ArrayList</code> instance in which each element of the - * list is one of the components making up the delegation tree - * of the given class loader. - */ - private static ArrayList getClassLoaderTree(ClassLoader classloader) { - ArrayList loaderList = new ArrayList(); - while(classloader != null) { - loaderList.add(classloader); - classloader = classloader.getParent(); - } - loaderList.add(null); //Append boot classloader - Collections.reverse(loaderList); - return loaderList; - } - - /** - * Utility method that displays the class loader delegation tree for - * the current context class loader. For each class loader in the tree, - * this method displays the locations from which that class loader - * will retrieve and load requested classes. - * <p> - * This method can be useful when debugging problems related to the - * receipt of exceptions such as <code>ClassNotFoundException</code>. - */ - public static void displayContextClassLoaderTree() { - Thread curThread = Thread.currentThread(); - ClassLoader curClassLoader = curThread.getContextClassLoader(); - displayClassLoaderTree(curClassLoader); - } - - /** - * Utility method that displays the class loader delegation tree for - * the given class loader. For each class loader in the tree, this - * method displays the locations from which that class loader will - * retrieve and load requested classes. - * <p> - * This method can be useful when debugging problems related to the - * receipt of exceptions such as <code>ClassNotFoundException</code>. - * - * Note that although this class' logger level is used to determine - * whether or not to display any information at all, the output is - * actually displayed using System.out.println. This is done to - * produce more readable output than the logger might produce. - * - * @param description descriptive <code>String</code> that, if - * non-<code>null</code>, will be logged prior to - * displaying the information about the - * <code>classloader</code>. - * - * @param classloader <code>ClassLoader</code> instance whose delegation - * tree is to be displayed. - */ - public static void displayClassLoaderTree(ClassLoader classloader) { - displayClassLoaderTree(null, classloader); - } - - public static void displayClassLoaderTree(String description, - ClassLoader classloader) - { - if( logger.isEnabledFor(Level.DEBUG) ) { - if(description != null) { - logger.log(Level.DEBUG, description); - } - - ArrayList loaderList = getClassLoaderTree(classloader); - System.out.println("ClassLoader Tree has " - + loaderList.size() + " levels"); - System.out.println(" cl0 -- Boot ClassLoader "); - ClassLoader curClassLoader = null; - for(int i=1; i < loaderList.size(); i++) { - System.out.println(" |"); - curClassLoader = (ClassLoader)loaderList.get(i); - System.out.print(" cl"+i+" -- ClassLoader " - +curClassLoader+": "); - if(curClassLoader instanceof URLClassLoader) { - URL[] urls = ((URLClassLoader)(curClassLoader)).getURLs(); - if(urls != null) { - System.out.print(urls[0]); - for(int j=1;j<urls.length;j++){ - System.out.print(", "+urls[j]); - } - } else {//urls == null - System.out.print("null search path"); - } - } else { - if(curClassLoader instanceof SecureClassLoader) { - System.out.print("is instance of SecureClassLoader"); - } else { - System.out.print("is unknown ClassLoader type"); - } - } - System.out.println(""); - } - System.out.println(""); - } - } - - /** - * Handles a <i>class loader mismatch</i> between the given - * <code>Serializable</code> object and the given <code>Class</code> - * type. - * - * If the class name of the given <code>obj</code> parameter - * is the same as the name of <code>classType</code>, but - * <code>obj</code> is not an instance of <code>classType</code>, - * then the difference may be due to unequal class loaders for the - * two parameters; which is referred to as a <i>class loader mismatch</i>. - * When such a mismatch occurs, the <code>instanceof</code> operator - * will return <code>false</code> and attempts to cast the given - * <code>obj</code> to the given <code>classType</code> will result - * in a <code>ClassCastException</code>. - * - * To address the situation just described, this method attempts to - * "reload" the given <code>obj</code>, using the <code>ClassLoader</code> - * of <code>classType</code>. This is accomplished by first - * marshalling and then unmarshalling the given <code>obj</code>, - * while the <i>current context class loader</i> is set to the - * <code>ClassLoader</code> of <code>classType</code>. - * - * Upon success, the newly loaded object is returned; which can then - * be successfully cast to the given <code>classType</code>. If the - * reload operation fails, <code>null</code> is returned. - */ - public static Serializable instanceOf(Serializable obj, Class classType) { - - if( classType.isInstance(obj) ) return obj; - - Class objClass = obj.getClass(); - ClassLoader classTypeCl = classType.getClassLoader(); - //marshall-and-unmarshal using the class type's classloader - try { - MarshalledInstance mInst = new MarshalledInstance(obj); - Serializable newObj = - (Serializable)(mInst.get(classTypeCl, false, null, null)); - if( classType.isInstance(newObj) ) return newObj; - - } catch(Throwable t) { - return null; - } - return null; - } - -} Added: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/CSVReaderBuilder.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/CSVReaderBuilder.java (rev 0) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/CSVReaderBuilder.java 2010-09-24 18:26:07 UTC (rev 3628) @@ -0,0 +1,204 @@ +package com.bigdata.util; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; + +public class CSVReaderBuilder { + /** <code>List</code> holding the header row, if any. */ + private final List<String> header = new ArrayList<String>(); + /** <code>List</code> of <code>List</code>s holding the columnar data */ + private final List<List<String>>rows = new ArrayList<List<String>>(); + /** <code>List</code> holding the current row being operated on. */ + private final List<String> currentRow = new ArrayList<String>(); + /** Flag determining whether or not to display the header row. Default is false. */ + private boolean suppressHeader = false; + /** Flag determining whether or not to display quoted content. Default is false. */ + private boolean suppressQoutes = false; + /** <code>String</code> used for column delimiter. Default is a comma. */ + private String columnDelimiter = ","; + /** <code>String</code> used for row delimiter. Default is a newline. */ + private String rowDelimter = "\n"; + /** <code>String</code> used for quote delimiter. Default is a double quote. */ + private String quoteDelimter = "\""; + + //Setters and getters + public String getQuoteDelimter() { + return quoteDelimter; + } + public void setQuoteDelimter(String quoteDelimter) { + this.quoteDelimter = quoteDelimter; + } + public boolean isSuppressQoutes() { + return suppressQoutes; + } + public void setSuppressQoutes(boolean suppressQoutes) { + this.suppressQoutes = suppressQoutes; + } + public String getColumnDelimiter() { + return columnDelimiter; + } + public void setColumnDelimiter(String columnDelimiter) { + this.columnDelimiter = columnDelimiter; + } + public String getRowDelimiter() { + return rowDelimter; + } + public void setRowDelimiter(String rowDelimter) { + this.rowDelimter = rowDelimter; + } + public boolean isSuppressHeader() { + return suppressHeader; + } + public void setSuppressHeader(boolean suppressHeader) { + this.suppressHeader = suppressHeader; + } + + /** Default constructor */ + CSVReaderBuilder() {} + + /** Adds the given string to the header row */ + public CSVReaderBuilder header(String h){header.add(h); return this;} + + /** Adds the given string to the current row */ + public CSVReaderBuilder column(String c){currentRow.add(c); return this;} + + /** Creates a new row by: 1) flushing the current row data, if any, to the collection + * of row data and 2) clearing the the current row. + */ + public CSVReaderBuilder newRow() { + flushCurrentRow(); + currentRow.clear(); + return this; + } + + /** + * Helper method for flushing and clearing the current row. + */ + private void flushCurrentRow() { + if (!currentRow.isEmpty()) { + List<String> t = new ArrayList<String>(); + for (String s: currentRow) { + t.add(s); + } + rows.add(t); + } + currentRow.clear(); + } + + /** + * Creates and returns a <code>Reader</code> object which contains the current set + * of header (optional) and data rows. The data will be formatted according to the + * current set of configurable attributes (e.g. delimiter settings). + * @return Reader which contains the formatted header and data rows. + */ + public Reader buildReader() { + StringBuilder sb = new StringBuilder(); + if (!suppressHeader) { + addHeader(sb); + } + flushCurrentRow(); + addRows(sb); + return new StringReader(sb.toString()); + } + + /** + * Helper method for adding (optional) header data to given <code>StringBuilder</code>. + * @param sb <code>StringBuilder</code> to append header row. + */ + private void addHeader(StringBuilder sb) { + sb.append(join(header)); + sb.append(getRowDelimiter()); + } + + /** + * Helper methos for adding data rows to the given <code>StringBuilder</code>. + * @param sb <code>StringBuilder</code> to append data rows. + */ + private void addRows(StringBuilder sb) { + for (List<String> row: rows) { + sb.append(join(row)); + sb.append(getRowDelimiter()); + } + } + + /** + * Helper method that optionally adds the configured quote delimiter to the given + * <code>String</code>. + * @param h The <code>String</code> to optionally quote. + * @return The optionally quoted <code>String</code> + */ + private String quote(String h) { + String quoted = h; + if (!suppressQoutes) { + quoted = getQuoteDelimter() + h + getQuoteDelimter(); + } + return quoted; + } + + /** + * Helper method that joins the given collection of <code>String</code> using the + * configured column delimiter. + * @param s the collection of strings to join + * @return String containing the collection's elements separated by the column delimiter. + */ + public String join(Collection<String> s) { + if (s == null || s.isEmpty()) return ""; + Iterator<String> iter = s.iterator(); + StringBuilder builder = new StringBuilder(quote(iter.next())); + while( iter.hasNext() ) + { + builder.append(getColumnDelimiter()).append(quote(iter.next())); + } + return builder.toString(); + } + + /** + * Test driver method for this class. [Not exhaustive.] + * @param args + * @throws Exception + */ + public static void main(String[] args) throws Exception { + CSVReaderBuilder cb = new CSVReaderBuilder(); + cb.header("A").header("B").header("C"); + cb.newRow().column("a").column("b").column("c"); + cb.newRow().column("x").column("y").column("z"); + cb.newRow().column(""); + cb.newRow().column("#"); + Reader r = cb.buildReader(); + System.out.println("Default listing..."); + listReader(r); + cb.setSuppressQoutes(true); + r = cb.buildReader(); + System.out.println("No quotes listing..."); + listReader(r); + cb.setSuppressHeader(true); + r = cb.buildReader(); + System.out.println("No quotes and no header listing..."); + listReader(r); + cb.setColumnDelimiter("\t"); + r = cb.buildReader(); + System.out.println("No quotes and no header and tab delimited listing..."); + listReader(r); + } + + /** + * Helper method for displaying content of the given <code>Reader</code> + * to <code>System.out</code>. + * @param r the <code>Reader</code> to read from. + * @throws IOException if there's a problem obtaining data from the <code>Reader</code>. + */ + private static void listReader(Reader r) throws IOException { + BufferedReader br = new BufferedReader(r); + String s = null; + while((s = br.readLine()) != null) { + System.out.println(s); + } + } +} + Modified: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java 2010-09-24 17:46:05 UTC (rev 3627) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java 2010-09-24 18:26:07 UTC (rev 3628) @@ -73,8 +73,6 @@ // Note: class is not debugged and is marked as deprecated, test is commented out. // suite.addTestSuite( TestHybridTimestampFactory.class ); - suite.addTestSuite(TestByteBufferBitVector.class); - suite.addTestSuite( TestCSVReader.class ); suite.addTestSuite( TestBootStateUtil.class ); return suite; Deleted: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestByteBufferBitVector.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestByteBufferBitVector.java 2010-09-24 17:46:05 UTC (rev 3627) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestByteBufferBitVector.java 2010-09-24 18:26:07 UTC (rev 3628) @@ -1,197 +0,0 @@ -/* - -Copyright (C) SYSTAP, LLC 2006-2008. All rights reserved. - -Contact: - SYSTAP, LLC - 4501 Tower Road - Greensboro, NC 27410 - lic...@bi... - -This program 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; version 2 of the License. - -This program 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 this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ -/* - * Created on Aug 6, 2009 - */ - -package com.bigdata.util; - -import it.unimi.dsi.bits.BitVector; - -import java.nio.ByteBuffer; - -import com.bigdata.util.ByteBufferBitVector; - -import junit.framework.TestCase2; - -/** - * Test suite for {@link ByteBufferBitVector}. - * - * @author <a href="mailto:tho...@us...">Bryan Thompson</a> - * @version $Id$ - */ -public class TestByteBufferBitVector extends TestCase2 { - - /** - * - */ - public TestByteBufferBitVector() { - } - - /** - * @param name - */ - public TestByteBufferBitVector(String name) { - super(name); - } - - /** Correct rejection test for ctor1. */ - public void test_ctor1_correct_rejection() { - - try { - new ByteBufferBitVector(null); - fail("Expecting: " + IllegalArgumentException.class); - } catch (IllegalArgumentException ex) { - if (log.isInfoEnabled()) - log.info("ignoring expected exception: " + ex); - } - - } - - public void test_ctor1() { - - final byte[] d = new byte[1]; - final ByteBuffer b = ByteBuffer.wrap(d); - final BitVector v = new ByteBufferBitVector(b); - - assertEquals("length", 8L, v.length()); - - // verify range check. - try { - v.getBoolean(-1); - fail("Expecting: " + IndexOutOfBoundsException.class); - } catch (IndexOutOfBoundsException ex) { - if (log.isInfoEnabled()) - log.info("Ignoring expected exception: " + ex); - } - - // verify range check. - try { - v.getBoolean(8); - fail("Expecting: " + IndexOutOfBoundsException.class); - } catch (IndexOutOfBoundsException ex) { - if (log.isInfoEnabled()) - log.info("Ignoring expected exception: " + ex); - } - - for (long i = 0; i < 8L; i++) - assertEquals(false, v.getBoolean(i)); - - // set bit zero. - d[0] |= (1 << 0); - if (log.isInfoEnabled()) - log.info(v.toString()); - assertEquals(true, v.getBoolean(0)); - - // clear bit zero. - d[0] &= ~(1 << 0); - if (log.isInfoEnabled()) - log.info(v.toString()); - assertEquals(false, v.getBoolean(0)); - - } - - /** - * Correct rejection and assumptions for ctor accepting offset and length - * options. - * - * @todo this tests with an even byte offset. Try w/ only a few bits offset. - */ - public void test_ctor2() { - - final byte[] d = new byte[3]; - final ByteBuffer b = ByteBuffer.wrap(d); - final BitVector v = new ByteBufferBitVector(b, 8, 8); - - assertEquals("length", 8L, v.length()); - - // verify range check. - try { - v.getBoolean(-1); - fail("Expecting: " + IndexOutOfBoundsException.class); - } catch (IndexOutOfBoundsException ex) { - if (log.isInfoEnabled()) - log.info("Ignoring expected exception: " + ex); - } - - // verify range check. - try { - v.getBoolean(8); - fail("Expecting: " + IndexOutOfBoundsException.class); - } catch (IndexOutOfBoundsException ex) { - if (log.isInfoEnabled()) - log.info("Ignoring expected exception: " + ex); - } - - for (long i = 0; i < 8L; i++) - assertEquals(false, v.getBoolean(i)); - - // set bit zero. - d[1] |= (1 << 0); - if (log.isInfoEnabled()) - log.info(v.toString()); - assertEquals(true, v.getBoolean(0)); - - // clear bit zero. - d[1] &= ~(1 << 0); - if (log.isInfoEnabled()) - log.info(v.toString()); - assertEquals(false, v.getBoolean(0)); - - } - - /** - * Verify set/clear of each bit in the first byte. - */ - public void test_getBoolean() { - - final byte[] d = new byte[1]; - final ByteBuffer b = ByteBuffer.wrap(d); - final BitVector v = new ByteBufferBitVector(b); - - // verify all bits are zero. - for (long i = 0; i < 8L; i++) - assertEquals(false, v.getBoolean(i)); - - // set/clear each bit in the first byte in turn. - for (int i = 0; i < 8; i++) { - - // set bit - d[0] |= (1 << i); - if (log.isInfoEnabled()) - log.info(v.toString() + " : i=" + i + ", (1<<" + i + ")=" - + (i << i)); - assertEquals(true, v.getBoolean(i)); - - // clear bit - d[0] &= ~(1 << i); - if (log.isInfoEnabled()) - log.info(v.toString()); - assertEquals(false, v.getBoolean(i)); - - } - - } - -} Modified: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestCSVReader.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestCSVReader.java 2010-09-24 17:46:05 UTC (rev 3627) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestCSVReader.java 2010-09-24 18:26:07 UTC (rev 3628) @@ -29,10 +29,20 @@ import java.io.ByteArrayInputStream; import java.io.IOException; +import java.io.InputStream; +import java.io.Reader; +import java.io.StringReader; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; +import java.util.Arrays; +import java.util.Date; import java.util.Iterator; +import java.util.List; import java.util.Map; +import java.util.NoSuchElementException; import java.util.TreeMap; import junit.framework.TestCase2; @@ -64,23 +74,41 @@ super(name); } - public void test_ctor_correctRejection() throws IOException { + public void test_ctor1_correctRejection() + throws IOException, SecurityException, NoSuchMethodException, + InstantiationException, IllegalAccessException, InvocationTargetException + { + Object[][] cmdLines = { + new Object[] {null, null}, + new Object[] {null, "UTF-8"}, + new Object[] {new ByteArrayInputStream(new byte[]{}), null}, + }; - try { - new CSVReader(null,"UTF-8"); - fail("Expecting: "+IllegalArgumentException.class); - } catch(IllegalArgumentException ex) { - log.info("Ignoring expected exception: "+ex); + Constructor<CSVReader> cons = + CSVReader.class.getConstructor(InputStream.class, String.class); + for (Object[] cmdLine: cmdLines) { + try { + cons.newInstance(cmdLine); + fail("Expecting: " + IllegalArgumentException.class.toString()); + } catch(InvocationTargetException ex) { + if (!(ex.getCause() instanceof IllegalArgumentException)) { + fail("Expecting: " + IllegalArgumentException.class.toString()); + } + //ignore -- expected + } } + } + + public void test_ctor2_correctRejection() throws IOException { try { - new CSVReader(new ByteArrayInputStream(new byte[]{}),null); - fail("Expecting: "+IllegalArgumentException.class); + Reader r = null; + new CSVReader(r); + fail("Expecting: " + IllegalArgumentException.class.toString()); } catch(IllegalArgumentException ex) { - log.info("Ignoring expected exception: "+ex); + //ignore -- expected } - - } + } /** * Test reads from a tab-delimited file <code>test.csv</code> with headers @@ -113,7 +141,7 @@ assertEquals(1,r.lineNo()); - assertEquals(headers, r.headers); + assertEquals(headers, r.getHeaders()); /* * 1st row of data. @@ -206,7 +234,359 @@ assertFalse(r.hasNext()); } + + private static Header[] convertStringToHeader(String[] sa) { + Header[] h = new Header[sa.length]; + int i=0; + for (String s: sa) { + h[i++] = new Header(s); + } + return h; + } + private static String[] stringHeaders = { "Header1", "Header2", "Header3" }; + private static String[] defaultStringHeaders = { "1", "2", "3" }; + + private static Header[] headers = convertStringToHeader(stringHeaders); + private static Header[] defaultHeaders = convertStringToHeader(defaultStringHeaders); + + private static Object[][] rows = { + { "Column11", "Column12", "Column13" }, + { "Column21", "Column22", "Column23" }, + { "Column31", "Column32", "Column33" }, + { "Column with spaces", "and more spaces", "and embedded \"quotes\"" }, + }; + + private static CSVReaderBuilder getDefaultTestCSVReaderBuilder() { + CSVReaderBuilder b = new CSVReaderBuilder(); + for (String header: stringHeaders) { + b.header(header); + } + for (Object[] row: rows) { + b.newRow(); + for (Object col: row) { + b.column(col.toString()); + } + } + return b; + } + + public void test_default_csv_reader_with_defaults() throws IOException { + CSVReaderBuilder cb = getDefaultTestCSVReaderBuilder(); + verify_data_and_header(new CSVReader(cb.buildReader())); + } + public void test_default_csv_reader_with_tabs() throws IOException { + CSVReaderBuilder cb = getDefaultTestCSVReaderBuilder(); + cb.setColumnDelimiter("\t"); + verify_data_and_header(new CSVReader(cb.buildReader())); + } + public void test_default_csv_reader_without_quotes() throws IOException { + CSVReaderBuilder cb = getDefaultTestCSVReaderBuilder(); + cb.setSuppressQoutes(true); + verify_data_and_header(new CSVReader(cb.buildReader())); + } + public void test_default_csv_reader_no_headers() throws IOException { + CSVReaderBuilder cb = getDefaultTestCSVReaderBuilder(); + cb.setSuppressHeader(true); + verify_data(new CSVReader(cb.buildReader()),defaultHeaders); + } + + private void verify_data_and_header(CSVReader cr) throws IOException { + // Read and verify header row + assertTrue(cr.hasNext()); + cr.readHeaders(); + assertEquals(cr.getHeaders(), headers); + verify_data(cr, headers); + } + + private void verify_data(CSVReader cr, Header[] headers) throws IOException { + //Read and verify data rows + for (int i=0; i < rows.length; i++) { + assertTrue(cr.hasNext()); + assertSameValues( newMap(headers, rows[i]), cr.next() ); + } + assertFalse(cr.hasNext()); + } + + public void test_header_cons_with_bad_args() { + try { + new Header(null); + fail("Constructed Header with null arg."); + } catch (IllegalArgumentException e){ + //ignore -- expected + } + try { + new Header(""); + fail("Constructed Header with empty arg."); + } catch (IllegalArgumentException e){ + //ignore -- expected + } + } + + public void test_header_cons_with_good_arg() { + String name = "abc"; + Header h = new Header(name); + assertEquals(h.getName(), name); + } + + public void test_header_equals() { + String name = "abc"; + Header h = new Header(name); + Header h_dup = new Header(name); + Header h_dup2 = new Header(name); + Header h_diff = new Header(name + "diff"); + + // Test reflexive property + assertTrue(h.equals(h)); + + // Test symmetric property + assertTrue(h.equals(h_dup) && h_dup.equals(h)); + + //Test transitive property + assertTrue(h.equals(h_dup) && h_dup.equals(h_dup2) && h.equals(h_dup2)); + + // consistency property already tested + + // Test negative cases + assertFalse(h.equals(null)); + + assertFalse(h.equals(name)); + + assertFalse(h.equals(h_diff)); + } + + public void test_header_hashcode() { + String name = "abc"; + Header h = new Header(name); + Header h_dup = new Header(name); + + assertTrue(h.hashCode()==h_dup.hashCode()); + } + + public void test_header_toString() { + String name = "abc"; + Header h = new Header(name); + Header h_dup = new Header(name); + + assertTrue(h.toString().equals(name)); + } + + public void test_setTailDelayMillis_bad_arg() throws IOException { + CSVReaderBuilder cb = getDefaultTestCSVReaderBuilder(); + CSVReader r = new CSVReader(cb.buildReader()); + try { + r.setTailDelayMillis(-1L); + fail("Created CSVReader with negative delay."); + } catch (IllegalArgumentException e) { + //ignore -- expected + } + } + + public void test_setTailDelayMillis_good_arg() throws IOException { + CSVReaderBuilder cb = getDefaultTestCSVReaderBuilder(); + CSVReader r = new CSVReader(cb.buildReader()); + long delay = 1L; + long oldDelay = 0L; + long tmpDelay = 0L; + tmpDelay = r.setTailDelayMillis(delay); + assertTrue(r.getTailDelayMillis()==delay); + assertTrue(tmpDelay==oldDelay); + } + + private static class DelayedReader extends StringReader { + + private boolean isReady = false; + private int maxDelayCount = 3; + private int delayCount = 1; + + public DelayedReader(String s) { + super(s); + } + + @Override + public boolean ready() { + if (delayCount++ > maxDelayCount) isReady = true; + return isReady; + } + + } + + public void test_delay_with_reader() throws IOException { + CSVReaderBuilder crb = new CSVReaderBuilder(); + StringReader s = + new DelayedReader( + crb.join(Arrays.asList(stringHeaders))); + CSVReader r = new CSVReader(s); + r.setTailDelayMillis(1000); // 1 sec + assertTrue(r.hasNext()); + r.readHeaders(); + Header[] actualHeaders = r.getHeaders(); + Header[] expectedHeaders = headers; + assertEquals(expectedHeaders, actualHeaders); + } + + public void test_delay_with_reader_with_comments_and_empty_lines() + throws IOException + { + CSVReaderBuilder crb = new CSVReaderBuilder(); + crb.header("H1").header("H2").header("H3"); + crb.newRow().column("c1").column("c2").column("c3"); + crb.newRow().column("# Comment line"); + crb.newRow().column(""); //Blank line + crb.newRow().column("d1").column("d2").column("d3"); + crb.setSuppressQoutes(true); // Otherwise # isn't first char + CSVReader r = new CSVReader(crb.buildReader()); + assertTrue(r.hasNext()); + r.readHeaders(); + Header[] actualHeaders = r.getHeaders(); + Header[] expectedHeaders = new Header[] { + new Header("H1"), + new Header("H2"), + new Header("H3"), + }; + assertEquals(expectedHeaders, actualHeaders); + //Check that two rows of data gets returned + Map<String, Object> actualRow = r.next(); + Map<String, Object> expectedRow = + newMap(expectedHeaders, + new Object[] { "c1", "c2", "c3"} ); + assertSameValues(expectedRow, actualRow); + actualRow = r.next(); + expectedRow = + newMap(expectedHeaders, + new Object[] { "d1", "d2", "d3"} ); + assertSameValues(expectedRow, actualRow); + assertFalse(r.hasNext()); + try { + r.next(); + fail("Successfully called next() on an empty reader."); + } catch (NoSuchElementException e) { + //ignore -- expected + } + } + + public void test_get_headers() + throws IOException + { + CSVReader r = new CSVReader(new StringReader("")); + assertNull(r.getHeaders()); + } + + public void test_get_headers2() + throws IOException + { + CSVReaderBuilder crb = new CSVReaderBuilder(); + CSVReader r = + new CSVReader( + new StringReader( + crb.join(Arrays.asList(stringHeaders)))); + r.readHeaders(); + Header[] actual = r.getHeaders(); + assertEquals(headers, actual); + } + + public void test_set_headers_null() + throws IOException + { + CSVReaderBuilder crb = new CSVReaderBuilder(); + CSVReader r = + new CSVReader( + new StringReader( + crb.join(Arrays.asList(stringHeaders)))); + try { + r.setHeaders(null); + fail("Was able to set null headers."); + } catch (IllegalArgumentException e) { + //ignore -- expected + } + } + + public void test_set_headers() + throws IOException + { + CSVReaderBuilder crb = new CSVReaderBuilder(); + CSVReader r = + new CSVReader( + new StringReader( + crb.join(Arrays.asList(stringHeaders)))); + r.readHeaders(); + Header[] actual = r.getHeaders(); + assertEquals(headers, actual); + r.setHeaders(defaultHeaders); + actual = r.getHeaders(); + assertEquals(defaultHeaders, actual); + + } + + public void test_set_header_out_of_bounds() + throws IOException + { + CSVReaderBuilder crb = new CSVReaderBuilder(); + CSVReader r = + new CSVReader( + new StringReader( + crb.join(Arrays.asList(stringHeaders)))); + r.readHeaders(); + Header[] actual = r.getHeaders(); + assertEquals(headers, actual); + try { + r.setHeader(stringHeaders.length, new Header("out-of-bounds")); + fail("Able to set an out-of-bounds header element."); + } catch (IndexOutOfBoundsException e) { + //ignore -- expected + } + } + public void test_set_header_null() + throws IOException + { + CSVReaderBuilder crb = new CSVReaderBuilder(); + CSVReader r = + new CSVReader( + new StringReader( + crb.join(Arrays.asList(stringHeaders)))); + r.readHeaders(); + Header[] actual = r.getHeaders(); + assertEquals(headers, actual); + try { + r.setHeader(stringHeaders.length-1, null); + fail("Able to set a null header element."); + } catch (IllegalArgumentException e) { + //ignore -- expected + } + } + + public void test_set_header_valid() + throws IOException + { + CSVReaderBuilder crb = new CSVReaderBuilder(); + CSVReader r = + new CSVReader( + new StringReader( + crb.join(Arrays.asList(stringHeaders)))); + r.readHeaders(); + Header[] actual = r.getHeaders(); + assertEquals(headers, actual); + Header[] headersClone = headers.clone(); + int last = headersClone.length-1; + headersClone[last] = new Header("replacement"); + r.setHeader(last, headersClone[last]); + actual = r.getHeaders(); + assertEquals(headersClone, actual); + } + + public void test_remove() + throws IOException + { + CSVReader r = + new CSVReader(new StringReader("bogus")); + try { + r.remove(); + fail("Successfully called unsupported operation."); + } catch (UnsupportedOperationException e) { + // ignore -- expected + } + } + protected void assertEquals(Header[] expected, Header[] actual) { assertEquals(expected.length,actual.length); @@ -215,7 +595,7 @@ if(!expected[i].equals( actual[i])) { - fail("headers["+i+"], expected ["+expected[i]+"]u not ["+actual[i]+"]" ); + fail("headers["+i+"], expected ["+expected[i]+"] not ["+actual[i]+"]" ); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <res...@us...> - 2010-09-27 13:44:44
|
Revision: 3634 http://bigdata.svn.sourceforge.net/bigdata/?rev=3634&view=rev Author: resendes Date: 2010-09-27 13:44:37 +0000 (Mon, 27 Sep 2010) Log Message: ----------- Added more test cases and cleanup for com.bigdata.util package. Modified Paths: -------------- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/EntryUtil.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java Added Paths: ----------- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestEntryUtil.java Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/EntryUtil.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/EntryUtil.java 2010-09-27 13:39:12 UTC (rev 3633) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/EntryUtil.java 2010-09-27 13:44:37 UTC (rev 3634) @@ -75,7 +75,7 @@ * type. If no element in the array is an instance of the given * type, then <code>null</code> is returned. */ - public static <T> T getEntryByType(Entry[] attrs, Class<T> type) + public static <T extends Entry> T getEntryByType(Entry[] attrs, Class<T> type) { if( (attrs == null) || (type == null) ) return null; for(int i=0; i<attrs.length; i++) { @@ -85,144 +85,144 @@ return null; }//end getEntryByType - /** - * Examines the given array of entries and returns an array of all - * elements that are an instance of the given class type. If no element in - * the array is an instance of the given type, then <code>null</code> is - * returned. - */ - public static <T> T[] getEntriesByType(Entry[] attrs, Class<T> type) - { - if( (attrs == null) || (type == null) ) return null; - ArrayList<T> matches = null; - for(int i=0; i<attrs.length; i++) { - if( !( type.isInstance(attrs[i]) ) ) continue; - if ( matches == null ) - matches = new ArrayList<T>(); - matches.add( (T)attrs[i] ); - }//end loop +// /** +// * Examines the given array of entries and returns an array of all +// * elements that are an instance of the given class type. If no element in +// * the array is an instance of the given type, then <code>null</code> is +// * returned. +// */ +// public static <T> T[] getEntriesByType(Entry[] attrs, Class<T> type) +// { +// if( (attrs == null) || (type == null) ) return null; +// ArrayList<T> matches = null; +// for(int i=0; i<attrs.length; i++) { +// if( !( type.isInstance(attrs[i]) ) ) continue; +// if ( matches == null ) +// matches = new ArrayList<T>(); +// matches.add( (T)attrs[i] ); +// }//end loop +// +// if ( matches == null ) return null; +// +// return matches.toArray +// ( (T[])java.lang.reflect.Array.newInstance +// ( type, matches.size() ) ); +// } - if ( matches == null ) return null; +// /** +// * Examines the given array of entries and returns a list of all +// * elements that are an instance of the given class type. If no element +// * in the array is an instance of the given type, then an empty list is +// * returned. +// */ +// public static <T> List<T> getEntryListByType(final Entry[] attrs, +// final Class<T> type) +// { +// if(attrs == null) { +// throw new NullPointerException("null attrs array"); +// } +// if(type == null) { +// throw new NullPointerException("null type"); +// } +// final List<T> matches = new ArrayList<T>(); +// for (final Entry attr : attrs) { +// if(type.isInstance(attr)){ +// matches.add(type.cast(attr)); +// } +// } +// return matches; +// } - return matches.toArray - ( (T[])java.lang.reflect.Array.newInstance - ( type, matches.size() ) ); - } +// /** +// * Examines the given array of entries and returns a list of all +// * elements that match the given <code>template</code>; where +// * the matching semantics are defined by the template-matching +// * semantics specified in the Lookup Service Specification. If no +// * element in the given array matches the template, then an empty +// * list is returned. +// */ +// public static <T extends Entry> List<T> getEntryList(final Entry[] attrs, +// final T template) +// { +// final List<T> matches = new ArrayList<T>(); +// for (final Entry attr : attrs) { +// if(LookupAttributes.matches(template, attr)){ +// matches.add((T) attr); +// } +// } +// return matches; +// } - /** - * Examines the given array of entries and returns a list of all - * elements that are an instance of the given class type. If no element - * in the array is an instance of the given type, then an empty list is - * returned. - */ - public static <T> List<T> getEntryListByType(final Entry[] attrs, - final Class<T> type) - { - if(attrs == null) { - throw new NullPointerException("null attrs array"); - } - if(type == null) { - throw new NullPointerException("null type"); - } - final List<T> matches = new ArrayList<T>(); - for (final Entry attr : attrs) { - if(type.isInstance(attr)){ - matches.add(type.cast(attr)); - } - } - return matches; - } +// /** +// * Using the given <code>Logger</code>, displays the contents +// * of the given array of entries. +// */ +// public static void displayEntrySet(Entry[] entries, Logger logger) { +// displayEntrySet(null, entries, null, logger); +// } - /** - * Examines the given array of entries and returns a list of all - * elements that match the given <code>template</code>; where - * the matching semantics are defined by the template-matching - * semantics specified in the Lookup Service Specification. If no - * element in the given array matches the template, then an empty - * list is returned. - */ - public static <T extends Entry> List<T> getEntryList(final Entry[] attrs, - final T template) - { - final List<T> matches = new ArrayList<T>(); - for (final Entry attr : attrs) { - if(LookupAttributes.matches(template, attr)){ - matches.add((T) attr); - } - } - return matches; - } +// /** +// * Using the given <code>Logger</code>, displays the contents +// * of the given array of entries. +// * <p> +// * Additionally, the identification of the output can be +// * customized using the given <code>entrySetName</code>. +// */ +// public static void displayEntrySet(Entry[] entries, +// String entrySetName, +// Logger logger) +// { +// displayEntrySet(null, entries, entrySetName, logger); +// } - /** - * Using the given <code>Logger</code>, displays the contents - * of the given array of entries. - */ - public static void displayEntrySet(Entry[] entries, Logger logger) { - displayEntrySet(null, entries, null, logger); - } +// /** +// * Using the given <code>Logger</code>, displays the contents +// * of the given array of entries. +// * <p> +// * Each line displayed is prefixed using the value of the +// * <code>prefix</code> parameter. +// */ +// public static void displayEntrySet(String prefix, +// Entry[] entries, +// Logger logger) +// { +// displayEntrySet(prefix, entries, null, logger); +// } - /** - * Using the given <code>Logger</code>, displays the contents - * of the given array of entries. - * <p> - * Additionally, the identification of the output can be - * customized using the given <code>entrySetName</code>. - */ - public static void displayEntrySet(Entry[] entries, - String entrySetName, - Logger logger) - { - displayEntrySet(null, entries, entrySetName, logger); - } +// /** +// * Using the given <code>Logger</code>, displays the contents +// * of the given array of entries. +// * <p> +// * Each line displayed is prefixed using the value of the +// * <code>prefix</code> parameter. Additionally, the identification +// * of the output can be customized using the given +// * <code>entrySetName</code>. +// */ +// public static void displayEntrySet(String prefix, +// Entry[] entries, +// String entrySetName, +// Logger logger) +// { +// if ( logger.isDebugEnabled() ) { +// if(prefix == null) prefix = ""; +// String name = ((entrySetName == null) ? +// "Entry Set" : entrySetName); +// if(entries == null) { +// logger.debug(prefix+": "+name+" = null"); +// } else if(entries.length <= 0) { +// logger.debug(prefix+": "+name+" = NO_ENTRIES"); +// } else { +// logger.debug(prefix+": "+name); +// logger.debug(prefix+": " +// +"-- Number of Entries = " + entries.length); +// for(int i=0; i<entries.length; i++) { +// displayEntry(entries[i], "", logger); +// }//end loop +// }//endif +// } +// } /** - * Using the given <code>Logger</code>, displays the contents - * of the given array of entries. - * <p> - * Each line displayed is prefixed using the value of the - * <code>prefix</code> parameter. - */ - public static void displayEntrySet(String prefix, - Entry[] entries, - Logger logger) - { - displayEntrySet(prefix, entries, null, logger); - } - - /** - * Using the given <code>Logger</code>, displays the contents - * of the given array of entries. - * <p> - * Each line displayed is prefixed using the value of the - * <code>prefix</code> parameter. Additionally, the identification - * of the output can be customized using the given - * <code>entrySetName</code>. - */ - public static void displayEntrySet(String prefix, - Entry[] entries, - String entrySetName, - Logger logger) - { - if ( logger.isDebugEnabled() ) { - if(prefix == null) prefix = ""; - String name = ((entrySetName == null) ? - "Entry Set" : entrySetName); - if(entries == null) { - logger.debug(prefix+": "+name+" = null"); - } else if(entries.length <= 0) { - logger.debug(prefix+": "+name+" = NO_ENTRIES"); - } else { - logger.debug(prefix+": "+name); - logger.debug(prefix+": " - +"-- Number of Entries = " + entries.length); - for(int i=0; i<entries.length; i++) { - displayEntry(entries[i], "", logger); - }//end loop - }//endif - } - } - - /** * Using the given <code>Logger</code>, displays the contents of * the given <code>entry</code>: Class, class loader, fields. */ @@ -230,19 +230,19 @@ displayEntry(null, entry, null, logger); } - /** - * Using the given <code>Logger</code>, displays the contents of - * the given <code>entry</code>: Class, class loader, fields. - * <p> - * Each line displayed is prefixed using the value of the - * <code>prefix</code> parameter. - */ - public static void displayEntry(String prefix, - Entry entry, - Logger logger) - { - displayEntry(prefix, entry, null, logger); - } +// /** +// * Using the given <code>Logger</code>, displays the contents of +// * the given <code>entry</code>: Class, class loader, fields. +// * <p> +// * Each line displayed is prefixed using the value of the +// * <code>prefix</code> parameter. +// */ +// public static void displayEntry(String prefix, +// Entry entry, +// Logger logger) +// { +// displayEntry(prefix, entry, null, logger); +// } /** * Using the given <code>Logger</code>, displays the contents of @@ -271,7 +271,7 @@ String label, Logger logger) { - if ( logger.isDebugEnabled() ) + if ( logger!= null && logger.isDebugEnabled() ) { if(prefix == null) prefix = ""; if(label == null) label = ""; @@ -305,80 +305,80 @@ } } - /** - * Using the given <code>Logger</code>, displays fields of the given - * <code>entry</code> instances that are not equal. Each line displayed - * is prefixed using the value of the <code>prefix</code> parameter. - */ - public static void displayDiff(String prefix, - Entry entry1, - Entry entry2, - Logger logger) - { - if ( logger.isDebugEnabled() ) { - if(prefix == null) prefix = ""; +// /** +// * Using the given <code>Logger</code>, displays fields of the given +// * <code>entry</code> instances that are not equal. Each line displayed +// * is prefixed using the value of the <code>prefix</code> parameter. +// */ +// public static void displayDiff(String prefix, +// Entry entry1, +// Entry entry2, +// Logger logger) +// { +// if ( logger.isDebugEnabled() ) { +// if(prefix == null) prefix = ""; +// +// String e1Str = (entry1 == null ? +// null : (entry1.getClass()).getName() ); +// String e2Str = (entry2 == null ? +// null : (entry2.getClass()).getName() ); +// +// Map<Field, List> diffMap = diff(entry1, entry2); +// +// if(diffMap == null) { +// logger.log(Level.DEBUG, prefix+": " +// +"CANNOT BE COMPARED: [entry1="+e1Str+"], " +// +"[entry2="+e2Str+"]"); +// return; +// }//endif +// +// if(diffMap.size() == 0) { +// logger.log(Level.DEBUG, prefix+": " +// +"NO DIFFERENCE: [entry1="+e1Str+"], " +// +"[entry2="+e2Str+"]"); +// return; +// }//endif +// +// Set<Map.Entry<Field, List>> fieldSet = diffMap.entrySet(); +// Iterator<Map.Entry<Field, List>> fieldItr = fieldSet.iterator(); +// while( fieldItr.hasNext() ) { +// Map.Entry<Field, List> pair = fieldItr.next(); +// Field field = pair.getKey(); +// List vals = pair.getValue(); +// String fieldName = field.getName(); +// if(vals.size() != 2) {//shouldn't happen +// logger.log(Level.WARN, "UNEXPECTED ERROR: " +// +"number of field values != 2 [field="+fieldName +// +", # of values="+vals.size()+", " +// +"vals="+vals+"]"); +// }//endif +// Object val1 = vals.get(0); +// Object val2 = vals.get(1); +// logger.log(Level.DEBUG, prefix+": " +// +e1Str+"."+fieldName+" = "+val1+" --> "+val2); +// }//end loop +// }//end(logger.isDebugEnabled) +// +// } - String e1Str = (entry1 == null ? - null : (entry1.getClass()).getName() ); - String e2Str = (entry2 == null ? - null : (entry2.getClass()).getName() ); +// public static void displayDiff(Entry entry1, Entry entry2, Logger logger) { +// displayDiff(null, entry1, entry2, logger); +// } - Map<Field, List> diffMap = diff(entry1, entry2); +// /** +// * Compares for equivalence, the contents of two individual entries. +// */ +// public static boolean compareEntries(Entry entry1, +// Entry entry2) +// { +// return ( compareEntrySets(null, +// new Entry[] {entry1}, +// new Entry[] {entry2}, +// null) ); +// } - if(diffMap == null) { - logger.log(Level.DEBUG, prefix+": " - +"CANNOT BE COMPARED: [entry1="+e1Str+"], " - +"[entry2="+e2Str+"]"); - return; - }//endif - - if(diffMap.size() == 0) { - logger.log(Level.DEBUG, prefix+": " - +"NO DIFFERENCE: [entry1="+e1Str+"], " - +"[entry2="+e2Str+"]"); - return; - }//endif - - Set<Map.Entry<Field, List>> fieldSet = diffMap.entrySet(); - Iterator<Map.Entry<Field, List>> fieldItr = fieldSet.iterator(); - while( fieldItr.hasNext() ) { - Map.Entry<Field, List> pair = fieldItr.next(); - Field field = pair.getKey(); - List vals = pair.getValue(); - String fieldName = field.getName(); - if(vals.size() != 2) {//shouldn't happen - logger.log(Level.WARN, "UNEXPECTED ERROR: " - +"number of field values != 2 [field="+fieldName - +", # of values="+vals.size()+", " - +"vals="+vals+"]"); - }//endif - Object val1 = vals.get(0); - Object val2 = vals.get(1); - logger.log(Level.DEBUG, prefix+": " - +e1Str+"."+fieldName+" = "+val1+" --> "+val2); - }//end loop - }//end(logger.isDebugEnabled) - - } - - public static void displayDiff(Entry entry1, Entry entry2, Logger logger) { - displayDiff(null, entry1, entry2, logger); - } - /** * Compares for equivalence, the contents of two individual entries. - */ - public static boolean compareEntries(Entry entry1, - Entry entry2) - { - return ( compareEntrySets(null, - new Entry[] {entry1}, - new Entry[] {entry2}, - null) ); - } - - /** - * Compares for equivalence, the contents of two individual entries. * <p> * Any lines displayed during the comparision will be displayed * using the given <code>Logger</code>. @@ -393,50 +393,50 @@ logger) ); } - /** - * Compares for equivalence, the contents of two individual entries. - * <p> - * Any lines displayed during the comparision will be displayed - * using the given <code>Logger</code>, and will be prefixed using - * the value of the <code>prefix</code> parameter. - */ - public static boolean compareEntries(String prefix, - Entry entry1, - Entry entry2, - Logger logger) - { - return ( compareEntrySets(prefix, - new Entry[] {entry1}, - new Entry[] {entry2}, - logger) ); - } +// /** +// * Compares for equivalence, the contents of two individual entries. +// * <p> +// * Any lines displayed during the comparision will be displayed +// * using the given <code>Logger</code>, and will be prefixed using +// * the value of the <code>prefix</code> parameter. +// */ +// public static boolean compareEntries(String prefix, +// Entry entry1, +// Entry entry2, +// Logger logger) +// { +// return ( compareEntrySets(prefix, +// new Entry[] {entry1}, +// new Entry[] {entry2}, +// logger) ); +// } /* ***************************************************************** */ /* ************************ compareEntrySets *********************** */ /* ***************************************************************** */ - /** - * Compares for equivalence, the contents of two sets of entries - * ignoring duplicate entries. - */ - public static boolean compareEntrySets(Entry[] entrySet1, - Entry[] entrySet2) - { - return compareEntrySets(null, entrySet1, entrySet2, null); - } +// /** +// * Compares for equivalence, the contents of two sets of entries +// * ignoring duplicate entries. +// */ +// public static boolean compareEntrySets(Entry[] entrySet1, +// Entry[] entrySet2) +// { +// return compareEntrySets(null, entrySet1, entrySet2, null); +// } - /** - * Compares for equivalence, the contents of two sets of entries - * ignoring duplicate entries. - * <p> - * Any lines displayed during the comparision will be displayed - * using the given <code>Logger</code>. - */ - public static boolean compareEntrySets(Entry[] entrySet1, - Entry[] entrySet2, - Logger logger) - { - return compareEntrySets(null, entrySet1, entrySet2, logger); - } +// /** +// * Compares for equivalence, the contents of two sets of entries +// * ignoring duplicate entries. +// * <p> +// * Any lines displayed during the comparision will be displayed +// * using the given <code>Logger</code>. +// */ +// public static boolean compareEntrySets(Entry[] entrySet1, +// Entry[] entrySet2, +// Logger logger) +// { +// return compareEntrySets(null, entrySet1, entrySet2, logger); +// } /** * Compares for equivalence, the contents of two sets of entries @@ -467,7 +467,7 @@ logger.trace(prefix+": entrySet1 = " +"null, entrySet2 != null"); }//endif - return false; + return false; }//endif } else {//entrySet1 != null if(entrySet2 == null) { @@ -475,7 +475,7 @@ logger.trace(prefix+": entrySet1 != " +"null, entrySet2 == null"); }//endif - return false; + return false; }//endif }//endif @@ -546,10 +546,10 @@ +": entries left over from comparison loop, " + "entry sets not equal"); }//endif - return false; + return false; }//endif - return true; + return true; } /** Returns public, non-static, non-transient, non-final fields contained @@ -708,255 +708,255 @@ } } - /** - * Convenience method that, given two <code>Entry</code> instances that - * are of the <i>same type</i>, determines which of the corresponding - * public fields of the given <code>Entry</code> instances are not equal, - * and returns a <code>Map</code> in which each key-value pair contains - * a key represented by the <code>Field</code> being compared, and a - * corresponding value represented by a <code>List</code> whose - * elements are the two values of the fields being compared; where the - * first element of the <code>List</code> is the value of the field - * in the first given <code>Entry</code>, and the second element of - * the <code>List</code> is the value of the field in the second - * <code>Entry</code> parameter. - * <p> - * If the <code>Entry</code> values input to this method are not the - * same type, then <code>null</code> is returned. If <code>null</code> - * is input for either or both of the <code>Entry</code> instances, - * then <code>null</code> is also returned. Finally, if the value of - * each public field of the first parameter equals the value of the - * corresponding field of the second parameter, then an empty - * <code>Map</code> is returned. - */ - public static Map<Field, List> diff(Entry e1, Entry e2) { - if (e1 == null || e2 == null) return null; - if (e1.getClass() != e2.getClass()) return null;//must be same type +// /** +// * Convenience method that, given two <code>Entry</code> instances that +// * are of the <i>same type</i>, determines which of the corresponding +// * public fields of the given <code>Entry</code> instances are not equal, +// * and returns a <code>Map</code> in which each key-value pair contains +// * a key represented by the <code>Field</code> being compared, and a +// * corresponding value represented by a <code>List</code> whose +// * elements are the two values of the fields being compared; where the +// * first element of the <code>List</code> is the value of the field +// * in the first given <code>Entry</code>, and the second element of +// * the <code>List</code> is the value of the field in the second +// * <code>Entry</code> parameter. +// * <p> +// * If the <code>Entry</code> values input to this method are not the +// * same type, then <code>null</code> is returned. If <code>null</code> +// * is input for either or both of the <code>Entry</code> instances, +// * then <code>null</code> is also returned. Finally, if the value of +// * each public field of the first parameter equals the value of the +// * corresponding field of the second parameter, then an empty +// * <code>Map</code> is returned. +// */ +// public static Map<Field, List> diff(Entry e1, Entry e2) { +// if (e1 == null || e2 == null) return null; +// if (e1.getClass() != e2.getClass()) return null;//must be same type +// +// Map<Field, List> retMap = new LinkedHashMap<Field, List>(); +// +// if (e1 == e2) return retMap; +// +// // compare each field +// Field[] fieldsArray1 = getFieldInfo(e1);//returns public fields +// Field[] fieldsArray2 = getFieldInfo(e2);//returns public fields +// try { +// for(int i=0; i<fieldsArray1.length; i++) { +// +// Field field1 = fieldsArray1[i]; +// Field field2 = fieldsArray2[i]; +// +// Object f1 = field1.get(e1);//value of field1 +// Object f2 = field2.get(e2);//value of field2 +// +// List fieldVals = new ArrayList(); +// +// if(f2 == f1) continue;//same obj or both null, f1 == f2, skip +// +// if(f2 == null || f1 == null) {//only 1 is null, f1 != f2 +// fieldVals.add(f1); +// fieldVals.add(f2); +// retMap.put(field1, fieldVals); +// continue;//next field +// }//endif +// +// if( !f2.equals(f1) ) {//test for arrays +// Class f2Class = f2.getClass(); +// Class f1Class = f1.getClass(); +// if( f2Class.isArray() && f1Class.isArray() ) { +// //determine if they are Object or primitive arrays +// Class f2Type = f2Class.getComponentType(); +// Class f1Type = f1Class.getComponentType(); +// +// if( !f2Type.equals(f1Type) ) {//field types not equal +// fieldVals.add(f1); +// fieldVals.add(f2); +// retMap.put(field1, fieldVals); +// continue;//next field +// }//endif +// +// boolean equalArrays = false; +// if( !f2Type.isPrimitive() && !f1Type.isPrimitive() ) { +// +// //types are equal & both non-primitive, use Object +// equalArrays = +// Arrays.equals( (Object[])f2, (Object[])f1 ); +// +// } else if(f2Type.isPrimitive()&&f1Type.isPrimitive()){ +// +// //types are equal & both primitive, use primitive +// if( f2Type.equals(Boolean.TYPE) ) { +// equalArrays = Arrays.equals( (boolean[])f2, +// (boolean[])f1 ); +// } else if( f2Type.equals(Character.TYPE) ) { +// equalArrays = Arrays.equals( (char[])f2, +// (char[])f1 ); +// } else if( f2Type.equals(Byte.TYPE) ) { +// equalArrays = Arrays.equals( (byte[])f2, +// (byte[])f1 ); +// } else if( f2Type.equals(Short.TYPE) ) { +// equalArrays = Arrays.equals( (short[])f2, +// (short[])f1 ); +// } else if( f2Type.equals(Integer.TYPE) ) { +// equalArrays = Arrays.equals( (int[])f2, +// (int[])f1 ); +// } else if( f2Type.equals(Long.TYPE) ) { +// equalArrays = Arrays.equals( (long[])f2, +// (long[])f1 ); +// } else if( f2Type.equals(Float.TYPE) ) { +// equalArrays = Arrays.equals( (float[])f2, +// (float[])f1 ); +// } else if( f2Type.equals(Double.TYPE) ) { +// equalArrays = Arrays.equals( (double[])f2, +// (double[])f1 ); +// }//endif +// +// //else 1 primitive, 1 not primitive ==> !equalArrays +// +// }//endif +// +// if( !equalArrays ) {//f1 not equal f2 +// fieldVals.add(f1); +// fieldVals.add(f2); +// retMap.put(field1, fieldVals); +// continue;//next field +// }//endif +// +// continue;//f1 equals f2, skip it and go to next field +// +// }//endif( f2Class.isArray() && f1Class.isArray() ) +// +// //(not arrays && !f2.equals(f1)) +// fieldVals.add(f1); +// fieldVals.add(f2); +// retMap.put(field1, fieldVals); +// +// }//endif( !f2.equals(f1) ) +// +// }//end loop +// +// return retMap; +// +// } catch (IllegalAccessException e) { +// // should never happen, all entry fields are public +// throw new AssertionError(e); +// } +// } - Map<Field, List> retMap = new LinkedHashMap<Field, List>(); +// /** +// * Convenience method that, given two <code>Entry</code> instances, +// * copies the values of the <i>usable</i> (<code>public</code>, +// * non-<code>transient</code>, non-<code>static</code>, +// * non-<code>final</code>) fields of the first <code>Entry</code> +// * parameter to the usable fields of the same name to the second given +// * <code>Entry</code> parameter. Any usable field from one of the +// * parameters that does not have a counterpart in the other parameter +// * will be by passed. This method can be useful, for example, when +// * converting an <code>AcinionAttribute</code> to a parallel +// * <code>AcinionEvent</code> for reporting outside of the system. +// * If <code>null</code> is input for either parameter, then +// * <code>null</code> is returned. +// */ +// public static Entry copyEntry(Entry e1, Entry e2, Logger logger) { +// if (e1 == null || e2 == null) return null; +// Entry retEntry = e2; +// String e1Name = (e1.getClass()).getSimpleName(); +// String retEntryName = (retEntry.getClass()).getSimpleName(); +// +// Field[] e1Fields = EntryUtil.getFieldInfo(e1); +// Field[] retEntryFields = EntryUtil.getFieldInfo(retEntry); +// if( e1Fields == null || e1Fields.length == 0 ) return null; +// if( retEntryFields == null || retEntryFields.length == 0 ) return null; +// for(int i=0; i<e1Fields.length; i++) { +// Field e1Field = e1Fields[i]; +// String e1FieldName = e1Field.getName(); +// for(int j=0; j<retEntryFields.length; j++) { +// Field retEntryField = retEntryFields[j]; +// String retEntryFieldName = retEntryField.getName(); +// String errStr = (logger == null ? null : +// "cannot set " +// +retEntryName+"."+retEntryFieldName +// +" to value of " +// +e1Name+"."+e1FieldName ); +// if( e1FieldName.equals(retEntryFieldName) ) { +// try { +// retEntryField.set( retEntry, e1Field.get(e1) ); +// } catch(IllegalArgumentException e) { +// if(logger != null) logger.log(Level.WARN, errStr); +// e.printStackTrace(); +// } catch(IllegalAccessException e) { +// if(logger != null) logger.log(Level.WARN, errStr); +// e.printStackTrace(); +// } +// }//endif +// }//end loop(j) +// }//end loop(i) +// return retEntry; +// } - if (e1 == e2) return retMap; +// /** +// * Returns an instance of the given <code>Entry</code> class with +// * all <i>usable</i> (public, non-static, non-transient, non-final) +// * fields set to <code>null</code>. The object returned by this method +// * can be used as a template that will match any <code>Entry</code> +// * that is of the same type as the <code>Entry</code> input to this +// * method. +// * +// * This method can be useful when working with an <code>Entry</code> +// * instance that defines a no-arg constructor that sets one or more +// * of its fields to a non-<code>null</code> value. +// */ +// public static Entry wildcardAll(Entry entry) { +// try { +// Class realClass = entry.getClass(); +// Entry template = (Entry) realClass.newInstance(); +// +// Field[] f = realClass.getFields(); +// for(int i = 0; i < f.length; i++) { +// if(! usableField(f[i])) continue; +// f[i].set(template, null); +// }//end loop +// return template; +// } catch (Throwable t) { +// Logger.getLogger(EntryUtil.class).error("wildcardEntry failed", t); +// } +// return null; +// } - // compare each field - Field[] fieldsArray1 = getFieldInfo(e1);//returns public fields - Field[] fieldsArray2 = getFieldInfo(e2);//returns public fields - try { - for(int i=0; i<fieldsArray1.length; i++) { +// /** +// * Returns a clone of the given {@link Entry}. +// * (From com.sun.jini.example.browser.ServiceEditor.) +// */ +// public static Entry cloneEntry(Entry attr) { +// try { +// Class realClass = attr.getClass(); +// Entry template = (Entry) realClass.newInstance(); +// +// Field[] f = realClass.getFields(); +// for(int i = 0; i < f.length; i++) { +// if(! usableField(f[i])) +// continue; +// f[i].set(template, f[i].get(attr)); +// } +// +// return template; +// } catch (Throwable t) { +// Logger.getLogger(EntryUtil.class).error("duplicating entry failed", t); +// } +// return null; +// } - Field field1 = fieldsArray1[i]; - Field field2 = fieldsArray2[i]; - - Object f1 = field1.get(e1);//value of field1 - Object f2 = field2.get(e2);//value of field2 - - List fieldVals = new ArrayList(); - - if(f2 == f1) continue;//same obj or both null, f1 == f2, skip - - if(f2 == null || f1 == null) {//only 1 is null, f1 != f2 - fieldVals.add(f1); - fieldVals.add(f2); - retMap.put(field1, fieldVals); - continue;//next field - }//endif - - if( !f2.equals(f1) ) {//test for arrays - Class f2Class = f2.getClass(); - Class f1Class = f1.getClass(); - if( f2Class.isArray() && f1Class.isArray() ) { - //determine if they are Object or primitive arrays - Class f2Type = f2Class.getComponentType(); - Class f1Type = f1Class.getComponentType(); - - if( !f2Type.equals(f1Type) ) {//field types not equal - fieldVals.add(f1); - fieldVals.add(f2); - retMap.put(field1, fieldVals); - continue;//next field - }//endif - - boolean equalArrays = false; - if( !f2Type.isPrimitive() && !f1Type.isPrimitive() ) { - - //types are equal & both non-primitive, use Object - equalArrays = - Arrays.equals( (Object[])f2, (Object[])f1 ); - - } else if(f2Type.isPrimitive()&&f1Type.isPrimitive()){ - - //types are equal & both primitive, use primitive - if( f2Type.equals(Boolean.TYPE) ) { - equalArrays = Arrays.equals( (boolean[])f2, - (boolean[])f1 ); - } else if( f2Type.equals(Character.TYPE) ) { - equalArrays = Arrays.equals( (char[])f2, - (char[])f1 ); - } else if( f2Type.equals(Byte.TYPE) ) { - equalArrays = Arrays.equals( (byte[])f2, - (byte[])f1 ); - } else if( f2Type.equals(Short.TYPE) ) { - equalArrays = Arrays.equals( (short[])f2, - (short[])f1 ); - } else if( f2Type.equals(Integer.TYPE) ) { - equalArrays = Arrays.equals( (int[])f2, - (int[])f1 ); - } else if( f2Type.equals(Long.TYPE) ) { - equalArrays = Arrays.equals( (long[])f2, - (long[])f1 ); - } else if( f2Type.equals(Float.TYPE) ) { - equalArrays = Arrays.equals( (float[])f2, - (float[])f1 ); - } else if( f2Type.equals(Double.TYPE) ) { - equalArrays = Arrays.equals( (double[])f2, - (double[])f1 ); - }//endif - - //else 1 primitive, 1 not primitive ==> !equalArrays - - }//endif - - if( !equalArrays ) {//f1 not equal f2 - fieldVals.add(f1); - fieldVals.add(f2); - retMap.put(field1, fieldVals); - continue;//next field - }//endif - - continue;//f1 equals f2, skip it and go to next field - - }//endif( f2Class.isArray() && f1Class.isArray() ) - - //(not arrays && !f2.equals(f1)) - fieldVals.add(f1); - fieldVals.add(f2); - retMap.put(field1, fieldVals); - - }//endif( !f2.equals(f1) ) - - }//end loop - - return retMap; - - } catch (IllegalAccessException e) { - // should never happen, all entry fields are public - throw new AssertionError(e); - } - } - - /** - * Convenience method that, given two <code>Entry</code> instances, - * copies the values of the <i>usable</i> (<code>public</code>, - * non-<code>transient</code>, non-<code>static</code>, - * non-<code>final</code>) fields of the first <code>Entry</code> - * parameter to the usable fields of the same name to the second given - * <code>Entry</code> parameter. Any usable field from one of the - * parameters that does not have a counterpart in the other parameter - * will be by passed. This method can be useful, for example, when - * converting an <code>AcinionAttribute</code> to a parallel - * <code>AcinionEvent</code> for reporting outside of the system. - * If <code>null</code> is input for either parameter, then - * <code>null</code> is returned. - */ - public static Entry copyEntry(Entry e1, Entry e2, Logger logger) { - if (e1 == null || e2 == null) return null; - Entry retEntry = e2; - String e1Name = (e1.getClass()).getSimpleName(); - String retEntryName = (retEntry.getClass()).getSimpleName(); - - Field[] e1Fields = EntryUtil.getFieldInfo(e1); - Field[] retEntryFields = EntryUtil.getFieldInfo(retEntry); - if( e1Fields == null || e1Fields.length == 0 ) return null; - if( retEntryFields == null || retEntryFields.length == 0 ) return null; - for(int i=0; i<e1Fields.length; i++) { - Field e1Field = e1Fields[i]; - String e1FieldName = e1Field.getName(); - for(int j=0; j<retEntryFields.length; j++) { - Field retEntryField = retEntryFields[j]; - String retEntryFieldName = retEntryField.getName(); - String errStr = (logger == null ? null : - "cannot set " - +retEntryName+"."+retEntryFieldName - +" to value of " - +e1Name+"."+e1FieldName ); - if( e1FieldName.equals(retEntryFieldName) ) { - try { - retEntryField.set( retEntry, e1Field.get(e1) ); - } catch(IllegalArgumentException e) { - if(logger != null) logger.log(Level.WARN, errStr); - e.printStackTrace(); - } catch(IllegalAccessException e) { - if(logger != null) logger.log(Level.WARN, errStr); - e.printStackTrace(); - } - }//endif - }//end loop(j) - }//end loop(i) - return retEntry; - } - - /** - * Returns an instance of the given <code>Entry</code> class with - * all <i>usable</i> (public, non-static, non-transient, non-final) - * fields set to <code>null</code>. The object returned by this method - * can be used as a template that will match any <code>Entry</code> - * that is of the same type as the <code>Entry</code> input to this - * method. - * - * This method can be useful when working with an <code>Entry</code> - * instance that defines a no-arg constructor that sets one or more - * of its fields to a non-<code>null</code> value. - */ - public static Entry wildcardAll(Entry entry) { - try { - Class realClass = entry.getClass(); - Entry template = (Entry) realClass.newInstance(); - - Field[] f = realClass.getFields(); - for(int i = 0; i < f.length; i++) { - if(! usableField(f[i])) continue; - f[i].set(template, null); - }//end loop - return template; - } catch (Throwable t) { - Logger.getLogger(EntryUtil.class).error("wildcardEntry failed", t); - } - return null; - } - - /** - * Returns a clone of the given {@link Entry}. - * (From com.sun.jini.example.browser.ServiceEditor.) - */ - public static Entry cloneEntry(Entry attr) { - try { - Class realClass = attr.getClass(); - Entry template = (Entry) realClass.newInstance(); - - Field[] f = realClass.getFields(); - for(int i = 0; i < f.length; i++) { - if(! usableField(f[i])) - continue; - f[i].set(template, f[i].get(attr)); - } - - return template; - } catch (Throwable t) { - Logger.getLogger(EntryUtil.class).error("duplicating entry failed", t); - } - return null; - } - - // from EntryRep - private static boolean usableField(Field field) { - Class desc = field.getDeclaringClass(); - - if(desc.isPrimitive()) { - throw new IllegalArgumentException( - "Primitive types not allowed in an Entry: " + field.getName() ); - } - - // skip anything that isn't a public per-object mutable field - int mods = field.getModifiers(); - return (0 == (mods & (Modifier.TRANSIENT | Modifier.STATIC | Modifier.FINAL))); - } +// // from EntryRep +// private static boolean usableField(Field field) { +// Class desc = field.getDeclaringClass(); +// +// if(desc.isPrimitive()) { +// throw new IllegalArgumentException( +// "Primitive types not allowed in an Entry: " + field.getName() ); +// } +// +// // skip anything that isn't a public per-object mutable field +// int mods = field.getModifiers(); +// return (0 == (mods & (Modifier.TRANSIENT | Modifier.STATIC | Modifier.FINAL))); +// } } Modified: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java 2010-09-27 13:39:12 UTC (rev 3633) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java 2010-09-27 13:44:37 UTC (rev 3634) @@ -75,6 +75,7 @@ suite.addTestSuite( TestCSVReader.class ); suite.addTestSuite( TestBootStateUtil.class ); + suite.addTestSuite( TestEntryUtil.class ); return suite; } Added: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestEntryUtil.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestEntryUtil.java (rev 0) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestEntryUtil.java 2010-09-27 13:44:37 UTC (rev 3634) @@ -0,0 +1,313 @@ +package com.bigdata.util; + +import java.lang.reflect.Field; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +import org.apache.log4j.Level; +import org.apache.log4j.Logger; + +import net.jini.core.entry.Entry; +import net.jini.entry.AbstractEntry; +import net.jini.lookup.entry.Address; +import net.jini.lookup.entry.Comment; +import net.jini.lookup.entry.Location; +import net.jini.lookup.entry.Name; +import net.jini.lookup.entry.ServiceType; +import junit.framework.TestCase; + +public class TestEntryUtil extends TestCase { + + public void testGetEntryByType_with_null_args() + throws SecurityException, NoSuchMethodException, + IllegalArgumentException, IllegalAccessException, InvocationTargetException + { + Object[][] cmdLines = { + {null, null}, + {null, Name.class}, + {new Entry[] {}, null} + }; + for (Object[] args: cmdLines) { + @SuppressWarnings("unchecked") + Object r = EntryUtil.getEntryByType( + (Entry[])args[0], (Class<? extends Entry>)args[1]); + assertNull(r); + } + } + + public void testGetEntryByType_with_emtpy_args() + throws SecurityException, NoSuchMethodException, + IllegalArgumentException, IllegalAccessException, InvocationTargetException + { + Name t = EntryUtil.getEntryByType(new Entry[]{}, Name.class); + assertNull(t); + } + + public void testGetEntryByType_no_match() + throws SecurityException, NoSuchMethodException, + IllegalArgumentException, IllegalAccessException, InvocationTargetException + { + Entry[] entries = new Entry[] { + new Address(), + new Comment(), + new Location() + }; + Name t = EntryUtil.getEntryByType(entries, Name.class); + assertNull(t); + } + + public void testGetEntryByType_match() + throws SecurityException, NoSuchMethodException, + IllegalArgumentException, IllegalAccessException, InvocationTargetException + { + Entry[] entries = new Entry[] { + new Address(), + new Comment(), + new Location() + }; + Location t = EntryUtil.getEntryByType(entries, Location.class); + assertNotNull(t); + } + + public void testDisplayEntryEntryLogger() { + EntryUtil.displayEntry( + new Address(), + getLevelLogger(Level.DEBUG)); + } + + public void testDisplayEntryEntryStringLogger() { + EntryUtil.displayEntry( + new Location(), + "Label", + getLevelLogger(Level.DEBUG)); + } + + public void testDisplayEntryStringEntryStringLogger() { + EntryUtil.displayEntry( + "Prefix", + new Comment("This is a comment."), + "Label", + getLevelLogger(Level.DEBUG)); + } + + public void testDisplayEntryStringEntryStringLogger_null() { + EntryUtil.displayEntry( + null, + null, + null, + getLevelLogger(Level.DEBUG)); + } + + private static void assertNotEquivalentEntries(Entry entry1, Entry entry2) { + assertFalse( + EntryUtil.compareEntries( + entry1, + entry2, + getLevelLogger(Level.TRACE))); + } + + public void testCompareEntries_not_equal_null() { + Entry entry1 = null; + Entry entry2 = new Name(); + assertNotEquivalentEntries(entry1, entry2); + assertNotEquivalentEntries(entry2, entry1); + } + + public void testCompareEntries_not_equal_diff_type() { + Entry entry1 = new Name(); + Entry entry2 = new Address(); + assertNotEquivalentEntries(entry1, entry2); + assertNotEquivalentEntries(entry2, entry1); + } + + public void testCompareEntries_not_equal_diff_content() { + Entry entry1 = new Name("Name1"); + Entry entry2 = new Name("Name2"); + assertNotEquivalentEntries(entry1, entry2); + assertNotEquivalentEntries(entry2, entry1); + } + + private static void assertEquivalentEntries(Entry entry1, Entry entry2) { + assertTrue( + EntryUtil.compareEntries( + entry1, + entry2, + getLevelLogger(Level.TRACE))); + } + + public void testCompareEntries_equal_null() { + Entry entry1 = null; + Entry entry2 = null; + assertEquivalentEntries(entry1, entry2); + assertEquivalentEntries(entry2, entry1); + } + + public void testCompareEntries_equal_same_content() { + Entry entry1 = new Name("Name1"); + Entry entry2 = new Name("Name1"); + assertEquivalentEntries(entry1, entry2); + assertEquivalentEntries(entry2, entry1); + } + + public void testCompareEntrySets_equiv_null() { + Entry[] entries1 = null; + Entry[] entries2 = null; + assertEquivalentSets(entries1, entries2); + assertEquivalentSets(entries2, entries1); + } + + public void testCompareEntrySets_equiv_empty() { + Entry[] entries1 = new Entry[] {}; + Entry[] entries2 = new Entry[] {}; + assertEquivalentSets(entries1, entries2); + assertEquivalentSets(entries2, entries1); + } + + public void testCompareEntrySets_equiv_non_empty_singleton() { + Entry[] entries1 = new Entry[] {new Address()}; + Entry[] entries2 = new Entry[] {new Address()}; + assertEquivalentSets(entries1, entries2); + assertEquivalentSets(entries2, entries1); + } + + public void testCompareEntrySets_equiv_non_empty_mulitple() { + Entry[] entries1 = new Entry[] {new Address(), new Name(), new Location()}; + Entry[] entries2 = new Entry[] {new Address(), new Name(), new Location()}; + assertEquivalentSets(entries1, entries2); + assertEquivalentSets(entries2, entries1); + } + + public void testCompareEntrySets_equiv_non_empty_mulitple_and_dups() { + Entry[] entries1 = + new Entry[] {new Address(), new Name(), new Location(), + new Location(), new Name()}; + Entry[] entries2 = + new Entry[] {new Address(), new Name(), new Location(), + new Address()}; + assertEquivalentSets(entries1, entries2); + assertEquivalentSets(entries2, entries1); + } + + private static void assertEquivalentSets(Entry[] entries1, Entry[] entries2) { + assertTrue( + EntryUtil.compareEntrySets("Equivalent", + entries1, + entries2, + getLevelLogger(Level.TRACE))); + } + + private static void assertNotEquivalentSets(Entry[] entries1, Entry[] entries2) { + assertFalse( + EntryUtil.compareEntrySets("Not equivalent", + entries1, + entries2, + getLevelLogger(Level.TRACE))); + } + + public void testCompareEntrySets_unequiv_null() { + Entry[] entries1 = null; + Entry[] entries2 = new Entry[] {}; + assertNotEquivalentSets(entries1, entries2); + assertNotEquivalentSets(entries2, entries1); + } + + public void testCompareEntrySets_unequiv_non_empty_singleton() { + Entry[] entries1 = new Entry[] {new Comment("C1")}; + Entry[] entries2 = new Entry[] {new Comment("C2")}; + assertNotEquivalentSets(entries1, entries2); + assertNotEquivalentSets(entries2, entries1); + } + + public void testCompareEntrySets_unequiv_non_empty_diff_size() { + Entry[] entries1 = new Entry[] {new Comment("C1")}; + Entry[] entries2 = new Entry[] {new Comment("C2"), new Comment("C3")}; + assertNotEquivalentSets(entries1, entries2); + assertNotEquivalentSets(entries2, entries1); + } + + public static class MyServiceType extends ServiceType { + private static final long serialVersionUID = 1L; + //Only public, non-transient/final/static are used for Entry objs + public String name = null; + public String desc = null; + + public MyServiceType() {} //default cons per spec + + public MyServiceType(String name, String desc) { + super(); + this.name = name; + this.desc = desc; + } + + @Override + public String getDisplayName() { + return name; + } + + @Override + public String getShortDescription() { + return desc; + } + } + + public void testCompareEntrySets_equiv_serviceType() { + Entry[] entries1 = new Entry[] {new MyServiceType("A", "B")}; + Entry[] entries2 = new Entry[] {new MyServiceType("A", "B")}; + assertEquivalentSets(entries1, entries2); + assertEquivalentSets(entries2, entries1); + } + + public void testCompareEntrySets_unequiv_serviceType() { + Entry[] entries1 = new Entry[] {new MyServiceType("A", "B")}; + Entry[] entries2 = new Entry[] {new MyServiceType("A", "C")}; + assertNotEquivalentSets(entries1, entries2); + assertNotEquivalentSets(entries2, entries1); + } + + public void testCompareEntrySets_unequiv_serviceType2() { + Entry[] entries1 = new Entry[] {new MyServiceType("A", "B")}; + Entry[] entries2 = new Entry[] {new MyServiceType("D", "B")}; + assertNotEquivalentSets(entries1, entries2); + assertNotEquivalentSets(entries2, entries1); + } + + public void testCompareEntrySets_unequiv_serviceType_null1() { + Entry[] entries1 = new Entry[] {new MyServiceType("A", "B")}; + Entry[] entries2 = new Entry[] {new MyServiceType(null, "B")}; + assertNotEquivalentSets(entries1, entries2); + assertNotEquivalentSets(entries2, entries1); + } + + public void testCompareEntrySets_unequiv_serviceType_null2() { + Entry[] entries1 = new Entry[] {new MyServiceType("A", "B")}; + Entry[] entries2 = new Entry[] {new MyServiceType("A", null)}; + assertNotEquivalentSets(entries1, entries2); + assertNotEquivalentSets(entries2, entries1); + } + + private static class MyEntryWithUnusableFields extends AbstractEntry { + private static final long serialVersionUID = 1L; // final, static, excluded + public final String finalString = "finalString"; // final, excluded + public transient String transientString = "transientString"; // trans, excluded + public static String staticString = "staticString"; // static, excluded + private String privateString = "privateString"; // private, excluded + public String publicString = "publicString"; // included + } + + public void testGetFieldInfo() { + MyEntryWithUnusableFields mf = new MyEntryWithUnusableFields(); + Field[] fields = EntryUtil.getFieldInfo(mf); + assertTrue(fields.length==1); + assertTrue(fields[0].getName().equals("publicString")); + } + + private static Logger getLevelLogger(Level level) { + Logger logger = getLogger(); + logger.setLevel(level); + return logger; + } + private static Logger getLogger() { + return Logger.getLogger(TestEntryUtil.class); + } + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <res...@us...> - 2010-09-27 18:53:26
|
Revision: 3640 http://bigdata.svn.sourceforge.net/bigdata/?rev=3640&view=rev Author: resendes Date: 2010-09-27 18:53:19 +0000 (Mon, 27 Sep 2010) Log Message: ----------- Next batch of changes for com.bigdata.util package Modified Paths: -------------- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/Format.java branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/HTMLUtility.java branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/InnerCause.java branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/MillisecondTimestampFactory.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestInnerCause.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestMillisecondTimestampFactory.java Added Paths: ----------- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestFormat.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestHTMLUtility.java Removed Paths: ------------- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/HybridTimestampFactory.java branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NanosecondTimestampFactory.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestHybridTimestampFactory.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestNanosecondTimestampFactory.java Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/Format.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/Format.java 2010-09-27 18:28:54 UTC (rev 3639) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/Format.java 2010-09-27 18:53:19 UTC (rev 3640) @@ -36,6 +36,7 @@ * the logger; which occurs only when the log level satisfies the * necessary criteria for the message to be logged. */ +//TODO - replace references with log level checks intstead public class Format { private final String pattern; Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/HTMLUtility.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/HTMLUtility.java 2010-09-27 18:28:54 UTC (rev 3639) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/HTMLUtility.java 2010-09-27 18:53:19 UTC (rev 3640) @@ -33,13 +33,6 @@ public class HTMLUtility { /** - * - */ - public HTMLUtility() { - super(); - } - - /** * <p> * Sometimes you want to escape something without using a DOM instance. This * method escapes a String value so that it may be written as the value of @@ -145,120 +138,120 @@ // return new String(retval.getBytes(enc), enc); // } - public static String escapeForXMLName(String s) { +// public static String escapeForXMLName(String s) { +// +// if( s == null ) { +// +// throw new IllegalArgumentException(); +// +// } +// +// int len = s.length(); +// +// if (len == 0) +// return s; +// +// StringBuffer sb = new StringBuffer(len + 20); +// +// char ch = s.charAt(0); +// +// if(Character.isDigit(ch)) +// { +// sb.append("_num_"); +// } +// +// for (int i = 0; i < len; i++) { +// +// ch = s.charAt(i); +// +// switch (ch) { +// +// case '"': +// sb.append("_quote_"); +// break; +// +// case '\'': +// sb.append("_apos_"); +// break; +// +// case '&': +// sb.append("_amp_"); +// break; +// +// case '<': +// sb.append("_lt_"); +// break; +// +// case '>': +// sb.append("_gt_"); +// break; +// +// case '$': +// sb.append("_dollar_"); +// break; +// +// case ':': +// sb.append("_colon_"); +// break; +// +// case '~': +// sb.append("_tilda_"); +// break; +// +// case '(': +// sb.append("_lparen_"); +// break; +// +// case ')': +// sb.append("_rparen_"); +// break; +// +// case ',': +// sb.append("_comma_"); +// break; +// +// case '=': +// sb.append("_eq_"); +// break; +// +// case '!': +// sb.append("_bang_"); +// break; +// +// case '?': +// sb.append("_quest_"); +// break; +// +// case '/': +// sb.append("_fw_slash_"); +// break; +// +// case '\\': +// sb.append("_bk_slash_"); +// break; +// +// case ';': +// sb.append("_semicolon_"); +// break; +// +// case '.': +// sb.append("_period_"); +// break; +// +// case '`': +// sb.append("_tic_"); +// break; +// +// default: +// sb.append(ch); +// break; +// +// } +// +// } +// +// return sb.toString(); +// +// } - if( s == null ) { - - throw new IllegalArgumentException(); - - } - - int len = s.length(); - - if (len == 0) - return s; - - StringBuffer sb = new StringBuffer(len + 20); - - char ch = s.charAt(0); - - if(Character.isDigit(ch)) - { - sb.append("_num_"); - } - - for (int i = 0; i < len; i++) { - - ch = s.charAt(i); - - switch (ch) { - - case '"': - sb.append("_quote_"); - break; - - case '\'': - sb.append("_apos_"); - break; - - case '&': - sb.append("_amp_"); - break; - - case '<': - sb.append("_lt_"); - break; - - case '>': - sb.append("_gt_"); - break; - - case '$': - sb.append("_dollar_"); - break; - - case ':': - sb.append("_colon_"); - break; - - case '~': - sb.append("_tilda_"); - break; - - case '(': - sb.append("_lparen_"); - break; - - case ')': - sb.append("_rparen_"); - break; - - case ',': - sb.append("_comma_"); - break; - - case '=': - sb.append("_eq_"); - break; - - case '!': - sb.append("_bang_"); - break; - - case '?': - sb.append("_quest_"); - break; - - case '/': - sb.append("_fw_slash_"); - break; - - case '\\': - sb.append("_bk_slash_"); - break; - - case ';': - sb.append("_semicolon_"); - break; - - case '.': - sb.append("_period_"); - break; - - case '`': - sb.append("_tic_"); - break; - - default: - sb.append(ch); - break; - - } - - } - - return sb.toString(); - - } - } Deleted: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/HybridTimestampFactory.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/HybridTimestampFactory.java 2010-09-27 18:28:54 UTC (rev 3639) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/HybridTimestampFactory.java 2010-09-27 18:53:19 UTC (rev 3640) @@ -1,227 +0,0 @@ -/** - -Copyright (C) SYSTAP, LLC 2006-2007. All rights reserved. - -Contact: - SYSTAP, LLC - 4501 Tower Road - Greensboro, NC 27410 - lic...@bi... - -This program 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; version 2 of the License. - -This program 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 this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ -/* - * Created on Sep 15, 2007 - */ - -package com.bigdata.util; - -import java.math.BigInteger; - -import org.apache.log4j.Logger; - -/** - * A timestamp factory using {@link System#currentTimeMillis()} and an internal - * counter to provide unique timestamps with greater than millisecond - * resolution. - * - * @author <a href="mailto:tho...@us...">Bryan Thompson</a> - * @version $Id$ - * - * @deprecated This class has not been fully debugged and SHOULD NOT be used. - */ -public class HybridTimestampFactory { - - /** - * Logger. - */ - public static final Logger log = Logger.getLogger(HybridTimestampFactory.class); - -// /** -// * Allows up to 1024 distinct timestamps per millisecond. -// */ -// public static HybridTimestampFactory INSTANCE = new HybridTimestampFactory(); - - /** - * The #of low bits in the generated timestamps that are allocated to the - * internal counter. - */ - private final int counterBits; - - /** - * The maximum value of the internal counter before it will rollover. On - * rollover the factory sleeps until a new time in milliseconds is reported - * by {@link System#currentTimeMillis()}. - */ - private final int maxCounter; - - /** - * The milliseconds component of the last generated timestamp (without - * erasure of the hit bits). - */ - private long lastTimestamp; - - /** - * The last value of the internal counter used to make a unique timestamp. - * This is reset each time the time returned by - * {@link System#currentTimeMillis()} differs from {@link #lastTimestamp}. - */ - private int counter = 0; - - /** - * The #of times the factory needed to sleep the current thread in order to - * generate a distinct timestamp. - */ - private long sleepCounter = 0L; - - /** - * The #of times the factory needed to sleep the current thread in order to - * generate a distinct timestamp. - */ - public long getSleepCounter() { - - return sleepCounter; - - } - - /** - * Allows up to 1024 distinct timestamps per millisecond. - */ - protected HybridTimestampFactory() { - - this( 10 ); - - } - - /** - * Allows up to <code>2^counterBits</code> distinct timestamps per - * millisecond. - * - * @param counterBits - * The #of bits in the long timestamp that are used to represent - * a counter. - * - * @todo Compute the maximum period after which the timestamps will - * overflow. - * - * @todo Set the epoch when the timestamp factory is created and persist - * that epoch so that overflow is set the maximum #of milliseconds - * into the future. Note that overflow will be the point after which - * we can no longer generate timestamps (aka transaction identifiers) - * for a given database. - */ - public HybridTimestampFactory(int counterBits) { - - if (counterBits < 0 || counterBits > 31) { - - // Note: would overflow an int32 at 32 bits. - - throw new IllegalArgumentException("counterBits must be in [0:31]"); - - } - - lastTimestamp = 0L; - - this.counterBits = counterBits; - - /* - * Construct a bit mask - this will have zeros in the high bits that - * correspond to the millis and ones in the low bits that correspond to - * the counter. - * - * @todo this is just Math.pow(2,counterBits)-1 and could be simplified as - * such (in the WormAddressManager also). - */ -// final long counterMask; -// { -// -// long mask = 0; -// -// long bit; -// -// for (int i = 0; i < counterBits; i++) { -// -// bit = (1L << i); -// -// mask |= bit; -// -// } -// -// counterMask = mask; -// -// } -// -// /* -// * The resulting mask is also the maximum value for the counter. -// */ -// -// maxCounter = (int)counterMask; - - maxCounter = BigInteger.valueOf(2).pow(counterBits).intValue() - 1; - - log.warn("#counterBits="+counterBits+", maxCounter="+maxCounter); - - } - - public long nextTimestamp() { - - long timestamp = System.currentTimeMillis(); - - // @todo this still does not work at counterBits == 0. - if (timestamp == lastTimestamp && (counter == maxCounter || counterBits == 0)) { - - // wait for the next millisecond. - - do { - - try { - -// System.err.print("S"); - - sleepCounter++; - - Thread.sleep(1/* ms */); - - } catch (InterruptedException ex) { - - /* ignore */ - - } - - timestamp = System.currentTimeMillis(); - - } while (timestamp == lastTimestamp); - - // this is a new millisecond. - - counter = 0; // reset the counter. - - lastTimestamp = timestamp; // update the last millisecond used. - - } else { - - // otherwise just increment the counter. - - counter++; - - } - - if (counterBits == 0) - return timestamp; - - return timestamp << counterBits | counter; - - } - -} Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/InnerCause.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/InnerCause.java 2010-09-27 18:28:54 UTC (rev 3639) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/InnerCause.java 2010-09-27 18:53:19 UTC (rev 3640) @@ -53,7 +53,6 @@ * @throws IllegalArgumentException * if any parameter is null. */ -// static public Throwable getInnerCause(Throwable t, Class cls) { static public Throwable getInnerCause(Throwable t, Class<? extends Throwable> cls) { if (t == null) @@ -97,8 +96,6 @@ * @throws IllegalArgumentException * if any parameter is null. */ -// static public boolean isInnerCause(Throwable t, Class cls) { - // Note: Use of generics commented out for 1.4 compatibility. static public boolean isInnerCause(Throwable t, Class<? extends Throwable>cls) { return getInnerCause(t, cls) != null; Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/MillisecondTimestampFactory.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/MillisecondTimestampFactory.java 2010-09-27 18:28:54 UTC (rev 3639) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/MillisecondTimestampFactory.java 2010-09-27 18:53:19 UTC (rev 3640) @@ -105,7 +105,7 @@ assertPositive(lowerBound); - if (_lastTimestamp < lowerBound) { + if (lowerBound < _lastTimestamp) { log.warn("Timestamp factory is being set to an earlier time!"); @@ -161,7 +161,6 @@ // current time. long timestamp = System.currentTimeMillis(); - ; if (_autoIncMode) { @@ -182,8 +181,7 @@ _autoIncMode = false; - log - .warn("Leaving auto-increment mode: time is going forward again: lastTimestamp=" + log.warn("Leaving auto-increment mode: time is going forward again: lastTimestamp=" + _lastTimestamp + ", millisTime=" + timestamp); // fall through. @@ -226,8 +224,7 @@ * by this factory moving forward. */ - log - .warn("Entering auto-increment mode : milliseconds go backward: lastTimestamp=" + log.warn("Entering auto-increment mode : milliseconds go backward: lastTimestamp=" + _lastTimestamp + ", millisTime=" + timestamp); _autoIncMode = true; Deleted: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NanosecondTimestampFactory.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NanosecondTimestampFactory.java 2010-09-27 18:28:54 UTC (rev 3639) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NanosecondTimestampFactory.java 2010-09-27 18:53:19 UTC (rev 3640) @@ -1,90 +0,0 @@ -/** - -Copyright (C) SYSTAP, LLC 2006-2007. All rights reserved. - -Contact: - SYSTAP, LLC - 4501 Tower Road - Greensboro, NC 27410 - lic...@bi... - -This program 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; version 2 of the License. - -This program 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 this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ -/* - * Created on Oct 26, 2006 - */ - -package com.bigdata.util; - -/** - * Timestamp factory class with no more than nanosecond resolution - values - * produced by this class MUST NOT be persisted. - * <p> - * Note: There are several problems with {@link System#nanoTime()} to date and - * the values MUST NOT be persisted. The underlying problem is that the epoch - * MAY (and in practice does) change from VM instance to VM instance, often when - * the machine is rebooted. For this reason, nano time can appear to "go - * backward" rendering it unsuitable for placing timestamps on commit records. - * This means that we do not have access to time-based method with more than - * millisecond resolution of creating "distinctions" for transaction - * identifiers. - * <p> - * Note: Nano time could be made to work in a robust nano time service as long - * as the base time for the service is adjusted on service start or rollover to - * never go backward. - * - * @author <a href="mailto:tho...@us...">Bryan Thompson</a> - * @version $Id$ - */ -public class NanosecondTimestampFactory { - - static long lastNanoTime = System.nanoTime(); - - /** - * Generates a timestamp with nanosecond precision that is guarenteed to be - * distinct from the last timestamp generated by this method within the same - * VM instance. - * - * @return A timestamp with nanosecond precision that MUST NOT be persisted. - */ - public static long nextNanoTime() { - - final int limit = 1000; - - int i = 0; - - long nanoTime; - - do { - - nanoTime = System.nanoTime(); - - if( i++ >= limit ) throw new AssertionError(); - - } while( nanoTime == lastNanoTime ); - - if(nanoTime<lastNanoTime) { - - throw new AssertionError("Nano time goes backward: lastNanoTime=" - + lastNanoTime + ", nanoTime=" + nanoTime); - - } - - lastNanoTime = nanoTime; - - return nanoTime; - - } - -} Modified: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java 2010-09-27 18:28:54 UTC (rev 3639) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java 2010-09-27 18:53:19 UTC (rev 3640) @@ -65,17 +65,12 @@ // test of the millisecond resolution timestamp factory. suite.addTestSuite( TestMillisecondTimestampFactory.class ); - - // test of the nanosecond resolution timestamp factory. - suite.addTestSuite( TestNanosecondTimestampFactory.class ); - - // test of the hybrid timestamp factory. - // Note: class is not debugged and is marked as deprecated, test is commented out. -// suite.addTestSuite( TestHybridTimestampFactory.class ); - + suite.addTestSuite( TestCSVReader.class ); suite.addTestSuite( TestBootStateUtil.class ); suite.addTestSuite( TestEntryUtil.class ); + suite.addTestSuite( TestFormat.class ); + suite.addTestSuite( TestHTMLUtility.class ); return suite; } Added: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestFormat.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestFormat.java (rev 0) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestFormat.java 2010-09-27 18:53:19 UTC (rev 3640) @@ -0,0 +1,17 @@ +package com.bigdata.util; + +import junit.framework.TestCase; + +public class TestFormat extends TestCase { + + public TestFormat(String name) { + super(name); + } + + public void testFormat() { + String fmtString = "Roses are {0}, violets are {1}"; + Object[] fmtArgs = new Object[] { "red", "blue" }; + Format f = new Format(fmtString, fmtArgs); + assertTrue("Roses are red, violets are blue".equals(f.toString())); + } +} Added: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestHTMLUtility.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestHTMLUtility.java (rev 0) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestHTMLUtility.java 2010-09-27 18:53:19 UTC (rev 3640) @@ -0,0 +1,31 @@ +package com.bigdata.util; + +import junit.framework.TestCase; + +public class TestHTMLUtility extends TestCase { + + public TestHTMLUtility(String name) { + super(name); + } + + public void testEscapeForXHTML() { + String bare = "A\"'<>&z"; + String expected = "A"'<>&z"; + String actual = HTMLUtility.escapeForXHTML(bare); + assertEquals(expected, actual); + } + public void testEscapeForXHTML_null() { + try { + HTMLUtility.escapeForXHTML(null); + fail("Successfully called escapeForXHTML with null."); + } catch (IllegalArgumentException e) { + //ignore -- expected + } + } + public void testEscapeForXHTML_empty() { + String expected = ""; + String actual = HTMLUtility.escapeForXHTML(""); + assertEquals(expected, actual); + } + +} Deleted: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestHybridTimestampFactory.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestHybridTimestampFactory.java 2010-09-27 18:28:54 UTC (rev 3639) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestHybridTimestampFactory.java 2010-09-27 18:53:19 UTC (rev 3640) @@ -1,101 +0,0 @@ -/** - -Copyright (C) SYSTAP, LLC 2006-2007. All rights reserved. - -Contact: - SYSTAP, LLC - 4501 Tower Road - Greensboro, NC 27410 - lic...@bi... - -This program 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; version 2 of the License. - -This program 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 this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ -/* - * Created on Sep 15, 2007 - */ - -package com.bigdata.util; - -import junit.framework.TestCase; - -/** - * Test suite for {@link HybridTimestampFactory}. - * - * @todo test ctor correct acceptance and correct rejection and internally - * computed fields. - * - * @todo test with all legal ctor values for counterBits and plot the #of - * distinct timestamps per millisecond as a function of counterBits. - * - * @author <a href="mailto:tho...@us...">Bryan Thompson</a> - * @version $Id$ - */ -public class TestHybridTimestampFactory extends TestCase { - - /** - * - */ - public TestHybridTimestampFactory() { - super(); - } - - /** - * @param arg0 - */ - public TestHybridTimestampFactory(String arg0) { - super(arg0); - } - - /** - * Test verifies that timestamps are always distinct from the last generated - * timestamp as generated by {@link HybridTimestampFactory#nextMillis()} and - * notes the actual granularity of the generated timestamps. - */ - public void test_nextTimestamp2() { - - final int limit = 100000; - - HybridTimestampFactory timestampFactory = new HybridTimestampFactory(10); - - final long begin = System.currentTimeMillis(); - - long lastTimestamp = begin - 1; - - long timestamp; - - for( int i=0; i<limit; i++ ) { - - timestamp = timestampFactory.nextTimestamp(); - - if (timestamp == lastTimestamp) - fail("Same timestamp?"); - - if (timestamp < lastTimestamp) - fail("Time goes backwards?"); - - lastTimestamp = timestamp; - - } - - long elapsed = System.currentTimeMillis() - begin; - - System.err.println("Generated " + limit + " timestamps in " + elapsed - + " milliseconds: ts/ms: " + limit / (double) elapsed); - - System.err.println("The #of times the factory invoked Thread.sleep(): " - + timestampFactory.getSleepCounter()); - - } - -} Modified: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestInnerCause.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestInnerCause.java 2010-09-27 18:28:54 UTC (rev 3639) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestInnerCause.java 2010-09-27 18:53:19 UTC (rev 3640) @@ -58,6 +58,11 @@ } + protected boolean isInnerCause(Throwable t, Class<? extends Throwable> cls) { + + return InnerCause.isInnerCause(t, cls); + + } public void test_getInnerCause_correctRejection() { try { @@ -91,7 +96,7 @@ Throwable t = new RuntimeException(); assertTrue(t == getInnerCause(t, RuntimeException.class)); - + assertTrue(isInnerCause(t, RuntimeException.class)); } /** @@ -103,7 +108,8 @@ Throwable t = new IOException(); assertTrue(t == getInnerCause(t, Exception.class)); - + assertTrue(isInnerCause(t, Exception.class)); + } /** @@ -114,7 +120,8 @@ Throwable t = new Exception(); assertNull(getInnerCause(t, IOException.class)); - + assertFalse(isInnerCause(t, IOException.class)); + } /** @@ -126,7 +133,8 @@ Throwable t = new Throwable(); assertNull(getInnerCause(t, Exception.class)); - + assertFalse(isInnerCause(t, Exception.class)); + } /** @@ -139,6 +147,7 @@ Throwable t = new Throwable(cause); assertTrue(cause == getInnerCause(t, Exception.class)); + assertTrue(isInnerCause(t, Exception.class)); } @@ -152,6 +161,7 @@ Throwable t = new Throwable(cause); assertTrue(cause == getInnerCause(t, Exception.class)); + assertTrue(isInnerCause(t, Exception.class)); } @@ -165,7 +175,8 @@ Throwable t = new RuntimeException(cause); assertNull( getInnerCause(t, IOException.class)); - + assertFalse(isInnerCause(t, IOException.class)); + } /** @@ -179,7 +190,7 @@ Throwable t = new Exception(cause); assertNull( getInnerCause(t, IOException.class) ); - + assertFalse(isInnerCause(t, IOException.class)); } } Modified: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestMillisecondTimestampFactory.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestMillisecondTimestampFactory.java 2010-09-27 18:28:54 UTC (rev 3639) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestMillisecondTimestampFactory.java 2010-09-27 18:53:19 UTC (rev 3640) @@ -165,4 +165,24 @@ } + public void test_nextMillis_wrap() { + final long startMillis = Long.MAX_VALUE; + MillisecondTimestampFactory.setLowerBound(startMillis); + try { + long timestamp = MillisecondTimestampFactory.nextMillis(); + fail("Successfully called nextMillis() with wrap aorund."); + } catch (IllegalStateException e) { + //ignore -- expected + } + } + + public void test_setLowerBound() { + final long startMillis = Long.MAX_VALUE; + //Synch to ensure atomic calling sequence + synchronized(MillisecondTimestampFactory.class) { + MillisecondTimestampFactory.setLowerBound(startMillis); + //Setting lower bound clears auot-inc mode + assertFalse(MillisecondTimestampFactory.isAutoIncMode()); + } + } } Deleted: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestNanosecondTimestampFactory.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestNanosecondTimestampFactory.java 2010-09-27 18:28:54 UTC (rev 3639) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestNanosecondTimestampFactory.java 2010-09-27 18:53:19 UTC (rev 3640) @@ -1,128 +0,0 @@ -/** - -Copyright (C) SYSTAP, LLC 2006-2007. All rights reserved. - -Contact: - SYSTAP, LLC - 4501 Tower Road - Greensboro, NC 27410 - lic...@bi... - -This program 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; version 2 of the License. - -This program 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 this program; if not, write to the Free Software -Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -*/ -/* - * Created on Oct 26, 2006 - */ - -package com.bigdata.util; - -import junit.framework.TestCase; - -/** - * Test suite for {@link NanosecondTimestampFactory}. - * - * @author <a href="mailto:tho...@us...">Bryan Thompson</a> - * @version $Id$ - */ -public class TestNanosecondTimestampFactory extends TestCase { - - public TestNanosecondTimestampFactory() { - - } - - public TestNanosecondTimestampFactory(String arg0) { - - super(arg0); - - } - - /** - * Test determines whether nano times are always distinct from the last - * generated nanos time (as assigned by {@link System#nanoTime()}. - * <p> - * Note: This test is NOT designed to pass/fail but simply to test determine - * a characteristic of the platform on which it is executing. - */ - public void test_nextNanoTime() { - - final int limit = 1000000; - - long lastNanoTime = System.nanoTime(); - long nanoTime; - long minDiff = Long.MAX_VALUE; - - for( int i=0; i<limit; i++ ) { - - nanoTime = System.nanoTime(); - - if (nanoTime == lastNanoTime) { - - System.err - .println("This platform can generate identical timestamps with nanosecond resolution"); - - return; - - } - - long diff = nanoTime - lastNanoTime; - - if( diff < 0 ) diff = -diff; - - if( diff < minDiff ) minDiff = diff; - - lastNanoTime = nanoTime; - - } - - System.err.println("Nano times appear to be distinct on this platorm."); - - System.err.println("Minimum difference in nanos is " + minDiff - + " over " + limit + " trials"); - - } - - /** - * Test verifies that nano times are always distinct from the last generated - * nanos time (as assigned by {@link NanosecondTimestampFactory#nextNanoTime()}. - */ - public void test_nextNanoTime2() { - - final int limit = 1000000; - - long lastNanoTime = System.nanoTime() - 1; - long nanoTime; - long minDiff = Long.MAX_VALUE; - - for( int i=0; i<limit; i++ ) { - - nanoTime = NanosecondTimestampFactory.nextNanoTime(); - - if( nanoTime == lastNanoTime ) fail("Same nano time?"); - - long diff = nanoTime - lastNanoTime; - - if( diff < 0 ) diff = -diff; - - if( diff < minDiff ) minDiff = diff; - - lastNanoTime = nanoTime; - - } - - System.err.println("Minimum difference in nanos is " + minDiff - + " over " + limit + " trials"); - - } - -} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <res...@us...> - 2010-09-27 23:50:49
|
Revision: 3645 http://bigdata.svn.sourceforge.net/bigdata/?rev=3645&view=rev Author: resendes Date: 2010-09-27 23:50:43 +0000 (Mon, 27 Sep 2010) Log Message: ----------- Next batch of updates for com.bigdata.util Modified Paths: -------------- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NT.java branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NV.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestEntryUtil.java Added Paths: ----------- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestNT.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestNV.java Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NT.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NT.java 2010-09-27 23:38:47 UTC (rev 3644) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NT.java 2010-09-27 23:50:43 UTC (rev 3645) @@ -60,22 +60,18 @@ } + @Override public int hashCode() { return hashCode; } + @Override public boolean equals(Object o) { - return equals((NT) o); + if (!(o instanceof NT)) { - } - - public boolean equals(NT o) { - - if (o == null) { - /* * Note: This handles a case where the other instance was a key in a * WeakHashMap and the reference for the key was cleared. This @@ -85,14 +81,15 @@ return false; } + NT nt = (NT)o; - if (this == o) + if (this == nt) return true; - if (!this.name.equals(o.name)) + if (!this.name.equals(nt.name)) return false; - if (this.timestamp != o.timestamp) + if (this.timestamp != nt.timestamp) return false; return true; Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NV.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NV.java 2010-09-27 23:38:47 UTC (rev 3644) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NV.java 2010-09-27 23:50:43 UTC (rev 3645) @@ -5,6 +5,8 @@ /** * A name-value pair. * + * Note: this class has a natural ordering that is inconsistent with equals. + * * @author <a href="mailto:tho...@us...">Bryan Thompson</a> * @version $Id$ */ @@ -56,16 +58,20 @@ } - public int hashCode() { - - return name.hashCode(); - + @Override + public int hashCode() { + return name.hashCode(); } - public boolean equals(NV o) { - - return name.equals(o.name) && value.equals(o.value); + @Override + public boolean equals(Object o) { + if (!(o instanceof NV)) { + return false; + } + NV nv = (NV)o; + return name.equals(nv.name) && value.equals(nv.value); + } /** @@ -79,34 +85,34 @@ } - /** - * Combines the two arrays, appending the contents of the 2nd array to the - * contents of the first array. - * - * @param a - * @param b - * @return - */ - public static NV[] concat(final NV[] a, final NV[] b) { +// /** +// * Combines the two arrays, appending the contents of the 2nd array to the +// * contents of the first array. +// * +// * @param a +// * @param b +// * @return +// */ +// public static NV[] concat(final NV[] a, final NV[] b) { +// +// if (a == null && b == null) +// return a; +// +// if (a == null) +// return b; +// +// if (b == null) +// return a; +// +// final NV[] c = (NV[]) java.lang.reflect.Array.newInstance(a.getClass() +// .getComponentType(), a.length + b.length); +// +// System.arraycopy(a, 0, c, 0, a.length); +// +// System.arraycopy(b, 0, c, a.length, b.length); +// +// return c; +// +// } - if (a == null && b == null) - return a; - - if (a == null) - return b; - - if (b == null) - return a; - - final NV[] c = (NV[]) java.lang.reflect.Array.newInstance(a.getClass() - .getComponentType(), a.length + b.length); - - System.arraycopy(a, 0, c, 0, a.length); - - System.arraycopy(b, 0, c, a.length, b.length); - - return c; - - } - } Modified: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java 2010-09-27 23:38:47 UTC (rev 3644) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java 2010-09-27 23:50:43 UTC (rev 3645) @@ -71,6 +71,8 @@ suite.addTestSuite( TestEntryUtil.class ); suite.addTestSuite( TestFormat.class ); suite.addTestSuite( TestHTMLUtility.class ); + suite.addTestSuite( TestNT.class ); + suite.addTestSuite( TestNV.class ); return suite; } Modified: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestEntryUtil.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestEntryUtil.java 2010-09-27 23:38:47 UTC (rev 3644) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestEntryUtil.java 2010-09-27 23:50:43 UTC (rev 3645) @@ -13,7 +13,6 @@ import net.jini.lookup.entry.Comment; import net.jini.lookup.entry.Location; import net.jini.lookup.entry.Name; -import net.jini.lookup.entry.ServiceType; import junit.framework.TestCase; public class TestEntryUtil extends TestCase { @@ -225,66 +224,6 @@ assertNotEquivalentSets(entries2, entries1); } - public static class MyServiceType extends ServiceType { - private static final long serialVersionUID = 1L; - //Only public, non-transient/final/static are used for Entry objs - public String name = null; - public String desc = null; - - public MyServiceType() {} //default cons per spec - - public MyServiceType(String name, String desc) { - super(); - this.name = name; - this.desc = desc; - } - - @Override - public String getDisplayName() { - return name; - } - - @Override - public String getShortDescription() { - return desc; - } - } - - public void testCompareEntrySets_equiv_serviceType() { - Entry[] entries1 = new Entry[] {new MyServiceType("A", "B")}; - Entry[] entries2 = new Entry[] {new MyServiceType("A", "B")}; - assertEquivalentSets(entries1, entries2); - assertEquivalentSets(entries2, entries1); - } - - public void testCompareEntrySets_unequiv_serviceType() { - Entry[] entries1 = new Entry[] {new MyServiceType("A", "B")}; - Entry[] entries2 = new Entry[] {new MyServiceType("A", "C")}; - assertNotEquivalentSets(entries1, entries2); - assertNotEquivalentSets(entries2, entries1); - } - - public void testCompareEntrySets_unequiv_serviceType2() { - Entry[] entries1 = new Entry[] {new MyServiceType("A", "B")}; - Entry[] entries2 = new Entry[] {new MyServiceType("D", "B")}; - assertNotEquivalentSets(entries1, entries2); - assertNotEquivalentSets(entries2, entries1); - } - - public void testCompareEntrySets_unequiv_serviceType_null1() { - Entry[] entries1 = new Entry[] {new MyServiceType("A", "B")}; - Entry[] entries2 = new Entry[] {new MyServiceType(null, "B")}; - assertNotEquivalentSets(entries1, entries2); - assertNotEquivalentSets(entries2, entries1); - } - - public void testCompareEntrySets_unequiv_serviceType_null2() { - Entry[] entries1 = new Entry[] {new MyServiceType("A", "B")}; - Entry[] entries2 = new Entry[] {new MyServiceType("A", null)}; - assertNotEquivalentSets(entries1, entries2); - assertNotEquivalentSets(entries2, entries1); - } - private static class MyEntryWithUnusableFields extends AbstractEntry { private static final long serialVersionUID = 1L; // final, static, excluded public final String finalString = "finalString"; // final, excluded Added: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestNT.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestNT.java (rev 0) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestNT.java 2010-09-27 23:50:43 UTC (rev 3645) @@ -0,0 +1,76 @@ +package com.bigdata.util; + +import com.bigdata.util.CSVReader.Header; + +import junit.framework.TestCase; + +public class TestNT extends TestCase { + + + public void testGetName() { + String name = "ABC"; + NT nt = new NT(name, 1L); + assertEquals(name, nt.getName()); + } + + public void testGetTimestamp() { + long time = 1L; + NT nt = new NT("ABC", time); + assertEquals(time, nt.getTimestamp()); + } + + public void testNT_null() { + try { + NT nt = new NT(null, 1L); + fail("Sucessfully called NT with a null name argument."); + } catch (IllegalArgumentException e) { + // ignore -- expected + } + } + + public void testEqualsObject() { + String name = "abc"; + long time = 1L; + NT h = new NT(name, time); + NT h_dup = new NT(name, time); + NT h_dup2 = new NT(name, time); + NT h_diff = new NT(name + "diff", time); + NT h_diff2 = new NT(name, (time + 1L)); + + // Test reflexive property + assertTrue(h.equals(h)); + + // Test symmetric property + assertTrue(h.equals(h_dup) && h_dup.equals(h)); + + //Test transitive property + assertTrue(h.equals(h_dup) && h_dup.equals(h_dup2) && h.equals(h_dup2)); + + // consistency property already tested + + // Test negative cases + assertFalse(h.equals(null)); + + assertFalse(h.equals(name)); + + assertFalse(h.equals(h_diff)); + assertFalse(h.equals(h_diff2)); + } + + public void test_hashcode() { + String name = "abc"; + long time = 1L; + NT h = new NT(name, time); + NT h_dup = new NT(name, time); + assertTrue(h.hashCode()==h_dup.hashCode()); + } + + public void test_toString() { + String name = "abc"; + long time = 1L; + NT h = new NT(name, time); + NT h_dup = new NT(name, time); + assertTrue(h.toString().equals("NT{name=" + "abc" + ",timestamp=" + 1L + "}")); + } + +} Added: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestNV.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestNV.java (rev 0) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestNV.java 2010-09-27 23:50:43 UTC (rev 3645) @@ -0,0 +1,102 @@ +package com.bigdata.util; + +import junit.framework.TestCase; + +public class TestNV extends TestCase { + + + public void testGetName() { + String name = "ABC"; + NV nt = new NV(name, name); + assertEquals(name, nt.getName()); + } + + public void testGetValue() { + String name = "ABC"; + NV nt = new NV(name, name); + assertEquals(name, nt.getValue()); + } + + public void testNV_null() { + try { + new NV(null, "abc"); + fail("Successfully called NV() with null name argument."); + } catch (IllegalArgumentException e) { + //ignore -- expected + } + } + + public void testToString() { + String name = "Name"; + String value = "Value"; + NV nv = new NV(name, value); + assertTrue((name+"="+value).equals(nv.toString())); + } + + public void testEqualsNV() { + + String name = "abc"; + String value = "xyz"; + NV h = new NV(name, value); + NV h_dup = new NV(name, value); + NV h_dup2 = new NV(name, value); + NV h_diff = new NV(name + "diff", value); + NV h_diff2 = new NV(name, (value + "diff")); + + // Test reflexive property + assertTrue(h.equals(h)); + + // Test symmetric property + assertTrue(h.equals(h_dup) && h_dup.equals(h)); + + //Test transitive property + assertTrue(h.equals(h_dup) && h_dup.equals(h_dup2) && h.equals(h_dup2)); + + // consistency property already tested + + // Test negative cases + assertFalse(h.equals(null)); + + assertFalse(h.equals(name)); + + assertFalse(h.equals(h_diff)); + assertFalse(h.equals(h_diff2)); + } + + public void testHashCode() { + String name = "abc"; + String value = "xyz"; + NV h = new NV(name, value); + NV h_dup = new NV(name, value); + assertTrue(h.hashCode()==h_dup.hashCode()); + } + + public void testCompareTo() { + String name = "bcd"; + String value = "xyz"; + String lessThanName = "abc"; + String greaterThanName = "cde"; + NV nv = new NV(name, value); + NV ltnv = new NV(lessThanName, value); + NV gtnv = new NV(greaterThanName, value); + assertTrue(nv.compareTo(nv) == 0); + assertTrue(ltnv.compareTo(nv) < 0); + assertTrue(gtnv.compareTo(nv) > 0); + } + + public void testCompareContract() { + /* + * The NV class has a natural ordering that is inconsistent with equals. + * When equals and compare align, need to switch this test and the note, above, + * in the NV source code. + */ + String name = "bcd"; + String value1 = "xyz"; + String value2 = "lmn"; + NV nv = new NV(name, value1); + NV nv_diff_val = new NV(name, value2); + assertFalse(nv.equals(nv_diff_val)); + assertTrue(nv.compareTo(nv_diff_val)==0); + } + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <res...@us...> - 2010-09-28 13:57:04
|
Revision: 3659 http://bigdata.svn.sourceforge.net/bigdata/?rev=3659&view=rev Author: resendes Date: 2010-09-28 13:36:17 +0000 (Tue, 28 Sep 2010) Log Message: ----------- Last batch of code for com.bigdata.util package Modified Paths: -------------- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NT.java branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NV.java branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/ReverseLongComparator.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java Added Paths: ----------- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestReverseLongComparator.java Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NT.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NT.java 2010-09-28 12:43:35 UTC (rev 3658) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NT.java 2010-09-28 13:36:17 UTC (rev 3659) @@ -69,7 +69,8 @@ @Override public boolean equals(Object o) { - + if (this==o) return true; + if (!(o instanceof NT)) { /* Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NV.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NV.java 2010-09-28 12:43:35 UTC (rev 3658) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NV.java 2010-09-28 13:36:17 UTC (rev 3659) @@ -65,6 +65,8 @@ @Override public boolean equals(Object o) { + if (this==o) return true; + if (!(o instanceof NV)) { return false; } Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/ReverseLongComparator.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/ReverseLongComparator.java 2010-09-28 12:43:35 UTC (rev 3658) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/ReverseLongComparator.java 2010-09-28 13:36:17 UTC (rev 3659) @@ -33,17 +33,19 @@ /** * Places {@link Long} values into descending order. - * + * Note: Creates a comparator that compares objects based on the inverse of their + * natural ordering. * @author <a href="mailto:tho...@us...">Bryan Thompson</a> * @version $Id$ */ public class ReverseLongComparator implements Comparator<Long>, Serializable { + private static final long serialVersionUID = -234224494051463945L; + /** - * + * Provides an inverse comparison to the <code>Comparator</code> interface. + * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ - private static final long serialVersionUID = -234224494051463945L; - public int compare(final Long o1, final Long o2) { final long l1 = o1.longValue(); Modified: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java 2010-09-28 12:43:35 UTC (rev 3658) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestAll.java 2010-09-28 13:36:17 UTC (rev 3659) @@ -28,7 +28,6 @@ package com.bigdata.util; -import com.bigdata.io.TestChecksumUtility; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; @@ -63,16 +62,16 @@ TestSuite suite = new TestSuite("util"); - // test of the millisecond resolution timestamp factory. - suite.addTestSuite( TestMillisecondTimestampFactory.class ); - + suite.addTestSuite( TestBootStateUtil.class ); suite.addTestSuite( TestCSVReader.class ); - suite.addTestSuite( TestBootStateUtil.class ); suite.addTestSuite( TestEntryUtil.class ); suite.addTestSuite( TestFormat.class ); suite.addTestSuite( TestHTMLUtility.class ); + suite.addTestSuite( TestInnerCause.class ); + suite.addTestSuite( TestMillisecondTimestampFactory.class ); suite.addTestSuite( TestNT.class ); suite.addTestSuite( TestNV.class ); + suite.addTestSuite( TestReverseLongComparator.class ); return suite; } Added: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestReverseLongComparator.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestReverseLongComparator.java (rev 0) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestReverseLongComparator.java 2010-09-28 13:36:17 UTC (rev 3659) @@ -0,0 +1,26 @@ +package com.bigdata.util; + +import junit.framework.TestCase; + +public class TestReverseLongComparator extends TestCase { + + public TestReverseLongComparator(String name) { + super(name); + } + + // Note: reverse comparison --> reverse of compare contract + public void testCompare_non_negative() { + ReverseLongComparator comp = new ReverseLongComparator(); + assertTrue(comp.compare(1L, 2L) > 0); + assertTrue(comp.compare(1L, 1L) == 0); + assertTrue(comp.compare(1L, 0L) < 1); + } + + public void testCompare_negative() { + ReverseLongComparator comp = new ReverseLongComparator(); + assertTrue(comp.compare(-2L, -1L) > 0); + assertTrue(comp.compare(-1L, -1L) == 0); + assertTrue(comp.compare(0L, -1L) < 1); + } + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <res...@us...> - 2010-09-28 18:10:45
|
Revision: 3667 http://bigdata.svn.sourceforge.net/bigdata/?rev=3667&view=rev Author: resendes Date: 2010-09-28 18:10:39 +0000 (Tue, 28 Sep 2010) Log Message: ----------- Some changes for a cleaner run: - CSVReader javadoc reference fix - NT dead code removal - TestMillisecondTimestampFactory added tearDown() method that resets the lowerbound of the global, static MillisecondTimestampFactory. This was needed because some of the unit tests were checking boundary conditions that were "persisted" to other tests (all executing under the same JVM). Modified Paths: -------------- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/CSVReader.java branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NT.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestMillisecondTimestampFactory.java Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/CSVReader.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/CSVReader.java 2010-09-28 17:02:48 UTC (rev 3666) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/CSVReader.java 2010-09-28 18:10:39 UTC (rev 3667) @@ -291,7 +291,7 @@ * The header definitions (initially null). * * @see #readHeaders() - * @see #setHeaders(String[]) + * @see #setHeaders(Header[]) */ protected Header[] headers; Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NT.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NT.java 2010-09-28 17:02:48 UTC (rev 3666) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/NT.java 2010-09-28 18:10:39 UTC (rev 3667) @@ -84,9 +84,6 @@ } NT nt = (NT)o; - if (this == nt) - return true; - if (!this.name.equals(nt.name)) return false; Modified: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestMillisecondTimestampFactory.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestMillisecondTimestampFactory.java 2010-09-28 17:02:48 UTC (rev 3666) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/TestMillisecondTimestampFactory.java 2010-09-28 18:10:39 UTC (rev 3667) @@ -185,4 +185,14 @@ assertFalse(MillisecondTimestampFactory.isAutoIncMode()); } } + + /** + * Reset "global" time back to normal after each run. Because + * MillisecondTimestampFactory is static, changes made in these + * tests will affect other tests in the same JVM. Therefore, need to + * reset value back to current time after each run. + */ + protected void tearDown() throws Exception { + MillisecondTimestampFactory.setLowerBound(System.currentTimeMillis()); + } } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <res...@us...> - 2010-10-04 13:27:15
|
Revision: 3721 http://bigdata.svn.sourceforge.net/bigdata/?rev=3721&view=rev Author: resendes Date: 2010-10-04 13:27:07 +0000 (Mon, 04 Oct 2010) Log Message: ----------- Added tests and fixes for ConfigDeployUtil class. Modified Paths: -------------- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/ConfigDeployUtil.java Added Paths: ----------- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/ConfigDeployUtilTest.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/ConfigDeployUtilTest2.java Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/ConfigDeployUtil.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/ConfigDeployUtil.java 2010-10-04 13:07:03 UTC (rev 3720) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/ConfigDeployUtil.java 2010-10-04 13:27:07 UTC (rev 3721) @@ -34,6 +34,8 @@ import java.io.FileInputStream; import java.io.IOException; import java.net.SocketException; +import java.text.NumberFormat; +import java.text.ParseException; import java.util.Arrays; import java.util.List; import java.util.Properties; @@ -57,7 +59,9 @@ private static final String TYPE = ".type"; private static final String FALLBACK_FEDNAME_FORMAT = "bigdata.test.group-%s"; - private static final String TEMPLATE_TOKEN_PATTERN = "@.*@"; + + //use current locale + private static final NumberFormat numberFormat = NumberFormat.getInstance(); public static String getString(String parameter) throws ConfigurationException @@ -88,23 +92,24 @@ return value; } - public static boolean getBoolean(String parameter) + public static boolean getBoolean(String parameter) throws ConfigurationException + { + boolean value; + value = validateBoolean(parameter, get(parameter)); + return value; + } + + private static boolean validateBoolean(String parameter, String value) throws ConfigurationException { boolean boolValue = false; - String value; - try { - value = get(parameter); - } catch (Exception ex) { - throw new ConfigurationException("parameter value ["+parameter+"] " - +"neither 'true' nor 'false'"); - } - if( value != null && value.equalsIgnoreCase("true") - || value.equalsIgnoreCase("false") ) + + if( value != null && (value.equalsIgnoreCase("true") + || value.equalsIgnoreCase("false")) ) { boolValue = Boolean.parseBoolean(value); } else { throw new ConfigurationException("parameter value ["+parameter+"] " - +"neither 'true' nor 'false'"); + +"is neither 'true' nor 'false'"); } return boolValue; } @@ -113,11 +118,7 @@ throws ConfigurationException { String value; - if(deploymentProps == null) { - deploymentProps = new Properties(); - loadDeployProps(deploymentProps); - } - value = deploymentProps.getProperty(parameter + DESCRIPTION); + value = getDeploymentProperties().getProperty(parameter + DESCRIPTION); return value; } @@ -125,11 +126,7 @@ throws ConfigurationException { String value; - if (deploymentProps == null) { - deploymentProps = new Properties(); - loadDeployProps(deploymentProps); - } - value = deploymentProps.getProperty(parameter + TYPE); + value = getDeploymentProperties().getProperty(parameter + TYPE); return value; } @@ -137,11 +134,7 @@ throws ConfigurationException { String value; - if (deploymentProps == null) { - deploymentProps = new Properties(); - loadDeployProps(deploymentProps); - } - value = deploymentProps.getProperty(parameter + DEFAULT); + value = getDeploymentProperties().getProperty(parameter + DEFAULT); if (value == null) { throw new ConfigurationException ("deployment parameter not found ["+parameter+"]"); @@ -150,7 +143,7 @@ } /** - * Returns a <code>String</code> array whose elments represent the + * Returns a <code>String</code> array whose elements represent the * lookup service groups to discover. If the system property named * "federation.name" is set then that value be used; otherwise, * the deployment properties files will be consulted. @@ -164,7 +157,7 @@ } /** - * Retrieve the federation name (also used as Jini group name) via this pecking pecking order: + * Retrieve the federation name (also used as Jini group name) via this pecking order: * <ol> * <li>From the Java system property: <code>federation.name</code></li> * <li>From the deployment properties file. Note that a value from the deployment @@ -254,11 +247,7 @@ private static String get(String parameter) throws ConfigurationException { String value; - if (deploymentProps == null) { - deploymentProps = new Properties(); - loadDeployProps(deploymentProps); - } - value = deploymentProps.getProperty(parameter); + value = getDeploymentProperties().getProperty(parameter); if (value == null) value = getDefault(parameter); return value; } @@ -267,7 +256,7 @@ throws ConfigurationException { String validValuesStr = - (String) deploymentProps.get(parameter + STRINGVALS); + (String) getDeploymentProperties().get(parameter + STRINGVALS); if (validValuesStr != null) { String[] validValues = validValuesStr.split(","); @@ -284,7 +273,7 @@ throws ConfigurationException { String validValuesStr = - (String)(deploymentProps.get(parameter + STRINGVALS)); + (String)(getDeploymentProperties().get(parameter + STRINGVALS)); String[] values = value.split(","); if (validValuesStr != null) { @@ -304,48 +293,77 @@ private static int validateInt(String parameter, String strvalue) throws ConfigurationException { - String maxString = (String)(deploymentProps.get(parameter + MAX)); - String minString = (String)(deploymentProps.get(parameter + MIN)); + String maxString = (String)(getDeploymentProperties().get(parameter + MAX)); + String minString = (String)(getDeploymentProperties().get(parameter + MIN)); int value = str2int(strvalue); if (maxString != null) { - int max = Integer.parseInt(maxString); - if (value > max) { - throw new ConfigurationException("parameter ["+parameter+"] " - +"exceeds maximum ["+max+"]"); + try { + int max = numberFormat.parse(maxString).intValue(); + if (value > max) { + throw new ConfigurationException("parameter ["+parameter+"] " + +"exceeds maximum ["+max+"]"); + } + } catch (ParseException e) { + throw new NumberFormatException( + "Invalid maximum integer for parameter: " + parameter); + } } + + if (minString != null) { + try { + int min = numberFormat.parse(minString).intValue(); + if (value < min) { + throw new ConfigurationException("parameter ["+parameter+"] " + + "is less than manimum ["+min+"]"); + } + } catch (ParseException e) { + throw new NumberFormatException( + "Invalid minimum integer for parameter: " + parameter); + } + } + return value; } private static long validateLong(String parameter, String strvalue) throws ConfigurationException { - String maxString = (String)(deploymentProps.get(parameter + MAX)); - String minString = (String)(deploymentProps.get(parameter + MIN)); + String maxString = (String)(getDeploymentProperties().get(parameter + MAX)); + String minString = (String)(getDeploymentProperties().get(parameter + MIN)); long value = str2long(strvalue); if (maxString != null) { - long max = Long.parseLong(maxString); - if (value > max) { - throw new ConfigurationException("parameter ["+parameter+"] " - +"exceeds maximum ["+max+"]"); + try { + long max = numberFormat.parse(maxString).longValue(); + if (value > max) { + throw new ConfigurationException("parameter ["+parameter+"] " + +"exceeds maximum ["+max+"]"); + } + } catch (ParseException e) { + throw new NumberFormatException( + "Invalid maximum long for parameter: " + parameter); + } } if (minString != null) { - long min = Long.parseLong(minString); - if (value < min) { - throw new ConfigurationException("parameter ["+parameter+"] " - +"is less than manimum " - +"["+min+"]"); - } + try { + long min = numberFormat.parse(minString).longValue(); + if (value < min) { + throw new ConfigurationException("parameter ["+parameter+"] " + + "is less than manimum ["+min+"]"); + } + } catch (ParseException e) { + throw new NumberFormatException( + "Invalid minimum long for parameter: " + parameter); + } } return value; } - private static File getPropertiesPath() { File rootDir = new File("/opt/bigdata"); //real installation String appHome = System.getProperty("appHome");//pstart @@ -372,30 +390,23 @@ } private static void loadDefaultProps(Properties deployProps) { - FileInputStream fis = null; - try { - File flnm = new File(getPropertiesPath(), "default-deploy.properties"); - fis = new FileInputStream(flnm); - deployProps.load(fis); - } catch (Exception ex) { - ex.printStackTrace(); - } finally { - if (fis != null) { - try { - fis.close(); - } catch (IOException ioex) { /* swallow */ } - } - } + loadPropsInternal("default-deploy.properties", deployProps, true); } private static void loadOverrideProps(Properties deployProps) { + loadPropsInternal("deploy.properties", deployProps, false); + } + + private static void loadPropsInternal(String propFileName, + Properties deployProps, boolean prtinTrace) + { FileInputStream fis = null; try { - File flnm = new File(getPropertiesPath(), "default-deploy.properties"); + File flnm = new File(getPropertiesPath(), propFileName); fis = new FileInputStream(flnm); deployProps.load(fis); } catch (Exception ex) { - // using all defaults + if (prtinTrace) ex.printStackTrace(); } finally { if (fis != null) { try { @@ -407,214 +418,52 @@ private static int str2int(String argx) { - long l; - - if( argx.trim().equals(Integer.MAX_VALUE) ) return Integer.MAX_VALUE; - if( argx.trim().equals(Integer.MIN_VALUE) ) return Integer.MIN_VALUE; - - l = str2long(argx); - if (l < Integer.MAX_VALUE && l > Integer.MIN_VALUE) { - return (int) l; - } else { - throw new NumberFormatException("Invalid number:"+argx - +" --number out of range"); - } + Number n = null; + try { + //TODO - truncation can occur -- check for overflow + n = numberFormat.parse(argx); + } catch (ParseException e) { + throw new NumberFormatException("Invalid integer: " + argx); + } + return n.intValue(); } private static long str2long(String argx) { - - int minDigitNumBetwnComma = 3; - - String arg = argx.trim(); - arg = arg.replaceAll("\"", ""); // strip all quotes - int sz = arg.length(); - - if( arg.equals("Long.MAX_VALUE") ) return Long.MAX_VALUE; - - if( arg.equals("Long.MIN_VALUE") ) return Long.MIN_VALUE; - - int asterPos = -1; - String arg1 = null; - String arg2 = null; - if( (asterPos = arg.indexOf("*")) != -1) { - int dotPos = -1; - arg1 = arg.substring(0, asterPos).trim(); - int denom1 = 1; - if( (dotPos = arg1.indexOf(".")) != -1) { - StringBuffer tmpBuf = new StringBuffer("1"); - int hitNumber = 0; - for (int i = dotPos + 1; i < (arg1.length() - dotPos); i++) { - if( Character.isDigit(arg1.charAt(i)) ) { - tmpBuf.append("0"); - } else { - break; - } - } - denom1 = Integer.valueOf(tmpBuf.toString()); - arg1 = arg1.substring(0, dotPos) + arg1.substring(dotPos + 1); - } - - arg2 = arg.substring(asterPos + 1).trim(); - int denom2 = 1; - if( (dotPos = arg2.indexOf(".")) != -1) { - StringBuffer tmpBuf = new StringBuffer("1"); - for(int i = dotPos + 1; i <= (arg2.length() - dotPos); i++) { - tmpBuf.append("0"); - } - - denom2 = Integer.valueOf(tmpBuf.toString()); - arg2 = arg2.substring(0, dotPos) + arg2.substring(dotPos + 1); - } - - long numerator = str2long(arg1) * str2long(arg2); - long denom = (denom1 * denom2); - - if (numerator % denom != 0) { - throw new NumberFormatException(" Bad value passed in:" + - ((double) (numerator) / - denom) + - ", expecting a long"); - } - return (numerator / denom); - } - - char unit = arg.charAt(sz - 1); - - String valScalar = arg.substring(0, (sz - 1)).trim(); - - long factor = 0l; - - switch (Character.toUpperCase(unit)) { - - case 'G': - factor = 1000000000l; - break; - case 'M': - factor = 1000000l; - break; - case 'K': - factor = 1000l; - break; - case 'B': - char unitPre = arg.charAt(sz - 2); - if (Character.isDigit(unitPre)) { - factor = -1l; - } else { - factor = - (Character.toUpperCase(unitPre) == - 'G' ? 1000000000l : (Character.toUpperCase(unitPre) == - 'M' ? 1000000l : (Character. - toUpperCase - (unitPre) == - 'K' ? 1000l : - -1l))); - valScalar = arg.substring(0, (sz - 2)).trim(); - } - break; - - default: - if (Character.isDigit(unit)) { - factor = 1l; - valScalar = arg; - } - } - if (factor == -1l) { - throw new NumberFormatException("Invalid number:" + arg); - } - - int comaPos = -1; - if( (comaPos = valScalar.indexOf(',')) != -1) { - if(valScalar.indexOf('.') != -1) { - throw new NumberFormatException("Invalid number:"+arg - +" both \",\" and decimal " - +"point are not supported"); - } - if( comaPos != 0 && comaPos != (valScalar.length() - 1) ) { - String[]spltByComa = valScalar.split(","); - valScalar = ""; - for (int i = spltByComa.length - 1; i >= 0; i--) { - if(i > 0 && spltByComa[i].length() < minDigitNumBetwnComma) - { - throw new NumberFormatException("Invalid number:"+arg - +" unexpected comma " - +"format"); - } - valScalar = spltByComa[i] + valScalar; - } - } else { - throw new NumberFormatException("Invalid number:\"" +arg - +"\" -unexpected comma in " - +"position: "+comaPos); - } - } - - int decimalPos = -1; - String valMultiplByFactor = null; - int numZero = 0; - try { - if( (decimalPos = valScalar.indexOf('.')) != -1) { - if (decimalPos != valScalar.lastIndexOf('.')) { - throw new NumberFormatException("Invalid number:" - +valScalar - +" --invalid decimal " - +"number, bad value"); - } - - String facStr = String.valueOf(factor); - int numZeroFactor = facStr.length() - 1; - int numDigitsAfterDecimal = - valScalar.length() - decimalPos - 1; - int countZero = 0; - for(int i = valScalar.length() - 1; i > decimalPos; i--) { - - if (valScalar.charAt(i) != '0') - break; - --numDigitsAfterDecimal; - countZero++; - } - numZero = numZeroFactor - numDigitsAfterDecimal; - if (numZero == numDigitsAfterDecimal) { - numZero = 0; - } - if(numZero < 0) { - throw new NumberFormatException("Invalid number:" - +valScalar - +" --invalid decimal " - +"number, numzero=" - + numZero); - } - - if(numZero >= 0) { - StringBuffer tmpStrNum = - new StringBuffer(20). - append(valScalar.substring(0, decimalPos)). - append(valScalar.substring(decimalPos + 1, - decimalPos + 1 + - numDigitsAfterDecimal)); - for(int i=0; i<numZero; i++) { - tmpStrNum.append('0'); - } - valMultiplByFactor = tmpStrNum.toString(); - } - - } - } catch(NumberFormatException nfe) { - throw new NumberFormatException("Invalid number:" +valScalar - +" --invalid decimal number, " - +"numZero="+numZero); - } - - long ret = -1l; - - Long ll = ((decimalPos != -1) ? Long.valueOf(valMultiplByFactor) - : (Long.valueOf(valScalar) * factor)); - if( (ret = Long.valueOf(ll)) >= Long.MAX_VALUE - || ret <= Long.MIN_VALUE) - { - throw new NumberFormatException("Invalid number:"+arg - +" --absolute value of number " - +"too big"); - } - return ret; + Number n = null; + try { + //TODO - truncation can occur -- check for overflow + n = numberFormat.parse(argx); + } catch (ParseException e) { + throw new NumberFormatException("Invalid long: " + argx); + } + return n.longValue(); } + + /** + * Returns reference to <code>deploymenyProps</code> field. If null, then the + * field is populated by looking for the default and override properties files + * (defined in <code>loadDefaultProps</code> and <code>loadOverrideProps</code>). + * This method is synchronized in order to ensure that the returned reference is + * a singleton instance. + * Note: This method should be private, but is needed by the unit test in order + * to access and modify the <code>Properties</code> method. + * @return Properties instance containing the default and user-defined overrides + * for configuration properties. + */ + synchronized static Properties getDeploymentProperties() { + if(deploymentProps == null) { + deploymentProps = new Properties(); + loadDeployProps(deploymentProps); + } + return deploymentProps; + } + + /** + * Convenience method intended for use by unit tests only. + * @param properties Sets <code>Properties</code> object + */ + synchronized static void setDeploymentProperties(Properties properties) { + deploymentProps = properties; + } + } Added: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/ConfigDeployUtilTest.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/ConfigDeployUtilTest.java (rev 0) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/ConfigDeployUtilTest.java 2010-10-04 13:27:07 UTC (rev 3721) @@ -0,0 +1,1128 @@ +/** + * + */ +package com.bigdata.util.config; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.net.SocketException; +import java.text.ParseException; +import java.util.Arrays; +import java.util.Properties; +import java.util.UUID; + +import net.jini.config.ConfigurationException; +import net.jini.core.discovery.LookupLocator; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.bigdata.attr.ServiceInfo; +import com.ibm.icu.text.NumberFormat; + +/** + * Note: These tests use a package protected method + * {@link com.bigdata.util.config.ConfigDeployUtil#getDeploymentProperties()} + * to set its underlying <code>Properties</code> object. + */ +public class ConfigDeployUtilTest { + /** + * Holds a reference to the default <code>Properties</code> object created by + * <code>ConfigDeployUtil</code>. The reference is reset on the + * <code>ConfigDeployUtil</code> object after these unit tests finish. + */ + private static Properties _old_properties = null; + + /** + * @throws java.lang.Exception + */ + @BeforeClass + public static void setUpBeforeClass() throws Exception { + _old_properties = ConfigDeployUtil.getDeploymentProperties(); + ConfigDeployUtil.setDeploymentProperties(new Properties()); + } + + /** + * @throws java.lang.Exception + */ + @AfterClass + public static void tearDownAfterClass() throws Exception { + ConfigDeployUtil.setDeploymentProperties(_old_properties); + } + + /** + * @throws java.lang.Exception + */ + @Before + public void setUp() throws Exception { + ConfigDeployUtil.getDeploymentProperties().clear(); + } + + /** + * @throws java.lang.Exception + */ + @After + public void tearDown() throws Exception { + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getString(java.lang.String)}. + */ + @Test + public void testGetString_bogus() { + try { + String k = "testGetString_bogus"; + String v = ConfigDeployUtil.getString(k); + fail("Successfully called getString with bogus parameter string: [" + + k + ":" + v + "]"); + } catch (ConfigurationException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getString(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetString_empty_name() throws ConfigurationException { + String key = "testGetString_empty_name"; + String value = ""; + ConfigDeployUtil.getDeploymentProperties().setProperty( + key, value); + String actual = ConfigDeployUtil.getString(key); + String expected = value; + assertEquals(actual, expected); + } + + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getString(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetString_valid_name() throws ConfigurationException { + String key = "testGetString_valid_name"; + String value = key + "_value"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key, value); + p.setProperty(key+".stringvals", value + ",other"); + String actual = ConfigDeployUtil.getString(key); + String expected = value; + assertEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getString(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetString_invalid_name() throws ConfigurationException { + String key = "testGetString_invalid_name"; + String value = key + "_value"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key, value); + p.setProperty(key+".stringvals", "other1,other2"); + try { + ConfigDeployUtil.getString(key); + fail("Successfully called getString with bogus parameter string: [" + + key + ":" + value + "]"); + } catch (ConfigurationException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetStringArray_array_bogus() throws ConfigurationException { + String key = "testGetStringArray_array_bogus"; + String value = null; + try { + ConfigDeployUtil.getStringArray(key); + fail("Successfully called getStringArray with bogus parameter string: [" + + key + ":" + value + "]"); + } catch (ConfigurationException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetStringArray_array_default_singleton() throws ConfigurationException { + String key = "testGetStringArray_array_default_singleton"; + String value = "infrastructure"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", value); + p.setProperty(key+".type", "string"); + p.setProperty(key+".stringvals", value + ",non-infrastructure,other"); + String[] actual = ConfigDeployUtil.getStringArray(key); + String[] expected = {value}; + assertArrayEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetStringArray_valid_singleton() throws ConfigurationException { + String key = "testGetStringArray_valid_singleton"; + String value = "infrastructure"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", value + "_default"); + p.setProperty(key, value); + p.setProperty(key+".type", "string"); + p.setProperty(key+".stringvals", value + ",non-infrastructure,other"); + String[] actual = ConfigDeployUtil.getStringArray(key); + String[] expected = {value}; + assertArrayEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetStringArray_invalid_singleton() throws ConfigurationException { + String key = "testGetStringArray_invalid_singleton"; + String value = "infrastructure"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", value + "_default"); + p.setProperty(key, value); + p.setProperty(key+".type", "string"); + p.setProperty(key+".stringvals", "non-infrastructure,other"); + try { + ConfigDeployUtil.getStringArray(key); + fail("Successfully called getStringArray with invalid parameter string: [" + + key + ":" + value + "]"); + } catch (ConfigurationException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetStringArray_array_default_multiple() throws ConfigurationException { + String key = "testGetStringArray_array_default_multiple"; + String value = "infrastructure1,infrastructure2"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", value); + p.setProperty(key+".type", "string"); + p.setProperty(key+".stringvals", value + ",non-infrastructure,other"); + String[] actual = ConfigDeployUtil.getStringArray(key); + String[] expected = value.split(","); + assertArrayEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetStringArray_array_valid_multiple() throws ConfigurationException { + String key = "testGetStringArray_array_valid_multiple"; + String value = "infrastructure1,infrastructure2"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", value); + p.setProperty(key+".type", "string"); + p.setProperty(key+".stringvals", value + ",non-infrastructure,other"); + String[] actual = ConfigDeployUtil.getStringArray(key); + String[] expected = value.split(","); + assertArrayEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetStringArray_array_invalid_multiple1() throws ConfigurationException { + String key = "testGetStringArray_array_invalid_multiple1"; + String value = "infrastructure1,infrastructure2"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", value); + p.setProperty(key+".type", "string"); + p.setProperty(key+".stringvals", "non-infrastructure,other"); + try { + ConfigDeployUtil.getStringArray(key); + fail("Successfully called getStringArray with invalid parameter string: [" + + key + ":" + value + "]"); + } catch (ConfigurationException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetStringArray_array_invalid_multiple2() throws ConfigurationException { + String key = "testGetStringArray_array_invalid_multiple2"; + String value = "infrastructure1,infrastructure2"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", value); + p.setProperty(key+".type", "string"); + p.setProperty(key+".stringvals", "infrastructure1,non-infrastructure,other"); + try { + ConfigDeployUtil.getStringArray(key); + fail("Successfully called getStringArray with invalid parameter string: [" + + key + ":" + value + "]"); + } catch (ConfigurationException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getInt(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetInt_bogus() throws ConfigurationException { + String key = "testGetInt_bogus"; + String value = null; + try { + ConfigDeployUtil.getInt(key); + fail("Successfully called getInt with invalid parameter string: [" + + key + ":" + value + "]"); + } catch (ConfigurationException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetInt_valid1() throws ConfigurationException { + String key = "testGetInt_valid1"; + String sValue = "2"; + int expected = Integer.parseInt(sValue); + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", "-1"); + p.setProperty(key+".max", "1000"); + p.setProperty(key+".type", "int"); + p.setProperty(key, sValue); + int actual = ConfigDeployUtil.getInt(key); + assertEquals(actual, expected); + } + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetInt_valid2() throws ConfigurationException { + String key = "testGetInt_valid2"; + String sValue = "-1"; + int expected = Integer.parseInt(sValue); + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", "-1"); + p.setProperty(key+".max", "1000"); + p.setProperty(key+".type", "int"); + p.setProperty(key, sValue); + int actual = ConfigDeployUtil.getInt(key); + assertEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetInt_valid3() throws ConfigurationException { + String key = "testGetInt_valid3"; + String sValue = "1000"; + int expected = Integer.parseInt(sValue); + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", "-1"); + p.setProperty(key+".max", "1000"); + p.setProperty(key+".type", "int"); + p.setProperty(key, sValue); + int actual = ConfigDeployUtil.getInt(key); + assertEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetInt_valid4() throws ConfigurationException { + String key = "testGetInt_valid4"; + String sValue = Integer.toString(Integer.MAX_VALUE); + int expected = Integer.MAX_VALUE; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", "-1"); + p.setProperty(key+".max", sValue); + p.setProperty(key+".type", "int"); + p.setProperty(key, sValue); + int actual = ConfigDeployUtil.getInt(key); + assertEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetInt_valid5() throws ConfigurationException { + String key = "testGetInt_valid5"; + String sValue = Integer.toString(Integer.MIN_VALUE); + int expected = Integer.MIN_VALUE; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", sValue); + p.setProperty(key+".max", "1000"); + p.setProperty(key+".type", "int"); + p.setProperty(key, sValue); + int actual = ConfigDeployUtil.getInt(key); + assertEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + * @throws ParseException + */ + @Test + public void testGetInt_valid6() throws ConfigurationException, ParseException { + String key = "testGetInt_valid5"; + String sValue = "1,000,000";//try string with separators + int expected = NumberFormat.getInstance().parse(sValue).intValue(); + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "0"); + p.setProperty(key+".min", "-1,000"); + p.setProperty(key+".max", "10,000,000"); + p.setProperty(key+".type", "int"); + p.setProperty(key, sValue); + int actual = ConfigDeployUtil.getInt(key); + assertEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetInt_invaild_min() throws ConfigurationException { + String key = "testGetInt_invaild_min"; + String sValue = "-2"; + int expected = Integer.parseInt(sValue); + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", "-1"); + p.setProperty(key+".max", "1000"); + p.setProperty(key+".type", "int"); + p.setProperty(key, sValue); + try { + ConfigDeployUtil.getInt(key); + fail("Successfully called getInt with invalid parameter string: [" + + key + ":" + sValue + "]"); + } catch (ConfigurationException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetInt_invaild_max() throws ConfigurationException { + String key = "testGetInt_invaild_max"; + String sValue = "2000"; + int expected = Integer.parseInt(sValue); + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", "-1"); + p.setProperty(key+".max", "1000"); + p.setProperty(key+".type", "int"); + p.setProperty(key, sValue); + try { + ConfigDeployUtil.getInt(key); + fail("Successfully called getInt with invalid parameter string: [" + + key + ":" + sValue + "]"); + } catch (ConfigurationException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetInt_invaild_not_a_number() throws ConfigurationException { + String key = "testGetInt_invaild_not_a_number"; + String sValue = "abcxyz"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", "-1"); + p.setProperty(key+".max", "10000"); + p.setProperty(key+".type", "int"); + p.setProperty(key, sValue); + try { + ConfigDeployUtil.getInt(key); + fail("Successfully called getLong with getLong parameter string: [" + + key + ":" + sValue + "]"); + } catch (NumberFormatException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetInt_invaild_max_not_a_number() throws ConfigurationException { + String key = "testGetInt_invaild_max_not_a_number"; + String sValue = "10000"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", "-1"); + p.setProperty(key+".max", "bogus_max_value"); + p.setProperty(key+".type", "int"); + p.setProperty(key, sValue); + try { + ConfigDeployUtil.getInt(key); + fail("Successfully called getLong with getLong parameter string: [" + + key + ":" + sValue + "]"); + } catch (NumberFormatException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetInt_invaild_min_not_a_number() throws ConfigurationException { + String key = "testGetInt_invaild_min_not_a_number"; + String sValue = "-1"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", "bogus_min_value"); + p.setProperty(key+".max", "10000"); + p.setProperty(key+".type", "int"); + p.setProperty(key, sValue); + try { + ConfigDeployUtil.getInt(key); + fail("Successfully called getLong with getLong parameter string: [" + + key + ":" + sValue + "]"); + } catch (NumberFormatException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getLong(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetLong_bogus() throws ConfigurationException { + String key = "testGetLong_bogus"; + String sValue = "2000"; + try { + ConfigDeployUtil.getLong(key); + fail("Successfully called getLong with bogus parameter string: [" + + key + ":" + sValue + "]"); + } catch (ConfigurationException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetLong_valid1() throws ConfigurationException { + String key = "testGetLong_valid1"; + String sValue = "2222"; + long expected = Long.parseLong(sValue); + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", "-1"); + p.setProperty(key+".max", "10000"); + p.setProperty(key+".type", "long"); + p.setProperty(key, sValue); + long actual = ConfigDeployUtil.getLong(key); + assertEquals(actual, expected); + } + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetLong_valid2() throws ConfigurationException { + String key = "testGetLong_valid2"; + String sValue = "-1"; + long expected = Long.parseLong(sValue); + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", "-1"); + p.setProperty(key+".max", "10000"); + p.setProperty(key+".type", "long"); + p.setProperty(key, sValue); + long actual = ConfigDeployUtil.getLong(key); + assertEquals(actual, expected); + } + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetLong_valid3() throws ConfigurationException { + String key = "testGetLong_valid3"; + String sValue = "10000"; + long expected = Long.parseLong(sValue); + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", "-1"); + p.setProperty(key+".max", "10000"); + p.setProperty(key+".type", "long"); + p.setProperty(key, sValue); + long actual = ConfigDeployUtil.getLong(key); + assertEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetLong_valid4() throws ConfigurationException { + String key = "testGetLong_valid4"; + String sValue = Long.toString(Long.MAX_VALUE); + long expected = Long.parseLong(sValue); + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", "-1"); + p.setProperty(key+".max", sValue); + p.setProperty(key+".type", "long"); + p.setProperty(key, sValue); + long actual = ConfigDeployUtil.getLong(key); + assertEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetLong_valid5() throws ConfigurationException { + String key = "testGetLong_valid5"; + String sValue = Long.toString(Long.MIN_VALUE); + long expected = Long.parseLong(sValue); + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", sValue); + p.setProperty(key+".max", "10000"); + p.setProperty(key+".type", "long"); + p.setProperty(key, sValue); + long actual = ConfigDeployUtil.getLong(key); + assertEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + * @throws ParseException + */ + @Test + public void testGetLong_valid6() throws ConfigurationException, ParseException { + String key = "testGetInt_valid6"; + String sValue = "1,000,000";//try string with separators + long expected = NumberFormat.getInstance().parse(sValue).longValue(); + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "0"); + p.setProperty(key+".min", "-1,000"); + p.setProperty(key+".max", "10,000,000"); + p.setProperty(key+".type", "long"); + p.setProperty(key, sValue); + long actual = ConfigDeployUtil.getLong(key); + assertEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetLong_invaild_min() throws ConfigurationException { + String key = "testGetLong_invaild_min"; + String sValue = "-20000"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", "-1"); + p.setProperty(key+".max", "10000"); + p.setProperty(key+".type", "int"); + p.setProperty(key, sValue); + try { + ConfigDeployUtil.getLong(key); + fail("Successfully called getInt with getLong parameter string: [" + + key + ":" + sValue + "]"); + } catch (ConfigurationException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetLong_invaild_max() throws ConfigurationException { + String key = "testGetLong_invaild_max"; + String sValue = "20000"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", "-1"); + p.setProperty(key+".max", "10000"); + p.setProperty(key+".type", "int"); + p.setProperty(key, sValue); + try { + ConfigDeployUtil.getLong(key); + fail("Successfully called getLong with getLong parameter string: [" + + key + ":" + sValue + "]"); + } catch (ConfigurationException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetLong_invaild_not_a_number() throws ConfigurationException { + String key = "testGetLong_invaild_max"; + String sValue = "abcxyz"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", "-1"); + p.setProperty(key+".max", "10000"); + p.setProperty(key+".type", "int"); + p.setProperty(key, sValue); + try { + ConfigDeployUtil.getLong(key); + fail("Successfully called getLong with getLong parameter string: [" + + key + ":" + sValue + "]"); + } catch (NumberFormatException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetLong_invaild_max_not_a_number() throws ConfigurationException { + String key = "testGetLong_invaild_max"; + String sValue = "1000"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", "-1"); + p.setProperty(key+".max", "bogus_max_value"); + p.setProperty(key+".type", "int"); + p.setProperty(key, sValue); + try { + ConfigDeployUtil.getLong(key); + fail("Successfully called getLong with getLong parameter string: [" + + key + ":" + sValue + "]"); + } catch (NumberFormatException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetLong_invaild_min_not_a_number() throws ConfigurationException { + String key = "testGetLong_invaild_max"; + String sValue = "1000"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "-1"); + p.setProperty(key+".min", "bogus_min_value"); + p.setProperty(key+".max", "10000"); + p.setProperty(key+".type", "int"); + p.setProperty(key, sValue); + try { + ConfigDeployUtil.getLong(key); + fail("Successfully called getLong with getLong parameter string: [" + + key + ":" + sValue + "]"); + } catch (NumberFormatException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getBoolean(java.lang.String)}. + */ + @Test + public void testGetBoolean_bogus() { + try { + String k = "bogus.field.name"; + boolean v = ConfigDeployUtil.getBoolean(k); + fail("Successfully called getBoolean with bogus parameter string: [" + + k + ":" + v + "]"); + } catch (ConfigurationException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getBoolean(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetBoolean_valid_true1() throws ConfigurationException { + String key = "testGetBoolean_valid_true1"; + String sValue = "true"; + boolean expected = Boolean.parseBoolean(sValue); + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "false"); + p.setProperty(key+".type", "boolean"); + p.setProperty(key, sValue); + boolean actual = ConfigDeployUtil.getBoolean(key); + assertEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getBoolean(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetBoolean_valid_true2() throws ConfigurationException { + String key = "testGetBoolean_valid_true2"; + String sValue = "TrUe"; + boolean expected = Boolean.parseBoolean(sValue); + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "false"); + p.setProperty(key+".type", "boolean"); + p.setProperty(key, sValue); + boolean actual = ConfigDeployUtil.getBoolean(key); + assertEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getBoolean(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetBoolean_valid_false1() throws ConfigurationException { + String key = "testGetBoolean_valid_false1"; + String sValue = "false"; + boolean expected = Boolean.parseBoolean(sValue); + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "true"); + p.setProperty(key+".type", "boolean"); + p.setProperty(key, sValue); + boolean actual = ConfigDeployUtil.getBoolean(key); + assertEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getBoolean(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetBoolean_valid_false2() throws ConfigurationException { + String key = "testGetBoolean_valid_false2"; + String sValue = "FaLsE"; + boolean expected = Boolean.parseBoolean(sValue); + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "true"); + p.setProperty(key+".type", "boolean"); + p.setProperty(key, sValue); + boolean actual = ConfigDeployUtil.getBoolean(key); + assertEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getBoolean(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetBoolean_invalid() throws ConfigurationException { + String key = "testGetBoolean_invalid"; + String sValue = "bogus"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", "Description"); + p.setProperty(key+".default", "true"); + p.setProperty(key+".type", "boolean"); + p.setProperty(key, sValue); + try { + ConfigDeployUtil.getBoolean(key); + fail("Successfully called getBoolean with invalid parameter string: [" + + key + ":" + sValue + "]"); + } catch (ConfigurationException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getDescription(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetDescription_bogus() throws ConfigurationException { + String key = "testGetDescription_bogus"; + String expected = null; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key, ""); + String actual = ConfigDeployUtil.getDescription(key); + assertEquals(actual, expected); + } + + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getDescription(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetDescription_valid() throws ConfigurationException { + String key = "testGetDescription_valid"; + String expected = key + "_desc"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".description", expected); + String actual = ConfigDeployUtil.getDescription(key); + assertEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getType(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetType_bogus() throws ConfigurationException { + String k = "testGetType_bogus"; + String actual = ConfigDeployUtil.getType(k); + String expected = null; + assertEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getType(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetType_valid() throws ConfigurationException { + String key = "testGetType_valid"; + String expected = "float"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".type", expected); + String actual = ConfigDeployUtil.getType(key); + assertEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getDefault(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetDefault_invalid() throws ConfigurationException { + String key = "testGetDefault_invalid"; + String sValue = null; + try { + ConfigDeployUtil.getDefault(key); + fail("Successfully called getDefault with bogus parameter string: [" + + key + ":" + sValue + "]"); + } catch (ConfigurationException e) { + //ignore -- exception + } + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getDefault(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetDefault_valid() throws ConfigurationException { + String key = "testGetDefault_valid"; + String expected = "defaultValue"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key + ".default", expected); + String actual = ConfigDeployUtil.getDefault(key); + assertEquals(actual, expected); + } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getGroupsToDiscover()}. + * @throws ConfigurationException + */ + @Test + public void testGetGroupsToDiscover_bogus() throws ConfigurationException { + try { + ConfigDeployUtil.... [truncated message content] |
From: <res...@us...> - 2010-10-11 18:33:56
|
Revision: 3768 http://bigdata.svn.sourceforge.net/bigdata/?rev=3768&view=rev Author: resendes Date: 2010-10-11 18:33:47 +0000 (Mon, 11 Oct 2010) Log Message: ----------- Fixes and unit tests for com.bigdata.util.config package. Modified Paths: -------------- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/ConfigDeployUtil.java branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/ConfigurationUtil.java branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/Log4jLoggingHandler.java branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/LogUtil.java branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/NicUtil.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/ConfigDeployUtilTest.java Added Paths: ----------- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/ConfigurationUtilTest.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/Log4jLoggingHandlerTest.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/LogUtilTest.java branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/NicUtilTest.java Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/ConfigDeployUtil.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/ConfigDeployUtil.java 2010-10-11 17:26:00 UTC (rev 3767) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/ConfigDeployUtil.java 2010-10-11 18:33:47 UTC (rev 3768) @@ -48,6 +48,12 @@ * invoked from within a Jini configuration. */ public class ConfigDeployUtil { + + private ConfigDeployUtil() { + //prevent instantiation + throw new AssertionError + ("ConfigDeployUtil cannot be instantiated"); + } private static Properties deploymentProps = null; @@ -63,6 +69,22 @@ //use current locale private static final NumberFormat numberFormat = NumberFormat.getInstance(); + /** + * Gets the <code>String</code> value associated with the given parameter + * in the configured properties file. The value, if any, returned will be: + * 1) the explicitly defined value for the property, or + * 2) the default value for that property, if a default exists. + * If the provided parameter has an associated set of valid entries in the + * properties files, then the value obtained, above, will be validated + * against those entries. If either the value (explicit or default) can't be + * found or fails the validation check, + * a <code>ConfigurationException</code> will be thrown. + * @param parameter The property name to lookup + * @return the <code>String</code> value associated the requested parameter, + * if available + * @throws ConfigurationException if the parameter value + * (explicit or default) was not defined. + */ public static String getString(String parameter) throws ConfigurationException { @@ -70,7 +92,23 @@ validateString(parameter, value); return value; } - + + /** + * Gets the <code>String[]</code> value associated with the given parameter + * in the configured properties file. The value, if any, returned will be: + * 1) the explicitly defined value for the property, or + * 2) the default value for that property, if a default exists. + * If the provided parameter has an associated set of valid entries in the + * properties files, then the component values obtained, above, will be validated + * against those entries. If either the value (explicit or default) can't be + * found or fails the validation check, + * a <code>ConfigurationException</code> will be thrown. + * @param parameter The property name to lookup + * @return the <code>String[]</code> value associated the requested parameter, + * if available + * @throws ConfigurationException if the parameter value + * (explicit or default) was not defined. + */ public static String[] getStringArray(String parameter) throws ConfigurationException { @@ -79,12 +117,46 @@ return value; } + /** + * Gets the <code>int</code> value associated with the given parameter + * in the configured properties file. The value, if any, returned will be: + * 1) the explicitly defined value for the property, or + * 2) the default value for that property, if a default exists. + * If the provided parameter has an associated set of valid entries in the + * properties files, then the value obtained, above, will be validated + * against those entries. If either the value (explicit or default) can't be + * found or fails the validation check, + * a <code>ConfigurationException</code> will be thrown. + * @param parameter The property name to lookup + * @return the <code>int</code> value associated the requested parameter, + * if available + * @throws ConfigurationException if the parameter value + * (explicit or default) was not defined. + */ + public static int getInt(String parameter) throws ConfigurationException { int value; value = validateInt(parameter, get(parameter)); return value; } + /** + * Gets the <code>long</code> value associated with the given parameter + * in the configured properties file. The value, if any, returned will be: + * 1) the explicitly defined value for the property, or + * 2) the default value for that property, if a default exists. + * If the provided parameter has an associated set of valid entries in the + * properties files, then the value obtained, above, will be validated + * against those entries. If either the value (explicit or default) can't be + * found or fails the validation check, + * a <code>ConfigurationException</code> will be thrown. + * @param parameter The property name to lookup + * @return the <code>long</code> value associated the requested parameter, + * if available + * @throws ConfigurationException if the parameter value + * (explicit or default) was not defined. + */ + public static long getLong(String parameter) throws ConfigurationException { long value; @@ -92,6 +164,22 @@ return value; } + /** + * Gets the <code>boolean</code> value associated with the given parameter + * in the configured properties file. The value, if any, returned will be: + * 1) the explicitly defined value for the property, or + * 2) the default value for that property, if a default exists. + * If the provided parameter has an associated set of valid entries in the + * properties files, then the value obtained, above, will be validated + * against those entries. If either the value (explicit or default) can't be + * found or fails the validation check, + * a <code>ConfigurationException</code> will be thrown. + * @param parameter The property name to lookup + * @return the <code>boolean</code> value associated the requested parameter, + * if available + * @throws ConfigurationException if the parameter value + * (explicit or default) was not defined. + */ public static boolean getBoolean(String parameter) throws ConfigurationException { boolean value; @@ -114,6 +202,17 @@ return boolValue; } + /** + * Gets the description value associated with the given parameter + * in the configured properties file. The method returns + * <code>null</code> if the property is not found. + * @param parameter The property name to lookup + * @return the <code>String</code> value associated the requested parameter, + * if available. Otherwise return <code>null</code> + * @throws ConfigurationException if there was a problem accessing + * the parameter value. + */ + public static String getDescription(String parameter) throws ConfigurationException { @@ -122,6 +221,18 @@ return value; } + /** + * Gets the type value associated with the given parameter + * in the configured properties file. The method returns + * <code>null</code> if the property is not found. + * @param parameter The property name to lookup + * @return the <code>String</code> value of the type + * associated the requested parameter, + * if available. Otherwise return <code>null</code> + * @throws ConfigurationException if there was a problem accessing + * the parameter value. + */ + public static String getType(String parameter) throws ConfigurationException { @@ -130,6 +241,15 @@ return value; } + /** + * Gets the default value associated with the given parameter + * in the configured properties file. + * @param parameter The property name to lookup + * @return the <code>String</code> value of the type + * associated the requested parameter, + * if available. Otherwise return <code>null</code> + * @throws ConfigurationException if no default value was specified + */ public static String getDefault(String parameter) throws ConfigurationException { @@ -445,10 +565,9 @@ * (defined in <code>loadDefaultProps</code> and <code>loadOverrideProps</code>). * This method is synchronized in order to ensure that the returned reference is * a singleton instance. - * Note: This method should be private, but is needed by the unit test in order - * to access and modify the <code>Properties</code> method. - * @return Properties instance containing the default and user-defined overrides - * for configuration properties. + * Note: This method should be private, but is needed by the unit tests in order + * to access and modify the underlying <code>Properties</code> object. + * @return Properties instance containing the configuration properties. */ synchronized static Properties getDeploymentProperties() { if(deploymentProps == null) { Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/ConfigurationUtil.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/ConfigurationUtil.java 2010-10-11 17:26:00 UTC (rev 3767) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/ConfigurationUtil.java 2010-10-11 18:33:47 UTC (rev 3768) @@ -28,10 +28,10 @@ import org.apache.log4j.Level; import org.apache.log4j.Logger; -import com.sun.jini.config.ConfigUtil; import net.jini.url.httpmd.HttpmdUtil; import java.io.IOException; +import java.net.UnknownHostException; /** * Utility class that provides a set of static convenience methods @@ -43,6 +43,11 @@ * This class cannot be instantiated. */ public class ConfigurationUtil { + + private ConfigurationUtil() { + //prevent instantiation + throw new AssertionError + ("ConfigurationUtil cannot be instantiated"); } private static final Logger logger = LogUtil.getLog4jLogger( ConfigurationUtil.class ); @@ -95,7 +100,7 @@ * <p> * Note that the <code>name</code> parameter is handled specially by * this method. The value input to that <code>String</code> parameter - * is interpretted in one of two ways by this method: + * is interpreted in one of two ways by this method: * <p><ul> * <li> The name of the local <i>network interface</i> over which the * class server will communicate with clients requesting the @@ -109,7 +114,7 @@ * This method first treats the value of the <code>name</code> parameter * as a network interface, attempting to determine that interface's * corresponding IP address. Should that attempt fail, then this method - * then assumes that the caller intended this parameter to be interpretted + * then assumes that the caller intended this parameter to be interpreted * as an IP address or host name; in which case, this method uses * the value of the parameter as the <i>address/host</i> component of * codebase being constructed. @@ -181,7 +186,7 @@ * any value, including <code>null</code>). * * @throws IllegalArgumentException if the value input for - * <code>port</code> is negtive. + * <code>port</code> is negative. */ public static String computeCodebase(String name, String jarFile, @@ -220,6 +225,10 @@ logger.log(Level.TRACE, name+" - not a valid " +"network interface, assuming host name"); } + if (ipAddr==null) { + throw new UnknownHostException( + "Could not determine IP address for given name:" + name); + } // Construct the codebase, either httpmd or http if(doHttpmd) { Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/Log4jLoggingHandler.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/Log4jLoggingHandler.java 2010-10-11 17:26:00 UTC (rev 3767) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/Log4jLoggingHandler.java 2010-10-11 18:33:47 UTC (rev 3768) @@ -60,11 +60,12 @@ this.log4jLogger = LogUtil.getLog4jRootLogger(); } - // Get the handler's configuration + // Set the handler's configuration this.setLevel(java.util.logging.Level.FINEST); this.setFormatter(new SimpleFormatter()); } + @Override public void publish(LogRecord record) { if(! isLoggable(record)) return; @@ -79,8 +80,10 @@ ( new XLoggingEvent(log4jLogger, record, formattedMessage) ); } + @Override public void close() { /* no-op */ } + @Override public void flush() { /* no-op */ } Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/LogUtil.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/LogUtil.java 2010-10-11 17:26:00 UTC (rev 3767) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/LogUtil.java 2010-10-11 18:33:47 UTC (rev 3768) @@ -25,11 +25,6 @@ package com.bigdata.util.config; -import java.io.File; -import java.util.Set; -import java.util.HashSet; - -import com.bigdata.DataFinder; import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; import org.apache.log4j.xml.DOMConfigurator; @@ -78,14 +73,31 @@ } } + /** + * Return log4j logger for the provided <code>String<code> argument. + * @param componentName The name of the logger to return + * @return log4j logger associated with the provided name + */ public static Logger getLog4jLogger(String componentName) { return Logger.getLogger(componentName); } + /** + * Return log4j logger for the provided <code>Class<code> argument. + * @param componentClass The class whose name will be used to return the + * associated logger. + * @return log4j logger associated with the provided class' name + */ + public static Logger getLog4jLogger(Class componentClass) { return Logger.getLogger(componentClass); } + /** + * Return the root log4j logger. + * @return the root log4j logger + */ + public static Logger getLog4jRootLogger() { return Logger.getRootLogger(); } Modified: branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/NicUtil.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/NicUtil.java 2010-10-11 17:26:00 UTC (rev 3767) +++ branches/bbb_cleanup/bigdata-core/src/main/java/com/bigdata/util/config/NicUtil.java 2010-10-11 18:33:47 UTC (rev 3768) @@ -78,7 +78,8 @@ * network interface to return (for example, typical * values for this parameter might be, "eth0", "eth1", * "hme01", "lo", etc., depending on how the underlying - * platform is configured). + * platform is configured). The empty string will + * return the loopback interface. * * @return an instance of <code>NetworkInterface</code> that represents * the network interface corresponding to the given @@ -154,13 +155,12 @@ * the desired network interface(s) correspond. * * @return an array whose elements are each instances of - * <code>NetworkInterface[]</code>, in which each such - * instance corresponds to the given <code>name</code>, - * or <code>null</code> if there is no network interface - * corresponding to that name value. + * <code>NetworkInterface</code>, in which each such + * instance corresponds to the given <code>name</code>. * - * Note that if the value given for the <code>name</code> - * parameter is the <code>String</code> "all", then this + * Note that if the special value "all" is given for the + * <code>name</code> + * parameter, then this * method will return an array containing all of the * network interfaces installed on the current node, * regardless of each interface's name. @@ -176,31 +176,24 @@ { NetworkInterface [] nics = null; if (name.equals("all")) { - Enumeration en = NetworkInterface.getNetworkInterfaces(); - List nicList = (en != null) ? - Collections.list(en) : Collections.EMPTY_LIST; - nics = (NetworkInterface[])(nicList.toArray - (new NetworkInterface[nicList.size()]) ); + Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); + List<NetworkInterface> nicList = + ((en != null) + ? Collections.list(en) + : Collections.<NetworkInterface>emptyList()); + nics = (nicList.toArray(new NetworkInterface[nicList.size()]) ); } else { - nics = new NetworkInterface[1]; - nics[0] = NetworkInterface.getByName(name); - if (nics[0] == null) { - // try to lookup by IP address - InetAddress targetIp = null; - try { - targetIp = InetAddress.getByName(name); - nics[0] = NetworkInterface.getByInetAddress(targetIp); - } catch (UnknownHostException uhe) { - // ignore, return null - } - } + NetworkInterface nif = getNetworkInterface(name); + nics = ((nif != null) + ? new NetworkInterface[] { nif } + : new NetworkInterface[0]); } return nics; } /** * Returns the instance of <code>InetAddress</code> that represents - * the i-th IP address assigned to the network interface having the + * the i-th IPv4 address assigned to the network interface having the * given <code>name</code> (where i is specified by the value of the * <code>index</code> parameter). * <p> @@ -268,7 +261,7 @@ * <code>localHost</code> is <code>false</code>. * * @throws IllegalArgumentException if the value input for - * <code>index</code> is negtive. + * <code>index</code> is negative. * * @throws IndexOutOfBoundsException if the value input for * <code>index</code> is out of range; that is if the value @@ -282,10 +275,14 @@ { // Validate input parameters if( (name == null) && (host == null) && (localHost == false) ) { - throw new NullPointerException("name cannot be null"); + throw new NullPointerException( + "Name and host cannot be null with localHost set to false."); } - if(index < 0) throw new IllegalArgumentException - ("index cannot be negative"); + + if(index < 0) { + throw new IllegalArgumentException("index cannot be negative"); + } + // Primary retrieval attempt NetworkInterface nic = null; try { @@ -376,6 +373,7 @@ public static String getMacAddress(String name) throws SocketException { String macAddr = null; NetworkInterface nic = NicUtil.getNetworkInterface(name); + if (nic==null) return null; byte[] hwAddr = nic.getHardwareAddress(); if( (hwAddr != null) && (hwAddr.length > 0) ) { StringBuffer strBuf = new StringBuffer(); @@ -390,6 +388,9 @@ macAddr = strBuf.toString(); } return macAddr; + //TODO - verify MAC address string representation + // (e.g. MSB->LSB ordering) + //TODO - verify that HW address is a MAC address } // /** @@ -530,7 +531,7 @@ * above. * <p> * Note that in all cases, if <code>true</code> is input - * for the <code>loopOk</code> parameter, then upon failing + * for the <code>loopbackOk</code> parameter, then upon failing * to find a valid ip address using the specified search * mechanism, this method will return the <i>loop back</i> * address; otherwise, <code>null</code> is returned. @@ -663,6 +664,8 @@ //get all nics on the current node Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces(); + if (nics == null) return null; + while( nics.hasMoreElements() ) { NetworkInterface curNic = nics.nextElement(); List<InterfaceAddress> interfaceAddrs = Modified: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/ConfigDeployUtilTest.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/ConfigDeployUtilTest.java 2010-10-11 17:26:00 UTC (rev 3767) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/ConfigDeployUtilTest.java 2010-10-11 18:33:47 UTC (rev 3768) @@ -115,6 +115,22 @@ String expected = value; assertEquals(actual, expected); } + + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getString(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetString_valid_name_default() throws ConfigurationException { + String key = "testGetString_valid_name"; + String value = key + "_value"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".default", value); + p.setProperty(key+".stringvals", value + ",other"); + String actual = ConfigDeployUtil.getString(key); + String expected = value; + assertEquals(actual, expected); + } /** * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getString(java.lang.String)}. @@ -135,6 +151,25 @@ //ignore -- exception } } + /** + * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getString(java.lang.String)}. + * @throws ConfigurationException + */ + @Test + public void testGetString_invalid_name_default() throws ConfigurationException { + String key = "testGetString_invalid_name"; + String value = key + "_value"; + Properties p = ConfigDeployUtil.getDeploymentProperties(); + p.setProperty(key+".default", value); + p.setProperty(key+".stringvals", "other1,other2"); + try { + ConfigDeployUtil.getString(key); + fail("Successfully called getString with bogus parameter string: [" + + key + ":" + value + "]"); + } catch (ConfigurationException e) { + //ignore -- exception + } + } /** * Test method for {@link com.bigdata.util.config.ConfigDeployUtil#getStringArray(java.lang.String)}. Added: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/ConfigurationUtilTest.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/ConfigurationUtilTest.java (rev 0) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/ConfigurationUtilTest.java 2010-10-11 18:33:47 UTC (rev 3768) @@ -0,0 +1,549 @@ +package com.bigdata.util.config; + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.IOException; +import java.lang.reflect.Method; +import java.net.InetAddress; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.UUID; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +public class ConfigurationUtilTest { + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testConcat_null() throws SecurityException, NoSuchMethodException { + String[][][] args = { + {null, null}, + {new String[0], null}, + {null, new String[0]} + }; + for (String[][] arg: args) { + try { + ConfigurationUtil.concat(arg[0], arg[1]); + fail("Successfully called concat() with null arg."); + } catch (NullPointerException e) { + // ignore -- expected. + } + } + } + + @Test + public void testConcat_empty() throws SecurityException, NoSuchMethodException { + String [] actual = ConfigurationUtil.concat(new String[0], new String[0]); + assertTrue(actual.length==0); + } + + @Test + public void testConcat_non_empty_singleton() throws SecurityException, NoSuchMethodException { + String[] a = { "abc" }; + String[] b = { "xyz" }; + String [] actual = ConfigurationUtil.concat(a, b); + assertTrue(actual.length==(a.length + b.length)); + assertArrayEquals("Arrays don't match", actual, combine(a, b)); + } + + @Test + public void testConcat_non_empty_multiple() throws SecurityException, NoSuchMethodException { + String[] a = { "abc", "def", "ghi", "jklmnop" }; + String[] b = { "qrs", "tuv", "wxyz" }; + String [] actual = ConfigurationUtil.concat(a, b); + assertTrue(actual.length==(a.length + b.length)); + List<String> l = new ArrayList<String>(); + l.addAll(Arrays.asList(a)); + l.addAll(Arrays.asList(b)); + assertArrayEquals("Arrays don't match", actual, l.toArray(new String[0])); + } + + @Test + public void testConcat_non_empty_multiple_embedded_null() + throws SecurityException, NoSuchMethodException + { + String[] a = { "abc", "def", null, "jklmnop" }; + String[] b = { "qrs", null, "wxyz" }; + String [] actual = ConfigurationUtil.concat(a, b); + assertTrue(actual.length==(a.length + b.length)); + List<String> l = new ArrayList<String>(); + l.addAll(Arrays.asList(a)); + l.addAll(Arrays.asList(b)); + assertArrayEquals("Arrays don't match", actual, l.toArray(new String[0])); + } + + @Test + public void testCreateArgList_null() { + Object[][] args = { + {null, null}, + {new String[0], null}, + }; + for (Object[] arg: args) { + try { + ConfigurationUtil.createArgList((String[])arg[0], (String)arg[1]); + fail("Successfully called createArgList() with null arg: " + + Arrays.asList(arg)); + } catch (NullPointerException e) { + // ignore -- expected. + } + } + } + + @Test + public void testCreateArgList_null2() { + //if second arg is empty or whitespace, return first arg + assertNull(ConfigurationUtil.createArgList(null, "")); + } + + @Test + public void testCreateArgList_null3() { + //if second arg is empty or whitespace, return first arg + assertNull(ConfigurationUtil.createArgList(null, " \t \t\t ")); + } + + @Test + public void testCreateArgList_empty() { + String[] orig = {"abc"}; + String extra = ""; + String[] sum = ConfigurationUtil.createArgList(orig, extra); + assertTrue(orig==sum);//identity obviates equals test + } + + @Test + public void testCreateArgList_single() { + String[] orig = {"abc"}; + String[] extraArray = new String[] {"xyz"}; + List<String> l = Arrays.asList(extraArray); + String extra = join(l); + String[] sum = ConfigurationUtil.createArgList(orig, extra); + assertArrayEquals(sum, combine(orig, extraArray)); + } + + @Test + public void testCreateArgList_multiple() { + String[] orig = {"abc"}; + String[] extraArray = new String[] {"rst", "uvw", "xyz"}; + List<String> l = Arrays.asList(extraArray); + String extra = join(l); + String[] sum = ConfigurationUtil.createArgList(orig, extra); + assertArrayEquals(sum, combine(orig, extraArray)); + } + + @Test + public void testComputeCodebase_5_arg_null() throws IOException { + Integer port = new Integer(5); + String jarf = "bogus_jar_file.jar"; + String name = "bogus_name"; + Object[][] args = { + {null, null, port, null, "sha"}, + {null, jarf, port, null, "sha"}, + {name, null, port, null, "sha"}, + {name, jarf, port, null, "sha"}, + }; + //Test int port method + for (Object[] arg: args) { + try { + ConfigurationUtil.computeCodebase( + (String)arg[0], (String)arg[1], + ((Integer)arg[2]).intValue(), + (String)arg[3], (String)arg[4]); + fail("Successfully called computeCodebase() with null arg: " + + Arrays.asList(arg)); + } catch (NullPointerException e) { + // ignore -- expected. + } + } + //Test String port method + for (Object[] arg: args) { + try { + ConfigurationUtil.computeCodebase( + (String)arg[0], (String)arg[1], + ((Integer)arg[2]).toString(), + (String)arg[3], (String)arg[4]); + fail("Successfully called computeCodebase() with null arg: " + + Arrays.asList(arg)); + } catch (NullPointerException e) { + // ignore -- expected. + } + } + + } + + @Test + public void testComputeCodebase_5_arg_invalid_port() throws IOException { + Integer port = new Integer(-1); + //Try int port + try { + ConfigurationUtil.computeCodebase( + "bogus_name", "bogus_jar_file.jar", + port.intValue(), "bogus_src", "bogus_md"); + fail("Successfully called computeCodebase() with negative port: " + + port); + } catch (IllegalArgumentException e) { + // ignore -- expected. + } + //Try String port + try { + ConfigurationUtil.computeCodebase( + "bogus_name", "bogus_jar_file.jar", + port.toString(), "bogus_src", "bogus_md"); + fail("Successfully called computeCodebase() with negative port: " + + port); + } catch (IllegalArgumentException e) { + // ignore -- expected. + } + } + + @Test + public void testComputeCodebase_5_arg_valid_hostname_http() throws IOException { + Integer port = new Integer(1234); + String hostname = InetAddress.getLocalHost().getHostAddress(); + String jarFile = "file.jar"; + Object[][] args = { + {hostname, jarFile, port, "src", null}, + {hostname, jarFile, port, "src", ""}, + {hostname, jarFile, port, "src", "off"}, + {hostname, jarFile, port, "src", "none"}, + }; + + //Test int port + for (Object[] arg: args) { + String urlString = ConfigurationUtil.computeCodebase( + (String)arg[0], (String)arg[1], + ((Integer)arg[2]).intValue(), + (String)arg[3], (String)arg[4]); //gen http url + testComputeCodebase_5_arg_valid_hostname_http_assert( + urlString, hostname, port, jarFile); + } + + //Test String port + for (Object[] arg: args) { + String urlString = ConfigurationUtil.computeCodebase( + (String)arg[0], (String)arg[1], + (String)arg[2].toString(), + (String)arg[3], (String)arg[4]); //gen http url + testComputeCodebase_5_arg_valid_hostname_http_assert( + urlString, hostname, port, jarFile); + } + } + + private void testComputeCodebase_5_arg_valid_hostname_http_assert( + String urlString, String hostname, Integer port, String jarFile) + throws MalformedURLException + { + URL url = new URL(urlString); + assertEquals(url.getProtocol(), "http"); + assertEquals(url.getHost(), hostname); //use IP to avoid DNS conversion + assertEquals(url.getPort(), port.intValue()); + assertEquals(url.getFile(), "/" + jarFile); + } + + @Test + public void testComputeCodebase_5_arg_invalid_hostname_http() throws IOException { + Integer port = new Integer(1234); + String hostname = UUID.randomUUID().toString(); + String jarFile = "file.jar"; + + //Test int port + try { + ConfigurationUtil.computeCodebase( + hostname, jarFile, port.intValue(), "", ""); + fail("Successfully called computeCodebase() with invalid hostname: " + + hostname); + + } catch (UnknownHostException e) { + //ignore -- expected + } + + //Test String port + try { + ConfigurationUtil.computeCodebase( + hostname, jarFile, port.toString(), "", ""); + fail("Successfully called computeCodebase() with invalid hostname: " + + hostname); + + } catch (UnknownHostException e) { + //ignore -- expected + } + } + + @Test + /** + * Note: this test assumes a well-known jar file under Sun's JDK and as + * such is JDK specific. + */ + public void testComputeCodebase_5_arg_valid_hostname_httpmd_md5() + throws IOException, URISyntaxException + { + Integer port = new Integer(1234); + String hostname = InetAddress.getLocalHost().getHostAddress(); + String jarFile = "rt.jar"; + String jarSrcPath = System.getProperty("java.home") + + File.separator + "lib"; + //Test int port + String urlString = ConfigurationUtil.computeCodebase( + hostname, jarFile, port.intValue(), jarSrcPath, "md5"); //gen httpmd url + testComputeCodebase_5_arg_valid_hostname_httpmd_md5_assert( + urlString, hostname, port, jarFile); + //Test String port + urlString = ConfigurationUtil.computeCodebase( + hostname, jarFile, port.toString(), jarSrcPath, "md5"); //gen httpmd url + testComputeCodebase_5_arg_valid_hostname_httpmd_md5_assert( + urlString, hostname, port, jarFile); + } + + private void testComputeCodebase_5_arg_valid_hostname_httpmd_md5_assert( + String urlString, String hostname, Integer port, String jarFile) + throws MalformedURLException, URISyntaxException + { + URI uri = new URI(urlString); + assertEquals(uri.getScheme(), "httpmd"); + assertEquals(uri.getHost(), hostname); //use IP to avoid DNS conversion + assertEquals(uri.getPort(), port.intValue()); + assertTrue(uri.getPath().startsWith("/" + jarFile + ";md5=")); + } + + @Test + /** + * Note: this test assumes a well-known jar file under Sun's JDK and as + * such is JDK specific. + */ + public void testComputeCodebase_5_arg_valid_hostname_httpmd_sha() + throws IOException, URISyntaxException + { + Integer port = new Integer(1234); + String hostname = InetAddress.getLocalHost().getHostAddress(); + String jarFile = "rt.jar"; + String jarSrcPath = System.getProperty("java.home") + + File.separator + "lib"; + //Test int port + String urlString = ConfigurationUtil.computeCodebase( + hostname, jarFile, port.intValue(), jarSrcPath, "sha"); //gen httpmd url + testComputeCodebase_5_arg_valid_hostname_httpmd_sha_assert( + urlString, hostname, port, jarFile); + //Test String port + urlString = ConfigurationUtil.computeCodebase( + hostname, jarFile, port.toString(), jarSrcPath, "sha"); //gen httpmd url + testComputeCodebase_5_arg_valid_hostname_httpmd_sha_assert( + urlString, hostname, port, jarFile); + } + + private void testComputeCodebase_5_arg_valid_hostname_httpmd_sha_assert( + String urlString, String hostname, Integer port, String jarFile) + throws MalformedURLException, URISyntaxException + { + URI uri = new URI(urlString); + assertEquals(uri.getScheme(), "httpmd"); + assertEquals(uri.getHost(), hostname); //use IP to avoid DNS conversion + assertEquals(uri.getPort(), port.intValue()); + assertTrue(uri.getPath().startsWith("/" + jarFile + ";sha=")); + } + + @Test + public void testComputeCodebase_3_arg_null() throws IOException { + Integer port = new Integer(5); + String jarf = "bogus_jar_file.jar"; + String name = "bogus_name"; + Object[][] args = { + {null, null, port}, + {null, jarf, port}, + {name, null, port}, + }; + //Test int port method + for (Object[] arg: args) { + try { + ConfigurationUtil.computeCodebase( + (String)arg[0], (String)arg[1], + ((Integer)arg[2]).intValue()); + fail("Successfully called computeCodebase() with null arg: " + + Arrays.asList(arg)); + } catch (NullPointerException e) { + // ignore -- expected. + } + } + //Test String port method + for (Object[] arg: args) { + try { + ConfigurationUtil.computeCodebase( + (String)arg[0], (String)arg[1], + ((Integer)arg[2]).toString()); + fail("Successfully called computeCodebase() with null arg: " + + Arrays.asList(arg)); + } catch (NullPointerException e) { + // ignore -- expected. + } + } + } + + @Test + public void testComputeCodebase_3_arg_invalid_port() throws IOException { + Integer port = new Integer(-1); + //Try int port + try { + ConfigurationUtil.computeCodebase( + "bogus_name", "bogus_jar_file.jar", port.intValue()); + fail("Successfully called computeCodebase() with negative port: " + + port); + } catch (IllegalArgumentException e) { + // ignore -- expected. + } + //Try String port + try { + ConfigurationUtil.computeCodebase( + "bogus_name", "bogus_jar_file.jar", port.toString()); + fail("Successfully called computeCodebase() with negative port: " + + port); + } catch (IllegalArgumentException e) { + // ignore -- expected. + } + } + + @Test + public void testComputeCodebase_3_arg_valid_hostname_http() throws IOException { + Integer port = new Integer(1234); + String hostname = InetAddress.getLocalHost().getHostAddress(); + String jarFile = "file.jar"; + + String urlString = ConfigurationUtil.computeCodebase( + hostname, jarFile, port.intValue()); //gen http url + testComputeCodebase_3_arg_valid_hostname_http_assert( + urlString, hostname, port, jarFile); + + + urlString = ConfigurationUtil.computeCodebase( + hostname, jarFile, port.toString()); //gen http url + testComputeCodebase_3_arg_valid_hostname_http_assert( + urlString, hostname, port, jarFile); + } + + private void testComputeCodebase_3_arg_valid_hostname_http_assert( + String urlString, String hostname, Integer port, String jarFile) + throws MalformedURLException + { + URL url = new URL(urlString); + assertEquals(url.getProtocol(), "http"); + assertEquals(url.getHost(), hostname); //use IP to avoid DNS conversion + assertEquals(url.getPort(), port.intValue()); + assertEquals(url.getFile(), "/" + jarFile); + } + + @Test + public void testComputeCodebase_3_arg_invalid_hostname_http() throws IOException { + Integer port = new Integer(1234); + String hostname = UUID.randomUUID().toString(); + String jarFile = "file.jar"; + + //Test int port + try { + ConfigurationUtil.computeCodebase( + hostname, jarFile, port.intValue()); + fail("Successfully called computeCodebase() with invalid hostname: " + + hostname); + } catch (UnknownHostException e) { + //ignore -- expected + } + + //Test String port + try { + ConfigurationUtil.computeCodebase( + hostname, jarFile, port.toString()); + fail("Successfully called computeCodebase() with invalid hostname: " + + hostname); + } catch (UnknownHostException e) { + //ignore -- expected + } + } + + @Test + /** + * Note: this test assumes a well-known jar file under Sun's JDK and as + * such is JDK specific. + */ + public void testComputeCodebase_port_not_number() + throws IOException, URISyntaxException + { + String port = "cafebabe"; + String hostname = InetAddress.getLocalHost().getHostAddress(); + String jarFile = "rt.jar"; + String jarSrcPath = System.getProperty("java.home") + + File.separator + "lib"; + // 5 arg method + try { + ConfigurationUtil.computeCodebase( + hostname, jarFile, port, jarSrcPath, "md5"); //gen httpmd url + fail("Successfully called computeCodebase() with invalid port: " + + port); + } catch (NumberFormatException e) { + //ignore -- expected + } + // 3 arg method + try { + ConfigurationUtil.computeCodebase( + hostname, jarFile, port); //gen httpmd url + fail("Successfully called computeCodebase() with invalid port: " + + port); + } catch (NumberFormatException e) { + //ignore -- expected + } + } + + /** + * Helper method that joins the given collection of <code>String</code> using the + * ASCII record separator (RS) character(\036). + * @param s the collection of strings to join + * @return String containing the collection's elements separated by + * the RS delimiter. + */ + private static String join(Collection<String> s) { + if (s == null || s.isEmpty()) return ""; + Iterator<String> iter = s.iterator(); + StringBuilder builder = new StringBuilder(iter.next()); + while( iter.hasNext() ) + { + builder.append('\036').append(iter.next()); + } + return builder.toString(); + } + + /** + * Helper method that combines two <code>String</code> arrays in order in which + * they are provided. + * @param s the collection of strings to join + * @return String containing the collection's elements separated by + * the RS delimiter. + */ + private static String[] combine(String[]a, String[]b) { + List<String> l = new ArrayList<String>(); + l.addAll(Arrays.asList(a)); + l.addAll(Arrays.asList(b)); + return l.toArray(new String[0]); + } +} Added: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/Log4jLoggingHandlerTest.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/Log4jLoggingHandlerTest.java (rev 0) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/Log4jLoggingHandlerTest.java 2010-10-11 18:33:47 UTC (rev 3768) @@ -0,0 +1,52 @@ +package com.bigdata.util.config; + +import static org.junit.Assert.*; + +import java.util.logging.Level; +import java.util.logging.LogRecord; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +public class Log4jLoggingHandlerTest { + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testFlush() { + Log4jLoggingHandler l = new Log4jLoggingHandler(); + l.flush(); + } + + @Test + public void testClose() { + Log4jLoggingHandler l = new Log4jLoggingHandler(); + l.close(); + } + + @Test + public void testPublishLogRecord() { + Log4jLoggingHandler l = new Log4jLoggingHandler(); + LogRecord rec = new LogRecord(Level.SEVERE, "Log message"); + l.publish(rec); + } + + //TODO - test static logic +} Added: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/LogUtilTest.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/LogUtilTest.java (rev 0) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/LogUtilTest.java 2010-10-11 18:33:47 UTC (rev 3768) @@ -0,0 +1,52 @@ +package com.bigdata.util.config; + +import static org.junit.Assert.*; + +import org.apache.log4j.Logger; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +public class LogUtilTest { + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetLog4jLoggerString() { + Logger l = LogUtil.getLog4jLogger(LogUtilTest.class); + assertNotNull(l); + assertEquals(LogUtilTest.class.getName(), l.getName()); + } + + @Test + public void testGetLog4jLoggerClass() { + Logger l = LogUtil.getLog4jLogger(LogUtilTest.class.getName()); + assertNotNull(l); + assertEquals(LogUtilTest.class.getName(), l.getName()); + } + + @Test + public void testGetLog4jRootLogger() { + Logger l = LogUtil.getLog4jRootLogger(); + assertNotNull(l); + assertEquals("root", l.getName()); + } + + //TODO - Still need to test static property logic +} Added: branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/NicUtilTest.java =================================================================== --- branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/NicUtilTest.java (rev 0) +++ branches/bbb_cleanup/bigdata-core/src/test/java/com/bigdata/util/config/NicUtilTest.java 2010-10-11 18:33:47 UTC (rev 3768) @@ -0,0 +1,1293 @@ +package com.bigdata.util.config; + +import static org.junit.Assert.*; + +import java.io.IOException; +import java.net.Inet4Address; +import java.net.InetAddress; +import java.net.InterfaceAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.net.UnknownHostException; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.UUID; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +public class NicUtilTest { + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + } + + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGetNetworkInterface_null() throws SocketException { + try { + NicUtil.getNetworkInterface(null); + fail("Successfully called getNetworkInterface() with null."); + } catch (NullPointerException e) { + //ignore -- expected + } + } + + @Test + public void testGetNetworkInterface_by_if_name() throws SocketException { + Enumeration<NetworkInterface> ifs = + NetworkInterface.getNetworkInterfaces(); + while(ifs.hasMoreElements()) { + NetworkInterface i = ifs.nextElement(); + assertEquals(NicUtil.getNetworkInterface(i.getName()), i); + } + } + + @Test + public void testGetNetworkInterface_by_host_name() throws SocketException { + boolean found = false; + for (Enumeration<NetworkInterface> ifs = + NetworkInterface.getNetworkInterfaces(); + ifs.hasMoreElements();) + { + NetworkInterface i = ifs.nextElement(); + for (Enumeration<InetAddress> ips = i.getInetAddresses(); + ips.hasMoreElements();) + { + InetAddress ip = ips.nextElement(); + NetworkInterface x = NicUtil.getNetworkInterface(ip.getHostAddress()); + assertNotNull(x); + assertEquals(i, x); + found = true; + } + } + + if (!found) fail("Could not find any IP address for testing."); + } + + @Test + public void testGetNetworkInterface_by_unknown_host_name() throws SocketException { + String unknownHost = getBogusHostname(); + NetworkInterface x = NicUtil.getNetworkInterface(unknownHost); + assertNull(x); + } + + @Test + public void testGetNetworkInterface_by_empty_host_name() throws SocketException { + NetworkInterface x = NicUtil.getNetworkInterface(""); + assertNotNull(x); + assertTrue(x.isLoopback()); + } + + @Test + public void testGetInetAddressMap() throws SocketException { + Map<InetAddress, String> expected = new HashMap<InetAddress, String>(); + for (Enumeration<NetworkInterface> ifs = + NetworkInterface.getNetworkInterfaces(); + ifs.hasMoreElements();) + { + NetworkInterface i = ifs.nextElement(); + for (Enumeration<InetAddress> ips = i.getInetAddresses(); + ips.hasMoreElements();) + { + InetAddress ip = ips.nextElement(); + expected.put(ip, i.getName()); + } + } + Map<InetAddress, String> actual = NicUtil.getInetAddressMap(); + assertEquals(actual, expected); + } + + @Test + public void testGetNetworkInterfaceArray_null() throws SocketException { + try { + NicUtil.getNetworkInterfaceArray(null); + fail("Successfully called getNetworkInterfaceArray with null."); + } catch (NullPointerException e) { + // ignore -- expected + } + } + + @Test + public void testGetNetworkInterfaceArray_unknown_host_name() throws SocketException { + String unknownHost = getBogusHostname(); + NetworkInterface[] x = NicUtil.getNetworkInterfaceArray(unknownHost); + assertEquals(x.length, 0); + } + + @Test + public void testGetNetworkInterfaceArray_known_host_name() throws SocketException { + Enumeration<NetworkInterface> ns = NetworkInterface.getNetworkInterfaces(); + List<NetworkInterface> ls = Collections.list(ns); + assert(ls.size()>0); + //Pick random entry from list. + Random r = new Random(); + //Note: size() must > 0, here. + String ifName = ls.get(r.nextInt(ls.size())).getName(); + NetworkInterface[] nifs = NicUtil.getNetworkInterfaceArray(ifName); + assertTrue(nifs.length > 0); + assertEquals(nifs[0].getName(), ifName); + } + + @Test + public void testGetNetworkInterfaceArray_known_ip_address() throws SocketException { + Result<String, NetworkInterface> res = + getNonLoopbackNetworkInterfaceWithInet4Address(); + NetworkInterface[] nifs = NicUtil.getNetworkInterfaceArray(res.getValue1()); + assertEquals(nifs.length, 1); + assertEquals(nifs[0], res.getValue2()); + } + + @Test + public void testGetNetworkInterfaceArray_all() throws SocketException { + List<NetworkInterface> expected = + Collections.list(NetworkInterface.getNetworkInterfaces()); + assertTrue(expected.size() > 0); + List<NetworkInterface> actual = + Arrays.asList(NicUtil.getNetworkInterfaceArray("all")); + assertEquals(actual.size(), expected.size()); + //Remove actual from expected -- should leave an empty list + expected.removeAll(actual); + assertTrue(expected.isEmpty()); + } + + @Test + public void testGetInetAddress_npe_args() { + String name = null; + int index = 0; + String host = null; + boolean localHost = false; + try{ + NicUtil.getInetAddress(name, index, host, localHost); + fail("Successfully called getInetAddress with invalid arguments."); + } catch (NullPointerException e) { + //ignore -- expected + } + } + + @Test + public void testGetInetAddress_negative_index() { + String name = null; + int index = -1; + String host = null; + boolean localHost = true; + try{ + NicUtil.getInetAddress(name, index, host, localHost); + fail("Successfully called getInetAddress with negative index."); + } catch (IllegalArgumentException e) { + //ignore -- expected + } + } + + @Test + public void testGetInetAddress_get_localhost_only() throws UnknownHostException { + String name = null; + int index = 0; + String host = null; + boolean localHost = true; + InetAddress expected = InetAddress.getLocalHost(); + InetAddress actual = NicUtil.getInetAddress(name, index, host, localHost); + assertEquals(expected, actual); + } + + @Test + public void testGetInetAddress_get_unknown_host_no_localhost() + throws UnknownHostException + { + String name = null; + int index = 0; + String host = getBogusHostname(); + boolean localHost = false; + InetAddress expected = null; + InetAddress actual = NicUtil.getInetAddress(name, index, host, localHost); + assertEquals(expected, actual); + } + + @Test + public void testGetInetAddress_get_unknown_host_with_localhost() + throws UnknownHostException + { + String name = null; + int index = 0; + String host = getBogusHostname(); + boolean localHost = true; + InetAddress expected = InetAddress.getLocalHost(); + InetAddress actual = NicUtil.getInetAddress(name, index, host, localHost); + assertEquals(expected, actual); + } + + @Test + public void testGetInetAddress_get_known_host_no_localhost() + throws UnknownHostException + { + String name = null; + int index = 0; + String host = InetAddress.getLocalHost().getHostName(); + boolean localHost = false; + InetAddress expected = InetAddress.getLocalHost(); + InetAddress actual = NicUtil.getInetAddress(name, index, host, localHost); + assertEquals(expected, actual); + } + + @Test + public void testGetInetAddress_get_known_host_with_localhost() + throws UnknownHostException + { + String name = null; + int index = 0; + String host = InetAddress.getLocalHost().getHostName(); + boolean localHost = true; + InetAddress expected = InetAddress.getLocalHost(); + InetAddress actual = NicUtil.getInetAddress(name, index, host, localHost); + assertEquals(expected, actual); + } + + @Test + public void testGetInetAddress_get_known_name_no_host_or_localhost() + throws UnknownHostException, SocketException + { + Result<String, NetworkInterface> res = + getNonLoopbackNetworkInterfaceWithInet4Address(); + String name = res.getValue2().getName(); + int index = 0; + String host = null; + boolean localHost = false; + List<InetAddress> expectedAddresses = + Collections.list(res.getValue2().getInetAddresses()); + assertFalse(expectedAddresses.isEmpty()); + InetAddress actual = NicUtil.getInetAddress(name, index, host, localHost); + assertNotNull(actual); + assertTrue(expectedAddresses.contains(actual)); + } + + @Test + public void testGetInetAddress_get_known_name_with_host_no_localhost() + throws UnknownHostException, SocketException + { + Result<String, NetworkInterface> res = + getNonLoopbackNetworkInterfaceWithInet4Address(); + String name = res.getValue2().getName(); + int index = 0; + String host = InetAddress.getLocalHost().getHostName(); + boolean localHost = false; + List<InetAddress> expectedAddresses = + Collections.list(res.getValue2().getInetAddresses()); + assertFalse(expectedAddresses.isEmpty()); + InetAddress actual = NicUtil.getInetAddress(name, index, host, localHost); + assertNotNull(actual); + assertTrue(expectedAddresses.contains(actual)); + } + + //TODO - Another test which ensures host != result.NetworkInterface + + @Test + public void testGetInetAddress_get_known_name_with_host_with_localhost() + throws UnknownHostException, SocketException + { + Result<String, NetworkInterface> res = + getNonLoopbackNetworkInterfaceWithInet4Address(); + String name = res.getValue1(); + int index = 0; + String host = InetAddress.getLocalHost().getHostName(); + boolean localHost = true; + List<InetAddress> expectedAddresses = + Collections.list(res.getValue2().getInetAddresses()); + assertFalse(expectedAddresses.isEmpty()); + InetAddress actual = NicUtil.getInetAddress(name, index, host, localHost); + assertNotNull(actual); + assertTrue(expectedAddresses.contains(actual)); + } + + //TODO - Another test which ensures host != result.NetworkInterface + + //TODO - test for multi-IP interface (e.g. index arg > 0) + + @Test + public void testGetMacAddress_null() throws SocketException { + try { + NicUtil.getMacAddress(null); + fail("Successfully called getMacAddress with null."); + } catch (NullPointerException e) { + //ignore -- exception + } + } + + @Test + public void testGetMacAddress_unknown() throws SocketException { + String mac = NicUtil.getMacAddress(UUID.randomUUID().toString()); + assertNull(mac); + } + + @Test + public void testGetMacAddress_known() throws SocketException, ParseException { + Result<byte[], NetworkInterface> res = + getFirstNetworkInterfaceWithMacAddress(); + String mac = NicUtil.getMacAddress(res.getValue2().getName()); + assertNotNull(mac); + //Note: not verifying MAC address via string representation + } + + + @Test + public void testGetIpAddressString_npe() { + try { + NicUtil.getIpAddress(null); + fail("Successfully called getIpAddress with null."); + } catch (NullPointerException e) { + //ignore -- expected + } + } + + @Test + public void testGetIpAddressString_unknown_host() { + assertNull(NicUtil.getIpAddress(getBogusHostname())); + } + + @Test + public void testGetIpAddressString_known_host() throws SocketException { + Result<String, NetworkInterface> res = + getNonLoopbackNetworkInterfaceWithInet4Address(); + String actual = + NicUtil.getIpAddress(res.getValue2().getName()); + assertEquals(res.getValue1(), actual); + } + + @Test + public void testGetIpAddressStringInt_npe() { + try { + NicUtil.getIpAddress(null, 0); + fail("Successfully called getIpAddress with null."); + } catch (NullPointerException e) { + //ignore -- expected + } + } + + @Test + public void testGetIpAddressStringInt_negative_index() { + try { + NicUtil.getIpAddress("", -1); + fail("Successfully called getIpAddress with" + + "a negative index."); + } catch (IllegalArgumentException e) { + //ignore -- expected + } + } + + @Test + public void testGetIpAddressStringInt_unknown_host() { + assertNull(NicUtil.getIpAddress(getBogusHostname(), 0)); + } + + @Test + public void testGetIpAddressStringInt_known_host() throws SocketException { + Result<String, NetworkInterface> res = + getNonLoopbackNetworkInterfaceWithInet4Address(); + String actual = + NicUtil.getIpAddress(res.getValue2().getName(), 0); + assertEquals(res.getValue1(), actual); + } + + @Test + public void testGetIpAddressStringString_npe() { + try { + NicUtil.getIpAddress((String)null, (String)null); + fail("Succcessfully called getIpAddress with null."); + }catch (NullPointerException e... [truncated message content] |