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] |
From: <pat...@us...> - 2009-07-17 21:26:08
|
Revision: 887 http://cishell.svn.sourceforge.net/cishell/?rev=887&view=rev Author: pataphil Date: 2009-07-17 21:25:53 +0000 (Fri, 17 Jul 2009) Log Message: ----------- Made 1.4-compliant. (Was 1.5.) Modified Paths: -------------- trunk/core/org.cishell.utilities/.classpath Removed Paths: ------------- trunk/core/org.cishell.utilities/tests/ Modified: trunk/core/org.cishell.utilities/.classpath =================================================================== --- trunk/core/org.cishell.utilities/.classpath 2009-07-17 21:13:00 UTC (rev 886) +++ trunk/core/org.cishell.utilities/.classpath 2009-07-17 21:25:53 UTC (rev 887) @@ -1,9 +1,7 @@ <?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.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/J2SE-1.4"/> <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> This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jrb...@us...> - 2009-07-24 17:46:39
|
Revision: 897 http://cishell.svn.sourceforge.net/cishell/?rev=897&view=rev Author: jrbibers Date: 2009-07-24 17:46:29 +0000 (Fri, 24 Jul 2009) Log Message: ----------- Added method to automate the common algorithm factory task of mutating a parameter in an object class definition to provide a dropdown list of options. Modified Paths: -------------- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java Modified: trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF =================================================================== --- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2009-07-24 17:44:30 UTC (rev 896) +++ trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2009-07-24 17:46:29 UTC (rev 897) @@ -15,4 +15,5 @@ prefuse.data.util, prefuse.util, prefuse.util.collections -Export-Package: org.cishell.utilities +Export-Package: org.cishell.utilities, + org.cishell.utilities.mutateParameter Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java 2009-07-24 17:44:30 UTC (rev 896) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java 2009-07-24 17:46:29 UTC (rev 897) @@ -3,107 +3,148 @@ import java.io.IOException; import java.util.LinkedHashMap; -import org.cishell.reference.service.metatype.BasicAttributeDefinition; import org.cishell.reference.service.metatype.BasicObjectClassDefinition; +import org.cishell.utilities.mutateParameter.AttributeDefinitionTransformer; +import org.cishell.utilities.mutateParameter.NullDropdownTransformer; +import org.cishell.utilities.mutateParameter.ObjectClassDefinitionTransformer; 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 - { + /* TODO The mutateParameter subpackage is meant to eliminate all of the loops + * that invoke the formFooAttributeDefinition methods. + */ + + 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); + cloneToDropdownAttributeDefinition(oldAttributeDefinition, + validStringColumnsInTable, + validStringColumnsInTable); return labelAttributeDefinition; } - public static AttributeDefinition formDateAttributeDefinition - (AttributeDefinition oldAttributeDefinition, Table table) - throws ColumnNotFoundException - { + 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); + cloneToDropdownAttributeDefinition(oldAttributeDefinition, + validDateColumnsInTable, + validDateColumnsInTable); return dateAttributeDefinition; } - public static AttributeDefinition formIntegerAttributeDefinition - (AttributeDefinition oldAttributeDefinition, Table table) - throws ColumnNotFoundException - { + 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); + cloneToDropdownAttributeDefinition(oldAttributeDefinition, + validIntegerColumnsInTable, + validIntegerColumnsInTable); return integerAttributeDefinition; } - public static AttributeDefinition formNumberAttributeDefinition - (AttributeDefinition oldAttributeDefinition, Table table) - throws ColumnNotFoundException { + 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); + cloneToDropdownAttributeDefinition(oldAttributeDefinition, + validNumberColumnsInTable, + validNumberColumnsInTable); return numberAttributeDefinition; } - public static AttributeDefinition formAttributeDefinitionFromMap - (AttributeDefinition oldAttributeDefinition, - LinkedHashMap map, - String[] types, - String[] keysToSkip, - String[] keysToAdd) { + // TODO: Change LinkedHashMap to Map? + 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); + cloneToDropdownAttributeDefinition(oldAttributeDefinition, + validNumberKeysInMap, + validNumberKeysInMap); return numberAttributeDefinition; } + public static AttributeDefinition cloneToDropdownAttributeDefinition( + AttributeDefinition oldAD, + final String[] optionLabels, + final String[] optionValues) { + AttributeDefinitionTransformer transformer = + new NullDropdownTransformer() { + public boolean shouldTransform(AttributeDefinition ad) { + return true; + } + + public String[] transformOptionLabels( + String[] oldOptionLabels) { + return optionLabels; + } + + public String[] transformOptionValues( + String[] oldOptionValues) { + return optionValues; + } + }; + + return transformer.transform(oldAD); + } + + /* Convenience method for a common mutation: + * Replacing a parameter (identified by its ID) with a dropdown list of + * options. + */ + public static BasicObjectClassDefinition mutateToDropdown( + ObjectClassDefinition oldOCD, + final String parameterID, + final String[] optionLabels, + final String[] optionValues) { + AttributeDefinitionTransformer dropdownTransformer = + new NullDropdownTransformer() { + public boolean shouldTransform(AttributeDefinition ad) { + return parameterID.equals(ad.getID()); + } + + public String[] transformOptionLabels( + String[] oldOptionLabels) { + return optionLabels; + } + public String[] transformOptionValues( + String[] oldOptionValues) { + return optionValues; + } + }; + + return ObjectClassDefinitionTransformer.apply(dropdownTransformer, + oldOCD); + } + public static BasicObjectClassDefinition createNewParameters( ObjectClassDefinition oldParameters) { try { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jrb...@us...> - 2009-08-03 16:41:46
|
Revision: 913 http://cishell.svn.sourceforge.net/cishell/?rev=913&view=rev Author: jrbibers Date: 2009-08-03 16:41:30 +0000 (Mon, 03 Aug 2009) Log Message: ----------- Added DropdownMutator. Use this class in the mutateParameters method of a ParameterMutator when you wish to replace some AttributeDefinition in an ObjectClassDefinition with a dropdown list of options, whose labels and values you supply. For an example usage, see edu.iu.scipolicy.visualization.geomaps.GeoMapsCirclesFactory.mutateParameters(Data[], ObjectClassDefinition). Modified Paths: -------------- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF trunk/core/org.cishell.utilities/src/org/cishell/utilities/AlgorithmUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/DefaultDictionary.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/NullDropdownTransformer.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java Added Paths: ----------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/DropdownMutator.java Modified: trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF =================================================================== --- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2009-08-03 16:33:43 UTC (rev 912) +++ trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2009-08-03 16:41:30 UTC (rev 913) @@ -4,7 +4,9 @@ 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", +Import-Package: org.cishell.framework;version="1.0.0", + org.cishell.framework.algorithm;version="1.0.0", + org.cishell.framework.data, org.cishell.reference.service.metatype, org.osgi.framework;version="1.4.0", org.osgi.service.metatype;version="1.1.0", Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/AlgorithmUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/AlgorithmUtilities.java 2009-08-03 16:33:43 UTC (rev 912) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/AlgorithmUtilities.java 2009-08-03 16:41:30 UTC (rev 913) @@ -1,6 +1,8 @@ package org.cishell.utilities; import org.cishell.framework.algorithm.AlgorithmFactory; +import org.cishell.framework.data.BasicData; +import org.cishell.framework.data.Data; import org.osgi.framework.BundleContext; import org.osgi.framework.InvalidSyntaxException; import org.osgi.framework.ServiceReference; @@ -45,4 +47,10 @@ return getAlgorithmFactoryByFilter(filter, bundleContext); } + + public static Data[] cloneSingletonData(Data[] data) { + return new Data[]{ new BasicData(data[0].getMetadata(), + data[0].getData(), + data[0].getFormat()) }; + } } \ No newline at end of file Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/DefaultDictionary.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/DefaultDictionary.java 2009-08-03 16:33:43 UTC (rev 912) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/DefaultDictionary.java 2009-08-03 16:41:30 UTC (rev 913) @@ -8,9 +8,8 @@ Object defaultValue; Dictionary wrappedDictionary; - public DefaultDictionary - (Object defaultValue, Dictionary wrappedDictionary) - { + public DefaultDictionary( + Object defaultValue, Dictionary wrappedDictionary) { this.defaultValue = defaultValue; this.wrappedDictionary = wrappedDictionary; } Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java 2009-08-03 16:33:43 UTC (rev 912) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java 2009-08-03 16:41:30 UTC (rev 913) @@ -74,8 +74,8 @@ // 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."); + throw new IOException( + "Failed to generate a file in the temporary directory."); } return temporaryFile; Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java 2009-08-03 16:33:43 UTC (rev 912) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java 2009-08-03 16:41:30 UTC (rev 913) @@ -1,6 +1,7 @@ package org.cishell.utilities; import java.io.IOException; +import java.util.Collection; import java.util.LinkedHashMap; import org.cishell.reference.service.metatype.BasicObjectClassDefinition; @@ -116,6 +117,17 @@ return transformer.transform(oldAD); } + public static BasicObjectClassDefinition mutateToDropdown( + ObjectClassDefinition oldOCD, + final String parameterID, + Collection optionLabels, + Collection optionValues) { + return mutateToDropdown(oldOCD, + parameterID, + (String[]) optionLabels.toArray(new String[0]), + (String[]) optionValues.toArray(new String[0])); + } + /* Convenience method for a common mutation: * Replacing a parameter (identified by its ID) with a dropdown list of * options. Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/DropdownMutator.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/DropdownMutator.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/DropdownMutator.java 2009-08-03 16:41:30 UTC (rev 913) @@ -0,0 +1,49 @@ +package org.cishell.utilities.mutateParameter; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import org.osgi.service.metatype.AttributeDefinition; +import org.osgi.service.metatype.ObjectClassDefinition; + +public class DropdownMutator { + private List transforms; + + public DropdownMutator() { + transforms = new ArrayList(); + } + + public void add(String id, Collection options) { + add(id, options, options); + } + + public void add(String id, Collection optionLabels, Collection optionValues) { + add(id, (String[]) optionLabels.toArray(new String[0]), (String[]) optionValues.toArray(new String[0])); + } + + public void add(String id, String[] options) { + add(id, options, options); + } + + public void add(final String id, final String[] optionLabels, final String[] optionValues) { + transforms.add( + new NullDropdownTransformer() { + public boolean shouldTransform(AttributeDefinition ad) { + return id.equals(ad.getID()); + } + + public String[] transformOptionLabels(String[] oldOptionLabels) { + return optionLabels; + } + + public String[] transformOptionValues(String[] oldOptionValues) { + return optionValues; + } + }); + } + + public ObjectClassDefinition mutate(ObjectClassDefinition ocd) { + return ObjectClassDefinitionTransformer.transform(ocd, transforms); + } +} Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/NullDropdownTransformer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/NullDropdownTransformer.java 2009-08-03 16:33:43 UTC (rev 912) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/NullDropdownTransformer.java 2009-08-03 16:41:30 UTC (rev 913) @@ -10,9 +10,7 @@ * transformOptionLabels, and transformOptionValues. */ public abstract class NullDropdownTransformer extends DropdownTransformer { - public boolean shouldTransform(AttributeDefinition ad) { - return false; - } + public abstract boolean shouldTransform(AttributeDefinition ad); public String transformID(String oldID) { return oldID; Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java 2009-08-03 16:33:43 UTC (rev 912) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java 2009-08-03 16:41:30 UTC (rev 913) @@ -36,9 +36,9 @@ /* Convenience method for batching transformations. * TODO Untested */ - public static BasicObjectClassDefinition transform( - BasicObjectClassDefinition oldOCD, List transformers) { - BasicObjectClassDefinition newOCD = oldOCD; + public static ObjectClassDefinition transform( + ObjectClassDefinition ocd, List transformers) { + ObjectClassDefinition newOCD = ocd; for ( Iterator it = transformers.iterator(); it.hasNext(); ) { AttributeDefinitionTransformer transformer = This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jrb...@us...> - 2009-10-13 17:58:04
|
Revision: 962 http://cishell.svn.sourceforge.net/cishell/?rev=962&view=rev Author: jrbibers Date: 2009-10-13 17:57:55 +0000 (Tue, 13 Oct 2009) Log Message: ----------- Corrected a design flaw in the mutateParameter utilities. To date, all parameters transformed using ObjectClassDefinitionTransformer have been uniformly written out with the attribute definition filter ObjectClassDefinition.REQUIRED. Now the transformer preserves each AttributeDefinition's original filter (currently one of ObjectClassDefinition.REQUIRED or ObjectClassDefinition.OPTIONAL, where this assumption is reflected in the constant ATOMIC_ATTRIBUTE_DEFINITION_FILTERS). This change should not alter the behavior of any plug-in currently depending on the mutateParameter utilities (since none, to my knowledge, have optional parameters). Modified Paths: -------------- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java Modified: trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF =================================================================== --- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2009-10-12 18:29:29 UTC (rev 961) +++ trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2009-10-13 17:57:55 UTC (rev 962) @@ -3,7 +3,7 @@ Bundle-Name: Utilities Plug-in Bundle-SymbolicName: org.cishell.utilities Bundle-Version: 1.0.0 -Bundle-RequiredExecutionEnvironment: J2SE-1.5 +Bundle-RequiredExecutionEnvironment: J2SE-1.4 Import-Package: org.cishell.framework;version="1.0.0", org.cishell.framework.algorithm;version="1.0.0", org.cishell.framework.data, Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java 2009-10-12 18:29:29 UTC (rev 961) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java 2009-10-13 17:57:55 UTC (rev 962) @@ -1,5 +1,7 @@ package org.cishell.utilities.mutateParameter; +import java.util.ArrayList; +import java.util.Collections; import java.util.Iterator; import java.util.List; @@ -9,10 +11,20 @@ import org.osgi.service.metatype.ObjectClassDefinition; public class ObjectClassDefinitionTransformer { - private static final int OUTGOING_ATTRIBUTES_FILTER = - ObjectClassDefinition.REQUIRED; - private static final int INCOMING_ATTRIBUTES_FILTER = - ObjectClassDefinition.ALL; + /** + * AttributeDefinition filters as described in ObjectClassDefinition. + * "Atomic" to exclude blanket filters like ObjectClassDefinition.ALL. + * @see ObjectClassDefinition#REQUIRED + * @see ObjectClassDefinition#OPTIONAL + * @see ObjectClassDefinition#ALL + */ + public static final List ATOMIC_ATTRIBUTE_DEFINITION_FILTERS; + static { + List l = new ArrayList(); + l.add(ObjectClassDefinition.REQUIRED); + l.add(ObjectClassDefinition.OPTIONAL); + ATOMIC_ATTRIBUTE_DEFINITION_FILTERS = Collections.unmodifiableList(l); + } /* Create newOCD from oldOCD by applying transformer * to each AttributeDefinition. @@ -23,12 +35,20 @@ BasicObjectClassDefinition newOCD = MutateParameterUtilities.createNewParameters(oldOCD); - AttributeDefinition[] oldADs = - oldOCD.getAttributeDefinitions(INCOMING_ATTRIBUTES_FILTER); - for (int ii = 0; ii < oldADs.length; ii++) { - newOCD.addAttributeDefinition( - OUTGOING_ATTRIBUTES_FILTER, - transformer.transform(oldADs[ii])); + // For each kind of AttributeDefinition filter .. + for (Iterator filterIt = ATOMIC_ATTRIBUTE_DEFINITION_FILTERS.iterator(); + filterIt.hasNext();) { + int filter = ((Integer) filterIt.next()).intValue(); + + // Grab all matching AttributeDefinitions and transform them. + AttributeDefinition[] oldADs = + oldOCD.getAttributeDefinitions(filter); + + for (int ii = 0; ii < oldADs.length; ii++) { + newOCD.addAttributeDefinition( + filter, + transformer.transform(oldADs[ii])); + } } return newOCD; @@ -42,6 +62,7 @@ for (Iterator it = transformers.iterator(); it.hasNext();) { AttributeDefinitionTransformer transformer = (AttributeDefinitionTransformer) it.next(); + newOCD = apply(transformer, newOCD); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jrb...@us...> - 2009-10-13 18:01:14
|
Revision: 963 http://cishell.svn.sourceforge.net/cishell/?rev=963&view=rev Author: jrbibers Date: 2009-10-13 18:01:02 +0000 (Tue, 13 Oct 2009) Log Message: ----------- Fixes previous commit: two missing Integer boxings due to my JDK compliance being set to 1.5 (out of sync with the execution environment 1.4). Modified Paths: -------------- trunk/core/org.cishell.utilities/.settings/org.eclipse.jdt.core.prefs trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/DropdownMutator.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java Modified: trunk/core/org.cishell.utilities/.settings/org.eclipse.jdt.core.prefs =================================================================== --- trunk/core/org.cishell.utilities/.settings/org.eclipse.jdt.core.prefs 2009-10-13 17:57:55 UTC (rev 962) +++ trunk/core/org.cishell.utilities/.settings/org.eclipse.jdt.core.prefs 2009-10-13 18:01:02 UTC (rev 963) @@ -1,7 +1,12 @@ -#Fri Jan 16 16:03:38 EST 2009 +#Tue Oct 13 13:58:27 EDT 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 +org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve +org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.debug.lineNumber=generate +org.eclipse.jdt.core.compiler.debug.localVariable=generate +org.eclipse.jdt.core.compiler.debug.sourceFile=generate +org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning +org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning +org.eclipse.jdt.core.compiler.source=1.3 Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/DropdownMutator.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/DropdownMutator.java 2009-10-13 17:57:55 UTC (rev 962) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/DropdownMutator.java 2009-10-13 18:01:02 UTC (rev 963) @@ -97,8 +97,8 @@ swappedList.add(listIt.next()); } - swappedList.set(0, (String) list.get(targetIndex)); - swappedList.set(targetIndex, (String) list.get(0)); + swappedList.set(0, list.get(targetIndex)); + swappedList.set(targetIndex, list.get(0)); return swappedList; } else { Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java 2009-10-13 17:57:55 UTC (rev 962) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java 2009-10-13 18:01:02 UTC (rev 963) @@ -21,8 +21,8 @@ public static final List ATOMIC_ATTRIBUTE_DEFINITION_FILTERS; static { List l = new ArrayList(); - l.add(ObjectClassDefinition.REQUIRED); - l.add(ObjectClassDefinition.OPTIONAL); + l.add(new Integer(ObjectClassDefinition.REQUIRED)); + l.add(new Integer(ObjectClassDefinition.OPTIONAL)); ATOMIC_ATTRIBUTE_DEFINITION_FILTERS = Collections.unmodifiableList(l); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fu...@us...> - 2010-01-21 20:31:35
|
Revision: 1020 http://cishell.svn.sourceforge.net/cishell/?rev=1020&view=rev Author: fugu13 Date: 2010-01-21 20:31:28 +0000 (Thu, 21 Jan 2010) Log Message: ----------- Add various database utilities. Modified Paths: -------------- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF trunk/core/org.cishell.utilities/src/org/cishell/utilities/DatabaseUtilities.java Added Paths: ----------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/Column.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ColumnPair.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/DatabaseTable.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ForeignKey.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ForeignKeyNameWithTable.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/InvalidRepresentationException.java Modified: trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF =================================================================== --- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-01-14 21:02:06 UTC (rev 1019) +++ trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-01-21 20:31:28 UTC (rev 1020) @@ -20,6 +20,7 @@ prefuse.util, prefuse.util.collections Export-Package: org.cishell.utilities, + org.cishell.utilities.database, org.cishell.utilities.mutateParameter, org.cishell.utilities.mutateParameter.defaultvalue, org.cishell.utilities.mutateParameter.dropdown, Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/DatabaseUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/DatabaseUtilities.java 2010-01-14 21:02:06 UTC (rev 1019) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/DatabaseUtilities.java 2010-01-21 20:31:28 UTC (rev 1020) @@ -2,12 +2,18 @@ import java.sql.Connection; import java.sql.SQLException; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import org.cishell.framework.algorithm.AlgorithmExecutionException; import org.cishell.service.database.Database; public class DatabaseUtilities { public static void closeConnectionQuietly(Connection connection) { + if(connection == null) { + return; + } try { connection.close(); } catch (SQLException e) { @@ -25,4 +31,38 @@ } return connection; } + + public static String getInExpression(List<String> columns, List<Map<String, Object>> valueMaps) { + String columnNames = implodeAndWrap(columns); + + List<String> values = new ArrayList<String>(); + for(Map<String, Object> oldValues : valueMaps) { + List<String> rowValues = new ArrayList<String>(); + for(String column : columns) { + rowValues.add(formatValue(oldValues.get(column))); + } + values.add(implodeAndWrap(rowValues)); + } + String columnValues = implodeAndWrap(values); + + + //first make part with column names + //then make part with groups of column values + return columnNames + " IN " + columnValues; + } + + //TODO: expand this to other sorts of SQL datatypes (per their Prefuse table equivalents) + public static String formatValue(Object value) { + if(value == null) { + return "NULL"; + } else if(value instanceof Number) { + return value.toString(); + } else { + return "'" + value.toString() + "'"; + } + } + + public static String implodeAndWrap(List<String> values) { + return "(" + StringUtilities.implodeList(values, ", ") + ")"; + } } Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/Column.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/Column.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/Column.java 2010-01-21 20:31:28 UTC (rev 1020) @@ -0,0 +1,55 @@ +package org.cishell.utilities.database; + +import java.sql.Types; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +public class Column { + + public final String name; + public final int type; + public final int size; + + public static final Map<Integer, String> TYPE_MAP = constructTypeMap(); + public static final Set<Integer> SIZED_TYPES = constructSizedTypes(); + + private static Map<Integer, String> constructTypeMap() { //if this ever gets derby specific, it shouldn't go here + Map<Integer, String> typeMap = new HashMap<Integer, String>() {{ + put(Types.CHAR, "char"); + put(Types.DATE, "date"); + put(Types.DOUBLE, "double"); + put(Types.FLOAT, "float"); + put(Types.INTEGER, "integer"); + put(Types.SMALLINT, "smallint"); + put(Types.TIME, "time"); + put(Types.VARCHAR, "varchar"); + }}; + return Collections.unmodifiableMap(typeMap); + } + + private static Set<Integer> constructSizedTypes() { + Set<Integer> sizedTypes = new HashSet<Integer>() {{ + add(Types.CHAR); + add(Types.VARCHAR); + + }}; + return null; + } + + public Column(String name, int type, int size) { + this.name = name; + this.type = type; + this.size = size; + } + + + + public String getDefinition() { + // TODO Auto-generated method stub + return null; + } + +} Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ColumnPair.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ColumnPair.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ColumnPair.java 2010-01-21 20:31:28 UTC (rev 1020) @@ -0,0 +1,23 @@ +package org.cishell.utilities.database; + +public final class ColumnPair { + public final String local; + public final String foreign; + + public ColumnPair(String local, String foreign) { + this.local = local; + this.foreign = foreign; + } + + public boolean equals(Object other) { + if(!(other instanceof ColumnPair)) { + return false; + } + ColumnPair o = (ColumnPair) other; + return o.local.equals(this.local) && o.foreign.equals(this.foreign); + } + + public int hashCode() { + return local.hashCode() * 31 + foreign.hashCode(); + } +} Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/DatabaseTable.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/DatabaseTable.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/DatabaseTable.java 2010-01-21 20:31:28 UTC (rev 1020) @@ -0,0 +1,193 @@ +package org.cishell.utilities.database; + +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.cishell.utilities.DatabaseUtilities; + +public final class DatabaseTable { + public final String catalog; + public final String schema; + public final String name; + + public DatabaseTable(String catalog, String schema, String name) { + this.catalog = catalog == null ? "" : catalog.intern(); + this.schema = schema == null ? "" : schema.intern(); + this.name = name == null ? "" : name.intern(); + } + + public static DatabaseTable fromRepresentation(String representation) throws InvalidRepresentationException { + String[] parts = representation.split("\\."); + switch(parts.length) { + case 1: + return new DatabaseTable(null, null, parts[0]); + case 2: + return new DatabaseTable(null, parts[0], parts[1]); + case 3: + return new DatabaseTable(parts[0], parts[1], parts[2]); + default: + throw new InvalidRepresentationException("The representation '" + representation + "' has the wrong number of parts!"); + } + } + + public static DatabaseTable[] availableTables(Connection connection) throws SQLException { + ResultSet results = connection.getMetaData().getTables(null, null, null, new String[]{"TABLE"}); + + List<DatabaseTable> tables = new ArrayList<DatabaseTable>(); + while(results.next()) { + tables.add(new DatabaseTable(results.getString(1), results.getString(2), results.getString(3))); + } + + results.close(); + + return tables.toArray(new DatabaseTable[]{}); + } + + public String toString() { + StringBuilder output = new StringBuilder(); + if(catalog != null && catalog != "") { + output.append(catalog); + output.append('.'); + } + if(schema != null && schema != "") { + output.append(schema); + output.append('.'); + } + + output.append(name); + + return output.toString(); + } + + public boolean equals(Object other) { + if(!(other instanceof DatabaseTable)) { + return false; + } + DatabaseTable o = (DatabaseTable) other; + return o.catalog == this.catalog && o.schema == this.schema && o.name == this.name; + } + + + public int hashCode() { + int hash = catalog.hashCode() * 7; + hash += schema.hashCode() * 5; + hash += name.hashCode() * 3; + return hash; + + } + + public boolean presentInDatabase(Connection connection) throws SQLException { + ResultSet results = connection.getMetaData().getTables(catalog, schema, name, new String[]{"TABLE"}); + boolean foundOne = results.next(); + results.close(); + return foundOne; + } + + public boolean hasPrimaryKey(Connection connection) throws SQLException { + return getPrimaryKeyColumns(connection).length != 0; + } + + public ForeignKey[] getRelations(Connection connection) throws SQLException { + ResultSet related = connection.getMetaData().getExportedKeys(catalog, schema, name); + Map<ForeignKeyNameWithTable, Set<ColumnPair>> correspondences = new HashMap<ForeignKeyNameWithTable, Set<ColumnPair>>(); + while(related.next()) { + String foreignKeyName = related.getString(12); + DatabaseTable relatedTable = new DatabaseTable(related.getString(5), related.getString(6), related.getString(7)); + ForeignKeyNameWithTable key = new ForeignKeyNameWithTable(foreignKeyName, relatedTable); + ColumnPair pair = new ColumnPair(related.getString(4), related.getString(8)); + if(!correspondences.containsKey(key)) { + correspondences.put(key, new HashSet<ColumnPair>()); + } + correspondences.get(key).add(pair); + } + + related.close(); + + return makeForeignKeys(correspondences); + } + + private ForeignKey[] makeForeignKeys( + Map<ForeignKeyNameWithTable, Set<ColumnPair>> correspondences) { + ForeignKey[] foreignKeys = new ForeignKey[correspondences.size()]; + int index = 0; + for(Map.Entry<ForeignKeyNameWithTable, Set<ColumnPair>> entry : correspondences.entrySet()) { + foreignKeys[index] = new ForeignKey(this, entry.getKey().table, entry.getValue()); + index++; + } + return foreignKeys; + } + + public String[] getPrimaryKeyColumns(Connection connection) throws SQLException { + ResultSet columns = connection.getMetaData().getPrimaryKeys(catalog, schema, name); + List<String> columnNames = new ArrayList<String>(); + while(columns.next()) { + columnNames.add(columns.getString(4)); + } + return columnNames.toArray(new String[]{}); + } + + public void deleteRowsByColumns(List<Map<String, Object>> otherEntities, Connection connection) throws SQLException { + if(otherEntities.size() == 0) { + return; + } + List<String> columns = new ArrayList<String>(otherEntities.get(0).keySet()); + String deleteStatement = constructDeleteStatement(columns, otherEntities); + connection.createStatement().executeUpdate(deleteStatement); + } + + private String constructDeleteStatement(List<String> columns, + List<Map<String, Object>> otherEntities) { + return "DELETE FROM " + this.toString() + " WHERE " + DatabaseUtilities.getInExpression(columns, otherEntities); + } + + public void duplicateTable(Connection originalConnection, + Connection newConnection) throws SQLException { + this.duplicateTableStructure(originalConnection, newConnection); + //TODO: finish + + } + + public void duplicateTableStructure(Connection originalConnection, + Connection newConnection) throws SQLException { + Column[] columns = getColumns(originalConnection); + String createStatement = createCreateStatement(columns); + newConnection.createStatement().executeUpdate(createStatement); + } + + private String createCreateStatement(Column[] columns) { + List<String> definitions = new ArrayList<String>(); + for(int ii = 0; ii < columns.length; ii++) { + definitions.add(columns[ii].getDefinition()); + } + return "CREATE TABLE " + this.toString() + DatabaseUtilities.implodeAndWrap(definitions); + } + + private Column[] getColumns(Connection connection) throws SQLException { + ResultSet results = connection.getMetaData().getColumns(this.catalog, this.schema, this.name, null); + List<Column> columns = new ArrayList<Column>(); + while(results.next()) { + columns.add(new Column(results.getString(4), results.getInt(5), results.getInt(7))); + } + return columns.toArray(new Column[]{}); + } + + public void transferPrimaryKey(Connection originalConnection, + Connection newConnection) { + // TODO Auto-generated method stub + + } + + public void pointForeignKeys(Connection originalConnection, + Connection newConnection) { + // TODO Auto-generated method stub + + } +} Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ForeignKey.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ForeignKey.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ForeignKey.java 2010-01-21 20:31:28 UTC (rev 1020) @@ -0,0 +1,82 @@ +package org.cishell.utilities.database; + +import java.sql.Connection; +import java.sql.SQLException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.cishell.utilities.DatabaseUtilities; +import org.cishell.utilities.StringUtilities; + +public final class ForeignKey { + + final public DatabaseTable localTable; + final public DatabaseTable otherTable; + final public Set<ColumnPair> pairs; + + public ForeignKey(DatabaseTable localTable, DatabaseTable otherTable, Set<ColumnPair> pairs) { + this.localTable = localTable; + this.otherTable = otherTable; + this.pairs = Collections.unmodifiableSet(pairs); + } + + public void repoint(List<Map<String, Object>> from, + Map<String, Object> to, Connection connection) throws SQLException { + + String updateQuery = constructUpdateQuery(from, to); + //TODO: remove + System.err.println("Issuing update: " + updateQuery); + connection.createStatement().executeUpdate(updateQuery); + + } + + private String constructUpdateQuery(List<Map<String, Object>> from, + Map<String, Object> to) { + return "UPDATE " + otherTable.toString() + " SET "+ formatUpdates(to) + " WHERE " + + DatabaseUtilities.getInExpression(getForeignColumnNames(), translateToForeignNames(from)); + } + + + + private List<Map<String, Object>> translateToForeignNames( + List<Map<String, Object>> from) { + List<Map<String, Object>> output = new ArrayList<Map<String, Object>>(); + for(Map<String, Object> fromValues : from) { + Map<String, Object> toValues = new HashMap<String, Object>(); + for(ColumnPair pair : pairs) { + toValues.put(pair.foreign, fromValues.get(pair.local)); + } + output.add(toValues); + } + + + return output; + } + + private List<String> getForeignColumnNames() { + List<String> foreignColumns = new ArrayList<String>(); + for(ColumnPair pair : pairs) { + foreignColumns.add(pair.foreign); + } + return foreignColumns; + } + + + + private String formatUpdates(Map<String, Object> to) { + List<String> updateStatements = new ArrayList<String>(); + for(ColumnPair pair : pairs) { + String foreignColumn = pair.foreign; + Object newValue = to.get(pair.local); + updateStatements.add(foreignColumn + " = " + DatabaseUtilities.formatValue(newValue)); + } + return StringUtilities.implodeList(updateStatements, ", "); + } + + + +} Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ForeignKeyNameWithTable.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ForeignKeyNameWithTable.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ForeignKeyNameWithTable.java 2010-01-21 20:31:28 UTC (rev 1020) @@ -0,0 +1,23 @@ +package org.cishell.utilities.database; + +public final class ForeignKeyNameWithTable { + public final String name; + public final DatabaseTable table; + + public ForeignKeyNameWithTable(String name, DatabaseTable table) { + this.name = name; + this.table = table; + } + + public boolean equals(Object other) { + if(!(other instanceof ForeignKeyNameWithTable)) { + return false; + } + ForeignKeyNameWithTable o = (ForeignKeyNameWithTable) other; + return o.name.equals(this.name) && o.table.equals(this.table); + } + + public int hashCode() { + return name.hashCode() * 31 + table.hashCode(); + } +} Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/InvalidRepresentationException.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/InvalidRepresentationException.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/InvalidRepresentationException.java 2010-01-21 20:31:28 UTC (rev 1020) @@ -0,0 +1,14 @@ +package org.cishell.utilities.database; + +public class InvalidRepresentationException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 1L; + + public InvalidRepresentationException(String message) { + super(message); + } + +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pat...@us...> - 2010-01-25 16:58:14
|
Revision: 1021 http://cishell.svn.sourceforge.net/cishell/?rev=1021&view=rev Author: pataphil Date: 2010-01-25 16:57:58 +0000 (Mon, 25 Jan 2010) Log Message: ----------- * Added TableUtilities.allAreNull() and TableUtilities.allAreNotNull(). * Added the package org.cishell.utilities.dictionary. * Did some refactoring in StringUtilities. * Added various utilities in StringUtilities. * Reviewed by Joseph. Modified Paths: -------------- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/IntegerParserWithDefault.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/StringUtilities.java Added Paths: ----------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/Pair.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/dictionary/ trunk/core/org.cishell.utilities/src/org/cishell/utilities/dictionary/DictionaryEntry.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/dictionary/DictionaryIterator.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/dictionary/DictionaryUtilities.java Modified: trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF =================================================================== --- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-01-21 20:31:28 UTC (rev 1020) +++ trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-01-25 16:57:58 UTC (rev 1021) @@ -19,8 +19,9 @@ prefuse.data.util, prefuse.util, prefuse.util.collections -Export-Package: org.cishell.utilities, - org.cishell.utilities.database, +Export-Package: org.cishell.utilities, + org.cishell.utilities.dictionary, + org.cishell.utilities.database, org.cishell.utilities.mutateParameter, org.cishell.utilities.mutateParameter.defaultvalue, org.cishell.utilities.mutateParameter.dropdown, Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayUtilities.java 2010-01-21 20:31:28 UTC (rev 1020) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayUtilities.java 2010-01-25 16:57:58 UTC (rev 1021) @@ -42,4 +42,26 @@ return clone; } + + // TODO: Find a better place to put this? + public static <T> boolean allAreNull(T... objects) { + for (T object : objects) { + if (object != null) { + return false; + } + } + + return true; + } + + // TODO: Find a better place to put this? + public static <T> boolean allAreNotNull(T... objects) { + for (T object : objects) { + if (object == null) { + return false; + } + } + + return true; + } } Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/IntegerParserWithDefault.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/IntegerParserWithDefault.java 2010-01-21 20:31:28 UTC (rev 1020) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/IntegerParserWithDefault.java 2010-01-25 16:57:58 UTC (rev 1021) @@ -1,9 +1,9 @@ package org.cishell.utilities; public class IntegerParserWithDefault { - public static final int DEFAULT = -1; + public static final Integer DEFAULT = null; - public static int parse(String target) { + public static Integer parse(String target) { try { return Integer.parseInt(target); } catch (Exception e) { Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/Pair.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/Pair.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/Pair.java 2010-01-25 16:57:58 UTC (rev 1021) @@ -0,0 +1,19 @@ +package org.cishell.utilities; + +public class Pair<S, T> { + S firstObject; + T secondObject; + + public Pair(S firstObject, T secondObject) { + this.firstObject = firstObject; + this.secondObject = secondObject; + } + + public S getFirstObject() { + return this.firstObject; + } + + public T getSecondObject() { + return this.secondObject; + } +} \ No newline at end of file Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/StringUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/StringUtilities.java 2010-01-21 20:31:28 UTC (rev 1020) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/StringUtilities.java 2010-01-25 16:57:58 UTC (rev 1021) @@ -93,21 +93,59 @@ } // TODO Think about instead using a Pattern, "\s*". Don't have to though. - public static boolean isEmptyOrWhiteSpace(String test) { - String trimmed = test.trim(); + public static boolean isEmptyOrWhitespace(String string) { + String trimmed = string.trim(); return (trimmed.length() == 0); } - public static boolean allAreEmptyOrWhiteSpace(String... tests) { - for (String test : tests) { - if (!isEmptyOrWhiteSpace(test)) { + public static boolean allAreEmptyOrWhitespace(String... strings) { + for (String string : strings) { + if (!isEmptyOrWhitespace(string)) { return false; } } return true; } + + public static boolean allAreNeitherEmptyNorWhitespace(String... strings) { + for (String string : strings) { + if (isEmptyOrWhitespace(string)) { + return false; + } + } + + return true; + } + + public static boolean isNull_Empty_OrWhitespace(String string) { + if (string == null) { + return true; + } + + return isEmptyOrWhitespace(string); + } + + public static boolean allAreNull_Empty_OrWhitespace(String... strings) { + for (String string : strings) { + if (!isNull_Empty_OrWhitespace(string)) { + return false; + } + } + + return true; + } + + public static boolean allAreNeitherNullNorEmptyNorWhitespace(String... strings) { + for (String string : strings) { + if (isNull_Empty_OrWhitespace(string)) { + return false; + } + } + + return true; + } public static int countOccurrencesOfChar( CharSequence characters, char target) { @@ -167,6 +205,14 @@ return (String[])cleanedStrings.toArray(new String[0]); } + public static String trimIfNotNull(String string) { + if (string == null) { + return null; + } + + return string.trim(); + } + public static String toSentenceCase(String word) { String cleanedWord = simpleClean(word); @@ -193,18 +239,25 @@ return -1; } - public static boolean validAndEquivalent(String string1, String string2) { - return (!isEmptyOrWhiteSpace(string1) && (string1.compareTo(string2) == 0)); + /* TODO Perhaps make a "hasContent" method in here and apply that terminology throughout. */ + public static boolean areValidAndEqual(String string1, String string2) { + return ( + !isNull_Empty_OrWhitespace(string1) && + !isNull_Empty_OrWhitespace(string2) && + (string1.equals(string2))); } - public static boolean validAndEquivalentIgnoreCase(String string1, String string2) { - return (!isEmptyOrWhiteSpace(string1) && (string1.compareToIgnoreCase(string2) == 0)); + public static boolean areValidAndEqualIgnoreCase(String string1, String string2) { + return ( + !isNull_Empty_OrWhitespace(string1) && + !isNull_Empty_OrWhitespace(string2) && + string1.equalsIgnoreCase(string2)); } // TODO: New Name. public static String simpleMerge(String string1, String string2) { - if (!isEmptyOrWhiteSpace(string1)) { - if (!isEmptyOrWhiteSpace(string2)) { + if (!isNull_Empty_OrWhitespace(string1)) { + if (!isNull_Empty_OrWhitespace(string2)) { if (string1.length() >= string2.length()) { return string1; } else { @@ -214,7 +267,7 @@ return string1; } } - else if (!isEmptyOrWhiteSpace(string2)) { + else if (!isNull_Empty_OrWhitespace(string2)) { return string2; } Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/dictionary/DictionaryEntry.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/dictionary/DictionaryEntry.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/dictionary/DictionaryEntry.java 2010-01-25 16:57:58 UTC (rev 1021) @@ -0,0 +1,19 @@ +package org.cishell.utilities.dictionary; + +public class DictionaryEntry<K, V> { + private K key; + private V value; + + public DictionaryEntry(K key, V value) { + this.key = key; + this.value = value; + } + + public K getKey() { + return this.key; + } + + public V getValue() { + return this.value; + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/dictionary/DictionaryIterator.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/dictionary/DictionaryIterator.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/dictionary/DictionaryIterator.java 2010-01-25 16:57:58 UTC (rev 1021) @@ -0,0 +1,37 @@ +package org.cishell.utilities.dictionary; + +import java.util.Dictionary; +import java.util.Enumeration; +import java.util.Iterator; + +public class DictionaryIterator<K, V> + implements Iterator<DictionaryEntry<K, V>>, Iterable<DictionaryEntry<K, V>> { + private Dictionary<K, V> dictionary; + Enumeration<K> keys; + + public DictionaryIterator(Dictionary<K, V> dictionary) { + this.dictionary = dictionary; + this.keys = dictionary.keys(); + } + + public boolean hasNext() { + return this.keys.hasMoreElements(); + } + + public DictionaryEntry<K, V> next() { + K nextKey = this.keys.nextElement(); + V nextValue = this.dictionary.get(nextKey); + + return new DictionaryEntry<K, V>(nextKey, nextValue); + } + + public void remove() { + String exceptionMessage = "remove() cannot be called on a DictionaryIterator."; + + throw new UnsupportedOperationException(exceptionMessage); + } + + public Iterator<DictionaryEntry<K, V>> iterator() { + return this; + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/dictionary/DictionaryUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/dictionary/DictionaryUtilities.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/dictionary/DictionaryUtilities.java 2010-01-25 16:57:58 UTC (rev 1021) @@ -0,0 +1,41 @@ +package org.cishell.utilities.dictionary; + +import java.util.Dictionary; +import java.util.Hashtable; + +public class DictionaryUtilities { + /// Side-effects the provided Dictionary. + public static <K, V> void addIfNotNull(Dictionary<K, V> dictionary, K key, V value) { + if ((key != null) && (value != null)) { + dictionary.put(key, value); + } + } + + /// Side-effects the provided Dictionary. + public static <K, V> void addIfNotNull( + Dictionary<K, V> dictionary, DictionaryEntry<K, V>... entries) { + for (DictionaryEntry<K, V> entry : entries) { + addIfNotNull(dictionary, entry.getKey(), entry.getValue()); + } + } + + public static <K, V> Dictionary<K, V> copyWithValuesThatAreNotNull( + Dictionary<K, V> originalDictionary, DictionaryEntry<K, V>... entries) { + Dictionary<K, V> newDictionary = copy(originalDictionary); + + addIfNotNull(newDictionary, entries); + + return newDictionary; + } + + public static <K, V> Dictionary<K, V> copy(Dictionary<K, V> originalDictionary) { + Dictionary<K, V> newDictionary = new Hashtable<K, V>(); + + for (DictionaryEntry<K, V> originalEntry : + new DictionaryIterator<K, V>(originalDictionary)) { + newDictionary.put(originalEntry.getKey(), originalEntry.getValue()); + } + + return newDictionary; + } +} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fu...@us...> - 2010-02-18 00:09:55
|
Revision: 1038 http://cishell.svn.sourceforge.net/cishell/?rev=1038&view=rev Author: fugu13 Date: 2010-02-18 00:09:49 +0000 (Thu, 18 Feb 2010) Log Message: ----------- Made merging faster. Made merging progresstrackable. Reviewed by Joseph. Modified Paths: -------------- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ColumnPair.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/DatabaseTable.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ForeignKey.java Added Paths: ----------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/Remover.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/Repointer.java Modified: trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF =================================================================== --- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-02-17 23:25:26 UTC (rev 1037) +++ trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-02-18 00:09:49 UTC (rev 1038) @@ -4,7 +4,10 @@ Bundle-SymbolicName: org.cishell.utilities Bundle-Version: 1.0.0 Bundle-RequiredExecutionEnvironment: J2SE-1.5 -Import-Package: org.cishell.framework;version="1.0.0", +Import-Package: com.google.common.annotations, + com.google.common.base, + com.google.common.collect, + org.cishell.framework;version="1.0.0", org.cishell.framework.algorithm;version="1.0.0", org.cishell.framework.data, org.cishell.reference.service.metatype, Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ColumnPair.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ColumnPair.java 2010-02-17 23:25:26 UTC (rev 1037) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ColumnPair.java 2010-02-18 00:09:49 UTC (rev 1038) @@ -20,4 +20,5 @@ public int hashCode() { return local.hashCode() * 31 + foreign.hashCode(); } + } Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/DatabaseTable.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/DatabaseTable.java 2010-02-17 23:25:26 UTC (rev 1037) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/DatabaseTable.java 2010-02-18 00:09:49 UTC (rev 1038) @@ -1,6 +1,7 @@ package org.cishell.utilities.database; import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; @@ -10,9 +11,15 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.SortedSet; import org.cishell.utilities.DatabaseUtilities; +import org.cishell.utilities.StringUtilities; +import com.google.common.collect.ImmutableSortedMap; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; + public final class DatabaseTable { public final String catalog; public final String schema; @@ -147,4 +154,37 @@ List<Map<String, Object>> otherEntities) { return "DELETE FROM " + this.toString() + " WHERE " + DatabaseUtilities.createSQLInExpression(columns, otherEntities); } + + private String formatDeleteEquals(Connection connection, String separator) throws SQLException { + //sorting is necessary to ensure keys and values match up + SortedSet<String> keys = Sets.newTreeSet(); + String[] primaryKeys = getPrimaryKeyColumns(connection); + for(String key : primaryKeys) { + keys.add(key + " = ?"); + } + return StringUtilities.implodeList(Lists.newArrayList(keys), separator); + } + + public Remover constructRemover(Connection connection) throws SQLException { + String deleteSql = "DELETE FROM " + this.toString() + " WHERE " + formatDeleteEquals(connection, " AND "); + final PreparedStatement statement = connection.prepareStatement(deleteSql); + return new Remover() { + public void remove(Map<String, Object> values) throws SQLException { + int index = 1; + for(Object value : ImmutableSortedMap.copyOf(values).values()) { + statement.setObject(index, value); + index++; + } + statement.addBatch(); + } + public int apply() throws SQLException { + int removed = 0; + int[] updates = statement.executeBatch(); + for(int ii = 0; ii < updates.length; ii++) { + removed += updates[ii]; + } + return removed; + } + }; + } } Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ForeignKey.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ForeignKey.java 2010-02-17 23:25:26 UTC (rev 1037) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ForeignKey.java 2010-02-18 00:09:49 UTC (rev 1038) @@ -1,17 +1,22 @@ package org.cishell.utilities.database; +import java.sql.Connection; +import java.sql.PreparedStatement; import java.sql.SQLException; -import java.sql.Statement; import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.SortedMap; +import java.util.SortedSet; -import org.cishell.utilities.DatabaseUtilities; import org.cishell.utilities.StringUtilities; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; + public final class ForeignKey { final public DatabaseTable localTable; @@ -21,38 +26,20 @@ public ForeignKey(DatabaseTable localTable, DatabaseTable otherTable, Set<ColumnPair> pairs) { this.localTable = localTable; this.otherTable = otherTable; - this.pairs = Collections.unmodifiableSet(pairs); + this.pairs = ImmutableSet.copyOf(pairs); } - public void repoint(List<Map<String, Object>> from, - Map<String, Object> to, Statement statement) throws SQLException { - - String updateQuery = constructUpdateQuery(from, to); - statement.addBatch(updateQuery); - - } - - private String constructUpdateQuery(List<Map<String, Object>> from, - Map<String, Object> to) { - return "UPDATE " + otherTable.toString() + " SET "+ formatUpdates(to) + " WHERE " - + DatabaseUtilities.createSQLInExpression(getForeignColumnNames(), translateToForeignNames(from)); - } - - private List<Map<String, Object>> translateToForeignNames( - List<Map<String, Object>> from) { - List<Map<String, Object>> output = new ArrayList<Map<String, Object>>(); - for(Map<String, Object> fromValues : from) { - Map<String, Object> toValues = new HashMap<String, Object>(); - for(ColumnPair pair : pairs) { - toValues.put(pair.foreign, fromValues.get(pair.local)); - } - output.add(toValues); - } + private Map<String, Object> translateToForeignNames( + Map<String, Object> from) { + //sorting is necessary to ensure keys and values match up + SortedMap<String, Object> to = Maps.newTreeMap(); + for(ColumnPair pair : pairs) { + to.put(pair.foreign, from.get(pair.local)); + } - - return output; + return to; } private List<String> getForeignColumnNames() { @@ -65,15 +52,38 @@ - private String formatUpdates(Map<String, Object> to) { - List<String> updateStatements = new ArrayList<String>(); + private String formatUpdateEquals(String separator) { + //sorting is necessary to ensure keys and values match up + SortedSet<String> updateStatements = Sets.newTreeSet(); for(ColumnPair pair : pairs) { String foreignColumn = pair.foreign; - Object newValue = to.get(pair.local); - updateStatements.add(foreignColumn + " = " + DatabaseUtilities.formatValue(newValue)); + updateStatements.add(foreignColumn + " = ?"); } - return StringUtilities.implodeList(updateStatements, ", "); + return StringUtilities.implodeList(Lists.newArrayList(updateStatements), separator); } + + public Repointer constructRepointer(Connection connection) throws SQLException { + final PreparedStatement statement = connection.prepareStatement("UPDATE " + otherTable.toString() + " SET " + formatUpdateEquals(", ") + " WHERE " + formatUpdateEquals(" AND ")); + return new Repointer() { + + public void repoint(Map<String, Object> primary, Map<String, Object> secondary) throws SQLException { + int index = 1; + for(Object primaryValue : primary.values()) { + statement.setObject(index, primaryValue); + index++; + } + for(Object secondaryValue : secondary.values()) { + statement.setObject(index, secondaryValue); + index++; + } + statement.addBatch(); + } + + public void apply() throws SQLException { + statement.executeBatch(); + } + }; + } Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/Remover.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/Remover.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/Remover.java 2010-02-18 00:09:49 UTC (rev 1038) @@ -0,0 +1,9 @@ +package org.cishell.utilities.database; + +import java.sql.SQLException; +import java.util.Map; + +public interface Remover { + public void remove(Map<String, Object> values) throws SQLException; + public int apply() throws SQLException; +} Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/Repointer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/Repointer.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/Repointer.java 2010-02-18 00:09:49 UTC (rev 1038) @@ -0,0 +1,10 @@ +package org.cishell.utilities.database; + +import java.sql.SQLException; +import java.util.Map; + +public interface Repointer { + public void repoint(Map<String, Object> primary, Map<String, Object> secondary) throws SQLException; + + public void apply() throws SQLException; +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pat...@us...> - 2010-03-17 20:11:45
|
Revision: 1050 http://cishell.svn.sourceforge.net/cishell/?rev=1050&view=rev Author: pataphil Date: 2010-03-17 20:11:38 +0000 (Wed, 17 Mar 2010) Log Message: ----------- * Added org.cishell.utilities.ProgressMonitorUtilities. * Reviewed by Micah. Modified Paths: -------------- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF Added Paths: ----------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ProgressMonitorUtilities.java Modified: trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF =================================================================== --- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-03-16 22:42:41 UTC (rev 1049) +++ trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-03-17 20:11:38 UTC (rev 1050) @@ -22,9 +22,9 @@ prefuse.data.util, prefuse.util, prefuse.util.collections -Export-Package: org.cishell.utilities, - org.cishell.utilities.dictionary, - org.cishell.utilities.database, +Export-Package: org.cishell.utilities, + org.cishell.utilities.database, + org.cishell.utilities.dictionary, org.cishell.utilities.mutateParameter, org.cishell.utilities.mutateParameter.defaultvalue, org.cishell.utilities.mutateParameter.dropdown, Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/ProgressMonitorUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ProgressMonitorUtilities.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/ProgressMonitorUtilities.java 2010-03-17 20:11:38 UTC (rev 1050) @@ -0,0 +1,27 @@ +package org.cishell.utilities; + +import org.cishell.framework.algorithm.AlgorithmCanceledException; +import org.cishell.framework.algorithm.ProgressMonitor; + +public class ProgressMonitorUtilities { + public static void handleCanceledAlgorithm(ProgressMonitor progressMonitor) + throws AlgorithmCanceledException { + if (progressMonitor.isCanceled()) { + throw new AlgorithmCanceledException(); + } + } + + public static void handlePausedAlgorithm(ProgressMonitor progressMonitor) { + while (progressMonitor.isPaused()) { + try { + Thread.sleep(1); + } catch (InterruptedException e) {} + } + } + + public static void handleCanceledOrPausedAlgorithm(ProgressMonitor progressMonitor) + throws AlgorithmCanceledException { + handleCanceledAlgorithm(progressMonitor); + handlePausedAlgorithm(progressMonitor); + } +} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pat...@us...> - 2010-07-08 17:37:48
|
Revision: 1082 http://cishell.svn.sourceforge.net/cishell/?rev=1082&view=rev Author: pataphil Date: 2010-07-08 17:37:42 +0000 (Thu, 08 Jul 2010) Log Message: ----------- * Committing (partially done) GUIModel framework and additional MapUtilities. Modified Paths: -------------- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java Added Paths: ----------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModel.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModelField.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/ModelFieldException.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/CheckBoxDataSynchronizer.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/DateDataSynchronizer.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/DropDownDataSynchronizer.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/ModelDataSynchronizer.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/TimeDataSynchronizer.java Modified: trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF =================================================================== --- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-07-06 20:19:54 UTC (rev 1081) +++ trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-07-08 17:37:42 UTC (rev 1082) @@ -36,6 +36,8 @@ org.cishell.utilities.mutateParameter.defaultvalue, org.cishell.utilities.mutateParameter.dropdown, org.cishell.utilities.osgi.logging, - org.cishell.utilities.swt + org.cishell.utilities.swt, + org.cishell.utilities.swt.model, + org.cishell.utilities.swt.model.datasynchronizer Require-Bundle: org.eclipse.ui;resolution:=optional, org.eclipse.core.runtime;resolution:=optional Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java 2010-07-06 20:19:54 UTC (rev 1081) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java 2010-07-08 17:37:42 UTC (rev 1082) @@ -2,6 +2,8 @@ import java.util.ArrayList; import java.util.Collection; +import java.util.HashMap; +import java.util.List; import java.util.Map; public class MapUtilities { @@ -20,4 +22,44 @@ return workingKeys; } + + public static<T> Map<T, T> mirror(Collection<T> items) { + Map<T, T> mirroredItems = new HashMap<T, T>(); + + for (T item : items) { + mirroredItems.put(item, item); + } + + return mirroredItems; + } + + public static<K, V> List<K> keysWithOrder(Map<K, V> map) { + List<K> keys = new ArrayList<K>(); + + for (K key : map.keySet()) { + keys.add(key); + } + + return keys; + } + + public static<K, V> Collection<V> valuesWithPreservedOrder(Map<K, V> map, Collection<K> keys) { + List<V> values = new ArrayList<V>(); + + for (K key : keys) { + values.add(map.get(key)); + } + + return values; + } + + public static<V> Map<Integer, V> mapIndexToValues(List<V> values) { + Map<Integer, V> valuesByIndex = new HashMap<Integer, V>(); + + for (int ii = 0; ii < values.size(); ii++) { + valuesByIndex.put(ii, values.get(ii)); + } + + return valuesByIndex; + } } \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModel.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModel.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModel.java 2010-07-08 17:37:42 UTC (rev 1082) @@ -0,0 +1,110 @@ +package org.cishell.utilities.swt.model; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.cishell.utilities.swt.model.datasynchronizer.CheckBoxDataSynchronizer; +import org.cishell.utilities.swt.model.datasynchronizer.DateDataSynchronizer; +import org.cishell.utilities.swt.model.datasynchronizer.DropDownDataSynchronizer; +import org.cishell.utilities.swt.model.datasynchronizer.ModelDataSynchronizer; +import org.cishell.utilities.swt.model.datasynchronizer.TimeDataSynchronizer; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Button; +import org.eclipse.swt.widgets.Combo; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.DateTime; + +public class GUIModel { + private Map<String, GUIModelField<?>> inputFieldsByName = + new HashMap<String, GUIModelField<?>>(); + + public GUIModel() { + } + + public Collection<String> getFieldNames() { + return this.inputFieldsByName.keySet(); + } + + public Collection<GUIModelField<?>> getFields() { + return this.inputFieldsByName.values(); + } + + public GUIModelField<?> getField(String name) { + return this.inputFieldsByName.get(name); + } + + public Button addCheckBox(String name, boolean on, Composite parent, int style) { + Button checkBox = new Button(parent, style | SWT.CHECK); + ModelDataSynchronizer<Boolean> dataSynchronizer = + new CheckBoxDataSynchronizer(checkBox, on); + GUIModelField<Boolean> field = + new GUIModelField<Boolean>(name, on, checkBox, dataSynchronizer); + addField(field); + + return checkBox; + } + + public Combo addDropDown( + String name, + int selectedIndex, + Collection<String> unorderedOptionLabels, + Map<String, String> optionValuesByLabels, + Composite parent, + int style) { + List<String> orderedOptionLabels = new ArrayList<String>(unorderedOptionLabels); + Combo dropDown = new Combo(parent, style | SWT.DROP_DOWN); + ModelDataSynchronizer<String> dataSynchronizer = new DropDownDataSynchronizer( + dropDown, selectedIndex, orderedOptionLabels, optionValuesByLabels); + GUIModelField<String> field = new GUIModelField<String>( + name, orderedOptionLabels.get(selectedIndex), dropDown, dataSynchronizer); + addField(field); + + return dropDown; + } + + // TODO: Test this out. + public DateTime addDate( + String name, org.joda.time.DateTime date, Composite parent, int style) { + DateTime dateSelector = new DateTime(parent, style | SWT.DATE); + ModelDataSynchronizer<org.joda.time.DateTime> dataSynchronizer = + new DateDataSynchronizer(dateSelector, date); + GUIModelField<org.joda.time.DateTime> field = new GUIModelField<org.joda.time.DateTime>( + name, date, dateSelector, dataSynchronizer); + addField(field); + + return dateSelector; + } + + // TODO: Test this out. + public DateTime addTime( + String name, org.joda.time.DateTime time, Composite parent, int style) { + DateTime timeSelector = new DateTime(parent, style | SWT.TIME); + ModelDataSynchronizer<org.joda.time.DateTime> dataSynchronizer = + new TimeDataSynchronizer(timeSelector, time); + GUIModelField<org.joda.time.DateTime> field = new GUIModelField<org.joda.time.DateTime>( + name, time, timeSelector, dataSynchronizer); + addField(field); + + return timeSelector; + } + + // TODO: addCalendar + +// public List addSingleSelectionList( +// String name, + + public<T> void addField(GUIModelField<T> field) { + String fieldName = field.getName(); + + if (this.inputFieldsByName.containsKey(fieldName)) { + String exceptionMessage = + "A field with the name \"" + fieldName + "\" already exists. Unable to continue."; + throw new ModelFieldException(exceptionMessage); + } + + this.inputFieldsByName.put(fieldName, field); + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModelField.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModelField.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModelField.java 2010-07-08 17:37:42 UTC (rev 1082) @@ -0,0 +1,51 @@ +package org.cishell.utilities.swt.model; + +import org.cishell.utilities.swt.model.datasynchronizer.ModelDataSynchronizer; +import org.eclipse.swt.widgets.Event; +import org.eclipse.swt.widgets.Listener; +import org.eclipse.swt.widgets.Widget; + +public class GUIModelField<T> { + private String name; + private T defaultValue; + private T value; + private Widget widget; + private ModelDataSynchronizer<T> dataSynchronizer; + + public GUIModelField( + String name, + T defaultValue, + Widget widget, + ModelDataSynchronizer<T> dataSynchronizer) { + this.name = name; + this.defaultValue = defaultValue; + this.value = this.defaultValue; + this.widget = widget; + this.dataSynchronizer = dataSynchronizer; + + this.widget.addListener(this.dataSynchronizer.swtUpdateListenerCode(), new Listener() { + public void handleEvent(Event event) { + if (event.type == GUIModelField.this.dataSynchronizer.swtUpdateListenerCode()) { + GUIModelField.this.value = + GUIModelField.this.dataSynchronizer.synchronizeFromGUI(); + } + } + }); + } + + public String getName() { + return this.name; + } + + public T getValue() { + return this.value; + } + + public void setValue(T value) { + this.value = this.dataSynchronizer.synchronizeToGUI(value); + } + + public void reset() { + this.value = this.dataSynchronizer.reset(this.defaultValue); + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/ModelFieldException.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/ModelFieldException.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/ModelFieldException.java 2010-07-08 17:37:42 UTC (rev 1082) @@ -0,0 +1,21 @@ +package org.cishell.utilities.swt.model; + +public class ModelFieldException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public ModelFieldException() { + super(); + } + + public ModelFieldException(String arg0) { + super(arg0); + } + + public ModelFieldException(Throwable arg0) { + super(arg0); + } + + public ModelFieldException(String arg0, Throwable arg1) { + super(arg0, arg1); + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/CheckBoxDataSynchronizer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/CheckBoxDataSynchronizer.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/CheckBoxDataSynchronizer.java 2010-07-08 17:37:42 UTC (rev 1082) @@ -0,0 +1,35 @@ +package org.cishell.utilities.swt.model.datasynchronizer; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Button; + +public class CheckBoxDataSynchronizer implements ModelDataSynchronizer<Boolean> { + private Button checkBox; + + public CheckBoxDataSynchronizer(Button checkBox, boolean on) { + this.checkBox = checkBox; + this.checkBox.setSelection(on); + } + + public int swtUpdateListenerCode() { + return SWT.Selection; + } + + public Boolean value() { + return this.checkBox.getSelection(); + } + + public Boolean synchronizeFromGUI() { + return value(); + } + + public Boolean synchronizeToGUI(Boolean value) { + this.checkBox.setSelection(value); + + return value; + } + + public Boolean reset(Boolean defaultValue) { + return synchronizeToGUI(defaultValue); + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/DateDataSynchronizer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/DateDataSynchronizer.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/DateDataSynchronizer.java 2010-07-08 17:37:42 UTC (rev 1082) @@ -0,0 +1,42 @@ +package org.cishell.utilities.swt.model.datasynchronizer; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.DateTime; + +public class DateDataSynchronizer implements ModelDataSynchronizer<org.joda.time.DateTime> { + private DateTime dateSelector; + + public DateDataSynchronizer(DateTime dateSelector, org.joda.time.DateTime date) { + this.dateSelector = dateSelector; + synchronizeToGUI(date); + } + + public int swtUpdateListenerCode() { + return SWT.Selection; + } + + public org.joda.time.DateTime value() { + return new org.joda.time.DateTime( + this.dateSelector.getYear(), + this.dateSelector.getMonth(), + this.dateSelector.getDay(), + 0, + 0, + 0, + 0); + } + + public org.joda.time.DateTime synchronizeFromGUI() { + return value(); + } + + public org.joda.time.DateTime synchronizeToGUI(org.joda.time.DateTime date) { + this.dateSelector.setDate(date.getYear(), date.getMonthOfYear(), date.getDayOfMonth()); + + return value(); + } + + public org.joda.time.DateTime reset(org.joda.time.DateTime defaultValue) { + return synchronizeToGUI(defaultValue); + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/DropDownDataSynchronizer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/DropDownDataSynchronizer.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/DropDownDataSynchronizer.java 2010-07-08 17:37:42 UTC (rev 1082) @@ -0,0 +1,54 @@ +package org.cishell.utilities.swt.model.datasynchronizer; + +import java.util.List; +import java.util.Map; + +import org.cishell.utilities.MapUtilities; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.Combo; + +import com.google.common.collect.BiMap; +import com.google.common.collect.HashBiMap; + +// TODO: Make this so options can change on it. +public class DropDownDataSynchronizer implements ModelDataSynchronizer<String> { + private Combo dropDown; + private BiMap<Integer, String> optionLabels; + private Map<String, String> optionValuesByLabels; + + public DropDownDataSynchronizer( + Combo dropDown, + int selectedIndex, + List<String> optionLabels, + Map<String, String> optionValuesByLabels) { + this.dropDown = dropDown; + this.optionLabels = HashBiMap.create(MapUtilities.mapIndexToValues(optionLabels)); + this.optionValuesByLabels = optionValuesByLabels; + + this.dropDown.setItems(optionLabels.toArray(new String[0])); + this.dropDown.select(selectedIndex); + } + + public int swtUpdateListenerCode() { + return SWT.Selection; + } + + public String value() { + return this.optionValuesByLabels.get( + this.optionLabels.get(this.dropDown.getSelectionIndex())); + } + + public String synchronizeFromGUI() { + return this.optionLabels.get(this.dropDown.getSelectionIndex()); + } + + public String synchronizeToGUI(String value) { + this.dropDown.select(this.optionLabels.inverse().get(value)); + + return value(); + } + + public String reset(String defaultValue) { + return synchronizeToGUI(defaultValue); + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/ModelDataSynchronizer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/ModelDataSynchronizer.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/ModelDataSynchronizer.java 2010-07-08 17:37:42 UTC (rev 1082) @@ -0,0 +1,9 @@ +package org.cishell.utilities.swt.model.datasynchronizer; + +public interface ModelDataSynchronizer<T> { + public int swtUpdateListenerCode(); + public T value(); + public T synchronizeFromGUI(); + public T synchronizeToGUI(T value); + public T reset(T defaultValue); +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/TimeDataSynchronizer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/TimeDataSynchronizer.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/TimeDataSynchronizer.java 2010-07-08 17:37:42 UTC (rev 1082) @@ -0,0 +1,43 @@ +package org.cishell.utilities.swt.model.datasynchronizer; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.DateTime; + +public class TimeDataSynchronizer implements ModelDataSynchronizer<org.joda.time.DateTime> { + private DateTime timeSelector; + + public TimeDataSynchronizer(DateTime timeSelector, org.joda.time.DateTime time) { + this.timeSelector = timeSelector; + synchronizeToGUI(time); + } + + public int swtUpdateListenerCode() { + return SWT.Selection; + } + + public org.joda.time.DateTime value() { + return new org.joda.time.DateTime( + 0, + 0, + 0, + this.timeSelector.getHours(), + this.timeSelector.getMinutes(), + this.timeSelector.getSeconds(), + 0); + } + + public org.joda.time.DateTime synchronizeFromGUI() { + return value(); + } + + public org.joda.time.DateTime synchronizeToGUI(org.joda.time.DateTime time) { + this.timeSelector.setTime( + time.getHourOfDay(), time.getMinuteOfHour(), time.getSecondOfMinute()); + + return value(); + } + + public org.joda.time.DateTime reset(org.joda.time.DateTime defaultValue) { + return synchronizeToGUI(defaultValue); + } +} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <kon...@us...> - 2010-09-27 18:03:04
|
Revision: 1136 http://cishell.svn.sourceforge.net/cishell/?rev=1136&view=rev Author: kongchinhua Date: 2010-09-27 18:02:57 +0000 (Mon, 27 Sep 2010) Log Message: ----------- Add ColorRegistry and ColorSchema for color management support - ColorSchema: Defined the scope of available colors of an application - ColorRegistry: assign color based on the given ColorSchema Reviewed by Patrick Modified Paths: -------------- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF Added Paths: ----------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/color/ trunk/core/org.cishell.utilities/src/org/cishell/utilities/color/ColorRegistry.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/color/ColorSchema.java Modified: trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF =================================================================== --- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-09-20 16:50:16 UTC (rev 1135) +++ trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-09-27 18:02:57 UTC (rev 1136) @@ -30,6 +30,7 @@ prefuse.util, prefuse.util.collections Export-Package: org.cishell.utilities, + org.cishell.utilities.color, org.cishell.utilities.database, org.cishell.utilities.dictionary, org.cishell.utilities.mutateParameter, Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/color/ColorRegistry.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/color/ColorRegistry.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/color/ColorRegistry.java 2010-09-27 18:02:57 UTC (rev 1136) @@ -0,0 +1,83 @@ +package org.cishell.utilities.color; + +import java.awt.Color; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * ColorRegistry provide algorithm to assign color to + * specific item that defined in <E>. It use generic + * so that the implementation can be use for any type + * of item. + * + * To use ColorRegistry, create your own ColorSchema + * that hold the set of available colors and also + * a default color if the color is out + * @author kongch + * + */ +public class ColorRegistry<K> { + private int currentIndex; + private ColorSchema colorSchema; + private Map<K, Color> registedColors; + + public ColorRegistry(ColorSchema colorSchema) { + this.currentIndex = 0; + this.colorSchema = colorSchema; + this.registedColors = new HashMap<K, Color>(); + } + + /** + * Get all the keys that hold the specified color. + * @return Return the registered keys + */ + public Set<K> getKeySet() { + return registedColors.keySet(); + } + + /** + * Request a color for the specific key. + * @param key - key must be type of <E> + * @return Return color that assigned to the specific + * key. If all the colors are fully used, the default + * color denied by the ColorSchema will be returned + */ + public Color getColorOf(K key) { + if (registedColors.containsKey(key)) { + return registedColors.get(key); + } else { + return reserveColorFor(key); + } + } + + /** + * Clear all entry and reset to initial state. + */ + public void clear() { + registedColors.clear(); + } + + /* + * Request a color from the color schema + */ + private Color reserveColorFor(K key) { + + Color color = colorSchema.get(getNextIndex()); + registedColors.put(key, color); + + return color; + } + + /* + * Return next color index + */ + private int getNextIndex() { + int index = currentIndex; + + if (currentIndex < colorSchema.size()) { + currentIndex++; + } + return index; + } +} Property changes on: trunk/core/org.cishell.utilities/src/org/cishell/utilities/color/ColorRegistry.java ___________________________________________________________________ Added: svn:mime-type + text/plain Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/color/ColorSchema.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/color/ColorSchema.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/color/ColorSchema.java 2010-09-27 18:02:57 UTC (rev 1136) @@ -0,0 +1,83 @@ +package org.cishell.utilities.color; + +import java.awt.Color; + +/** + * ColorSchema defined a set of colors to be used for + * an application. This allows the interchange of color + * schema set if needed. + * + * Schema contains a set of available color and a + * default color value. The defaultColor will be + * set to BLACK if it is not given + * @author kongch + * + */ +public class ColorSchema { + private int totalColors; + private Color[] colors; + private Color defaultColor; + + public ColorSchema(Color[] colors, Color defaultColor) { + setColors(colors); + setDefaultColor(defaultColor); + } + + /** + * The size of the color in schema which is not including + * defaultColor. + * @return Return the size of the color array + */ + public int size() { + return this.totalColors; + } + + /** + * Get color by index. + * @param index - index of the color in the schema + * @return Return a defaultColor if the given index is + * out of bound. Else return the color of the given + * index + */ + public Color get(int index) { + if (index > this.totalColors) { + return getDefaultColor(); + } + + return this.colors[index]; + } + + /** + * Get the set of available color. + * @return Always return the set of color under schema + */ + public Color[] getColors() { + return this.colors; + } + + /** + * Get the default color. + * @return Always return the default color + */ + public Color getDefaultColor() { + return this.defaultColor; + } + + private void setColors(Color[] colors) { + if (colors == null) { + this.colors = new Color[]{}; + } else { + this.colors = colors; + } + this.totalColors = this.colors.length; + } + + private void setDefaultColor(Color defaultColor) { + /* Assigned to BLACK if it is not given */ + if (defaultColor == null) { + this.defaultColor = Color.BLACK; + } else { + this.defaultColor = defaultColor; + } + } +} Property changes on: trunk/core/org.cishell.utilities/src/org/cishell/utilities/color/ColorSchema.java ___________________________________________________________________ Added: svn:mime-type + text/plain This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jrb...@us...> - 2012-01-10 23:51:26
|
Revision: 1300 http://cishell.svn.sourceforge.net/cishell/?rev=1300&view=rev Author: jrbibers Date: 2012-01-10 23:51:20 +0000 (Tue, 10 Jan 2012) Log Message: ----------- New "process" subpackage for CIShell utilities. Three new classes for working with java.lang.Process. Core functionality is (1) emptying the standard output and standard error streams as a running process fills them since the process would otherwise block indefinitely and (2) capturing the exit value and standard output and standard error messages of the completed process as a ProcessResult. Manifest updated to export this new package. Reviewed by David. Modified Paths: -------------- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF Added Paths: ----------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/process/ trunk/core/org.cishell.utilities/src/org/cishell/utilities/process/OutputGobblingProcessRunner.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/process/ProcessResult.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/process/StreamGobbler.java Modified: trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF =================================================================== --- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2012-01-09 16:19:32 UTC (rev 1299) +++ trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2012-01-10 23:51:20 UTC (rev 1300) @@ -36,4 +36,5 @@ org.cishell.utilities.mutateParameter, org.cishell.utilities.mutateParameter.defaultvalue, org.cishell.utilities.mutateParameter.dropdown, - org.cishell.utilities.osgi.logging + org.cishell.utilities.osgi.logging, + org.cishell.utilities.process Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/process/OutputGobblingProcessRunner.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/process/OutputGobblingProcessRunner.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/process/OutputGobblingProcessRunner.java 2012-01-10 23:51:20 UTC (rev 1300) @@ -0,0 +1,64 @@ +package org.cishell.utilities.process; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; + +import com.google.common.base.Objects; + +/** + * {@link Process#waitFor()} may wait indefinitely if the running process's stdout and stderr + * streams are not emptied as they fill. + * + * See + * <a href="http://stackoverflow.com/questions/2150723/process-waitfor-threads-and-inputstreams">here</a> + * or + * <a href="http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html">here</a> for details. + * + */ +public class OutputGobblingProcessRunner { + private ProcessBuilder processBuilder; + private String charsetName; + + public OutputGobblingProcessRunner(ProcessBuilder processBuilder, String charsetName) { + this.processBuilder = processBuilder; + this.charsetName = charsetName; + } + + public ProcessResult run() throws IOException, InterruptedException { + // Start the process + Process process = processBuilder.start(); + + // Set up and start the stdout and stderr gobblers + ByteArrayOutputStream stdoutStream = new ByteArrayOutputStream(); + StreamGobbler stdoutGobbler = new StreamGobbler(process.getInputStream(), stdoutStream); + + ByteArrayOutputStream stderrStream = new ByteArrayOutputStream(); + StreamGobbler stderrGobbler = new StreamGobbler(process.getErrorStream(), stderrStream); + + stdoutGobbler.start(); + stderrGobbler.start(); + + // Wait for the process to finish + int exitValue = process.waitFor(); + + // Interrupt the gobblers and wait for both to die + stdoutGobbler.interrupt(); + stderrGobbler.interrupt(); + stdoutGobbler.join(); + stderrGobbler.join(); + + // Dump gobbler messages + String stdoutMessage = stdoutStream.toString(charsetName).trim(); + String stderrMessage = stderrStream.toString(charsetName).trim(); + + return new ProcessResult(exitValue, stdoutMessage, stderrMessage); + } + + @Override + public String toString() { + return Objects.toStringHelper(this) + .add("processBuilder", processBuilder) + .add("charsetName", charsetName) + .toString(); + } +} Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/process/ProcessResult.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/process/ProcessResult.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/process/ProcessResult.java 2012-01-10 23:51:20 UTC (rev 1300) @@ -0,0 +1,98 @@ +package org.cishell.utilities.process; + +import com.google.common.base.Joiner; +import com.google.common.base.Objects; + +/** + * Value class for the result of {@link OutputGobblingProcessRunner#run()}. + * Represents a process's exit value and messages to standard out and standard error, + * both as a single String. + */ +public class ProcessResult { + private int exitValue; + private String stdoutMessage; + private String stderrMessage; + + /** + * @param exitValue A completed {@link Process}'s exit value. + * @param stdoutMessage A completed {@link Process}'s messages to standard output as one String. + * @param stderrMessage A completed {@link Process}'s messages to standard error as one String. + */ + public ProcessResult(int exitValue, String stdoutMessage, String stderrMessage) { + this.exitValue = exitValue; + this.stdoutMessage = stdoutMessage; + this.stderrMessage = stderrMessage; + } + + public int getExitValue() { + return exitValue; + } + + /** + * @return The message to standard output. + */ + public String getStdoutMessage() { + return stdoutMessage; + } + + /** + * @return The message to standard error. + */ + public String getStderrMessage() { + return stderrMessage; + } + + /** + * @return True if and only if the exit value is zero. + */ + public boolean isExitNormal() { + return (exitValue == 0); + } + + /** + * @return A plain-text report of the exit value and standard output/error messages. + */ + public String report() { + return Joiner.on(" ").join( + String.format("The program returned exit value %d.", exitValue), + reportStreamContents("standard output", stdoutMessage), + reportStreamContents("standard error", stderrMessage)); + } + + private static String reportStreamContents(String streamName, String contents) { + if (contents.isEmpty()) { + return String.format("No messages to %s.", streamName); + } else { + return String.format("Message to %s: [[%s]].", streamName, contents); + } + } + + @Override + public boolean equals(Object thatObject) { + if (!(thatObject instanceof ProcessResult)) { + return false; + } + + ProcessResult that = (ProcessResult) thatObject; + + return (Objects.equal(this.exitValue, + that.exitValue) + && Objects.equal(this.stdoutMessage, + that.stdoutMessage) + && Objects.equal(this.stderrMessage, + that.stderrMessage)); + } + @Override + public int hashCode() { + return Objects.hashCode(exitValue, stdoutMessage, stderrMessage); + } + + @Override + public String toString() { + return Objects.toStringHelper(this) + .add("exitValue", exitValue) + .add("stdoutMessage", stdoutMessage) + .add("stderrMessage", stderrMessage) + .toString(); + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/process/StreamGobbler.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/process/StreamGobbler.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/process/StreamGobbler.java 2012-01-10 23:51:20 UTC (rev 1300) @@ -0,0 +1,60 @@ +package org.cishell.utilities.process; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.PrintWriter; + +import com.google.common.base.Objects; + +/** + * Running this thread empties {@link #inputStream} into {@link #outputStream}. + * <p/> + * Adapted from + * <a href="http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4">this guide</a>. + */ +public class StreamGobbler extends Thread { + private InputStream inputStream; + private OutputStream outputStream; + + /** + * @param inputStream Stream for reading. + * @param outputStream Stream for writing. + */ + public StreamGobbler(InputStream inputStream, OutputStream outputStream) { + this.inputStream = inputStream; + this.outputStream = outputStream; + } + + /** + * Empties this gobbler's {@link InputStream} into its {@link OutputStream}. + */ + @Override + public void run() { + try { + PrintWriter printWriter = new PrintWriter(outputStream); + + InputStreamReader inputStreamReader = new InputStreamReader(inputStream); + BufferedReader bufferedReader = new BufferedReader(inputStreamReader); + String line = null; + while ((line = bufferedReader.readLine()) != null) { + printWriter.println(line); + } + + printWriter.flush(); + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException("Problem reading messages from process.", e); + } + } + + @Override + public String toString() { + return Objects.toStringHelper(this) + .add("inputStream", inputStream) + .add("outputStream", outputStream) + .toString(); + } +} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jrb...@us...> - 2009-10-27 22:03:11
|
Revision: 974 http://cishell.svn.sourceforge.net/cishell/?rev=974&view=rev Author: jrbibers Date: 2009-10-27 22:03:00 +0000 (Tue, 27 Oct 2009) Log Message: ----------- Added AlgorithmUtilities method for trying to parse filenames from the DataProperty.LABEL from a Data. It chains up through DataProperty.PARENT until one is found or we reach the topmost parent. Restructured the mutateParameters package and updated dependent plug-ins to reflect this. Added a new AttributeDefinitionTransformer for setting default values. Reviewed by Patrick. Modified Paths: -------------- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF trunk/core/org.cishell.utilities/src/org/cishell/utilities/AlgorithmUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/AttributeDefinitionTransformer.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java Added Paths: ----------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/defaultvalue/ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/defaultvalue/DefaultDefaultValueTransformer.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/defaultvalue/DefaultValueTransformer.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DefaultDropdownTransformer.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DropdownMutator.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DropdownTransformer.java Removed Paths: ------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/DropdownMutator.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/DropdownTransformer.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/NullDropdownTransformer.java Modified: trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF =================================================================== --- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2009-10-21 19:17:41 UTC (rev 973) +++ trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2009-10-27 22:03:00 UTC (rev 974) @@ -18,4 +18,6 @@ prefuse.util, prefuse.util.collections Export-Package: org.cishell.utilities, - org.cishell.utilities.mutateParameter + org.cishell.utilities.mutateParameter, + org.cishell.utilities.mutateParameter.defaultvalue, + org.cishell.utilities.mutateParameter.dropdown Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/AlgorithmUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/AlgorithmUtilities.java 2009-10-21 19:17:41 UTC (rev 973) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/AlgorithmUtilities.java 2009-10-27 22:03:00 UTC (rev 974) @@ -1,13 +1,16 @@ package org.cishell.utilities; +import java.io.File; +import java.util.Dictionary; + import org.cishell.framework.algorithm.AlgorithmFactory; import org.cishell.framework.data.BasicData; import org.cishell.framework.data.Data; +import org.cishell.framework.data.DataProperty; 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)... @@ -53,4 +56,64 @@ data[0].getData(), data[0].getFormat()) }; } + + /** + * Check data's label for something that looks like a file path. + * If found, try to extract a filename. + * If either bit fails, check same on the parent data, if present. + * The first filename-y text found this way is returned. + * If we fail all the way to the top parent (that is, data == null), return the empty string. + * + * @param data From whose label and parent labels to attempt filename extractions. + * @return A guess at the filename from data's label or its (transitively) parent labels. + * null when none can be found. + */ + /* TODO: A superior approach might be to define a new "standard" metadata + * property (i.e. DataProperty.ORIGINAL_DATASET or something). + * When searching for the source data (file)name, that new property would + * take precedent, and guessSourceDataFilename would be a default. + * To do this properly, the File Load algorithm would need to set this new + * property to the filename the user chose. On the same token, upon + * receiving a new data item, the Data Manager algorithm would set this new + * property to the data item's label if not set already. + */ + public static String guessSourceDataFilename(Data data) { + if (data == null) { + return ""; + } + + Dictionary metadata = data.getMetadata(); + String label = (String) metadata.get(DataProperty.LABEL); + Data parent = (Data) metadata.get(DataProperty.PARENT); + + if (label != null && label.indexOf(File.separator) != -1) { + /* If fileSeparator is a single backslash, + * escape it for the split() regular expression. + */ + String escapedFileSeparator = File.separator; + if ("\\".equals(escapedFileSeparator)) { + escapedFileSeparator = "\\\\"; + } + + String[] pathTokens = label.split(escapedFileSeparator); + + String guessedFilename = pathTokens[pathTokens.length - 1]; + + int lastExtensionSeparatorIndex = guessedFilename.lastIndexOf("."); + if (lastExtensionSeparatorIndex != -1) { + // Part before the extension ("foo" for "foo.bar"). + String guessedNameProper = + guessedFilename.substring(0, lastExtensionSeparatorIndex); + // ".bar" for "foo.bar". + String guessedExtension = guessedFilename.substring(lastExtensionSeparatorIndex); + String[] extensionTokens = guessedExtension.split("\\s+"); + + return guessedNameProper + extensionTokens[0]; + } else { + return guessSourceDataFilename(parent); + } + } else { + return guessSourceDataFilename(parent); + } + } } \ No newline at end of file Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java 2009-10-21 19:17:41 UTC (rev 973) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java 2009-10-27 22:03:00 UTC (rev 974) @@ -6,15 +6,16 @@ import org.cishell.reference.service.metatype.BasicObjectClassDefinition; import org.cishell.utilities.mutateParameter.AttributeDefinitionTransformer; -import org.cishell.utilities.mutateParameter.NullDropdownTransformer; import org.cishell.utilities.mutateParameter.ObjectClassDefinitionTransformer; +import org.cishell.utilities.mutateParameter.defaultvalue.DefaultDefaultValueTransformer; +import org.cishell.utilities.mutateParameter.dropdown.DefaultDropdownTransformer; import org.osgi.service.metatype.AttributeDefinition; import org.osgi.service.metatype.ObjectClassDefinition; import prefuse.data.Table; public class MutateParameterUtilities { - /* TODO The mutateParameter subpackage is meant to eliminate all of the loops + /* TODO The mutateParameter subpackage is meant to replace most of the loops * that invoke the formFooAttributeDefinition methods. */ @@ -98,7 +99,7 @@ final String[] optionLabels, final String[] optionValues) { AttributeDefinitionTransformer transformer = - new NullDropdownTransformer() { + new DefaultDropdownTransformer() { public boolean shouldTransform(AttributeDefinition ad) { return true; } @@ -138,9 +139,9 @@ final String[] optionLabels, final String[] optionValues) { AttributeDefinitionTransformer dropdownTransformer = - new NullDropdownTransformer() { + new DefaultDropdownTransformer() { public boolean shouldTransform(AttributeDefinition ad) { - return parameterID.equals(ad.getID()); + return ad.getID().equals(parameterID); } public String[] transformOptionLabels( @@ -153,10 +154,27 @@ } }; - return ObjectClassDefinitionTransformer.apply(dropdownTransformer, - oldOCD); + return ObjectClassDefinitionTransformer.apply(dropdownTransformer, oldOCD); } + public static BasicObjectClassDefinition mutateDefaultValue( + ObjectClassDefinition oldOCD, + final String parameterID, + final String defaultValue) { + AttributeDefinitionTransformer transformer = + new DefaultDefaultValueTransformer() { + public boolean shouldTransform(AttributeDefinition ad) { + return ad.getID().equals(parameterID); + } + + public String transformDefaultValue(String[] oldDefaultValue) { + return defaultValue; + } + }; + + return ObjectClassDefinitionTransformer.apply(transformer, oldOCD); + } + public static BasicObjectClassDefinition createNewParameters( ObjectClassDefinition oldParameters) { try { Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/AttributeDefinitionTransformer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/AttributeDefinitionTransformer.java 2009-10-21 19:17:41 UTC (rev 973) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/AttributeDefinitionTransformer.java 2009-10-27 22:03:00 UTC (rev 974) @@ -2,9 +2,8 @@ import org.osgi.service.metatype.AttributeDefinition; -/* There would be one implementation of this interface for each useful - * constructor of BasicAttributeDefinition, where the transform is defined as in - * DropdownTransformer. +/** + * This interface and its sub-interfaces correspond to constructors of BasicObjectClassDefinition. */ public interface AttributeDefinitionTransformer { public boolean shouldTransform(AttributeDefinition ad); Deleted: trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/DropdownMutator.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/DropdownMutator.java 2009-10-21 19:17:41 UTC (rev 973) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/DropdownMutator.java 2009-10-27 22:03:00 UTC (rev 974) @@ -1,127 +0,0 @@ -package org.cishell.utilities.mutateParameter; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.cishell.utilities.ArrayUtilities; -import org.osgi.service.metatype.AttributeDefinition; -import org.osgi.service.metatype.ObjectClassDefinition; - -/* For aggregating and applying DropdownTransforms. - * Many convenience methods are given to support arrays vs. Lists - * and default vs. no default. - * The core functionality - * is in add(final String, final String[], final String[]) - * and mutate(ObjectClassDefinition) - */ -public class DropdownMutator { - private List transforms; - - public DropdownMutator() { - transforms = new ArrayList(); - } - - public ObjectClassDefinition mutate(ObjectClassDefinition ocd) { - return ObjectClassDefinitionTransformer.transform(ocd, transforms); - } - - public void add(String id, List options, String defaultOption) { - add(id, swapToFront(options, defaultOption)); - } - - public void add(String id, List options) { - add(id, options, options); - } - - public void add(String id, - List optionLabels, - String defaultOptionLabel, - List optionValues, - String defaultOptionValue) { - add(id, - swapToFront(optionLabels, defaultOptionLabel), - swapToFront(optionValues, defaultOptionValue)); - } - - public void add(String id, List optionLabels, List optionValues) { - add(id, - (String[]) optionLabels.toArray(new String[0]), - (String[]) optionValues.toArray(new String[0])); - } - - public void add(String id, String[] options, String defaultOption) { - add(id, swapToFront(options, defaultOption)); - } - - public void add(String id, String[] options) { - add(id, options, options); - } - - public void add(final String id, - final String[] optionLabels, - String defaultOptionLabel, - final String[] optionValues, - String defaultOptionValue) { - add(id, - swapToFront(optionLabels, defaultOptionLabel), - swapToFront(optionValues, defaultOptionValue)); - } - - public void add(final String id, - final String[] optionLabels, - final String[] optionValues) { - transforms.add( - new NullDropdownTransformer() { - public boolean shouldTransform(AttributeDefinition ad) { - return id.equals(ad.getID()); - } - - public String[] transformOptionLabels(String[] oldOptionLabels) { - return optionLabels; - } - - public String[] transformOptionValues(String[] oldOptionValues) { - return optionValues; - } - }); - } - - private static List swapToFront(List list, String target) { - if (list.contains(target)) { - int targetIndex = list.indexOf(target); - - List swappedList = new ArrayList(list.size()); - - for (Iterator listIt = list.iterator(); listIt.hasNext();) { - swappedList.add(listIt.next()); - } - - swappedList.set(0, list.get(targetIndex)); - swappedList.set(targetIndex, list.get(0)); - - return swappedList; - } else { - return list; - } - } - - private static String[] swapToFront(String[] array, String target) { - int targetIndex = ArrayUtilities.indexOf(array, target); - - if (targetIndex != -1) { - String[] swappedArray = new String[array.length]; - - for (int ii = 0; ii < array.length; ii++) { - swappedArray[ii] = array[ii]; - } - - swappedArray[0] = array[targetIndex]; - swappedArray[targetIndex] = array[0]; - - return swappedArray; - } else { - return array; - } - } -} Deleted: trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/DropdownTransformer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/DropdownTransformer.java 2009-10-21 19:17:41 UTC (rev 973) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/DropdownTransformer.java 2009-10-27 22:03:00 UTC (rev 974) @@ -1,27 +0,0 @@ -package org.cishell.utilities.mutateParameter; - -import org.cishell.reference.service.metatype.BasicAttributeDefinition; -import org.osgi.service.metatype.AttributeDefinition; - -public abstract class DropdownTransformer - implements AttributeDefinitionTransformer { - public AttributeDefinition transform(AttributeDefinition oldAD) { - if (shouldTransform(oldAD)) { - return - new BasicAttributeDefinition( - transformID(oldAD.getID()), - transformName(oldAD.getName()), - transformDescription(oldAD.getDescription()), - transformType(oldAD.getType()), - transformOptionLabels(oldAD.getOptionLabels()), - transformOptionValues(oldAD.getOptionValues())); - } - else { - return oldAD; - } - } - - public abstract String[] transformOptionLabels(String[] oldOptionLabels); - public abstract String[] transformOptionValues(String[] oldOptionValues); -} - Deleted: trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/NullDropdownTransformer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/NullDropdownTransformer.java 2009-10-21 19:17:41 UTC (rev 973) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/NullDropdownTransformer.java 2009-10-27 22:03:00 UTC (rev 974) @@ -1,38 +0,0 @@ -package org.cishell.utilities.mutateParameter; - -import org.osgi.service.metatype.AttributeDefinition; - -/* A dropdown-forming AttributeDefinition transformer which by default - * performs no transformation. - * This is a convenient access to DropdownTransformer where you may override - * methods to transform only the arguments that you wish to modify. - * The typical case would be extending shouldTransform (think of as a filter), - * transformOptionLabels, and transformOptionValues. - */ -public abstract class NullDropdownTransformer extends DropdownTransformer { - public abstract boolean shouldTransform(AttributeDefinition ad); - - public String transformID(String oldID) { - return oldID; - } - - public String transformName(String oldName) { - return oldName; - } - - public String transformDescription(String oldDescription) { - return oldDescription; - } - - public int transformType(int oldType) { - return oldType; - } - - public String[] transformOptionLabels(String[] oldOptionLabels) { - return oldOptionLabels; - } - - public String[] transformOptionValues(String[] oldOptionValues) { - return oldOptionValues; - } -} \ No newline at end of file Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java 2009-10-21 19:17:41 UTC (rev 973) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java 2009-10-27 22:03:00 UTC (rev 974) @@ -16,7 +16,6 @@ * "Atomic" to exclude blanket filters like ObjectClassDefinition.ALL. * @see ObjectClassDefinition#REQUIRED * @see ObjectClassDefinition#OPTIONAL - * @see ObjectClassDefinition#ALL */ public static final List ATOMIC_ATTRIBUTE_DEFINITION_FILTERS; static { Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/defaultvalue/DefaultDefaultValueTransformer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/defaultvalue/DefaultDefaultValueTransformer.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/defaultvalue/DefaultDefaultValueTransformer.java 2009-10-27 22:03:00 UTC (rev 974) @@ -0,0 +1,41 @@ +package org.cishell.utilities.mutateParameter.defaultvalue; + +import org.osgi.service.metatype.AttributeDefinition; + +/** + * Default Default-Value Transformer (the first in the sense of this being the simplest + * implementation of DefaultValueTransformer. + * <p/> + * A (single-valued) default-value-setting AttributeDefinition transformer + * which by default performs no transformation. + * <p/> + * This is a convenient access to DefaultValueTransformer where you may override + * methods to transform only the arguments that you wish to modify. + * The typical case would be extending shouldTransform (think of as a filter) + * and transformDefaultValue. + * + * @see org.cishell.utilities.MutateParameterUtilities#mutateDefaultValue(ObjectClassDefinition, String, String) + */ +public abstract class DefaultDefaultValueTransformer extends DefaultValueTransformer { + public abstract boolean shouldTransform(AttributeDefinition ad); + + public String transformDescription(String oldDescription) { + return oldDescription; + } + + public String transformID(String oldID) { + return oldID; + } + + public String transformName(String oldName) { + return oldName; + } + + public int transformType(int oldType) { + return oldType; + } + + public String transformDefaultValue(String oldDefaultValue) { + return oldDefaultValue; + } +} Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/defaultvalue/DefaultValueTransformer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/defaultvalue/DefaultValueTransformer.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/defaultvalue/DefaultValueTransformer.java 2009-10-27 22:03:00 UTC (rev 974) @@ -0,0 +1,26 @@ +package org.cishell.utilities.mutateParameter.defaultvalue; + +import org.cishell.reference.service.metatype.BasicAttributeDefinition; +import org.cishell.utilities.mutateParameter.AttributeDefinitionTransformer; +import org.osgi.service.metatype.AttributeDefinition; + +public abstract class DefaultValueTransformer implements AttributeDefinitionTransformer { + /** + * @see BasicAttributeDefinition#BasicAttributeDefinition(String, String, String, int, String) + */ + public AttributeDefinition transform(AttributeDefinition oldAD) { + if (shouldTransform(oldAD)) { + return + new BasicAttributeDefinition( + transformID(oldAD.getID()), + transformName(oldAD.getName()), + transformDescription(oldAD.getDescription()), + transformType(oldAD.getType()), + transformDefaultValue(oldAD.getDefaultValue())); + } else { + return oldAD; + } + } + + public abstract String transformDefaultValue(String[] oldDefaultValue); +} Copied: trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DefaultDropdownTransformer.java (from rev 972, trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/NullDropdownTransformer.java) =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DefaultDropdownTransformer.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DefaultDropdownTransformer.java 2009-10-27 22:03:00 UTC (rev 974) @@ -0,0 +1,40 @@ +package org.cishell.utilities.mutateParameter.dropdown; + +import org.osgi.service.metatype.AttributeDefinition; + +/** + * A dropdown-forming AttributeDefinition transformer which by default performs no transformation. + * This is a convenient access to DropdownTransformer where you may override + * methods to transform only the arguments that you wish to modify. + * The typical case would be extending shouldTransform (think of as a filter), + * transformOptionLabels, and transformOptionValues. + * + * @see org.cishell.utilities.MutateParameterUtilities#mutateToDropdown(ObjectClassDefinition, String, String[], String[]) + */ +public abstract class DefaultDropdownTransformer extends DropdownTransformer { + public abstract boolean shouldTransform(AttributeDefinition ad); + + public String transformID(String oldID) { + return oldID; + } + + public String transformName(String oldName) { + return oldName; + } + + public String transformDescription(String oldDescription) { + return oldDescription; + } + + public int transformType(int oldType) { + return oldType; + } + + public String[] transformOptionLabels(String[] oldOptionLabels) { + return oldOptionLabels; + } + + public String[] transformOptionValues(String[] oldOptionValues) { + return oldOptionValues; + } +} \ No newline at end of file Copied: trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DropdownMutator.java (from rev 972, trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/DropdownMutator.java) =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DropdownMutator.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DropdownMutator.java 2009-10-27 22:03:00 UTC (rev 974) @@ -0,0 +1,128 @@ +package org.cishell.utilities.mutateParameter.dropdown; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + +import org.cishell.utilities.ArrayUtilities; +import org.cishell.utilities.mutateParameter.ObjectClassDefinitionTransformer; +import org.osgi.service.metatype.AttributeDefinition; +import org.osgi.service.metatype.ObjectClassDefinition; + +/* For aggregating and applying DropdownTransforms. + * Many convenience methods are given to support arrays vs. Lists + * and default vs. no default. + * The core functionality + * is in add(final String, final String[], final String[]) + * and mutate(ObjectClassDefinition) + */ +public class DropdownMutator { + private List transforms; + + public DropdownMutator() { + transforms = new ArrayList(); + } + + public ObjectClassDefinition mutate(ObjectClassDefinition ocd) { + return ObjectClassDefinitionTransformer.transform(ocd, transforms); + } + + public void add(String id, List options, String defaultOption) { + add(id, swapToFront(options, defaultOption)); + } + + public void add(String id, List options) { + add(id, options, options); + } + + public void add(String id, + List optionLabels, + String defaultOptionLabel, + List optionValues, + String defaultOptionValue) { + add(id, + swapToFront(optionLabels, defaultOptionLabel), + swapToFront(optionValues, defaultOptionValue)); + } + + public void add(String id, List optionLabels, List optionValues) { + add(id, + (String[]) optionLabels.toArray(new String[0]), + (String[]) optionValues.toArray(new String[0])); + } + + public void add(String id, String[] options, String defaultOption) { + add(id, swapToFront(options, defaultOption)); + } + + public void add(String id, String[] options) { + add(id, options, options); + } + + public void add(final String id, + final String[] optionLabels, + String defaultOptionLabel, + final String[] optionValues, + String defaultOptionValue) { + add(id, + swapToFront(optionLabels, defaultOptionLabel), + swapToFront(optionValues, defaultOptionValue)); + } + + public void add(final String id, + final String[] optionLabels, + final String[] optionValues) { + transforms.add( + new DefaultDropdownTransformer() { + public boolean shouldTransform(AttributeDefinition ad) { + return id.equals(ad.getID()); + } + + public String[] transformOptionLabels(String[] oldOptionLabels) { + return optionLabels; + } + + public String[] transformOptionValues(String[] oldOptionValues) { + return optionValues; + } + }); + } + + private static List swapToFront(List list, String target) { + if (list.contains(target)) { + int targetIndex = list.indexOf(target); + + List swappedList = new ArrayList(list.size()); + + for (Iterator listIt = list.iterator(); listIt.hasNext();) { + swappedList.add(listIt.next()); + } + + swappedList.set(0, list.get(targetIndex)); + swappedList.set(targetIndex, list.get(0)); + + return swappedList; + } else { + return list; + } + } + + private static String[] swapToFront(String[] array, String target) { + int targetIndex = ArrayUtilities.indexOf(array, target); + + if (targetIndex != -1) { + String[] swappedArray = new String[array.length]; + + for (int ii = 0; ii < array.length; ii++) { + swappedArray[ii] = array[ii]; + } + + swappedArray[0] = array[targetIndex]; + swappedArray[targetIndex] = array[0]; + + return swappedArray; + } else { + return array; + } + } +} Copied: trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DropdownTransformer.java (from rev 972, trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/DropdownTransformer.java) =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DropdownTransformer.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DropdownTransformer.java 2009-10-27 22:03:00 UTC (rev 974) @@ -0,0 +1,31 @@ +package org.cishell.utilities.mutateParameter.dropdown; + +import org.cishell.reference.service.metatype.BasicAttributeDefinition; +import org.cishell.utilities.mutateParameter.AttributeDefinitionTransformer; +import org.osgi.service.metatype.AttributeDefinition; + +public abstract class DropdownTransformer + implements AttributeDefinitionTransformer { + /** + * @see BasicAttributeDefinition#BasicAttributeDefinition(String, String, String, int, String[], String[]) + */ + public AttributeDefinition transform(AttributeDefinition oldAD) { + if (shouldTransform(oldAD)) { + return + new BasicAttributeDefinition( + transformID(oldAD.getID()), + transformName(oldAD.getName()), + transformDescription(oldAD.getDescription()), + transformType(oldAD.getType()), + transformOptionLabels(oldAD.getOptionLabels()), + transformOptionValues(oldAD.getOptionValues())); + } + else { + return oldAD; + } + } + + public abstract String[] transformOptionLabels(String[] oldOptionLabels); + public abstract String[] transformOptionValues(String[] oldOptionValues); +} + This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pat...@us...> - 2010-01-13 16:55:41
|
Revision: 1017 http://cishell.svn.sourceforge.net/cishell/?rev=1017&view=rev Author: pataphil Date: 2010-01-13 16:55:34 +0000 (Wed, 13 Jan 2010) Log Message: ----------- * Added StringUtilities.allAreEmptyOrWhiteSpace (which wraps StringUtilities.isEmptyOrWhiteSpace). * Added org.cishell.utilities.osgi.logging.LogMessageHandler. Modified Paths: -------------- trunk/core/org.cishell.utilities/.classpath trunk/core/org.cishell.utilities/.settings/org.eclipse.jdt.core.prefs trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF trunk/core/org.cishell.utilities/src/org/cishell/utilities/StringUtilities.java Added Paths: ----------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/osgi/ trunk/core/org.cishell.utilities/src/org/cishell/utilities/osgi/logging/ trunk/core/org.cishell.utilities/src/org/cishell/utilities/osgi/logging/LogMessageHandler.java Modified: trunk/core/org.cishell.utilities/.classpath =================================================================== --- trunk/core/org.cishell.utilities/.classpath 2010-01-07 22:49:43 UTC (rev 1016) +++ trunk/core/org.cishell.utilities/.classpath 2010-01-13 16:55:34 UTC (rev 1017) @@ -1,6 +1,6 @@ <?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.4"/> + <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="output" path="bin"/> Modified: trunk/core/org.cishell.utilities/.settings/org.eclipse.jdt.core.prefs =================================================================== --- trunk/core/org.cishell.utilities/.settings/org.eclipse.jdt.core.prefs 2010-01-07 22:49:43 UTC (rev 1016) +++ trunk/core/org.cishell.utilities/.settings/org.eclipse.jdt.core.prefs 2010-01-13 16:55:34 UTC (rev 1017) @@ -1,12 +1,12 @@ -#Tue Oct 13 13:58:27 EDT 2009 +#Wed Jan 13 11:39:50 EST 2010 eclipse.preferences.version=1 org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.2 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.5 org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.4 +org.eclipse.jdt.core.compiler.compliance=1.5 org.eclipse.jdt.core.compiler.debug.lineNumber=generate org.eclipse.jdt.core.compiler.debug.localVariable=generate org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.assertIdentifier=warning -org.eclipse.jdt.core.compiler.problem.enumIdentifier=warning -org.eclipse.jdt.core.compiler.source=1.3 +org.eclipse.jdt.core.compiler.problem.assertIdentifier=error +org.eclipse.jdt.core.compiler.problem.enumIdentifier=error +org.eclipse.jdt.core.compiler.source=1.5 Modified: trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF =================================================================== --- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-01-07 22:49:43 UTC (rev 1016) +++ trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-01-13 16:55:34 UTC (rev 1017) @@ -3,13 +3,14 @@ Bundle-Name: Utilities Plug-in Bundle-SymbolicName: org.cishell.utilities Bundle-Version: 1.0.0 -Bundle-RequiredExecutionEnvironment: J2SE-1.4 +Bundle-RequiredExecutionEnvironment: J2SE-1.5 Import-Package: org.cishell.framework;version="1.0.0", org.cishell.framework.algorithm;version="1.0.0", org.cishell.framework.data, org.cishell.reference.service.metatype, org.cishell.service.database, org.osgi.framework;version="1.4.0", + org.osgi.service.log;version="1.3.0", org.osgi.service.metatype;version="1.1.0", prefuse, prefuse.data, @@ -21,4 +22,5 @@ Export-Package: org.cishell.utilities, org.cishell.utilities.mutateParameter, org.cishell.utilities.mutateParameter.defaultvalue, - org.cishell.utilities.mutateParameter.dropdown + org.cishell.utilities.mutateParameter.dropdown, + org.cishell.utilities.osgi.logging Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/StringUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/StringUtilities.java 2010-01-07 22:49:43 UTC (rev 1016) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/StringUtilities.java 2010-01-13 16:55:34 UTC (rev 1017) @@ -98,6 +98,16 @@ return (trimmed.length() == 0); } + + public static boolean allAreEmptyOrWhiteSpace(String... tests) { + for (String test : tests) { + if (!isEmptyOrWhiteSpace(test)) { + return false; + } + } + + return true; + } public static int countOccurrencesOfChar( CharSequence characters, char target) { Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/osgi/logging/LogMessageHandler.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/osgi/logging/LogMessageHandler.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/osgi/logging/LogMessageHandler.java 2010-01-13 16:55:34 UTC (rev 1017) @@ -0,0 +1,101 @@ +package org.cishell.utilities.osgi.logging; + +import java.util.HashMap; +import java.util.Map; + +import org.osgi.service.log.LogService; + +// TODO: Get reviewed. +// TODO: Make 1.4 compatible and move to cishell utilities? +public class LogMessageHandler { + private LogService logger; + private Map<MessageTypeIndicator, MessageType> messageTypes = + new HashMap<MessageTypeIndicator, MessageType>(); + + public LogMessageHandler(LogService logger) { + this.logger = logger; + } + + /** + * If typeIndicator is already an added message type, its count will be + * reset and maximum count overridden. + */ + public MessageTypeIndicator addMessageType( + String description, int maximumCount) { + MessageTypeIndicator typeIndicator = new MessageTypeIndicator(); + this.messageTypes.put( + typeIndicator, new MessageType(description, maximumCount)); + + return typeIndicator; + } + + /** + * logMessage will always be logged if typeIndicator has not been added + * prior to calling this. + */ + public void logMessage( + MessageTypeIndicator typeIndicator, + int logLevel, + String logMessage) { + MessageType messageType = this.messageTypes.get(typeIndicator); + + if (messageType != null) { + if (messageType.messageLogged()) { + this.logger.log(logLevel, logMessage); + } + } else { + this.logger.log(logLevel, logMessage); + } + } + + public void printOverloadedMessageTypes(int logLevel) { + for (MessageType messageType : this.messageTypes.values()) { + if (messageType.wasOverloaded()) { + this.logger.log(logLevel, messageType.toString()); + } + } + } + + public class MessageTypeIndicator {} + + private class MessageType { + private String description; + private int maximumCount; + private int foundCount = 0; + private int overLoadedCount = 0; + + public MessageType(String description, int maximumCount) { + this.description = description; + this.maximumCount = maximumCount; + } + + public boolean hasAnyLeft() { + return this.foundCount != this.maximumCount; + } + + public boolean wasOverloaded() { + return this.overLoadedCount > 0; + } + + public boolean messageLogged() { + if (hasAnyLeft()) { + this.foundCount++; + + return true; + } else { + this.overLoadedCount++; + + return false; + } + } + + public String toString() { + return + "Found " + + this.overLoadedCount + + " more " + + this.description + + "."; + } + } +} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pat...@us...> - 2010-03-26 20:12:13
|
Revision: 1064 http://cishell.svn.sourceforge.net/cishell/?rev=1064&view=rev Author: pataphil Date: 2010-03-26 20:12:06 +0000 (Fri, 26 Mar 2010) Log Message: ----------- * Added FileUtilities.extractFileNameWithExtension. * Added JodaDateUtilities. * Not reviewed. Modified Paths: -------------- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java Added Paths: ----------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/JodaDateUtilities.java Modified: trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF =================================================================== --- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-03-26 18:08:35 UTC (rev 1063) +++ trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-03-26 20:12:06 UTC (rev 1064) @@ -12,6 +12,13 @@ org.cishell.framework.data, org.cishell.reference.service.metatype, org.cishell.service.database, + org.joda.time, + org.joda.time.base, + org.joda.time.chrono, + org.joda.time.convert, + org.joda.time.field, + org.joda.time.format, + org.joda.time.tz, org.osgi.framework;version="1.4.0", org.osgi.service.log;version="1.3.0", org.osgi.service.metatype;version="1.1.0", Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java 2010-03-26 18:08:35 UTC (rev 1063) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java 2010-03-26 20:12:06 UTC (rev 1064) @@ -433,4 +433,8 @@ return fileNameWithoutExtension; } + + public static String extractFileNameWithExtension(String fileLabel) { + return extractFileName(fileLabel) + getFileExtension(fileLabel); + } } \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/JodaDateUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/JodaDateUtilities.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/JodaDateUtilities.java 2010-03-26 20:12:06 UTC (rev 1064) @@ -0,0 +1,22 @@ +package org.cishell.utilities; + +import org.joda.time.DateTime; +import org.joda.time.format.DateTimeFormat; +import org.joda.time.format.DateTimeFormatter; + +public class JodaDateUtilities { + public static String easyDateTimeFormat(String format) { + DateTime currentDateAndTime = new DateTime(); + DateTimeFormatter formatter = DateTimeFormat.forPattern(format); + + return formatter.print(currentDateAndTime); + } + + public static String easyDateFormat() { + return easyDateTimeFormat("MMM dd, yyyy"); + } + + public static String easyDateAndTimeFormat() { + return easyDateTimeFormat("MMM dd, yyyy; hh:mmaa"); + } +} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pat...@us...> - 2010-07-01 20:11:48
|
Revision: 1078 http://cishell.svn.sourceforge.net/cishell/?rev=1078&view=rev Author: pataphil Date: 2010-07-01 20:11:42 +0000 (Thu, 01 Jul 2010) Log Message: ----------- * Added org.cishell.utilities.swt to org.cishell.utilities. * Added optional SWT dependencies to the manifest. * Discussed with Micah. Modified Paths: -------------- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF Added Paths: ----------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/SWTUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/URLClickedListener.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/URLMouseCursorListener.java Modified: trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF =================================================================== --- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-06-24 18:18:27 UTC (rev 1077) +++ trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-07-01 20:11:42 UTC (rev 1078) @@ -35,4 +35,7 @@ org.cishell.utilities.mutateParameter, org.cishell.utilities.mutateParameter.defaultvalue, org.cishell.utilities.mutateParameter.dropdown, - org.cishell.utilities.osgi.logging + org.cishell.utilities.osgi.logging, + org.cishell.utilities.swt +Require-Bundle: org.eclipse.ui;resolution:=optional, + org.eclipse.core.runtime;resolution:=optional Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/SWTUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/SWTUtilities.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/SWTUtilities.java 2010-07-01 20:11:42 UTC (rev 1078) @@ -0,0 +1,98 @@ +package org.cishell.utilities.swt; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyleRange; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.graphics.Color; +import org.eclipse.swt.widgets.Display; + +public class SWTUtilities { + /* + * Append the given string to the console with the given color, this will do the job of + * checking for URLs within the string and registering the proper listeners on them as well. + */ + public static void appendStringWithURL( + StyledText textField, + URLClickedListener urlListener, + URLMouseCursorListener urlCursorListener, + String message, + Color normalColor, + Color urlColor) { + + //find a URL in the message + + int index = message.indexOf("http://"); + if (index == -1) { + index = message.indexOf("https://"); + } + if (index == -1) { + index = message.indexOf("www."); + } + + if (index > -1) { + String url = message.substring(index); + if (url.indexOf(") ") > -1) { + url = url.substring(0, url.indexOf(") ")); + } + else if (url.indexOf(" ") > -1) { + url = url.substring(0, url.indexOf(" ")); + if (url.trim().endsWith(".") ){ + url=url.substring(0, url.length()-1); + } + } + if (url.endsWith(".\n") || url.endsWith(".\t")){ + url=url.substring(0, url.length()-2); + } + if (url.indexOf("\n") > -1) { + url = url.substring(0, url.indexOf("\n")); + } + if (url.indexOf("\t") > -1) { + url = url.substring(0, url.indexOf("\n")); + } + + + syncedStyledPrint(textField, message.substring(0, index), normalColor, SWT.NORMAL); + urlListener.addURL(textField.getText().length(), url); + urlCursorListener.addURL(textField.getText().length(), url); + syncedStyledPrint(textField, url, urlColor, SWT.BOLD); + appendStringWithURL( + textField, + urlListener, + urlCursorListener, + message.substring(index + url.length()), + normalColor,urlColor); + } else { + syncedStyledPrint(textField, message, normalColor, SWT.NORMAL); + } + } + + /* + * Helper to actually format the string with a style range and + * append it to the StyledText control. + */ + + public static void syncedStyledPrint( + final StyledText textField, final String message, final Color color, final int style) { + Display.getDefault().syncExec(new Runnable() { + public void run(){ + styledPrint(textField, message, color, style); + } + }); + } + + public static void styledPrint(StyledText textField, String message, Color color, int style) { + if (!textField.isDisposed()) { + textField.append(message); + + StyleRange styleRange = new StyleRange(); + styleRange.start = textField.getText().length() - message.length(); + styleRange.length = message.length(); + styleRange.foreground = color; + styleRange.fontStyle = style; + textField.setStyleRange(styleRange); + + // This makes it autoscroll. + textField.setTopIndex(textField.getLineCount()); + } + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/URLClickedListener.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/URLClickedListener.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/URLClickedListener.java 2010-07-01 20:11:42 UTC (rev 1078) @@ -0,0 +1,70 @@ +package org.cishell.utilities.swt; + +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.events.MouseAdapter; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.program.Program; + +/* + * Listens for clicks on urls and launches a browser appropriately. + */ +public class URLClickedListener extends MouseAdapter { + private Map<Integer, String> offsetsToURLs = new HashMap<Integer, String>(); + private Map<String, String> urlsToDisplayURLs = new HashMap<String, String>(); + private StyledText textField; + + public URLClickedListener(StyledText textField) { + super(); + this.textField = textField; + } + + public void addURL(int offset, String url) { + addURL(offset, url, url); + } + + public void addURL(int offset, String url, String displayURL) { + this.offsetsToURLs.put(offset, url); + this.urlsToDisplayURLs.put(url, displayURL); + } + + public void mouseDown(MouseEvent event) { + if (event.button != 1) { + return; + } + + int clickedPosition = determineClickedPosition(event); + + if (clickedPosition < 0) { + return; + } + + for (Integer offset : this.offsetsToURLs.keySet().toArray(new Integer[0])) { + String url = this.offsetsToURLs.get(offset); + String displayURL = this.urlsToDisplayURLs.get(url); + + if ((displayURL != null) && + (clickedPosition >= offset.intValue()) && + (clickedPosition <= (offset.intValue() + displayURL.length()))) { + try { + Program.launch(url); + } catch (Exception e) { + } + } + } + } + + private int determineClickedPosition(MouseEvent event) { + int clickedPosition = -1; + + try { + clickedPosition = this.textField.getOffsetAtLocation(new Point(event.x, event.y)); + } catch (IllegalArgumentException ex) { + } + + return clickedPosition; + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/URLMouseCursorListener.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/URLMouseCursorListener.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/URLMouseCursorListener.java 2010-07-01 20:11:42 UTC (rev 1078) @@ -0,0 +1,79 @@ +package org.cishell.utilities.swt; + +import java.util.HashMap; +import java.util.Map; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.events.MouseEvent; +import org.eclipse.swt.events.MouseMoveListener; +import org.eclipse.swt.graphics.Cursor; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.widgets.Composite; + +/* + * Monitors the mouse and changes the cursor when it is over a URL. + */ +public class URLMouseCursorListener implements MouseMoveListener { + private Map<Integer, String> offsetsToURLs = new HashMap<Integer, String>(); + private Map<String, String> urlsToDisplayURLs = new HashMap<String, String>(); + private Composite parent; + private StyledText textField; + + public URLMouseCursorListener(Composite parent, StyledText textField) { + this.parent = parent; + this.textField = textField; + } + + public void addURL(int offset, String url) { + addURL(offset, url, url); + } + + public void addURL(int offset, String url, String displayURL) { + this.offsetsToURLs.put(new Integer(offset), url); + this.urlsToDisplayURLs.put(url, displayURL); + } + + public void mouseMove(MouseEvent event) { + int urlOffsetOfMousePosition = determineURLOffsetOfMousePosition(event); + Integer[] urlOffsets = this.offsetsToURLs.keySet().toArray(new Integer[0]); + boolean mouseIsOverURL = determineIfMouseIsHoveringOverURL(urlOffsetOfMousePosition, urlOffsets); + Cursor cursor = new Cursor(parent.getDisplay(), determineMouseCursor(mouseIsOverURL)); + textField.setCursor(cursor); + } + + private int determineURLOffsetOfMousePosition(MouseEvent event) { + try { + return textField.getOffsetAtLocation(new Point(event.x, event.y)); + } catch (IllegalArgumentException e) { + Cursor cursor = new Cursor(parent.getDisplay(), SWT.CURSOR_ARROW); + textField.setCursor(cursor); + } + + return -1; + } + + private boolean determineIfMouseIsHoveringOverURL( + int urlOffsetOfMousePosition, Integer[] urlOffsets) { + for (Integer urlOffset : urlOffsets) { + String url = this.offsetsToURLs.get(urlOffset); + + if ((urlOffset != null) && + (url != null) && + (urlOffsetOfMousePosition >= urlOffset.intValue()) && + (urlOffsetOfMousePosition <= (urlOffset.intValue() + url.length()))) { + return true; + } + } + + return false; + } + + private int determineMouseCursor(boolean mouseIsOverURL) { + if (mouseIsOverURL) { + return SWT.CURSOR_HAND; + } else { + return SWT.CURSOR_ARROW; + } + } +} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pat...@us...> - 2010-08-02 20:27:00
|
Revision: 1101 http://cishell.svn.sourceforge.net/cishell/?rev=1101&view=rev Author: pataphil Date: 2010-08-02 20:26:54 +0000 (Mon, 02 Aug 2010) Log Message: ----------- * Moved ObjectContainer to org.cishell.utilities.datastructure. Modified Paths: -------------- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUIBuilderUtilities.java Removed Paths: ------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ObjectContainer.java Modified: trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF =================================================================== --- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-08-02 20:26:26 UTC (rev 1100) +++ trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-08-02 20:26:54 UTC (rev 1101) @@ -12,6 +12,7 @@ org.cishell.framework.data, org.cishell.reference.service.metatype, org.cishell.service.database, + org.cishell.utilities.datastructure, org.joda.time, org.joda.time.base, org.joda.time.chrono, Deleted: trunk/core/org.cishell.utilities/src/org/cishell/utilities/ObjectContainer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ObjectContainer.java 2010-08-02 20:26:26 UTC (rev 1100) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/ObjectContainer.java 2010-08-02 20:26:54 UTC (rev 1101) @@ -1,12 +0,0 @@ -package org.cishell.utilities; - -public class ObjectContainer<T> { - public T object; - - public ObjectContainer() { - } - - public ObjectContainer(T object) { - this.object = object; - } -}; \ No newline at end of file Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUIBuilderUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUIBuilderUtilities.java 2010-08-02 20:26:26 UTC (rev 1100) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUIBuilderUtilities.java 2010-08-02 20:26:54 UTC (rev 1101) @@ -1,6 +1,6 @@ package org.cishell.utilities.swt; -import org.cishell.utilities.ObjectContainer; +import org.cishell.utilities.datastructure.ObjectContainer; import org.eclipse.swt.SWT; import org.eclipse.swt.events.ShellEvent; import org.eclipse.swt.events.ShellListener; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pat...@us...> - 2010-08-03 17:23:48
|
Revision: 1106 http://cishell.svn.sourceforge.net/cishell/?rev=1106&view=rev Author: pataphil Date: 2010-08-03 17:23:41 +0000 (Tue, 03 Aug 2010) Log Message: ----------- * Moved SWT Utilities out to org.cishell.utilities.swt bundle. Modified Paths: -------------- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF Removed Paths: ------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/ExpandableComponentWidget.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/FileSaveAs.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUIBuilderUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUICanceledException.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GridContainer.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/SWTUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/ScrolledComponentFactory.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/URLClickedListener.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/URLMouseCursorListener.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModel.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModelField.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModelGroup.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/ModelFieldException.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/ Modified: trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF =================================================================== --- trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-08-03 17:21:00 UTC (rev 1105) +++ trunk/core/org.cishell.utilities/META-INF/MANIFEST.MF 2010-08-03 17:23:41 UTC (rev 1106) @@ -36,9 +36,4 @@ org.cishell.utilities.mutateParameter, org.cishell.utilities.mutateParameter.defaultvalue, org.cishell.utilities.mutateParameter.dropdown, - org.cishell.utilities.osgi.logging, - org.cishell.utilities.swt, - org.cishell.utilities.swt.model, - org.cishell.utilities.swt.model.datasynchronizer -Require-Bundle: org.eclipse.ui;resolution:=optional, - org.eclipse.core.runtime;resolution:=optional + org.cishell.utilities.osgi.logging Deleted: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/ExpandableComponentWidget.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/ExpandableComponentWidget.java 2010-08-03 17:21:00 UTC (rev 1105) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/ExpandableComponentWidget.java 2010-08-03 17:23:41 UTC (rev 1106) @@ -1,243 +0,0 @@ -package org.cishell.utilities.swt; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.ScrolledComposite; -import org.eclipse.swt.layout.GridData; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Label; - -/** - * This is meant to be subclassed. - */ -public class ExpandableComponentWidget<T> extends Composite { - public static final int COLUMN_AREA_LAYOUT_VERTICAL_SPACING = 1; - public static final int VERTICAL_SCROLL_INCREMENT = 50; - - private ScrolledComponentFactory<T> componentFactory; - private Composite headerArea; - private ScrolledComposite scrollingArea; - private GridContainer scrolledAreaGrid; - private Composite footerArea; - private List<T> components = new ArrayList<T>(); - private int uniqueComponentCount = 0; - private Collection<Label> columnLabels; - - public ExpandableComponentWidget( - Composite parent, ScrolledComponentFactory<T> componentFactory) { - super(parent, SWT.NONE); - this.componentFactory = componentFactory; - - setLayout(createLayout()); - this.headerArea = createHeaderArea(); - this.scrollingArea = createScrollingArea(); - this.footerArea = createFooterArea(); - this.scrolledAreaGrid = createScrolledAreaGrid(this.scrollingArea); - - this.scrollingArea.setExpandHorizontal(true); - this.scrollingArea.setExpandVertical(true); - this.scrollingArea.setAlwaysShowScrollBars(true); - fixSize(); - this.scrollingArea.setContent(this.scrolledAreaGrid.getActualParent()); - this.scrollingArea.getVerticalBar().setPageIncrement(VERTICAL_SCROLL_INCREMENT); - this.columnLabels = createColumnLabels(this.scrolledAreaGrid.getActualParent(), SWT.NONE); - } - - public Composite getHeaderArea() { - return this.headerArea; - } - - public Composite getFooterArea() { - return this.footerArea; - } - - public List<T> getComponents() { - return Collections.unmodifiableList(this.components); - } - - public int getColumnCount() { - return 1; - } - - public T addComponent(int style, Map<String, Object> arguments) { - // TODO: Fix this terrible hack? - if (this.components.size() == 0) { - for (Label columnLabel : this.columnLabels) { - columnLabel.setVisible(true); - } - } - - final int componentCount = this.components.size(); - T component = this.componentFactory.constructWidget( - this, this.scrolledAreaGrid, style, arguments, componentCount, this.uniqueComponentCount); - this.uniqueComponentCount++; - - fixSize(); - - this.components.add(component); - - return component; - } - - public void removeComponent(int index) { - this.scrolledAreaGrid.removeRow(index); - this.components.remove(index); - fixSize(); - - for (int ii = 0; ii < this.components.size(); ii++) { - this.componentFactory.reindexComponent(this.components.get(ii), ii); - } - - // TODO: Fix this terrible hack? - if (this.components.size() == 0) { - for (Label columnLabel : this.columnLabels) { - columnLabel.setVisible(false); - } - } - } - - public Collection<Label> createColumnLabels(Composite parent, int style) { - List<Label> columnLabels = new ArrayList<Label>(); - - for (String columnLabelText : createColumnLabelTexts()) { - Label columnLabel = new Label(parent, style); - columnLabel.setLayoutData(createColumnLabelLayoutData()); - columnLabel.setText(columnLabelText); - columnLabels.add(columnLabel); - } - - return columnLabels; - } - - public Collection<String> createColumnLabelTexts() { - List<String> columnLabelTexts = new ArrayList<String>(); - - for (int ii = 0; ii < getColumnCount(); ii++) { - columnLabelTexts.add("Column " + ii); - } - - return columnLabelTexts; - } - - private void fixSize() { - Composite scrolledArea = this.scrolledAreaGrid.getActualParent(); - this.scrollingArea.setMinSize(scrolledArea.computeSize(SWT.DEFAULT, SWT.DEFAULT)); - scrolledArea.pack(); - } - - protected Composite createHeaderArea() { - Composite headerArea = new Composite(this, SWT.NONE); - headerArea.setLayoutData(createHeaderAreaLayoutData()); - headerArea.setLayout(createHeaderLayout()); - - return headerArea; - } - - protected GridData createHeaderAreaLayoutData() { - GridData layoutData = new GridData(SWT.FILL, SWT.TOP, true, false); - - return layoutData; - } - - protected GridLayout createHeaderLayout() { - GridLayout layout = new GridLayout(1, false); - GUIBuilderUtilities.clearMargins(layout); - GUIBuilderUtilities.clearSpacing(layout); - - return layout; - } - - protected ScrolledComposite createScrollingArea() { - ScrolledComposite scrollingArea = - new ScrolledComposite(this, SWT.BORDER | SWT.V_SCROLL); - scrollingArea.setLayoutData(createScrollingAreaLayoutData()); - scrollingArea.setLayout(createScrollingLayout()); - - return scrollingArea; - } - - protected GridData createScrollingAreaLayoutData() { - GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true); - - return layoutData; - } - - private GridLayout createScrollingLayout() { - GridLayout layout = new GridLayout(1, true); - GUIBuilderUtilities.clearMargins(layout); - GUIBuilderUtilities.clearSpacing(layout); - - return layout; - } - - protected Composite createFooterArea() { - Composite footerArea = new Composite(this, SWT.BORDER); - footerArea.setLayoutData(createFooterAreaLayoutData()); - footerArea.setLayout(createFooterLayout()); - - return footerArea; - } - - protected GridData createFooterAreaLayoutData() { - GridData layoutData = new GridData(SWT.FILL, SWT.TOP, true, false); - - return layoutData; - } - - protected GridLayout createFooterLayout() { - GridLayout layout = new GridLayout(1, false); - GUIBuilderUtilities.clearMargins(layout); - GUIBuilderUtilities.clearSpacing(layout); - - return layout; - } - - private GridContainer createScrolledAreaGrid(Composite parent) { - Composite columnArea = new Composite(parent, SWT.NONE); - columnArea.setLayoutData(createScrolledAreaLayoutData()); - final int columnCount = getColumnCount(); - columnArea.setLayout(createScrolledAreaLayout(columnCount)); - - return new GridContainer(columnArea, columnCount); - } - - protected GridData createScrolledAreaLayoutData() { - GridData layoutData = new GridData(SWT.FILL, SWT.FILL, true, true); - - return layoutData; - } - - protected GridLayout createScrolledAreaLayout(int columnCount) { - GridLayout layout = new GridLayout(columnCount, false); -// GUIBuilderUtilities.clearMargins(layout); -// GUIBuilderUtilities.clearSpacing(layout); - - return layout; - } - - protected GridData createColumnLabelLayoutData() { - GridData layoutData = new GridData(SWT.CENTER, SWT.CENTER, false, false); - - return layoutData; - } - - protected GridData createComponentLayoutData() { - GridData layoutData = new GridData(SWT.FILL, SWT.TOP, true, false); - - return layoutData; - } - - private static GridLayout createLayout() { - GridLayout layout = new GridLayout(1, true); - GUIBuilderUtilities.clearMargins(layout); - GUIBuilderUtilities.clearSpacing(layout); - - return layout; - } -} \ No newline at end of file Deleted: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/FileSaveAs.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/FileSaveAs.java 2010-08-03 17:21:00 UTC (rev 1105) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/FileSaveAs.java 2010-08-03 17:23:41 UTC (rev 1106) @@ -1,52 +0,0 @@ -package org.cishell.utilities.swt; - -import java.io.File; - -import org.cishell.utilities.StringUtilities; -import org.eclipse.jface.dialogs.MessageDialog; -import org.eclipse.swt.widgets.FileDialog; -import org.eclipse.swt.widgets.Shell; - -public class FileSaveAs { - public static final String DEFAULT_WINDOW_TITLE = "Save As"; - public static final String CONFIRMATION_DIALOG_FORMAT = - "%s already exists.\nDo you want to replace it?"; -// public static final String YES_BUTTON_LABEL = "Yes"; -// public static final String NO_BUTTON_LABEL = "No"; -// public static final String[] BUTTON_LABELS = { YES_BUTTON_LABEL, NO_BUTTON_LABEL }; - - public static String saveFileAs(Shell parent) { - FileDialog saveDialog = new FileDialog(parent); - saveDialog.setText(DEFAULT_WINDOW_TITLE); - - return saveFileAs(saveDialog); - } - - public static String saveFileAs(Shell parent, int style) { - FileDialog saveDialog = new FileDialog(parent, style); - saveDialog.setText(DEFAULT_WINDOW_TITLE); - - return saveFileAs(saveDialog); - } - - public static String saveFileAs(FileDialog saveDialog) { - while (true) { - String selectedFilePath = saveDialog.open(); - - if (StringUtilities.isNull_Empty_OrWhitespace(selectedFilePath)) { - return null; - } else { - if (new File(selectedFilePath).exists()) { - if (MessageDialog.openConfirm( - saveDialog.getParent(), - saveDialog.getText(), - String.format(CONFIRMATION_DIALOG_FORMAT, selectedFilePath))) { - return selectedFilePath; - } - } else { - return selectedFilePath; - } - } - } - } -} \ No newline at end of file Deleted: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUIBuilderUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUIBuilderUtilities.java 2010-08-03 17:21:00 UTC (rev 1105) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUIBuilderUtilities.java 2010-08-03 17:23:41 UTC (rev 1106) @@ -1,124 +0,0 @@ -package org.cishell.utilities.swt; - -import org.cishell.utilities.datastructure.ObjectContainer; -import org.eclipse.swt.SWT; -import org.eclipse.swt.events.ShellEvent; -import org.eclipse.swt.events.ShellListener; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.layout.GridLayout; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.Event; -import org.eclipse.swt.widgets.Listener; -import org.eclipse.swt.widgets.Shell; - -public class GUIBuilderUtilities { - public static Display createDisplay() { - return new Display(); - } - - public static Shell createShell( - Display display, - String windowTitle, - int windowWidth, - int windowHeight, - int columnCount, - boolean clearSpacing) { - Shell shell = new Shell(display, SWT.CLOSE | SWT.MIN | SWT.TITLE); - shell.setText(windowTitle); - shell.setSize(windowWidth, windowHeight); - shell.setLayout(createShellLayout(columnCount, clearSpacing)); - - return shell; - } - - public static GridLayout createShellLayout(int columnCount, boolean clearSpacing) { - GridLayout layout = new GridLayout(columnCount, true); - - if (clearSpacing) { - clearSpacing(layout); - } - - return layout; - } - - public static void openShell( - Shell shell, int windowHeight, boolean useWindowHeightToSizeShell) { -// if (useWindowHeightToSizeShell) { -// /* (So far, we've created the shell at the maximum possible size we'll allow -// * (according to windowHeight). This line shrinks the shell to be a more fitting size -// * if the actual contents (i.e. our (number of) columns) are smaller than the maximum -// * size we set.) -// */ -// Point shellSize = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT); -// shell.setMinimumSize(shellSize.x, Math.min(windowHeight, shellSize.y)); -// } - - shell.pack(); - shell.open(); - - if (useWindowHeightToSizeShell) { - Point shellSize = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT); - shell.setSize(shell.getSize().x, Math.min(windowHeight, shellSize.y)); - } - } - - public static void swtLoop(Display display, Shell shell) { - while (!shell.isDisposed()) { - if (!display.readAndDispatch()) { - display.sleep(); - } - } - - display.dispose(); - } - - public static void clearMargins(GridLayout layout) { - layout.marginTop = layout.marginBottom = layout.marginHeight = 0; - layout.marginLeft = layout.marginRight = layout.marginWidth = 0; - } - - public static void clearSpacing(GridLayout layout) { - layout.horizontalSpacing = layout.verticalSpacing = 0; - } - - public static void setCancelable( - final Shell shell, final ObjectContainer<GUICanceledException> exceptionThrown) { - shell.addListener(SWT.Traverse, new Listener() { - public void handleEvent(Event event) { - switch (event.detail) { - case SWT.TRAVERSE_ESCAPE: - shell.close(); - event.detail = SWT.TRAVERSE_NONE; - event.doit = false; - -// if (exceptionThrown != null) { -// String exceptionMessage = "Canceled by user."; -// exceptionThrown.object = new GUICanceledException(exceptionMessage); -// } - - break; - } - } - }); - shell.addShellListener(new ShellListener() { - public void shellActivated(ShellEvent event) { - } - - public void shellClosed(ShellEvent event) { - if (exceptionThrown != null) { - String exceptionMessage = "Canceled by user."; - exceptionThrown.object = new GUICanceledException(exceptionMessage); - } - } - - public void shellDeactivated(ShellEvent event) { - } - - public void shellDeiconified(ShellEvent event) { - } - - public void shellIconified(ShellEvent event) { - } - }); - } -} \ No newline at end of file Deleted: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUICanceledException.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUICanceledException.java 2010-08-03 17:21:00 UTC (rev 1105) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUICanceledException.java 2010-08-03 17:23:41 UTC (rev 1106) @@ -1,21 +0,0 @@ -package org.cishell.utilities.swt; - -public class GUICanceledException extends Exception { - private static final long serialVersionUID = 1L; - - public GUICanceledException() { - super(); - } - - public GUICanceledException(String arg0) { - super(arg0); - } - - public GUICanceledException(Throwable arg0) { - super(arg0); - } - - public GUICanceledException(String arg0, Throwable arg1) { - super(arg0, arg1); - } -} \ No newline at end of file Deleted: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GridContainer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GridContainer.java 2010-08-03 17:21:00 UTC (rev 1105) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GridContainer.java 2010-08-03 17:23:41 UTC (rev 1106) @@ -1,92 +0,0 @@ -package org.cishell.utilities.swt; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Widget; - -public class GridContainer { - private Composite actualParent; - private int columnCount; - private List<GridRow> rows = new ArrayList<GridRow>(); - - public GridContainer(Composite actualParent, int columnCount) { - this.actualParent = actualParent; - this.columnCount = columnCount; - } - - public Composite getActualParent() { - return this.actualParent; - } - - public int getColumnCount() { - return this.columnCount; - } - - public int getRowCount() { - return this.rows.size(); - } - - public GridRow addComponent(Widget component) { - GridRow lastRow = getOrCreateLastUsableRow(); - lastRow.addComponent(component); - - return lastRow; - } - - public void removeRow(int rowIndex) { - this.rows.get(rowIndex).dispose(); - this.rows.remove(rowIndex); - } - - private GridRow getOrCreateLastUsableRow() { - final int rowCount = getRowCount(); - - if (rowCount == 0) { - return addNewRow(); - } else { - GridRow lastRow = this.rows.get(rowCount - 1); - - if (lastRow.componentCount < getColumnCount()) { - return lastRow; - } else { - return addNewRow(); - } - } - } - - private GridRow addNewRow() { - GridRow row = new GridRow(getRowCount()); - this.rows.add(row); - - return row; - } - - public class GridRow { - private int rowIndex; - private int componentCount = 0; - private Collection<Widget> components = - new ArrayList<Widget>(GridContainer.this.columnCount); - - private GridRow(int rowIndex) { - this.rowIndex = rowIndex; - } - - public int getRowIndex() { - return this.rowIndex; - } - - private void addComponent(Widget component) { - this.components.add(component); - this.componentCount++; - } - - private void dispose() { - for (Widget component : this.components) { - component.dispose(); - } - } - } -} Deleted: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/SWTUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/SWTUtilities.java 2010-08-03 17:21:00 UTC (rev 1105) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/SWTUtilities.java 2010-08-03 17:23:41 UTC (rev 1106) @@ -1,123 +0,0 @@ -package org.cishell.utilities.swt; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StyleRange; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.graphics.Color; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.Display; - -public class SWTUtilities { - /* - * Append the given string to the console with the given color, this will do the job of - * checking for URLs within the string and registering the proper listeners on them as well. - */ - public static void appendStringWithURL( - StyledText textField, - URLClickedListener urlListener, - URLMouseCursorListener urlCursorListener, - String message, - Color normalColor, - Color urlColor) { - - //find a URL in the message - - int index = message.indexOf("http://"); - if (index == -1) { - index = message.indexOf("https://"); - } - if (index == -1) { - index = message.indexOf("www."); - } - - if (index > -1) { - String url = message.substring(index); - if (url.indexOf(") ") > -1) { - url = url.substring(0, url.indexOf(") ")); - } - else if (url.indexOf(" ") > -1) { - url = url.substring(0, url.indexOf(" ")); - if (url.trim().endsWith(".") ){ - url=url.substring(0, url.length()-1); - } - } - if (url.endsWith(".\n") || url.endsWith(".\t")){ - url=url.substring(0, url.length()-2); - } - if (url.indexOf("\n") > -1) { - url = url.substring(0, url.indexOf("\n")); - } - if (url.indexOf("\t") > -1) { - url = url.substring(0, url.indexOf("\n")); - } - - - syncedStyledPrint(textField, message.substring(0, index), normalColor, SWT.NORMAL); - urlListener.addURL(textField.getText().length(), url); - urlCursorListener.addURL(textField.getText().length(), url); - syncedStyledPrint(textField, url, urlColor, SWT.BOLD); - appendStringWithURL( - textField, - urlListener, - urlCursorListener, - message.substring(index + url.length()), - normalColor,urlColor); - } else { - syncedStyledPrint(textField, message, normalColor, SWT.NORMAL); - } - } - - /* - * Helper to actually format the string with a style range and - * append it to the StyledText control. - */ - - public static void syncedStyledPrint( - final StyledText textField, final String message, final Color color, final int style) { - Display.getDefault().syncExec(new Runnable() { - public void run(){ - styledPrint(textField, message, color, style); - } - }); - } - - public static void styledPrint(StyledText textField, String message, Color color, int style) { - if (!textField.isDisposed()) { - textField.append(message); - - StyleRange styleRange = new StyleRange(); - styleRange.start = textField.getText().length() - message.length(); - styleRange.length = message.length(); - styleRange.foreground = color; - styleRange.fontStyle = style; - textField.setStyleRange(styleRange); - - // This makes it autoscroll. - textField.setTopIndex(textField.getLineCount()); - } - } - - public static void printURL( - Composite parent, - StyledText textField, - String url, - String displayURL, - Color color, - int style) { - URLClickedListener urlClickedListener = new URLClickedListener(textField); - URLMouseCursorListener urlCursorListener = - new URLMouseCursorListener(parent, textField); - textField.addMouseListener(urlClickedListener); - textField.addMouseMoveListener(urlCursorListener); - - urlClickedListener.addURL( - textField.getText().length(), url, displayURL); - urlCursorListener.addURL( - textField.getText().length(), url, displayURL); - SWTUtilities.styledPrint( - textField, - displayURL, - color, - style); - } -} \ No newline at end of file Deleted: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/ScrolledComponentFactory.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/ScrolledComponentFactory.java 2010-08-03 17:21:00 UTC (rev 1105) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/ScrolledComponentFactory.java 2010-08-03 17:23:41 UTC (rev 1106) @@ -1,15 +0,0 @@ -package org.cishell.utilities.swt; - -import java.util.Map; - -public interface ScrolledComponentFactory<T> { - public T constructWidget( - ExpandableComponentWidget<T> componentWidget, - GridContainer scrolledAreaGrid, - int style, - Map<String, Object> arguments, - int index, - int uniqueIndex); - - public void reindexComponent(T component, int newIndex); -} \ No newline at end of file Deleted: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/URLClickedListener.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/URLClickedListener.java 2010-08-03 17:21:00 UTC (rev 1105) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/URLClickedListener.java 2010-08-03 17:23:41 UTC (rev 1106) @@ -1,70 +0,0 @@ -package org.cishell.utilities.swt; - -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.events.MouseAdapter; -import org.eclipse.swt.events.MouseEvent; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.program.Program; - -/* - * Listens for clicks on urls and launches a browser. - */ -public class URLClickedListener extends MouseAdapter { - private Map<Integer, String> offsetsToURLs = new HashMap<Integer, String>(); - private Map<String, String> urlsToDisplayURLs = new HashMap<String, String>(); - private StyledText textField; - - public URLClickedListener(StyledText textField) { - super(); - this.textField = textField; - } - - public void addURL(int offset, String url) { - addURL(offset, url, url); - } - - public void addURL(int offset, String url, String displayURL) { - this.offsetsToURLs.put(offset, url); - this.urlsToDisplayURLs.put(url, displayURL); - } - - public void mouseDown(MouseEvent event) { - if (event.button != 1) { - return; - } - - int clickedPosition = determineClickedPosition(event); - - if (clickedPosition < 0) { - return; - } - - for (Integer offset : this.offsetsToURLs.keySet().toArray(new Integer[0])) { - String url = this.offsetsToURLs.get(offset); - String displayURL = this.urlsToDisplayURLs.get(url); - - if ((displayURL != null) && - (clickedPosition >= offset.intValue()) && - (clickedPosition <= (offset.intValue() + displayURL.length()))) { - try { - Program.launch(url); - } catch (Exception e) { - } - } - } - } - - private int determineClickedPosition(MouseEvent event) { - int clickedPosition = -1; - - try { - clickedPosition = this.textField.getOffsetAtLocation(new Point(event.x, event.y)); - } catch (IllegalArgumentException ex) { - } - - return clickedPosition; - } -} \ No newline at end of file Deleted: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/URLMouseCursorListener.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/URLMouseCursorListener.java 2010-08-03 17:21:00 UTC (rev 1105) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/URLMouseCursorListener.java 2010-08-03 17:23:41 UTC (rev 1106) @@ -1,79 +0,0 @@ -package org.cishell.utilities.swt; - -import java.util.HashMap; -import java.util.Map; - -import org.eclipse.swt.SWT; -import org.eclipse.swt.custom.StyledText; -import org.eclipse.swt.events.MouseEvent; -import org.eclipse.swt.events.MouseMoveListener; -import org.eclipse.swt.graphics.Cursor; -import org.eclipse.swt.graphics.Point; -import org.eclipse.swt.widgets.Composite; - -/* - * Monitors the mouse and changes the cursor when it is over a URL. - */ -public class URLMouseCursorListener implements MouseMoveListener { - private Map<Integer, String> offsetsToURLs = new HashMap<Integer, String>(); - private Map<String, String> urlsToDisplayURLs = new HashMap<String, String>(); - private Composite parent; - private StyledText textField; - - public URLMouseCursorListener(Composite parent, StyledText textField) { - this.parent = parent; - this.textField = textField; - } - - public void addURL(int offset, String url) { - addURL(offset, url, url); - } - - public void addURL(int offset, String url, String displayURL) { - this.offsetsToURLs.put(new Integer(offset), url); - this.urlsToDisplayURLs.put(url, displayURL); - } - - public void mouseMove(MouseEvent event) { - int urlOffsetOfMousePosition = determineURLOffsetOfMousePosition(event); - Integer[] urlOffsets = this.offsetsToURLs.keySet().toArray(new Integer[0]); - boolean mouseIsOverURL = determineIfMouseIsHoveringOverURL(urlOffsetOfMousePosition, urlOffsets); - Cursor cursor = new Cursor(parent.getDisplay(), determineMouseCursor(mouseIsOverURL)); - textField.setCursor(cursor); - } - - private int determineURLOffsetOfMousePosition(MouseEvent event) { - try { - return textField.getOffsetAtLocation(new Point(event.x, event.y)); - } catch (IllegalArgumentException e) { - Cursor cursor = new Cursor(parent.getDisplay(), SWT.CURSOR_ARROW); - textField.setCursor(cursor); - } - - return -1; - } - - private boolean determineIfMouseIsHoveringOverURL( - int urlOffsetOfMousePosition, Integer[] urlOffsets) { - for (Integer urlOffset : urlOffsets) { - String url = this.offsetsToURLs.get(urlOffset); - - if ((urlOffset != null) && - (url != null) && - (urlOffsetOfMousePosition >= urlOffset.intValue()) && - (urlOffsetOfMousePosition <= (urlOffset.intValue() + url.length()))) { - return true; - } - } - - return false; - } - - private int determineMouseCursor(boolean mouseIsOverURL) { - if (mouseIsOverURL) { - return SWT.CURSOR_HAND; - } else { - return SWT.CURSOR_ARROW; - } - } -} \ No newline at end of file Deleted: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModel.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModel.java 2010-08-03 17:21:00 UTC (rev 1105) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModel.java 2010-08-03 17:23:41 UTC (rev 1106) @@ -1,190 +0,0 @@ -package org.cishell.utilities.swt.model; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import org.cishell.utilities.swt.model.datasynchronizer.CheckBoxDataSynchronizer; -import org.cishell.utilities.swt.model.datasynchronizer.DropDownDataSynchronizer; -import org.cishell.utilities.swt.model.datasynchronizer.ModelDataSynchronizer; -import org.cishell.utilities.swt.model.datasynchronizer.SingleListSelectionDataSynchronizer; -import org.cishell.utilities.swt.model.datasynchronizer.TextDataSynchronizer; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Button; -import org.eclipse.swt.widgets.Combo; -import org.eclipse.swt.widgets.Composite; -import org.eclipse.swt.widgets.List; -import org.eclipse.swt.widgets.Text; -import org.eclipse.swt.widgets.Widget; - -public class GUIModel { - private Map<String, GUIModelGroup> groups = new HashMap<String, GUIModelGroup>(); - - public GUIModel() { - } - - public Collection<String> getGroupNames() { - return this.groups.keySet(); - } - - public Collection<GUIModelGroup> getGroups() { - return this.groups.values(); - } - - public GUIModelGroup getGroup(String name) { - if (!this.groups.containsKey(name)) { - GUIModelGroup newGroup = new GUIModelGroup(name); - this.groups.put(name, newGroup); - - return newGroup; - } else { - return this.groups.get(name); - } - } - - public GUIModelField<Boolean, Button, CheckBoxDataSynchronizer> addCheckBox( - String groupName, String name, boolean on, Composite parent, int style) { - Button checkBox = new Button(parent, style | SWT.CHECK); - CheckBoxDataSynchronizer dataSynchronizer = new CheckBoxDataSynchronizer(checkBox, on); - GUIModelField<Boolean, Button, CheckBoxDataSynchronizer> field = - new GUIModelField<Boolean, Button, CheckBoxDataSynchronizer>( - name, on, checkBox, dataSynchronizer); - addField(groupName, field); - - return field; - } - - public GUIModelField<String, Combo, DropDownDataSynchronizer> addDropDown( - String groupName, - String name, - int selectedIndex, - Collection<String> unorderedOptionLabels, - Map<String, String> optionValuesByLabels, - Composite parent, - int style) { - java.util.List<String> orderedOptionLabels = new ArrayList<String>(unorderedOptionLabels); - Combo dropDown = new Combo(parent, style | SWT.DROP_DOWN); - DropDownDataSynchronizer dataSynchronizer = new DropDownDataSynchronizer( - dropDown, selectedIndex, orderedOptionLabels, optionValuesByLabels); - GUIModelField<String, Combo, DropDownDataSynchronizer> field = - new GUIModelField<String, Combo, DropDownDataSynchronizer>( - name, - optionValuesByLabels.get(orderedOptionLabels.get(selectedIndex)), - dropDown, - dataSynchronizer); - addField(groupName, field); - - return field; - } - - // TODO: addMultiSelectionDropDown - - // TODO: Test this out. - // TODO: Make it so the build works with this stuff. -// public GUIModelField< -// org.joda.time.DateTime, org.eclipse.swt.widgets.DateTime, DateDataSynchronizer> -// addDate(String name, org.joda.time.DateTime date, Composite parent, int style) { -// org.eclipse.swt.widgets.DateTime dateSelector = -// new org.eclipse.swt.widgets.DateTime(parent, style | SWT.DATE); -// DateDataSynchronizer dataSynchronizer = new DateDataSynchronizer(dateSelector, date); -// GUIModelField< -// org.joda.time.DateTime, org.eclipse.swt.widgets.DateTime, DateDataSynchronizer> field = -// new GUIModelField< -// org.joda.time.DateTime, -// org.eclipse.swt.widgets.DateTime, -// DateDataSynchronizer>( -// name, date, dateSelector, dataSynchronizer); -// addField(field); -// -// return field; -// } - - // TODO: Test this out. -// public GUIModelField< -// org.joda.time.DateTime, org.eclipse.swt.widgets.DateTime, TimeDataSynchronizer> -// addTime(String name, org.joda.time.DateTime time, Composite parent, int style) { -// org.eclipse.swt.widgets.DateTime timeSelector = -// new org.eclipse.swt.widgets.DateTime(parent, style | SWT.TIME); -// TimeDataSynchronizer dataSynchronizer = new TimeDataSynchronizer(timeSelector, time); -// GUIModelField< -// org.joda.time.DateTime, org.eclipse.swt.widgets.DateTime, TimeDataSynchronizer> field = -// new GUIModelField< -// org.joda.time.DateTime, -// org.eclipse.swt.widgets.DateTime, -// TimeDataSynchronizer>( -// name, time, timeSelector, dataSynchronizer); -// addField(field); -// -// return field; -// } - - // TODO: addCalendar - - // TODO: Test this out. - public GUIModelField<String, List, SingleListSelectionDataSynchronizer> addList( - String groupName, - String name, - int selectedIndex, - Collection<String> unorderedOptionLabels, - Map<String, String> optionValuesByLabels, - Composite parent, - int style) { - java.util.List<String> orderedOptionLabels = new ArrayList<String>(unorderedOptionLabels); - List list = new List(parent, style | SWT.SINGLE); - SingleListSelectionDataSynchronizer dataSynchronizer = - new SingleListSelectionDataSynchronizer( - list, selectedIndex, orderedOptionLabels, optionValuesByLabels); - GUIModelField<String, List, SingleListSelectionDataSynchronizer> field = - new GUIModelField<String, List, SingleListSelectionDataSynchronizer>( - name, list.getItem(selectedIndex), list, dataSynchronizer); - addField(groupName, field); - - return field; - } - - // TODO: addMultiSelectionList - // TODO: addProgressBar - // TODO: addSash? - // TODO: addSlider - // TODO: addScale - // TODO: addSpinner - // TODO: addStyledText - - public GUIModelField<String, Text, TextDataSynchronizer> addText( - String groupName, - String name, - String value, - boolean isMultiLined, - Composite parent, - int style) { - if (isMultiLined) { - style = style | SWT.MULTI; - } else { - style = style | SWT.SINGLE; - } - - Text text = new Text(parent, style); - TextDataSynchronizer dataSynchronizer = new TextDataSynchronizer(text, value); - GUIModelField<String, Text, TextDataSynchronizer> field = - new GUIModelField<String, Text, TextDataSynchronizer>( - name, value, text, dataSynchronizer); - addField(groupName, field); - - return field; - } - - public<T> void addField( - String groupName, - GUIModelField<T, ? extends Widget, ? extends ModelDataSynchronizer<?>> field) { - GUIModelGroup group = getGroup(groupName); - group.addField(field); - } - - public<T> void removeField( - GUIModelField<T, ? extends Widget, ? extends ModelDataSynchronizer<?>> field) { - for (GUIModelGroup group : this.groups.values()) { - group.removeField(field); - } - } -} \ No newline at end of file Deleted: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModelField.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModelField.java 2010-08-03 17:21:00 UTC (rev 1105) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModelField.java 2010-08-03 17:23:41 UTC (rev 1106) @@ -1,65 +0,0 @@ -package org.cishell.utilities.swt.model; - -import org.cishell.utilities.swt.model.datasynchronizer.ModelDataSynchronizer; -import org.eclipse.swt.widgets.Event; -import org.eclipse.swt.widgets.Listener; -import org.eclipse.swt.widgets.Widget; - -public class GUIModelField<T, U extends Widget, V extends ModelDataSynchronizer<T>> { - private String name; - private T defaultValue; - private T previousValue; - private T value; - private U widget; - private V dataSynchronizer; - - public GUIModelField( - String name, - T defaultValue, - U widget, - V dataSynchronizer) { - this.name = name; - this.defaultValue = defaultValue; - this.value = this.defaultValue; - this.widget = widget; - this.dataSynchronizer = dataSynchronizer; - - this.widget.addListener(this.dataSynchronizer.swtUpdateListenerCode(), new Listener() { - public void handleEvent(Event event) { - if (event.type == GUIModelField.this.dataSynchronizer.swtUpdateListenerCode()) { - GUIModelField.this.previousValue = GUIModelField.this.value; - GUIModelField.this.value = - GUIModelField.this.dataSynchronizer.synchronizeFromGUI(); - } - } - }); - } - - public String getName() { - return this.name; - } - - public T getPreviousValue() { - return this.previousValue; - } - - public T getValue() { - return this.value; - } - - public U getWidget() { - return this.widget; - } - - public V getDataSynchronizer() { - return this.dataSynchronizer; - } - - public void setValue(T value) { - this.value = this.dataSynchronizer.synchronizeToGUI(value); - } - - public void reset() { - this.value = this.dataSynchronizer.reset(this.defaultValue); - } -} \ No newline at end of file Deleted: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModelGroup.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModelGroup.java 2010-08-03 17:21:00 UTC (rev 1105) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModelGroup.java 2010-08-03 17:23:41 UTC (rev 1106) @@ -1,57 +0,0 @@ -package org.cishell.utilities.swt.model; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; - -import org.cishell.utilities.swt.model.datasynchronizer.ModelDataSynchronizer; -import org.eclipse.swt.widgets.Widget; - -public class GUIModelGroup { - private String name; - private Map<String, GUIModelField<?, ? extends Widget, ? extends ModelDataSynchronizer<?>>> - inputFieldsByName = new HashMap< - String, GUIModelField<?, ? extends Widget, ? extends ModelDataSynchronizer<?>>>(); - - public GUIModelGroup(String name) { - this.name = name; - } - - public String getName() { - return this.name; - } - - public Collection<String> getFieldNames() { - return this.inputFieldsByName.keySet(); - } - - public Collection< - GUIModelField<?, ? extends Widget, ? extends ModelDataSynchronizer<?>>> getFields() { - return this.inputFieldsByName.values(); - } - - public GUIModelField< - ?, ? extends Widget, ? extends ModelDataSynchronizer<?>> getField(String name) { - return this.inputFieldsByName.get(name); - } - - public<T> void addField( - GUIModelField<T, ? extends Widget, ? extends ModelDataSynchronizer<?>> field) { - String fieldName = field.getName(); - - if (this.inputFieldsByName.containsKey(fieldName)) { - String exceptionMessage = - "A field with the name \"" + fieldName + "\" already exists. Unable to continue."; - throw new ModelFieldException(exceptionMessage); - } - - this.inputFieldsByName.put(fieldName, field); - } - - public<T> void removeField( - GUIModelField<T, ? extends Widget, ? extends ModelDataSynchronizer<?>> field) { - if (this.inputFieldsByName.containsValue(field)) { - this.inputFieldsByName.remove(field.getName()); - } - } -} \ No newline at end of file Deleted: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/ModelFieldException.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/ModelFieldException.java 2010-08-03 17:21:00 UTC (rev 1105) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/ModelFieldException.java 2010-08-03 17:23:41 UTC (rev 1106) @@ -1,21 +0,0 @@ -package org.cishell.utilities.swt.model; - -public class ModelFieldException extends RuntimeException { - private static final long serialVersionUID = 1L; - - public ModelFieldException() { - super(); - } - - public ModelFieldException(String arg0) { - super(arg0); - } - - public ModelFieldException(Throwable arg0) { - super(arg0); - } - - public ModelFieldException(String arg0, Throwable arg1) { - super(arg0, arg1); - } -} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |