From: <pat...@us...> - 2009-07-17 21:13:13
|
Revision: 886 http://cishell.svn.sourceforge.net/cishell/?rev=886&view=rev Author: pataphil Date: 2009-07-17 21:13:00 +0000 (Fri, 17 Jul 2009) Log Message: ----------- Initial commit. Used to be edu.iu.scipolicy.utilities, but they are general-purpose for all CIShell projects. Added Paths: ----------- trunk/core/org.cishell.utilities/.classpath trunk/core/org.cishell.utilities/.project trunk/core/org.cishell.utilities/.settings/ trunk/core/org.cishell.utilities/.settings/org.eclipse.jdt.core.prefs trunk/core/org.cishell.utilities/.settings/org.eclipse.pde.core.prefs trunk/core/org.cishell.utilities/META-INF/ trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF trunk/core/org.cishell.utilities/build.properties trunk/core/org.cishell.utilities/src/ trunk/core/org.cishell.utilities/src/org/ trunk/core/org.cishell.utilities/src/org/cishell/ trunk/core/org.cishell.utilities/src/org/cishell/utilities/ trunk/core/org.cishell.utilities/src/org/cishell/utilities/AlgorithmNotFoundException.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/AlgorithmUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayListUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/ColumnNotFoundException.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/DateUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/DefaultDictionary.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/FAQCalendar.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/ImageUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/NumberUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/SetUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/StringUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/TableUtilities.java trunk/core/org.cishell.utilities/tests/ trunk/core/org.cishell.utilities/tests/edu/ trunk/core/org.cishell.utilities/tests/edu/iu/ trunk/core/org.cishell.utilities/tests/edu/iu/scipolicy/ trunk/core/org.cishell.utilities/tests/edu/iu/scipolicy/utilities/ trunk/core/org.cishell.utilities/tests/edu/iu/scipolicy/utilities/DateUtilitiesTest.java trunk/core/org.cishell.utilities/tests/edu/iu/scipolicy/utilities/DefaultDictionaryTest.java trunk/core/org.cishell.utilities/tests/edu/iu/scipolicy/utilities/FAQCalendarTest.java trunk/core/org.cishell.utilities/tests/edu/iu/scipolicy/utilities/FileUtilitiesTest.java trunk/core/org.cishell.utilities/tests/edu/iu/scipolicy/utilities/ImageUtilitiesTest.java trunk/core/org.cishell.utilities/tests/edu/iu/scipolicy/utilities/MutateParameterUtilitiesTest.java trunk/core/org.cishell.utilities/tests/edu/iu/scipolicy/utilities/StringUtilitiesTest.java trunk/core/org.cishell.utilities/tests/edu/iu/scipolicy/utilities/TableUtilitiesTest.java Added: trunk/core/org.cishell.utilities/.classpath =================================================================== --- trunk/core/org.cishell.utilities/.classpath (rev 0) +++ trunk/core/org.cishell.utilities/.classpath 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,9 @@ +<?xml version="1.0" encoding="UTF-8"?> +<classpath> + <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.5"/> + <classpathentry kind="con" path="org.eclipse.pde.core.requiredPlugins"/> + <classpathentry kind="src" path="src"/> + <classpathentry kind="src" path="tests"/> + <classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/4"/> + <classpathentry kind="output" path="bin"/> +</classpath> Added: trunk/core/org.cishell.utilities/.project =================================================================== --- trunk/core/org.cishell.utilities/.project (rev 0) +++ trunk/core/org.cishell.utilities/.project 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,28 @@ +<?xml version="1.0" encoding="UTF-8"?> +<projectDescription> + <name>org.cishell.utilities</name> + <comment></comment> + <projects> + </projects> + <buildSpec> + <buildCommand> + <name>org.eclipse.jdt.core.javabuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.ManifestBuilder</name> + <arguments> + </arguments> + </buildCommand> + <buildCommand> + <name>org.eclipse.pde.SchemaBuilder</name> + <arguments> + </arguments> + </buildCommand> + </buildSpec> + <natures> + <nature>org.eclipse.pde.PluginNature</nature> + <nature>org.eclipse.jdt.core.javanature</nature> + </natures> +</projectDescription> Added: trunk/core/org.cishell.utilities/.settings/org.eclipse.jdt.core.prefs =================================================================== --- trunk/core/org.cishell.utilities/.settings/org.eclipse.jdt.core.prefs (rev 0) +++ trunk/core/org.cishell.utilities/.settings/org.eclipse.jdt.core.prefs 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,7 @@ +#Fri Jan 16 16:03:38 EST 2009 +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 +org.eclipse.jdt.core.compiler.compliance=1.5 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.5 Added: trunk/core/org.cishell.utilities/.settings/org.eclipse.pde.core.prefs =================================================================== --- trunk/core/org.cishell.utilities/.settings/org.eclipse.pde.core.prefs (rev 0) +++ trunk/core/org.cishell.utilities/.settings/org.eclipse.pde.core.prefs 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,4 @@ +#Fri Jan 16 16:03:38 EST 2009 +eclipse.preferences.version=1 +pluginProject.extensions=false +resolve.requirebundle=false Added: trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF =================================================================== --- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF (rev 0) +++ trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,18 @@ +Manifest-Version: 1.0 +Bundle-ManifestVersion: 2 +Bundle-Name: Utilities Plug-in +Bundle-SymbolicName: org.cishell.utilities +Bundle-Version: 1.0.0 +Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Import-Package: org.cishell.framework.algorithm;version="1.0.0", + org.cishell.reference.service.metatype, + org.osgi.framework;version="1.4.0", + org.osgi.service.metatype;version="1.1.0", + prefuse, + prefuse.data, + prefuse.data.column, + prefuse.data.tuple, + prefuse.data.util, + prefuse.util, + prefuse.util.collections +Export-Package: org.cishell.utilities Added: trunk/core/org.cishell.utilities/build.properties =================================================================== --- trunk/core/org.cishell.utilities/build.properties (rev 0) +++ trunk/core/org.cishell.utilities/build.properties 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,4 @@ +source.. = src/ +output.. = bin/ +bin.includes = META-INF/,\ + . Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/AlgorithmNotFoundException.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/AlgorithmNotFoundException.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/AlgorithmNotFoundException.java 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,21 @@ +package org.cishell.utilities; + +public class AlgorithmNotFoundException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public AlgorithmNotFoundException() { + super(); + } + + public AlgorithmNotFoundException(String arg0) { + super(arg0); + } + + public AlgorithmNotFoundException(Throwable arg0) { + super(arg0); + } + + public AlgorithmNotFoundException(String arg0, Throwable arg1) { + super(arg0, arg1); + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/AlgorithmUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/AlgorithmUtilities.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/AlgorithmUtilities.java 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,48 @@ +package org.cishell.utilities; + +import org.cishell.framework.algorithm.AlgorithmFactory; +import org.osgi.framework.BundleContext; +import org.osgi.framework.InvalidSyntaxException; +import org.osgi.framework.ServiceReference; + + +public class AlgorithmUtilities { + // TODO: ISILoadAndCleanAlgorithmFactory should use this? + // It's copied directly from it (and cleaned up a little bit)... + public static AlgorithmFactory getAlgorithmFactoryByFilter( + String filter, BundleContext bundleContext) + throws AlgorithmNotFoundException { + ServiceReference[] algorithmFactoryReferences; + + try { + algorithmFactoryReferences = bundleContext.getServiceReferences( + AlgorithmFactory.class.getName(), filter); + } catch (InvalidSyntaxException invalidSyntaxException) { + throw new AlgorithmNotFoundException(invalidSyntaxException); + } + + if (algorithmFactoryReferences != null && + algorithmFactoryReferences.length != 0) { + ServiceReference algorithmFactoryReference = + algorithmFactoryReferences[0]; + + AlgorithmFactory algorithmFactory = + (AlgorithmFactory)bundleContext.getService( + algorithmFactoryReference); + + return algorithmFactory; + } + else { + throw new AlgorithmNotFoundException("Unable to find an " + + "algorithm that satisfied the following filter:\n" + filter); + } + } + + public static AlgorithmFactory getAlgorithmFactoryByPID( + String pid, BundleContext bundleContext) + throws AlgorithmNotFoundException { + String filter = "(service.pid=" + pid + ")"; + + return getAlgorithmFactoryByFilter(filter, bundleContext); + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayListUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayListUtilities.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayListUtilities.java 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,38 @@ +package org.cishell.utilities; + +import java.util.ArrayList; +import java.util.Arrays; + +public class ArrayListUtilities { + public static ArrayList unionArrayLists(ArrayList arrayList1, + ArrayList arrayList2, + String[] keysToSkip, + String[] keysToAdd) { + ArrayList union = new ArrayList(); + + for (int ii = 0; ii < arrayList1.size(); ii++) { + Object element = arrayList1.get(ii); + + if (!union.contains(element) && + Arrays.binarySearch(keysToSkip, element) < 0) { + union.add(element); + } + } + + for (int ii = 0; ii < arrayList2.size(); ii++) { + Object element = arrayList2.get(ii); + + if (!union.contains(element)) { + union.add(element); + } + } + + for (String keyToAdd : keysToAdd) { + if (!union.contains(keyToAdd)) { + union.add(keyToAdd); + } + } + + return union; + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/ColumnNotFoundException.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ColumnNotFoundException.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/ColumnNotFoundException.java 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,21 @@ +package org.cishell.utilities; + +public class ColumnNotFoundException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public ColumnNotFoundException() { + super(); + } + + public ColumnNotFoundException(String arg0) { + super(arg0); + } + + public ColumnNotFoundException(Throwable arg0) { + super(arg0); + } + + public ColumnNotFoundException(String arg0, Throwable arg1) { + super(arg0, arg1); + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/DateUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/DateUtilities.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/DateUtilities.java 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,335 @@ +package org.cishell.utilities; + +import java.text.DateFormat; +import java.text.ParseException; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; + +// TODO: Fix this class. +public class DateUtilities { + public final static double AVERAGE_MILLIS_PER_MONTH = + (365.24 * 24 * 60 * 60 * 1000 / 12); + + // TODO: Is this actually necessary? + public static Date[] generateDaysBetweenDates(Date startDate, Date endDate) { + GregorianCalendar startDateCalendar = + new GregorianCalendar(startDate.getYear() + 1900, + startDate.getMonth(), + startDate.getDate()); + + GregorianCalendar endDateCalendar = + new GregorianCalendar(endDate.getYear() + 1900, + endDate.getMonth(), + endDate.getDate()); + + // Return an empty set of days (Dates) if the start date is actually AFTER + // the end date. + if (startDateCalendar.getTimeInMillis() > endDateCalendar.getTimeInMillis()) + return new Date [0]; + + // There is at least one day between the provided start and end dates (dates + // themselves included). + + ArrayList workingDaysBetweenDates = new ArrayList(); + GregorianCalendar currentCalendarForDateThatWeAreCalculating = + (GregorianCalendar)startDateCalendar.clone(); + final Date actualEndDateAccordingToCalendar = endDateCalendar.getTime(); + boolean shouldKeepGeneratingDaysBetweenDates = true; + + // This is the meat of the Date generation. + while (shouldKeepGeneratingDaysBetweenDates) { + // Get the current calculated date. + Date currentCalculatedDate = + currentCalendarForDateThatWeAreCalculating.getTime(); + + // Add the current date that we are calculating. + workingDaysBetweenDates.add(currentCalculatedDate); + + // Move the current calendar for the date that we are calculating + // forward in time a day. + currentCalendarForDateThatWeAreCalculating.add(Calendar.DATE, 1); + + // Should we stop now? + if ((currentCalculatedDate.getYear() == + actualEndDateAccordingToCalendar.getYear()) && + (currentCalculatedDate.getMonth() == + actualEndDateAccordingToCalendar.getMonth()) && + (currentCalculatedDate.getDate() == + actualEndDateAccordingToCalendar.getDate())) + { + shouldKeepGeneratingDaysBetweenDates = false; + } + } + + Date[] finalDaysBetweenDates = new Date [workingDaysBetweenDates.size()]; + + return (Date[])workingDaysBetweenDates.toArray(finalDaysBetweenDates); + } + + public static int calculateDaysBetween(Date[] dateSet) { + return dateSet.length; + } + + public static int calculateDaysBetween(Date startDate, Date endDate) { + FAQCalendar startDateCalendar = new FAQCalendar(startDate.getYear(), + startDate.getMonth(), + startDate.getDate()); + + FAQCalendar endDateCalendar = new FAQCalendar(endDate.getYear(), + endDate.getMonth(), + endDate.getDate()); + + return (int)startDateCalendar.diffDayPeriods(endDateCalendar); + } + + public static int calculateMonthsBetween(Date startDate, Date endDate) { + int roundedMonthsBetween = (int)Math.round + ((endDate.getTime() - startDate.getTime()) / AVERAGE_MILLIS_PER_MONTH); + + if (roundedMonthsBetween > 0) { + return roundedMonthsBetween; + } + else { + // HACK(?): There must be at least one month between + // (even if they're both the same month). + return 1; + } + } + + // Assumes dateSet is sorted from earliest to latest. + public static Date[] getNewYearsDatesFromDateSet(Date[] dateSet) { + ArrayList workingNewYearsDates = new ArrayList(); + + // Return an empty set if there are no dates. + if (dateSet.length == 0) + return new Date [0]; + + // If the first date is not a new year's date, add a new year's date for + // that date's year. + if ((dateSet[0].getMonth() != 0) || (dateSet[0].getDate() != 1)) + workingNewYearsDates.add(new Date(dateSet[0].getYear(), 0, 1)); + + // Find each date that has the month and day of 1-1 (well, 0-1 because Date + // is stupid). + for (int ii = 0; ii < dateSet.length; ii++) { + if ((dateSet[ii].getMonth() == 0) && (dateSet[ii].getDate() == 1)) + workingNewYearsDates.add(dateSet[ii]); + } + + Date[] finalNewYearsDates = new Date [workingNewYearsDates.size()]; + + return (Date[])workingNewYearsDates.toArray(finalNewYearsDates); + } + + public static Date[] generateNewYearsDatesBetweenDates(Date startDate, + Date endDate) + { + final int startDateYear = startDate.getYear(); + final int endDateYear = endDate.getYear(); + // The number of years between the two years (inclusive). + final int numYearsBetween = ((endDateYear - startDateYear) + 1); + + // Return an empty array if the start date is after the end date. + if (numYearsBetween == 0) + return new Date[] { }; + + Date[] newYearsDatesBetween = new Date [numYearsBetween]; + + for (int ii = 0; ii < numYearsBetween; ii++) + newYearsDatesBetween[ii] = new Date((startDateYear + ii), 0, 1); + + return newYearsDatesBetween; + } + + // TODO: This could also REALLY be improved. + public static Date[] generateFirstOfTheMonthDatesBetweenDates(Date[] dateSet) { + ArrayList workingFirstOfTheMonthDates = new ArrayList(); + + // Find each date that has the day of 1. + for (int ii = 0; ii < dateSet.length; ii++) { + if (dateSet[ii].getDate() == 1) + workingFirstOfTheMonthDates.add(dateSet[ii]); + } + + Date[] finalFirstOfTheMonthDates = + new Date [workingFirstOfTheMonthDates.size()]; + + return (Date[])workingFirstOfTheMonthDates.toArray + (finalFirstOfTheMonthDates); + } + + public static Date[] generateFirstOfTheMonthDatesBetweenDates(Date startDate, + Date endDate) + { + Date[] allDaysBetweenDates = generateDaysBetweenDates(startDate, endDate); + + return generateFirstOfTheMonthDatesBetweenDates(allDaysBetweenDates); + } + + //TODO: These should be sorted so the first format checked is the most likely format, etc... + private static final DateFormat[] ACCEPTED_DATE_FORMATS = { + DateFormat.getDateInstance(DateFormat.FULL), + new SimpleDateFormat("d-MM-yy"), + new SimpleDateFormat("d-MM-yyyy"), + new SimpleDateFormat("dd-MM-yy"), + new SimpleDateFormat("dd-MM-yyyy"), + new SimpleDateFormat("d/MM/yy"), + new SimpleDateFormat("dd/MM/yy"), + new SimpleDateFormat("d/MM/yyyy"), + new SimpleDateFormat("dd/MMM/yyyy"), + new SimpleDateFormat("d-MMM-yy"), + new SimpleDateFormat("d-MMM-yyyy"), + new SimpleDateFormat("dd-MMM-yy"), + new SimpleDateFormat("dd-MMM-yyyy"), + new SimpleDateFormat("d/MMM/yy"), + new SimpleDateFormat("dd/MMM/yy"), + new SimpleDateFormat("d/MMM/yyyy"), + new SimpleDateFormat("dd/MMM/yyyy"), + new SimpleDateFormat("yyyy"), + DateFormat.getDateInstance(DateFormat.SHORT), + DateFormat.getDateInstance(DateFormat.MEDIUM), + DateFormat.getDateInstance(DateFormat.LONG), + }; + + public static Date parseDate(String dateString) + throws ParseException { + for (DateFormat format : ACCEPTED_DATE_FORMATS) { + try { + format.setLenient(false); + Date date = format.parse(dateString); + + if (date.getYear() < 1900) { + date.setYear(date.getYear() + 1900); + } + + return date; + } + catch (ParseException dateParseException) { + continue; + } + } + + String exceptionMessage = "Could not parse the field " + + "'" + dateString + "'" + + " as a date."; + + throw new ParseException(exceptionMessage, 0); + } + + public static Date interpretObjectAsDate(Object object) + throws ParseException{ + final String EMPTY_DATE_MESSAGE = "An empty date was found."; + + String objectAsString = object.toString(); + + // TODO: These if's are a result of a "bug" in Prefuse's. + // CSV Table Reader, which interprets a column as being an array type + // if it has empty cells. + if (object instanceof Date) { + return (Date)object; + } + else if (object instanceof short[]) { + short[] year = (short[])object; + + if (year.length == 0) { + throw new ParseException(EMPTY_DATE_MESSAGE, 0); + } + else { + objectAsString = "" + year[0]; + } + } + else if (object instanceof Short[]) { + Short[] year = (Short[])object; + + if (year.length == 0) { + throw new ParseException(EMPTY_DATE_MESSAGE, 0); + } + else { + objectAsString = "" + year[0]; + } + } + else if (object instanceof int[]) { + int[] year = (int[])object; + + if (year.length == 0) { + throw new ParseException(EMPTY_DATE_MESSAGE, 0); + } + else { + objectAsString = "" + year[0]; + } + } + else if (object instanceof Integer[]) { + Integer[] year = (Integer[])object; + + if (year.length == 0) { + throw new ParseException(EMPTY_DATE_MESSAGE, 0); + } + else { + objectAsString = year.toString(); + } + } + else if (object instanceof long[]) { + long[] year = (long[])object; + + if (year.length == 0) { + throw new ParseException(EMPTY_DATE_MESSAGE, 0); + } + else { + objectAsString = "" + year[0]; + } + } + else if (object instanceof Long[]) { + Long[] year = (Long[])object; + + if (year.length == 0) { + throw new ParseException(EMPTY_DATE_MESSAGE, 0); + } + else { + objectAsString = "" + year[0]; + } + } + else if (object instanceof String[]) { + String[] year = (String[])object; + + if (year.length == 0) { + throw new ParseException(EMPTY_DATE_MESSAGE, 0); + } + else { + objectAsString = year[0]; + } + } + + return parseDate(objectAsString); + } + +// private java.util.Date parseDate(String dateString) +// throws AlgorithmExecutionException { +// for (DateFormat format : ACCEPTED_DATE_FORMATS) { +// try { +// format.setLenient(false); +// java.util.Date date = format.parse(dateString); +// //WE PARSED THE DATE SUCCESSFULLY (if we get to this point)! +// //Finish up our processing and return the date. +// +// //TODO: Methinks this is a hack we should eliminate +// if (date.getYear() < 1900) +// date.setYear(date.getYear() + 1900); +// java.sql.Date dateForSQL = new java.sql.Date(date.getTime()); +// return dateForSQL; +// } catch (ParseException e) { +// continue; +// } +// } +// +// //we could not parse the date with any of the accepted formats. +// +// String exceptionMessage = +// "Could not parse the field " + +// "'" + dateString + "'" + +// " as a date. Aborting the algorithm."; +// throw new AlgorithmExecutionException(exceptionMessage); +// } +} Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/DefaultDictionary.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/DefaultDictionary.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/DefaultDictionary.java 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,58 @@ +package org.cishell.utilities; + +import java.util.Dictionary; +import java.util.Enumeration; +import java.util.Hashtable; + +public class DefaultDictionary extends Dictionary { + Object defaultValue; + Dictionary wrappedDictionary; + + public DefaultDictionary + (Object defaultValue, Dictionary wrappedDictionary) + { + this.defaultValue = defaultValue; + this.wrappedDictionary = wrappedDictionary; + } + + public DefaultDictionary(Object defaultValue) { + this(defaultValue, new Hashtable()); + } + + public Object getDefaultValue() { + return this.defaultValue; + } + + public Enumeration elements() { + return this.wrappedDictionary.elements(); + } + + public Object get(Object key) { + Object wrappedDictionaryGetResult = this.wrappedDictionary.get(key); + + if (wrappedDictionaryGetResult == null) + return this.defaultValue; + + return wrappedDictionaryGetResult; + } + + public boolean isEmpty() { + return this.wrappedDictionary.isEmpty(); + } + + public Enumeration keys() { + return this.wrappedDictionary.keys(); + } + + public Object put(Object key, Object value) { + return this.wrappedDictionary.put(key, value); + } + + public Object remove(Object key) { + return this.wrappedDictionary.remove(key); + } + + public int size() { + return this.wrappedDictionary.size(); + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/FAQCalendar.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/FAQCalendar.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/FAQCalendar.java 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,100 @@ +package org.cishell.utilities; + +import java.util.Calendar; +import java.util.GregorianCalendar; + +// Patrick: I found this on Google. Thanks to Paul Hill! +// Found at: http://www.xmission.com/~goodhill/dates/deltaDates.html + +/** + * Demonstration of delta day calculations. + * @author Paul Hill + * @copyright 2004 Paul Hill + */ +public class FAQCalendar extends GregorianCalendar { + /** + * All minutes have this many milliseconds except the last minute of the day on a day defined with + * a leap second. + */ + public static final long MILLISECS_PER_MINUTE = 60*1000; + + /** + * Number of milliseconds per hour, except when a leap second is inserted. + */ + public static final long MILLISECS_PER_HOUR = 60*MILLISECS_PER_MINUTE; + + /** + * Number of leap seconds per day expect on + * <BR/>1. days when a leap second has been inserted, e.g. 1999 JAN 1. + * <BR/>2. Daylight-savings "spring forward" or "fall back" days. + */ + protected static final long MILLISECS_PER_DAY = 24*MILLISECS_PER_HOUR; + + /**** + * Value to add to the day number returned by this calendar to find the Julian Day number. + * This is the Julian Day number for 1/1/1970. + * Note: Since the unix Day number is the same from local midnight to local midnight adding + * JULIAN_DAY_OFFSET to that value results in the chronologist, historians, or calenderists + * Julian Day number. + * @see http://www.hermetic.ch/cal_stud/jdn.htm + */ + public static final long EPOCH_UNIX_ERA_DAY = 2440588L; + + /** + * @see java.util.GregorianCalendar#GregorianCalendar() + */ + public FAQCalendar() { + super(); + } + /** + * @param millisecondTime - time as a binary Unix/Java time value. + * @see java.util.GregorianCalendar + */ + public FAQCalendar( long millisecondTime ) { + super(); + this.setTimeInMillis( millisecondTime); + } + + /** + * @see java.util.GregorianCalendar#GregorianCalendar(int, int, int) + */ + public FAQCalendar( int y, int m, int d ) { + super( y, m, d ); + } + + /** + * @see java.util.GregorianCalendar#GregorianCalendar(int, int, int, int, int, int) + */ + public FAQCalendar( int y, int m, int d, int h, int min, int s ) { + super( y, m, d, h, min, s ); + } + + /** + * @return Day number where day 0 is 1/1/1970, as per the Unix/Java date/time epoch. + */ + public long getUnixDay() { + long offset = get(Calendar.ZONE_OFFSET) + get(Calendar.DST_OFFSET); + long day = (long)Math.floor( (double)(getTime().getTime() + offset ) / ((double)MILLISECS_PER_DAY) ); + return day; + } + + /** + * @return LOCAL Chronologists Julian day number each day starting from midnight LOCAL TIME. + * @see http://tycho.usno.navy.mil/mjd.html for more information about local C-JDN + */ + public long getJulianDay() { + return getUnixDay() + EPOCH_UNIX_ERA_DAY; + } + /** + * find the number of days from this date to the given end date. + * later end dates result in positive values. + * Note this is not the same as subtracting day numbers. Just after midnight subtracted from just before + * midnight is 0 days for this method while subtracting day numbers would yields 1 day. + * @param end - any Calendar representing the moment of time at the end of the interval for calculation. + */ + public long diffDayPeriods(Calendar end) { + long endL = end.getTimeInMillis() + end.getTimeZone().getOffset( end.getTimeInMillis() ); + long startL = this.getTimeInMillis() + this.getTimeZone().getOffset( this.getTimeInMillis() ); + return (endL - startL) / MILLISECS_PER_DAY; + } +} Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,144 @@ +package org.cishell.utilities; + +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; + +import javax.imageio.ImageIO; + +public class FileUtilities { + // Return a File pointing to the directory specified in temporaryDirectoryPath, + // creating the directory if it doesn't already exist. + private static File createTemporaryDirectory(String temporaryDirectoryPath) { + return ensureDirectoryExists(temporaryDirectoryPath + File.separator + "temp"); + } + + // Attempt to create a temporary file on disk whose name is passed in. + public static File createTemporaryFile(File temporaryDirectory, + String temporaryDirectoryPath, + String temporaryFileName, + String temporaryFileExtension) + { + ensureDirectoryExists(temporaryDirectoryPath); + + File temporaryFile; + + try { + temporaryFile = File.createTempFile("NWB-Session-" + temporaryFileName, + "." + temporaryFileExtension, + temporaryDirectory); + } + catch (IOException e) { + // We couldn't make the temporary file in the temporary directory + // using the standard Java File temporary file scheme (?), so we're + // coming up with our own temporary file (that we hope doesn't already + // exist). + temporaryFile = new File(temporaryDirectoryPath + File.separator + + temporaryFileName + "temp." + + temporaryFileExtension); + + if (!temporaryFile.exists()) { + try { + temporaryFile.createNewFile(); + } + catch (IOException e2) { + throw new RuntimeException(e2); + } + + temporaryFile.deleteOnExit(); + } + } + + return temporaryFile; + } + + // Attempt to create a temporary file on disk in a temporary directory (that may + // also be created, if necessary). + public static File createTemporaryFileInTemporaryDirectory + (String temporaryDirectoryPath, + String temporaryFileName, + String temporaryFileExtension) throws IOException + { + // Get/create the temporary directory. + File temporaryDirectory = createTemporaryDirectory(temporaryDirectoryPath); + + // Attempt to create the temporary file in our temporary directory now. + File temporaryFile = createTemporaryFile(temporaryDirectory, + temporaryDirectoryPath, + temporaryFileName, + temporaryFileExtension); + + // If the creation of the temporary file failed, throw an exception. + if (temporaryFile == null) { + throw new IOException + ("Failed to generate a file in the temporary directory."); + } + + return temporaryFile; + } + + public static String getDefaultTemporaryDirectory() { + return System.getProperty("java.io.tmpdir"); + } + + public static File createTemporaryFileInDefaultTemporaryDirectory + (String temporaryFileName, + String temporaryFileExtension) throws IOException + { + return createTemporaryFileInTemporaryDirectory + (getDefaultTemporaryDirectory(), + temporaryFileName, + temporaryFileExtension); + } + + public static File writeBufferedImageIntoTemporaryDirectory + (BufferedImage bufferedImage, + String imageType) throws IOException, Exception + { + // Get the system-wide temporary directory path. + String temporaryDirectoryPath = getDefaultTemporaryDirectory(); + File temporaryImageFile = + createTemporaryFileInTemporaryDirectory(temporaryDirectoryPath, + "nwb-temp", + imageType); + + // Attempt to write the image to the temporary file on disk. + if (!ImageIO.write(bufferedImage, imageType, temporaryImageFile)) { + throw new Exception + ("No valid image writer was found for the image type " + imageType); + } + + return temporaryImageFile; + } + + public static File writeTextIntoTemporaryDirectory(String text, + String fileExtension) + throws IOException, Exception + { + // Get the system-wide temporary directory path. + String temporaryDirectoryPath = getDefaultTemporaryDirectory(); + File temporaryTextFile = + createTemporaryFileInTemporaryDirectory(temporaryDirectoryPath, + "nwb-temp", + fileExtension); + + FileWriter textFileWriter = new FileWriter(temporaryTextFile); + + textFileWriter.write(text); + textFileWriter.flush(); + + return temporaryTextFile; + } + + private static File ensureDirectoryExists(String directoryPath) { + File directory = new File(directoryPath); + + if (!directory.exists()) { + directory.mkdir(); + directory.deleteOnExit(); + } + + return directory; + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/ImageUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ImageUtilities.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/ImageUtilities.java 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,27 @@ +package org.cishell.utilities; + +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; + +public class ImageUtilities { + // Constants. + private static final int TEMPORARY_IMAGE_WIDTH = 640; + private static final int TEMPORARY_IMAGE_HEIGHT = 480; + + public static BufferedImage createBufferedImageFilledWithColor + (Color fillColor) { + // Create the image (that we will fill and output). + BufferedImage bufferedImage = new BufferedImage(TEMPORARY_IMAGE_WIDTH, + TEMPORARY_IMAGE_HEIGHT, + BufferedImage.TYPE_INT_RGB); + + // Get the image's graphics context so we can paint to/fill the image. + Graphics2D bufferedImageGraphics2D = bufferedImage.createGraphics(); + + // Fill the image with the color passed in. + bufferedImageGraphics2D.setBackground(fillColor); + + return bufferedImage; + } +}; \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,25 @@ +package org.cishell.utilities; + +import java.util.ArrayList; +import java.util.Map; +import java.util.Set; + +public class MapUtilities { + public static String[] getValidKeysOfTypesInMap(Map map, + String[] types, + String[] keysToSkip, + String[] keysToAdd) + throws ColumnNotFoundException { + ArrayList workingKeys = new ArrayList(); + Set entrySet = map.entrySet(); + + for (String type : types) { + ArrayList keysForType = + SetUtilities.getKeysOfMapEntrySetWithValue(entrySet, type); + workingKeys = ArrayListUtilities.unionArrayLists( + workingKeys, keysForType, keysToSkip, keysToAdd); + } + + return (String[])workingKeys.toArray(new String[0]); + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,123 @@ +package org.cishell.utilities; + +import java.io.IOException; +import java.util.LinkedHashMap; + +import org.cishell.reference.service.metatype.BasicAttributeDefinition; +import org.cishell.reference.service.metatype.BasicObjectClassDefinition; +import org.osgi.service.metatype.AttributeDefinition; +import org.osgi.service.metatype.ObjectClassDefinition; + +import prefuse.data.Table; + +public class MutateParameterUtilities { + public static AttributeDefinition formLabelAttributeDefinition + (AttributeDefinition oldAttributeDefinition, Table table) + throws ColumnNotFoundException + { + String[] validStringColumnsInTable = + TableUtilities.getValidStringColumnNamesInTable(table); + + AttributeDefinition labelAttributeDefinition = + new BasicAttributeDefinition(oldAttributeDefinition.getID(), + oldAttributeDefinition.getName(), + oldAttributeDefinition.getDescription(), + AttributeDefinition.STRING, + validStringColumnsInTable, + validStringColumnsInTable); + + return labelAttributeDefinition; + } + + public static AttributeDefinition formDateAttributeDefinition + (AttributeDefinition oldAttributeDefinition, Table table) + throws ColumnNotFoundException + { + String[] validDateColumnsInTable = + TableUtilities.getValidDateColumnNamesInTable(table); + + AttributeDefinition dateAttributeDefinition = + new BasicAttributeDefinition(oldAttributeDefinition.getID(), + oldAttributeDefinition.getName(), + oldAttributeDefinition.getDescription(), + AttributeDefinition.STRING, + validDateColumnsInTable, + validDateColumnsInTable); + + return dateAttributeDefinition; + } + + public static AttributeDefinition formIntegerAttributeDefinition + (AttributeDefinition oldAttributeDefinition, Table table) + throws ColumnNotFoundException + { + String[] validIntegerColumnsInTable = + TableUtilities.getValidIntegerColumnNamesInTable(table); + + AttributeDefinition integerAttributeDefinition = + new BasicAttributeDefinition(oldAttributeDefinition.getID(), + oldAttributeDefinition.getName(), + oldAttributeDefinition.getDescription(), + AttributeDefinition.STRING, + validIntegerColumnsInTable, + validIntegerColumnsInTable); + + return integerAttributeDefinition; + } + + public static AttributeDefinition formNumberAttributeDefinition + (AttributeDefinition oldAttributeDefinition, Table table) + throws ColumnNotFoundException { + String[] validNumberColumnsInTable = + TableUtilities.getValidNumberColumnNamesInTable(table); + + AttributeDefinition numberAttributeDefinition = + new BasicAttributeDefinition(oldAttributeDefinition.getID(), + oldAttributeDefinition.getName(), + oldAttributeDefinition.getDescription(), + AttributeDefinition.STRING, + validNumberColumnsInTable, + validNumberColumnsInTable); + + return numberAttributeDefinition; + } + + public static AttributeDefinition formAttributeDefinitionFromMap + (AttributeDefinition oldAttributeDefinition, + LinkedHashMap map, + String[] types, + String[] keysToSkip, + String[] keysToAdd) { + String[] validNumberKeysInMap = + MapUtilities.getValidKeysOfTypesInMap( + map, types, keysToSkip, keysToAdd); + + AttributeDefinition numberAttributeDefinition = + new BasicAttributeDefinition( + oldAttributeDefinition.getID(), + oldAttributeDefinition.getName(), + oldAttributeDefinition.getDescription(), + AttributeDefinition.STRING, + validNumberKeysInMap, + validNumberKeysInMap); + + return numberAttributeDefinition; + } + + public static BasicObjectClassDefinition createNewParameters( + ObjectClassDefinition oldParameters) { + try { + return + new BasicObjectClassDefinition(oldParameters.getID(), + oldParameters.getName(), + oldParameters.getDescription(), + oldParameters.getIcon(16)); + } + catch (IOException e) { + return new BasicObjectClassDefinition + (oldParameters.getID(), + oldParameters.getName(), + oldParameters.getDescription(), null); + } + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/NumberUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/NumberUtilities.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/NumberUtilities.java 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,121 @@ +package org.cishell.utilities; + +public class NumberUtilities { + public static Double interpretObjectAsDouble(Object object) + throws NumberFormatException { + final String EMPTY_CELL_MESSAGE = "An empty number cell was found."; + + // TODO: These if's are a result of a "bug" in Prefuse's. + // CSV Table Reader, which interprets a column as being an array type + // if it has empty cells. + if (object instanceof Number) { + Number number = (Number)object; + + return new Double(number.doubleValue()); + } + else if (object instanceof short[]) { + short[] objectAsShortArray = (short[])object; + + if (objectAsShortArray.length == 0) { + throw new NumberFormatException(EMPTY_CELL_MESSAGE); + } + else { + return new Double((double)objectAsShortArray[0]); + } + } + else if (object instanceof Short[]) { + Short[] objectAsShortArray = (Short[])object; + + if (objectAsShortArray.length == 0) { + throw new NumberFormatException(EMPTY_CELL_MESSAGE); + } + else { + return objectAsShortArray[0].doubleValue(); + } + } + else if (object instanceof int[]) { + int[] objectAsIntArray = (int[])object; + + if (objectAsIntArray.length == 0) { + throw new NumberFormatException(EMPTY_CELL_MESSAGE); + } + else { + return new Double((double)objectAsIntArray[0]); + } + } + else if (object instanceof Integer[]) { + Integer[] objectAsIntegerArray = (Integer[])object; + + if (objectAsIntegerArray.length == 0) { + throw new NumberFormatException(EMPTY_CELL_MESSAGE); + } + else { + return objectAsIntegerArray[0].doubleValue(); + } + } + else if (object instanceof long[]) { + long[] objectAsLongArray = (long[])object; + + if (objectAsLongArray.length == 0) { + throw new NumberFormatException(EMPTY_CELL_MESSAGE); + } + else { + return new Double((double)objectAsLongArray[0]); + } + } + else if (object instanceof Long[]) { + Long[] objectAsLongArray = (Long[])object; + + if (objectAsLongArray.length == 0) { + throw new NumberFormatException(EMPTY_CELL_MESSAGE); + } + else { + return objectAsLongArray[0].doubleValue(); + } + } + else if (object instanceof float[]) { + float[] objectAsFloatArray = (float[])object; + + if (objectAsFloatArray.length == 0) { + throw new NumberFormatException(EMPTY_CELL_MESSAGE); + } + else { + return new Double((double)objectAsFloatArray[0]); + } + } + else if (object instanceof Float[]) { + Float[] objectAsFloatArray = (Float[])object; + + if (objectAsFloatArray.length == 0) { + throw new NumberFormatException(EMPTY_CELL_MESSAGE); + } + else { + return objectAsFloatArray[0].doubleValue(); + } + } + else if (object instanceof double[]) { + double[] objectAsDoubleArray = (double[])object; + + if (objectAsDoubleArray.length == 0) { + throw new NumberFormatException(EMPTY_CELL_MESSAGE); + } + else { + return new Double(objectAsDoubleArray[0]); + } + } + else if (object instanceof Double[]) { + Double[] objectAsDoubleArray = (Double[])object; + + if (objectAsDoubleArray.length == 0) { + throw new NumberFormatException(EMPTY_CELL_MESSAGE); + } + else { + return objectAsDoubleArray[0]; + } + } + + String objectAsString = object.toString(); + + return new Double(objectAsString); + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/SetUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/SetUtilities.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/SetUtilities.java 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,24 @@ +package org.cishell.utilities; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Map; +import java.util.Set; + +public class SetUtilities { + public static ArrayList getKeysOfMapEntrySetWithValue(Set mapEntrySet, + Object value) { + ArrayList keysOfMapEntrySetWithValue = new ArrayList(); + Iterator mapEntrySetIterator = mapEntrySet.iterator(); + + while (mapEntrySetIterator.hasNext()) { + Map.Entry entry = (Map.Entry)mapEntrySetIterator.next(); + + if (entry.getValue().equals(value)) { + keysOfMapEntrySetWithValue.add(entry.getKey()); + } + } + + return keysOfMapEntrySetWithValue; + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/StringUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/StringUtilities.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/StringUtilities.java 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,17 @@ +package org.cishell.utilities; + +public class StringUtilities { + public static String implodeStringArray(String[] stringArray, String separator) { + final int stringArrayLength = stringArray.length; + StringBuilder workingResultString = new StringBuilder(); + + for (int ii = 0; ii < stringArrayLength; ii++) { + workingResultString.append(stringArray[ii]); + if (ii != stringArrayLength - 1) { + workingResultString.append(separator); + } + } + + return workingResultString.toString(); + } +} Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/TableUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/TableUtilities.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/TableUtilities.java 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,241 @@ +package org.cishell.utilities; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import prefuse.data.Schema; +import prefuse.data.Table; +import prefuse.util.collections.IntIterator; + +public class TableUtilities { + public static String[] filterSchemaColumnNamesByClass + (Schema schema, Class objectClass) throws ColumnNotFoundException + { + ArrayList workingColumnNames = new ArrayList(); + + for (int ii = 0; ii < schema.getColumnCount(); ii++) { + if (objectClass.isAssignableFrom(schema.getColumnType(ii))) + workingColumnNames.add(schema.getColumnName(ii)); + } + + if (workingColumnNames.size() == 0) { + throw new ColumnNotFoundException + ("No column of type " + objectClass.getName() + " was found."); + } + + String[] finalColumnNames = new String [workingColumnNames.size()]; + + return (String[])workingColumnNames.toArray(finalColumnNames); + } + + public static List getAllColumnNames(Schema schema) + throws ColumnNotFoundException { + List workingColumnNames = new ArrayList(); + + for (int ii = 0; ii < schema.getColumnCount(); ii++) { + workingColumnNames.add(schema.getColumnName(ii)); + } + + if (workingColumnNames.size() == 0) { + throw new ColumnNotFoundException + ("No columns found in the schema."); + } + + return workingColumnNames; + } + + public static String formNonConflictingNewColumnName( + Schema schema, String suggestedColumnName) + throws ColumnNotFoundException { + List workingColumnNames = getAllColumnNames(schema); + + if(!workingColumnNames.contains(suggestedColumnName)) { + return suggestedColumnName; + } + else { + int columnNameSuffix = 1; + while(true) { + String newColumnName = + suggestedColumnName.concat("_" + columnNameSuffix); + if(!workingColumnNames.contains(newColumnName)) { + return newColumnName; + } + columnNameSuffix++; + } + } + } + + public static String[] filterSchemaColumnNamesByClasses + (Schema schema, Class[] objectClasses) throws ColumnNotFoundException + { + ArrayList workingColumnNames = new ArrayList(); + + for (int ii = 0; ii < schema.getColumnCount(); ii++) { + for (Class objectClass : objectClasses) { + if (objectClass.isAssignableFrom(schema.getColumnType(ii))) { + workingColumnNames.add(schema.getColumnName(ii)); + + break; + } + } + } + + if (workingColumnNames.size() > 0) { + String[] finalColumnNames = new String [workingColumnNames.size()]; + + return (String[])workingColumnNames.toArray(finalColumnNames); + } + // An exception is thrown if there is not at least 1 column name. + else { + StringBuffer objectClassesString = new StringBuffer(); + objectClassesString.append("["); + + for (int ii = 0; ii < objectClasses.length; ii++) { + objectClassesString.append(objectClasses[ii].getName()); + + if ((ii + 1) < objectClasses.length) { + objectClassesString.append(", "); + } + } + + objectClassesString.append("]"); + + throw new ColumnNotFoundException + ("No column of types " + objectClassesString + " was found."); + } + } + + public static String[] getValidStringColumnNamesInTable(Table table) + throws ColumnNotFoundException + { + return filterSchemaColumnNamesByClass(table.getSchema(), String.class); + } + + public static String[] getValidDateColumnNamesInTable(Table table) + throws ColumnNotFoundException + { + Class[] possibleDateClasses = { + Date.class, + int.class, + Integer.class, + String.class, + int[].class, + Integer[].class, + String[].class, + }; + + return filterSchemaColumnNamesByClasses(table.getSchema(), + possibleDateClasses); + } + + public static String[] getValidIntegerColumnNamesInTable(Table table) + throws ColumnNotFoundException + { + Class[] possibleIntegerClasses = { + int.class, + Integer.class, + int[].class, + Integer[].class + }; + + return filterSchemaColumnNamesByClasses(table.getSchema(), + possibleIntegerClasses); + } + + public static String[] getValidNumberColumnNamesInTable(Table table) + throws ColumnNotFoundException { + Class[] possibleNumberClasses = { + byte.class, + byte[].class, + Byte.class, + Byte[].class, + short.class, + short[].class, + Short.class, + Short[].class, + int.class, + int[].class, + Integer.class, + Integer[].class, + long.class, + long[].class, + Long.class, + Long[].class, + float.class, + float[].class, + Float.class, + Float[].class, + double.class, + double[].class, + Double.class, + Double[].class + }; + + return filterSchemaColumnNamesByClasses(table.getSchema(), + possibleNumberClasses); + } + + public static Table createTableUsingSchema(Schema tableSchema) { + final int numTableColumns = tableSchema.getColumnCount(); + Table table = new Table(); + + for (int ii = 0; ii < numTableColumns; ii++) { + table.addColumn(tableSchema.getColumnName(ii), + tableSchema.getColumnType(ii)); + } + + return table; + } + + public static void copyTableRow(int newTableRow, + int originalTableRow, + Table newTable, + Table originalTable) + { + final int numTableColumns = originalTable.getColumnCount(); + + for (int ii = 0; ii < numTableColumns; ii++) + newTable.set(newTableRow, ii, originalTable.get(originalTableRow, ii)); + } + + public static Table + copyNRowsFromTableUsingIntIterator(Table originalTable, + IntIterator iterator, + int topN, + boolean isDescending) + { + // TODO: Add a couple comments in this method + + Schema tableSchema = originalTable.getSchema(); + final int numTableRows = originalTable.getRowCount(); + Table newTable = createTableUsingSchema(tableSchema); + final int numRowsToCopy = Math.min(numTableRows, topN); + int[] originalTableRowsToCopy = new int [numTableRows]; + + newTable.addRows(numRowsToCopy); + + for (int ii = 0; ii < numTableRows; ii++) + originalTableRowsToCopy[ii] = iterator.nextInt(); + + // TODO: Comment the side-effects here + + if (!isDescending) { + for (int ii = 0; ii < numRowsToCopy; ii++) { + copyTableRow + (ii, originalTableRowsToCopy[ii], newTable, originalTable); + } + } + else { + for (int ii = 0; ii < numRowsToCopy; ii++) + { + copyTableRow(ii, + originalTableRowsToCopy[numTableRows - ii - 1], + newTable, + originalTable); + } + } + + return newTable; + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/tests/edu/iu/scipolicy/utilities/DateUtilitiesTest.java =================================================================== --- trunk/core/org.cishell.utilities/tests/edu/iu/scipolicy/utilities/DateUtilitiesTest.java (rev 0) +++ trunk/core/org.cishell.utilities/tests/edu/iu/scipolicy/utilities/DateUtilitiesTest.java 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,178 @@ +package edu.iu.scipolicy.utilities; + +import static org.junit.Assert.fail; + +import java.util.Date; + +import org.cishell.utilities.DateUtilities; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +public class DateUtilitiesTest { + @Before + public void setUp() throws Exception { + } + + @After + public void tearDown() throws Exception { + } + + @Test + public void testGenerateDaysBetweenSameDates() { + Date startDate = new Date(1984, 0, 1); + Date endDate = startDate; + + Date[] datesBetween = + DateUtilities.generateDaysBetweenDates(startDate, endDate); + + if ((datesBetween.length != 1) || (!datesBetween[0].equals(startDate))) + fail(); + } + + @Test + public void testGenerateDaysBetweenReversedDates() { + Date startDate = new Date(1984, 0, 2); + Date endDate = new Date(1984, 0, 1); + + Date[] datesBetween = + DateUtilities.generateDaysBetweenDates(startDate, endDate); + + if ((datesBetween == null) || (datesBetween.length != 0)) + fail(); + } + + @Test + public void testGenerateDaysBetweenDates() { + Date startDate = new Date(1984, 0, 1); + Date endDate = new Date(1984, 0, 25); + + Date[] datesBetween = + DateUtilities.generateDaysBetweenDates(startDate, endDate); + + if ((datesBetween == null) || (datesBetween.length == 0)) + fail(); + + for (int ii = 0; ii < datesBetween.length; ii++) { + int expectedDay = (ii + 1); + + if ((datesBetween[ii].getYear() != startDate.getYear()) || + (datesBetween[ii].getMonth() != startDate.getMonth()) || + (datesBetween[ii].getDate() != expectedDay)) + { + fail(); + } + } + } + + @Test + public void testCalculateDaysBetweenDateArray() { + Date startDate = new Date(1984, 0, 1); + Date endDate = new Date(1984, 0, 2); + Date[] dateArray = new Date[] { startDate, endDate }; + + if (DateUtilities.calculateDaysBetween(dateArray) != 2) + fail(); + } + + @Test + public void testCalculateDaysBetweenDateDate() { + Date startDate = new Date(1984, 0, 1); + Date endDate = new Date(1984, 0, 25); + + if (DateUtilities.calculateDaysBetween(startDate, endDate) != 24) + fail(); + } + + @Test + public void testCalculateMonthsBetween() { + Date startDate = new Date(1984, 0, 1); + Date endDate = new Date(1984, 1, 1); + + if (DateUtilities.calculateMonthsBetween(startDate, endDate) != 1) + fail(); + } + + @Test + public void testGetNewYearsDatesFromDateSet() { + Date startDate = new Date(1984, 0, 1); + Date endDate = new Date (2000, 2, 15); + + Date[] datesBetween = + DateUtilities.generateDaysBetweenDates(startDate, endDate); + + Date[] newYearsDates = + DateUtilities.getNewYearsDatesFromDateSet(datesBetween); + + for (int ii = 0; ii < newYearsDates.length; ii++) { + if ((newYearsDates[ii].getYear() != (1984 + ii)) || + (newYearsDates[ii].getMonth() != 0) || + (newYearsDates[ii].getDate() != 1)) + { + fail(); + } + } + } + + @Test + public void testGenerateNewYearsDatesBetweenDates() { + Date startDate = new Date(1984, 0, 1); + Date endDate = new Date(2000, 2, 15); + + Date[] newYearsDates = + DateUtilities.generateNewYearsDatesBetweenDates(startDate, endDate); + + for (int ii = 0; ii < newYearsDates.length; ii++) { + if ((newYearsDates[ii].getYear() != (1984 + ii)) || + (newYearsDates[ii].getMonth() != 0) || + (newYearsDates[ii].getDate() != 1)) + { + fail(); + } + } + } + + @Test + public void testGenerateFirstOfTheMonthDatesBetweenDatesDateDate() { + Date startDate = new Date(1984, 0, 1); + Date endDate = new Date(1984, 11, 31); + + Date[] datesBetween = + DateUtilities.generateDaysBetweenDates(startDate, endDate); + + Date[] firstOfTheMonthDates = + DateUtilities.generateFirstOfTheMonthDatesBetweenDates + (startDate, endDate); + + for (int ii = 0; ii < firstOfTheMonthDates.length; ii++) { + if ((firstOfTheMonthDates[ii].getYear() != startDate.getYear()) || + (firstOfTheMonthDates[ii].getMonth() != ii) || + (firstOfTheMonthDates[ii].getDate() != 1)) + { + fail(); + } + } + } + + @Test + public void testGenerateFirstOfTheMonthDatesBetweenDatesDateArray() { + Date startDate = new Date(1984, 0, 1); + Date endDate = new Date(1984, 11, 31); + + Date[] datesBetween = + DateUtilities.generateDaysBetweenDates(startDate, endDate); + + Date[] firstOfTheMonthDates = + DateUtilities.generateFirstOfTheMonthDatesBetweenDates + (datesBetween); + + for (int ii = 0; ii < firstOfTheMonthDates.length; ii++) { + if ((firstOfTheMonthDates[ii].getYear() != startDate.getYear()) || + (firstOfTheMonthDates[ii].getMonth() != ii) || + (firstOfTheMonthDates[ii].getDate() != 1)) + { + fail(); + } + } + } +} Added: trunk/core/org.cishell.utilities/tests/edu/iu/scipolicy/utilities/DefaultDictionaryTest.java =================================================================== --- trunk/core/org.cishell.utilities/tests/edu/iu/scipolicy/utilities/DefaultDictionaryTest.java (rev 0) +++ trunk/core/org.cishell.utilities/tests/edu/iu/scipolicy/utilities/DefaultDictionaryTest.java 2009-07-17 21:13:00 UTC (rev 886) @@ -0,0 +1,111 @@ +package edu.iu.s... [truncated message content] |