[CIShell-SVN] SF.net SVN: cishell:[1025]
trunk/core/org.cishell.utilities/src/org/cishell /utilities
From: <fu...@us...> - 2010-01-26 16:51:38
|
Revision: 1025 http://cishell.svn.sourceforge.net/cishell/?rev=1025&view=rev Author: fugu13 Date: 2010-01-26 16:51:30 +0000 (Tue, 26 Jan 2010) Log Message: ----------- Some minor changes. Modified Paths: -------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/DatabaseUtilities.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 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-26 16:34:27 UTC (rev 1024) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/DatabaseUtilities.java 2010-01-26 16:51:30 UTC (rev 1025) @@ -31,8 +31,8 @@ } return connection; } - - public static String getInExpression(List<String> columns, List<Map<String, Object>> valueMaps) { + // TODO: I'd prefer something like createSQLInExpression + public static String createSQLInExpression(List<String> columns, List<Map<String, Object>> valueMaps) { String columnNames = implodeAndWrap(columns); List<String> values = new ArrayList<String>(); @@ -62,6 +62,7 @@ } } + //TODO: Consider abstracting what you're wrapping with and making this a StringUtility. public static String implodeAndWrap(List<String> values) { return "(" + StringUtilities.implodeList(values, ", ") + ")"; } 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-01-26 16:34:27 UTC (rev 1024) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/DatabaseTable.java 2010-01-26 16:51:30 UTC (rev 1025) @@ -145,7 +145,7 @@ private String constructDeleteStatement(List<String> columns, List<Map<String, Object>> otherEntities) { - return "DELETE FROM " + this.toString() + " WHERE " + DatabaseUtilities.getInExpression(columns, otherEntities); + return "DELETE FROM " + this.toString() + " WHERE " + DatabaseUtilities.createSQLInExpression(columns, otherEntities); } public void duplicateTable(Connection originalConnection, 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-01-26 16:34:27 UTC (rev 1024) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ForeignKey.java 2010-01-26 16:51:30 UTC (rev 1025) @@ -37,7 +37,7 @@ 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)); + + DatabaseUtilities.createSQLInExpression(getForeignColumnNames(), translateToForeignNames(from)); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
[CIShell-SVN] SF.net SVN: cishell:[1041]
trunk/core/org.cishell.utilities/src/org/cishell /utilities
From: <pat...@us...> - 2010-03-03 21:47:48
|
Revision: 1041 http://cishell.svn.sourceforge.net/cishell/?rev=1041&view=rev Author: pataphil Date: 2010-03-03 21:47:35 +0000 (Wed, 03 Mar 2010) Log Message: ----------- * Added NumberUtilities.roundToNDecimalPlaces(). * Cleaned up/refactored TableUtilities and added TableUtilities.extractDoubleFromCell(). * Finally had LogMessageHandler reviewed and refactored to be more straightforward. * Reviewed by Joseph. Modified Paths: -------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/NumberUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/TableUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/osgi/logging/LogMessageHandler.java Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/NumberUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/NumberUtilities.java 2010-02-23 18:33:04 UTC (rev 1040) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/NumberUtilities.java 2010-03-03 21:47:35 UTC (rev 1041) @@ -133,6 +133,13 @@ } } + public static double roundToNDecimalPlaces(double original, int decimalPlaceCount) { + String formatString = "#." + StringUtilities.multiply("#", decimalPlaceCount); + DecimalFormat format = new DecimalFormat(formatString); + + return Double.valueOf(format.format(original)); + } + public static boolean isEven(long number) { return ((number % 2) == 0); } Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/TableUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/TableUtilities.java 2010-02-23 18:33:04 UTC (rev 1040) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/TableUtilities.java 2010-03-03 21:47:35 UTC (rev 1041) @@ -11,125 +11,145 @@ import prefuse.util.collections.IntIterator; public class TableUtilities { - public static String[] filterSchemaColumnNamesByClass - (Schema schema, Class objectClass) throws ColumnNotFoundException - { - ArrayList workingColumnNames = new ArrayList(); + public static Table copyTable(Table oldTable) { + Schema oldSchema = oldTable.getSchema(); + Table newTable = oldSchema.instantiate(); + + for (Iterator rowIt = oldTable.tuples(); rowIt.hasNext();) { + Tuple row = (Tuple) rowIt.next(); + newTable.addTuple(row); + } + + return newTable; + } - for (int ii = 0; ii < schema.getColumnCount(); ii++) { - if (objectClass.isAssignableFrom(schema.getColumnType(ii))) - workingColumnNames.add(schema.getColumnName(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 (workingColumnNames.size() == 0) { - throw new ColumnNotFoundException - ("No column of type " + objectClass.getName() + " was found."); + 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); + } + } - String[] finalColumnNames = new String [workingColumnNames.size()]; + return newTable; + } - return (String[])workingColumnNames.toArray(finalColumnNames); + 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 List getAllColumnNames(Schema schema) - throws ColumnNotFoundException { - List workingColumnNames = new ArrayList(); - + + public static List<String> getAllColumnNames(Schema schema) throws ColumnNotFoundException { + List<String> workingColumnNames = new ArrayList<String>(); + 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."); + throw new ColumnNotFoundException("No columns found in the schema."); } return workingColumnNames; } - - public static String formNonConflictingNewColumnName( - Schema schema, String suggestedColumnName) + + public static String[] getValidStringColumnNamesInTable(Table table) 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++; - } - } + return filterSchemaColumnNamesByClass(table.getSchema(), String.class); + } + + 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 String formNonConflictingNewColumnName( - Schema schema, String[] suggestedColumnNames) + + public static String[] getValidIntegerColumnNamesInTable(Table table) throws ColumnNotFoundException { - List workingColumnNames = getAllColumnNames(schema); + Class<?>[] possibleIntegerClasses = { + int.class, + Integer.class, + int[].class, + Integer[].class + }; + + return filterSchemaColumnNamesByClasses(table.getSchema(), possibleIntegerClasses); + } - boolean suggestedNameFound = false; - for(int suggestedNameIndex = 0; suggestedNameIndex < suggestedColumnNames.length; suggestedNameIndex++) { - for(int i = 0; i < workingColumnNames.size(); i++) { - if(workingColumnNames.get(i).toString().equalsIgnoreCase(suggestedColumnNames[suggestedNameIndex])) { - suggestedNameFound = true; - break; - } - } - /* - * To ensure that whenever a suggested name is found in the original column schema, create a name. - * */ - if(suggestedNameFound) { - break; - } - } + public static String[] getValidDateColumnNamesInTable(Table table) + throws ColumnNotFoundException { + Class<?>[] possibleDateClasses = { + Date.class, + int.class, + Integer.class, + String.class, + int[].class, + Integer[].class, + String[].class, + }; - /* - * If none of the suggested names are conflicting then return the first suggested name. - * */ - if(!suggestedNameFound) { - return suggestedColumnNames[0]; - } + return filterSchemaColumnNamesByClasses(table.getSchema(), possibleDateClasses); + } - /* - * This part of code will be executed only if the suggested names are already present in the - * column schema. - * */ - boolean newColumnNameFound = false; - int columnNameSuffix = 2; - while(true) { - /* - * The pattern for new names will be taken from the first suggested column name. - * */ - String newColumnName = - suggestedColumnNames[0].concat("_" + columnNameSuffix); - for(int i = 0; i < workingColumnNames.size(); i++) { - if(workingColumnNames.get(i).toString().equalsIgnoreCase(newColumnName)) { - newColumnNameFound = true; - break; - } - } - if(!newColumnNameFound) { - return newColumnName; - } - columnNameSuffix++; - } - } - - public static String[] filterSchemaColumnNamesByClasses - (Schema schema, Class[] objectClasses) throws ColumnNotFoundException - { - ArrayList workingColumnNames = new ArrayList(); + public static String[] filterSchemaColumnNamesByClasses( + Schema schema, Class<?>[] objectClasses) throws ColumnNotFoundException { + ArrayList<String> workingColumnNames = new ArrayList<String>(); for (int ii = 0; ii < schema.getColumnCount(); ii++) { - for (int jj = 0; jj < objectClasses.length; jj++) { - Class objectClass = objectClasses[jj]; - + for (Class<?> objectClass : objectClasses) { if (objectClass.isAssignableFrom(schema.getColumnType(ii))) { workingColumnNames.add(schema.getColumnName(ii)); @@ -142,9 +162,8 @@ 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 { + } else { + // An exception is thrown if there is not at least 1 column name. StringBuffer objectClassesString = new StringBuffer(); objectClassesString.append("["); @@ -158,79 +177,108 @@ objectClassesString.append("]"); - throw new ColumnNotFoundException - ("No column of types " + objectClassesString + " was found."); + 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, - }; + + public static String[] filterSchemaColumnNamesByClass(Schema schema, Class<?> objectClass) + throws ColumnNotFoundException { + ArrayList<String> workingColumnNames = new ArrayList<String>(); + + for (int ii = 0; ii < schema.getColumnCount(); ii++) { + if (objectClass.isAssignableFrom(schema.getColumnType(ii))) + workingColumnNames.add(schema.getColumnName(ii)); + } - 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); - } + 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 String[] getValidNumberColumnNamesInTable(Table table) + public static String formNonConflictingNewColumnName(Schema schema, String suggestedColumnName) 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 - }; + List<String> 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 formNonConflictingNewColumnName( + Schema schema, String[] suggestedColumnNames) throws ColumnNotFoundException { + List<String> workingColumnNames = getAllColumnNames(schema); + boolean suggestedNameFound = false; + + for (String suggestedName : suggestedColumnNames) { + for (String workingColumnName : workingColumnNames) { + if (workingColumnName.equalsIgnoreCase(suggestedName)) { + suggestedNameFound = true; + + break; + } + } + + /* + * To ensure that whenever a suggested name is found in the original column schema, + * create a name. + */ + if (suggestedNameFound) { + break; + } + } - return filterSchemaColumnNamesByClasses(table.getSchema(), - possibleNumberClasses); + /* + * If none of the suggested names are conflicting then return the first suggested name. + */ + if(!suggestedNameFound) { + return suggestedColumnNames[0]; + } + + /* + * This part of code will be executed only if the suggested names are already present in + * the column schema. + */ + boolean newColumnNameFound = false; + int columnNameSuffix = 2; + + while(true) { + /* + * The pattern for new names will be taken from the first suggested column name. + */ + String newColumnName = suggestedColumnNames[0].concat("_" + columnNameSuffix); + + for (String workingColumnName : workingColumnNames) { + if (workingColumnName.equalsIgnoreCase(newColumnName)) { + newColumnNameFound = true; + + break; + } + } + + if (!newColumnNameFound) { + return newColumnName; + } + + columnNameSuffix++; + } } /** @@ -241,73 +289,16 @@ Table table = new Table(); for (int ii = 0; ii < numTableColumns; ii++) { - table.addColumn(tableSchema.getColumnName(ii), - tableSchema.getColumnType(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); - } - } + public static double extractDoubleFromCell(Tuple row, String columnName) + throws NumberFormatException { + double value = NumberUtilities.interpretObjectAsDouble(row.get(columnName)).doubleValue(); - return newTable; + return value; } - - public static Table copyTable(Table oldTable) { - Schema oldSchema = oldTable.getSchema(); - Table newTable = oldSchema.instantiate(); - - for (Iterator rowIt = oldTable.tuples(); rowIt.hasNext();) { - Tuple row = (Tuple) rowIt.next(); - newTable.addTuple(row); - } - - return newTable; - } } \ No newline at end of file Modified: 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 2010-02-23 18:33:04 UTC (rev 1040) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/osgi/logging/LogMessageHandler.java 2010-03-03 21:47:35 UTC (rev 1041) @@ -5,12 +5,10 @@ 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>(); + private Map<MessageTypeDescriptor, MessageType> messageTypes = + new HashMap<MessageTypeDescriptor, MessageType>(); public LogMessageHandler(LogService logger) { this.logger = logger; @@ -20,82 +18,65 @@ * 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)); + public MessageTypeDescriptor addMessageType(String description, int maximumCount) { + MessageTypeDescriptor typeIndicator = new MessageTypeDescriptor(); + 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) { + /// message will always be logged if typeIndicator has not been added prior to calling this. + public void handleMessage(MessageTypeDescriptor typeIndicator, int logLevel, String message) { MessageType messageType = this.messageTypes.get(typeIndicator); if (messageType != null) { - if (messageType.messageLogged()) { - this.logger.log(logLevel, logMessage); - } + messageType.logMessage(logLevel, message, this.logger); } else { - this.logger.log(logLevel, logMessage); + this.logger.log(logLevel, message); } } public void printOverloadedMessageTypes(int logLevel) { for (MessageType messageType : this.messageTypes.values()) { - if (messageType.wasOverloaded()) { - this.logger.log(logLevel, messageType.toString()); + if (messageType.isOverloaded()) { + this.logger.log(logLevel, messageType.reportOverloads()); } } } - public class MessageTypeIndicator {} + // TODO: Javadoc what this is all about. (I will later.) + public class MessageTypeDescriptor {} - private class MessageType { + private static class MessageType { private String description; private int maximumCount; private int foundCount = 0; - private int overLoadedCount = 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 void logMessage(int logLevel, String message, LogService logger) { + if (shouldStillLog()) { + logger.log(logLevel, message); + this.foundCount++; + } else { + this.overloadedCount++; + } } - public boolean wasOverloaded() { - return this.overLoadedCount > 0; + public String reportOverloads() { + return "Found " + this.overloadedCount + " more " + this.description + "."; } - public boolean messageLogged() { - if (hasAnyLeft()) { - this.foundCount++; - - return true; - } else { - this.overLoadedCount++; - - return false; - } + private boolean shouldStillLog() { + return this.foundCount < this.maximumCount; } - public String toString() { - return - "Found " + - this.overLoadedCount + - " more " + - this.description + - "."; + private boolean isOverloaded() { + return this.overloadedCount > 0; } } } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
[CIShell-SVN] SF.net SVN: cishell:[1057]
trunk/core/org.cishell.utilities/src/org/cishell /utilities
From: <pat...@us...> - 2010-03-22 20:05:04
|
Revision: 1057 http://cishell.svn.sourceforge.net/cishell/?rev=1057&view=rev Author: pataphil Date: 2010-03-22 20:04:57 +0000 (Mon, 22 Mar 2010) Log Message: ----------- * Mutate Parameter utilities now allow attributes to be explicitly ignored. * Reviewed by Joseph. Modified Paths: -------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DropdownMutator.java Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java 2010-03-19 22:38:14 UTC (rev 1056) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java 2010-03-22 20:04:57 UTC (rev 1057) @@ -1,6 +1,7 @@ package org.cishell.utilities; import java.io.IOException; +import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; @@ -154,7 +155,8 @@ } }; - return ObjectClassDefinitionTransformer.apply(dropdownTransformer, oldOCD); + return ObjectClassDefinitionTransformer.apply( + dropdownTransformer, oldOCD, new ArrayList<String>()); } public static BasicObjectClassDefinition mutateDefaultValue( @@ -172,7 +174,8 @@ } }; - return ObjectClassDefinitionTransformer.apply(transformer, oldOCD); + return ObjectClassDefinitionTransformer.apply( + transformer, oldOCD, new ArrayList<String>()); } public static BasicObjectClassDefinition createNewParameters( 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 2010-03-19 22:38:14 UTC (rev 1056) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java 2010-03-22 20:04:57 UTC (rev 1057) @@ -1,6 +1,7 @@ package org.cishell.utilities.mutateParameter; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; @@ -30,7 +31,8 @@ */ public static BasicObjectClassDefinition apply( AttributeDefinitionTransformer transformer, - ObjectClassDefinition oldOCD) { + ObjectClassDefinition oldOCD, + Collection<String> attributesToIgnore) { BasicObjectClassDefinition newOCD = MutateParameterUtilities.createNewParameters(oldOCD); @@ -44,9 +46,10 @@ oldOCD.getAttributeDefinitions(filter); for (int ii = 0; ii < oldADs.length; ii++) { - newOCD.addAttributeDefinition( - filter, - transformer.transform(oldADs[ii])); + if (!attributesToIgnore.contains(oldADs[ii].getID())) { + newOCD.addAttributeDefinition( + filter, transformer.transform(oldADs[ii])); + } } } @@ -55,14 +58,14 @@ // Convenience method for batching transformations. public static ObjectClassDefinition transform( - ObjectClassDefinition ocd, List transformers) { + ObjectClassDefinition ocd, List transformers, Collection<String> attributesToIgnore) { ObjectClassDefinition newOCD = ocd; for (Iterator it = transformers.iterator(); it.hasNext();) { AttributeDefinitionTransformer transformer = (AttributeDefinitionTransformer) it.next(); - newOCD = apply(transformer, newOCD); + newOCD = apply(transformer, newOCD, attributesToIgnore); } return newOCD; Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DropdownMutator.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DropdownMutator.java 2010-03-19 22:38:14 UTC (rev 1056) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DropdownMutator.java 2010-03-22 20:04:57 UTC (rev 1057) @@ -2,8 +2,9 @@ import java.util.ArrayList; import java.util.Arrays; -import java.util.Iterator; +import java.util.HashSet; import java.util.List; +import java.util.Set; import org.cishell.utilities.ArrayUtilities; import org.cishell.utilities.mutateParameter.ObjectClassDefinitionTransformer; @@ -19,13 +20,15 @@ */ public class DropdownMutator { private List transforms; + private Set<String> attributesToIgnore = new HashSet<String>(); public DropdownMutator() { transforms = new ArrayList(); } public ObjectClassDefinition mutate(ObjectClassDefinition ocd) { - return ObjectClassDefinitionTransformer.transform(ocd, transforms); + return ObjectClassDefinitionTransformer.transform( + ocd, transforms, this.attributesToIgnore); } public void add(String id, List options, String defaultOption) { @@ -36,20 +39,23 @@ 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, + 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])); + add( + id, + (String[]) optionLabels.toArray(new String[0]), + (String[]) optionValues.toArray(new String[0])); } public void add(String id, String[] options, String defaultOption) { @@ -60,34 +66,49 @@ add(id, options, options); } - public void add(final String id, - final String[] optionLabels, - String defaultOptionLabel, - final String[] optionValues, - String defaultOptionValue) { - add(id, + public void add( + final String id, + final String[] optionLabels, + String defaultOptionLabel, + final String[] optionValues, + String defaultOptionValue) { + if (!shouldIgnore(id)) { + 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; - } - }); + public void add( + final String id, + final String[] optionLabels, + final String[] optionValues) { + if (!shouldIgnore(id)) { + 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; + } + }); + } } + + public void ignore(String id) { + this.attributesToIgnore.add(id); + } + + public boolean shouldIgnore(String id) { + return this.attributesToIgnore.contains(id); + } private static List swapToFront(List list, String target) { String[] temp = (String[]) list.toArray(new String[]{}); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
[CIShell-SVN] SF.net SVN: cishell:[1076]
trunk/core/org.cishell.utilities/src/org/cishell /utilities
From: <pat...@us...> - 2010-06-20 19:33:22
|
Revision: 1076 http://cishell.svn.sourceforge.net/cishell/?rev=1076&view=rev Author: pataphil Date: 2010-06-20 19:33:14 +0000 (Sun, 20 Jun 2010) Log Message: ----------- * Cleaned AlgorithmUtilities. * Refactored implodeList, renaming it to implodeItems and changing its signature to accept a Collection instead of List (making it more generic). Subsequently added implodeList back, wrapping implodeItems, to make depedencies happy. * Added org.cishell.utilities.mutateParameter.MetaAttributeDefinition (container for AD type (required, optional) and AD itself). * Added ListUtilities. * Made DefaultDictionary Java 1.5 (K, V). * Updated reference to implodeList in various places. Modified Paths: -------------- 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/DatabaseUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/DefaultDictionary.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/StringUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/Column.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/ListUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/MetaAttributeDefinition.java Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/AlgorithmUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/AlgorithmUtilities.java 2010-06-20 19:16:46 UTC (rev 1075) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/AlgorithmUtilities.java 2010-06-20 19:33:14 UTC (rev 1076) @@ -20,26 +20,21 @@ // 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 { + 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); - + + if (algorithmFactoryReferences != null && algorithmFactoryReferences.length != 0) { + ServiceReference algorithmFactoryReference = algorithmFactoryReferences[0]; + AlgorithmFactory algorithmFactory = (AlgorithmFactory)bundleContext.getService( + algorithmFactoryReference); + return algorithmFactory; } else { @@ -47,19 +42,18 @@ "algorithm that satisfied the following filter:\n" + filter); } } - + public static AlgorithmFactory getAlgorithmFactoryByPID( - String pid, BundleContext bundleContext) - throws AlgorithmNotFoundException { + String pid, BundleContext bundleContext) throws AlgorithmNotFoundException { String filter = "(service.pid=" + pid + ")"; - + return getAlgorithmFactoryByFilter(filter, bundleContext); } public static Data[] cloneSingletonData(Data[] data) { - return new Data[]{ new BasicData(data[0].getMetadata(), - data[0].getData(), - data[0].getFormat()) }; + return new Data[] { + new BasicData(data[0].getMetadata(), data[0].getData(), data[0].getFormat()) + }; } /** @@ -82,29 +76,30 @@ * receiving a new data item, the Data Manager algorithm would set this new * property to the data item's label if not set already. */ + @SuppressWarnings("unchecked") // Raw Dictionary 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[] 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 = @@ -130,8 +125,7 @@ Dictionary parameters, CIShellContext ciShellContext) throws AlgorithmExecutionException { - Algorithm algorithm = - algorithmFactory.createAlgorithm(data, parameters, ciShellContext); + Algorithm algorithm = algorithmFactory.createAlgorithm(data, parameters, ciShellContext); if ((progressMonitor != null) && (algorithm instanceof ProgressTrackable)) { ProgressTrackable progressTrackable = (ProgressTrackable)algorithm; Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayListUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayListUtilities.java 2010-06-20 19:16:46 UTC (rev 1075) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayListUtilities.java 2010-06-20 19:33:14 UTC (rev 1076) @@ -79,8 +79,7 @@ List prefixList = list.subList(0, requestedPrefixSize); if (!prefixList.isEmpty()) { - affixes.add( - StringUtilities.implodeList(prefixList, separator)); + affixes.add(StringUtilities.implodeItems(prefixList, separator)); } affixes.add(ellipsis); @@ -91,13 +90,13 @@ list.size()); if (!suffixList.isEmpty()) { affixes.add( - StringUtilities.implodeList(suffixList, separator)); + StringUtilities.implodeItems(suffixList, separator)); } - return StringUtilities.implodeList(affixes, separator); + return StringUtilities.implodeItems(affixes, separator); } else { // Just implode the list. - return StringUtilities.implodeList(list, separator); + return StringUtilities.implodeItems(list, separator); } } } Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/DatabaseUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/DatabaseUtilities.java 2010-06-20 19:16:46 UTC (rev 1075) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/DatabaseUtilities.java 2010-06-20 19:33:14 UTC (rev 1076) @@ -102,6 +102,6 @@ //TODO: Consider abstracting what you're wrapping with and making this a StringUtility. public static String implodeAndWrap(List<String> values) { - return "(" + StringUtilities.implodeList(values, ", ") + ")"; + return "(" + StringUtilities.implodeItems(values, ", ") + ")"; } } Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/DefaultDictionary.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/DefaultDictionary.java 2010-06-20 19:16:46 UTC (rev 1075) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/DefaultDictionary.java 2010-06-20 19:33:14 UTC (rev 1076) @@ -4,30 +4,29 @@ import java.util.Enumeration; import java.util.Hashtable; -public class DefaultDictionary extends Dictionary { - Object defaultValue; - Dictionary wrappedDictionary; +public class DefaultDictionary<K, V> extends Dictionary<K, V> { + V defaultValue; + Dictionary<K, V> wrappedDictionary; - public DefaultDictionary( - Object defaultValue, Dictionary wrappedDictionary) { + public DefaultDictionary(V defaultValue, Dictionary<K, V> wrappedDictionary) { this.defaultValue = defaultValue; this.wrappedDictionary = wrappedDictionary; } - public DefaultDictionary(Object defaultValue) { - this(defaultValue, new Hashtable()); + public DefaultDictionary(V defaultValue) { + this(defaultValue, new Hashtable<K, V>()); } public Object getDefaultValue() { return this.defaultValue; } - public Enumeration elements() { + public Enumeration<V> elements() { return this.wrappedDictionary.elements(); } - public Object get(Object key) { - Object wrappedDictionaryGetResult = this.wrappedDictionary.get(key); + public V get(Object key) { + V wrappedDictionaryGetResult = this.wrappedDictionary.get(key); if (wrappedDictionaryGetResult == null) return this.defaultValue; @@ -39,15 +38,15 @@ return this.wrappedDictionary.isEmpty(); } - public Enumeration keys() { + public Enumeration<K> keys() { return this.wrappedDictionary.keys(); } - public Object put(Object key, Object value) { + public V put(K key, V value) { return this.wrappedDictionary.put(key, value); } - public Object remove(Object key) { + public V remove(Object key) { return this.wrappedDictionary.remove(key); } Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/ListUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ListUtilities.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/ListUtilities.java 2010-06-20 19:33:14 UTC (rev 1076) @@ -0,0 +1,18 @@ +package org.cishell.utilities; + +import java.util.ArrayList; +import java.util.List; + +public class ListUtilities { + public static<T> List<T> createAndFillList(T... contents) { + return fillList(new ArrayList<T>(), contents); + } + + public static<T> List<T> fillList(List<T> list, T... contents) { + for (T content : contents) { + list.add(content); + } + + return list; + } +} \ 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-06-20 19:16:46 UTC (rev 1075) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/StringUtilities.java 2010-06-20 19:33:14 UTC (rev 1076) @@ -1,11 +1,14 @@ package org.cishell.utilities; import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; import java.util.List; +import java.util.StringTokenizer; public class StringUtilities { - public static String implodeStringArray(String[] stringArray, - String separator) { + // TODO: Make this wrap implodeItems. + public static String implodeStringArray(String[] stringArray, String separator) { final int stringArrayLength = stringArray.length; StringBuffer workingResultString = new StringBuffer(); @@ -18,16 +21,25 @@ return workingResultString.toString(); } - + + /* TODO: This is a wrapper for implodeItems. All new/updated code should refer to implodeItems + * from now on. + */ + @SuppressWarnings("unchecked") // Raw List. public static String implodeList(List list, String separator) { + return implodeItems(list, separator); + } + + public static<T> String implodeItems(Collection<T> items, String separator) { StringBuffer workingResultString = new StringBuffer(); - - final int listLength = list.size(); - - for (int ii = 0; ii < listLength; ii++) { - workingResultString.append(list.get(ii)); + + for (Iterator<T> it = items.iterator(); it.hasNext(); ) { +// for (int ii = 0; ii < listLength; ii++) { +// workingResultString.append(list.get(ii)); + workingResultString.append(it.next()); - boolean isLastElement = (ii == listLength - 1); +// boolean isLastElement = (ii == listLength - 1); + boolean isLastElement = !it.hasNext(); if (!isLastElement) { workingResultString.append(separator); } @@ -36,9 +48,8 @@ return workingResultString.toString(); } - public static String[] filterStringsByPattern(String[] stringsToFilter, - String pattern) { - ArrayList filteredStrings = new ArrayList(); + public static String[] filterStringsByPattern(String[] stringsToFilter, String pattern) { + ArrayList<String> filteredStrings = new ArrayList<String>(); for (int ii = 0; ii < stringsToFilter.length; ii++) { if (!stringsToFilter[ii].matches(pattern)) { @@ -51,7 +62,7 @@ public static String[] filterEmptyStrings(String[] stringsToFilter) { // TODO: This maybe should use filterStringsByPattern? - ArrayList filteredStrings = new ArrayList(); + ArrayList<String> filteredStrings = new ArrayList<String>(); for (int ii = 0; ii < stringsToFilter.length; ii++) { if (!"".equals(stringsToFilter[ii])) { @@ -147,8 +158,7 @@ return true; } - public static int countOccurrencesOfChar( - CharSequence characters, char target) { + public static int countOccurrencesOfChar(CharSequence characters, char target) { int count = 0; for (int ii = 0; ii < characters.length(); ii++) { @@ -196,7 +206,7 @@ } public static final String[] simpleCleanStrings(String[] strings) { - List cleanedStrings = new ArrayList(); + List<String> cleanedStrings = new ArrayList<String>(); for (int ii = 0; ii < strings.length; ii ++) { cleanedStrings.add(StringUtilities.simpleClean(strings[ii])); @@ -302,17 +312,36 @@ } public static String getNthToken( - String originalString, - String separator, - int index, - boolean trim) { + String originalString, String separator, int index, boolean trim) { + return getAllTokens(originalString, separator, trim)[index]; + } + public static String[] getAllTokens( + String originalString, String separator, boolean trim) { String[] tokens = originalString.split(separator); if (trim) { - return tokens[index].trim(); + String[] trimmedTokens = new String[tokens.length]; + + for (int ii = 0; ii < tokens.length; ii++) { + trimmedTokens[ii] = tokens[ii].trim(); + } + + return trimmedTokens; } else { - return tokens[index]; + return tokens; } } + + public static String[] tokenizeByWhitespace(String originalString) { + StringTokenizer tokenizer = new StringTokenizer(originalString); + int tokenCount = tokenizer.countTokens(); + String[] tokens = new String[tokenCount]; + + for (int ii = 0; ii < tokenCount; ii++) { + tokens[ii] = tokenizer.nextToken(); + } + + return tokens; + } } Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/Column.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/Column.java 2010-06-20 19:16:46 UTC (rev 1075) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/Column.java 2010-06-20 19:33:14 UTC (rev 1076) @@ -13,7 +13,7 @@ public final int type; public final int size; - public static final Map<Integer, String> TYPE_MAP = constructTypeMap(); + 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 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-06-20 19:16:46 UTC (rev 1075) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/DatabaseTable.java 2010-06-20 19:33:14 UTC (rev 1076) @@ -162,7 +162,7 @@ for(String key : primaryKeys) { keys.add(key + " = ?"); } - return StringUtilities.implodeList(Lists.newArrayList(keys), separator); + return StringUtilities.implodeItems(Lists.newArrayList(keys), separator); } public Remover constructRemover(Connection connection) throws SQLException { 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-06-20 19:16:46 UTC (rev 1075) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/database/ForeignKey.java 2010-06-20 19:33:14 UTC (rev 1076) @@ -59,7 +59,7 @@ String foreignColumn = pair.foreign; updateStatements.add(foreignColumn + " = ?"); } - return StringUtilities.implodeList(Lists.newArrayList(updateStatements), separator); + return StringUtilities.implodeItems(Lists.newArrayList(updateStatements), separator); } public Repointer constructRepointer(Connection connection) throws SQLException { Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/MetaAttributeDefinition.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/MetaAttributeDefinition.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/MetaAttributeDefinition.java 2010-06-20 19:33:14 UTC (rev 1076) @@ -0,0 +1,21 @@ +package org.cishell.utilities.mutateParameter; + +import org.osgi.service.metatype.AttributeDefinition; + +public class MetaAttributeDefinition { + private int type; + private AttributeDefinition attributeDefinition; + + public MetaAttributeDefinition(int type, AttributeDefinition attributeDefinition) { + this.type = type; + this.attributeDefinition = attributeDefinition; + } + + public int getType() { + return this.type; + } + + public AttributeDefinition getAttributeDefinition() { + return this.attributeDefinition; + } +} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
[CIShell-SVN] SF.net SVN: cishell:[1080]
trunk/core/org.cishell.utilities/src/org/cishell /utilities
From: <pat...@us...> - 2010-07-06 20:09:03
|
Revision: 1080 http://cishell.svn.sourceforge.net/cishell/?rev=1080&view=rev Author: pataphil Date: 2010-07-06 20:08:57 +0000 (Tue, 06 Jul 2010) Log Message: ----------- * Partially made Java 1.5. Modified Paths: -------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayListUtilities.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/SetUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DropdownMutator.java Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayListUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayListUtilities.java 2010-07-01 20:13:22 UTC (rev 1079) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayListUtilities.java 2010-07-06 20:08:57 UTC (rev 1080) @@ -1,40 +1,34 @@ package org.cishell.utilities; import java.util.ArrayList; -import java.util.Arrays; +import java.util.Collection; +import java.util.HashSet; import java.util.List; 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) { + // TODO: Move this to CollectionUtilities. + public static<T> Collection<T> unionCollections( + Collection<T> items1, + Collection<T> items2, + Collection<T> keysToSkip) { + Collection<T> union = new HashSet<T>(); + + if (keysToSkip == null) { + keysToSkip = new HashSet<T>(); + } + + for (T element : items1) { + if (!union.contains(element) && !keysToSkip.contains(element)) { union.add(element); } } - - for (int ii = 0; ii < arrayList2.size(); ii++) { - Object element = arrayList2.get(ii); - - if (!union.contains(element)) { + + for (T element : items2) { + if (!union.contains(element) && !keysToSkip.contains(element)) { union.add(element); } } - for (int ii = 0; ii < keysToAdd.length; ii++) { - String keyToAdd = keysToAdd[ii]; - if (!union.contains(keyToAdd)) { - union.add(keyToAdd); - } - } - return union; } 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-01 20:13:22 UTC (rev 1079) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java 2010-07-06 20:08:57 UTC (rev 1080) @@ -1,24 +1,23 @@ package org.cishell.utilities; import java.util.ArrayList; +import java.util.Collection; import java.util.Map; -import java.util.Set; public class MapUtilities { - public static String[] getValidKeysOfTypesInMap( - Map map, String[] types, String[] keysToSkip, String[] keysToAdd) + public static<K, V> Collection<K> getValidKeysOfTypesInMap( + Map<K, V> map, Collection<V> types, Collection<K> keysToSkip) throws ColumnNotFoundException { - ArrayList workingKeys = new ArrayList(); - Set entrySet = map.entrySet(); - - for (int ii = 0; ii < types.length; ii++) { - String type = types[ii]; - ArrayList keysForType = + Collection<K> workingKeys = new ArrayList<K>(); + Collection<Map.Entry<K, V>> entrySet = map.entrySet(); + + for (V type : types) { + Collection<K> keysForType = SetUtilities.getKeysOfMapEntrySetWithValue(entrySet, type); - workingKeys = ArrayListUtilities.unionArrayLists( - workingKeys, keysForType, keysToSkip, keysToAdd); + workingKeys = + ArrayListUtilities.unionCollections(workingKeys, keysForType, keysToSkip); } - return (String[])workingKeys.toArray(new String[0]); + return workingKeys; } } \ 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 2010-07-01 20:13:22 UTC (rev 1079) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/MutateParameterUtilities.java 2010-07-06 20:08:57 UTC (rev 1080) @@ -2,6 +2,7 @@ import java.io.IOException; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Map; @@ -23,8 +24,8 @@ public static AttributeDefinition formLabelAttributeDefinition( AttributeDefinition oldAttributeDefinition, Table table) throws ColumnNotFoundException { - String[] validStringColumnsInTable = - TableUtilities.getValidStringColumnNamesInTable(table); + Collection<String> validStringColumnsInTable = + Arrays.asList(TableUtilities.getValidStringColumnNamesInTable(table)); AttributeDefinition labelAttributeDefinition = cloneToDropdownAttributeDefinition( oldAttributeDefinition, validStringColumnsInTable, validStringColumnsInTable); @@ -35,7 +36,8 @@ public static AttributeDefinition formDateAttributeDefinition( AttributeDefinition oldAttributeDefinition, Table table) throws ColumnNotFoundException { - String[] validDateColumnsInTable = TableUtilities.getValidDateColumnNamesInTable(table); + Collection<String> validDateColumnsInTable = + Arrays.asList(TableUtilities.getValidDateColumnNamesInTable(table)); AttributeDefinition dateAttributeDefinition = cloneToDropdownAttributeDefinition( oldAttributeDefinition, validDateColumnsInTable, validDateColumnsInTable); @@ -46,8 +48,8 @@ public static AttributeDefinition formIntegerAttributeDefinition( AttributeDefinition oldAttributeDefinition, Table table) throws ColumnNotFoundException { - String[] validIntegerColumnsInTable = - TableUtilities.getValidIntegerColumnNamesInTable(table); + Collection<String> validIntegerColumnsInTable = + Arrays.asList(TableUtilities.getValidIntegerColumnNamesInTable(table)); AttributeDefinition integerAttributeDefinition = cloneToDropdownAttributeDefinition( oldAttributeDefinition, validIntegerColumnsInTable, validIntegerColumnsInTable); @@ -58,8 +60,8 @@ public static AttributeDefinition formNumberAttributeDefinition( AttributeDefinition oldAttributeDefinition, Table table) throws ColumnNotFoundException { - String[] validNumberColumnsInTable = - TableUtilities.getValidNumberColumnNamesInTable(table); + Collection<String> validNumberColumnsInTable = + Arrays.asList(TableUtilities.getValidNumberColumnNamesInTable(table)); AttributeDefinition numberAttributeDefinition = cloneToDropdownAttributeDefinition( oldAttributeDefinition, validNumberColumnsInTable, validNumberColumnsInTable); @@ -69,12 +71,12 @@ public static AttributeDefinition formAttributeDefinitionFromMap( AttributeDefinition oldAttributeDefinition, - Map<String, String> map, - String[] types, - String[] keysToSkip, + Map<String, String> attributes, + Collection<String> types, + Collection<String> keysToSkip, String[] keysToAdd) { - String[] validNumberKeysInMap = MapUtilities.getValidKeysOfTypesInMap( - map, types, keysToSkip, keysToAdd); + Collection<String> validNumberKeysInMap = + MapUtilities.getValidKeysOfTypesInMap(attributes, types, keysToSkip); AttributeDefinition numberAttributeDefinition = cloneToDropdownAttributeDefinition( oldAttributeDefinition, validNumberKeysInMap, validNumberKeysInMap); @@ -83,18 +85,20 @@ } public static AttributeDefinition cloneToDropdownAttributeDefinition( - AttributeDefinition oldAD, final String[] optionLabels, final String[] optionValues) { + AttributeDefinition oldAD, + final Collection<String> optionLabels, + final Collection<String> optionValues) { AttributeDefinitionTransformer transformer = new DefaultDropdownTransformer() { public boolean shouldTransform(AttributeDefinition ad) { return true; } public String[] transformOptionLabels(String[] oldOptionLabels) { - return optionLabels; + return optionLabels.toArray(new String[0]); } public String[] transformOptionValues(String[] oldOptionValues) { - return optionValues; + return optionValues.toArray(new String[0]); } }; Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/SetUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/SetUtilities.java 2010-07-01 20:13:22 UTC (rev 1079) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/SetUtilities.java 2010-07-06 20:08:57 UTC (rev 1080) @@ -1,18 +1,18 @@ package org.cishell.utilities; -import java.util.ArrayList; +import java.util.Collection; +import java.util.HashSet; 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(); - + public static<K, V> Collection<K> getKeysOfMapEntrySetWithValue( + Collection<Map.Entry<K, V>> mapEntries, V value) { + Collection<K> keysOfMapEntrySetWithValue = new HashSet<K>(); + Iterator<Map.Entry<K, V>> mapEntrySetIterator = mapEntries.iterator(); + while (mapEntrySetIterator.hasNext()) { - Map.Entry entry = (Map.Entry)mapEntrySetIterator.next(); + Map.Entry<K, V> entry = mapEntrySetIterator.next(); if (entry.getValue().equals(value)) { keysOfMapEntrySetWithValue.add(entry.getKey()); 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 2010-07-01 20:13:22 UTC (rev 1079) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/ObjectClassDefinitionTransformer.java 2010-07-06 20:08:57 UTC (rev 1080) @@ -1,13 +1,13 @@ package org.cishell.utilities.mutateParameter; -import java.util.ArrayList; +import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; -import java.util.List; import org.cishell.reference.service.metatype.BasicObjectClassDefinition; import org.cishell.utilities.MutateParameterUtilities; +import org.cishell.utilities.mutateParameter.dropdown.DropdownTransformer; import org.osgi.service.metatype.AttributeDefinition; import org.osgi.service.metatype.ObjectClassDefinition; @@ -18,37 +18,40 @@ * @see ObjectClassDefinition#REQUIRED * @see ObjectClassDefinition#OPTIONAL */ - public static final List ATOMIC_ATTRIBUTE_DEFINITION_FILTERS; - static { - List l = new ArrayList(); - l.add(new Integer(ObjectClassDefinition.REQUIRED)); - l.add(new Integer(ObjectClassDefinition.OPTIONAL)); - ATOMIC_ATTRIBUTE_DEFINITION_FILTERS = Collections.unmodifiableList(l); - } + public static final Collection<Integer> ATOMIC_ATTRIBUTE_DEFINITION_FILTERS = + Collections.unmodifiableList(Arrays.asList( + new Integer(ObjectClassDefinition.REQUIRED), + new Integer(ObjectClassDefinition.OPTIONAL))); +// static { +// List l = new ArrayList(); +// l.add(new Integer(ObjectClassDefinition.REQUIRED)); +// l.add(new Integer(ObjectClassDefinition.OPTIONAL)); +// ATOMIC_ATTRIBUTE_DEFINITION_FILTERS = Collections.unmodifiableList(l); +// } /* Create newOCD from oldOCD by applying transformer * to each AttributeDefinition. */ public static BasicObjectClassDefinition apply( AttributeDefinitionTransformer transformer, - ObjectClassDefinition oldOCD, + ObjectClassDefinition oldObjectClassDefinition, Collection<String> attributesToIgnore) { BasicObjectClassDefinition newOCD = - MutateParameterUtilities.createNewParameters(oldOCD); + MutateParameterUtilities.createNewParameters(oldObjectClassDefinition); // For each kind of AttributeDefinition filter .. - for (Iterator filterIt = ATOMIC_ATTRIBUTE_DEFINITION_FILTERS.iterator(); + for (Iterator<Integer> filterIt = ATOMIC_ATTRIBUTE_DEFINITION_FILTERS.iterator(); filterIt.hasNext();) { - int filter = ((Integer) filterIt.next()).intValue(); + int filter = filterIt.next().intValue(); // Grab all matching AttributeDefinitions and transform them. - AttributeDefinition[] oldADs = - oldOCD.getAttributeDefinitions(filter); - - for (int ii = 0; ii < oldADs.length; ii++) { - if (!attributesToIgnore.contains(oldADs[ii].getID())) { + AttributeDefinition[] oldAttributeDefintions = + oldObjectClassDefinition.getAttributeDefinitions(filter); + + for (AttributeDefinition attributeDefinition : oldAttributeDefintions) { + if (!attributesToIgnore.contains(attributeDefinition.getID())) { newOCD.addAttributeDefinition( - filter, transformer.transform(oldADs[ii])); + filter, transformer.transform(attributeDefinition)); } } } @@ -58,16 +61,17 @@ // Convenience method for batching transformations. public static ObjectClassDefinition transform( - ObjectClassDefinition ocd, List transformers, Collection<String> attributesToIgnore) { - ObjectClassDefinition newOCD = ocd; + ObjectClassDefinition objectClassDefinition, + Collection<DropdownTransformer> transformers, + Collection<String> attributesToIgnore) { + ObjectClassDefinition newObjectClassDefinition = objectClassDefinition; - for (Iterator it = transformers.iterator(); it.hasNext();) { - AttributeDefinitionTransformer transformer = - (AttributeDefinitionTransformer) it.next(); - - newOCD = apply(transformer, newOCD, attributesToIgnore); + for (Iterator<DropdownTransformer> it = transformers.iterator(); it.hasNext();) { + DropdownTransformer transformer = it.next(); + newObjectClassDefinition = + apply(transformer, newObjectClassDefinition, attributesToIgnore); } - return newOCD; + return newObjectClassDefinition; } } \ No newline at end of file Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DropdownMutator.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DropdownMutator.java 2010-07-01 20:13:22 UTC (rev 1079) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/mutateParameter/dropdown/DropdownMutator.java 2010-07-06 20:08:57 UTC (rev 1080) @@ -2,8 +2,8 @@ import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; import java.util.HashSet; -import java.util.List; import java.util.Set; import org.cishell.utilities.ArrayUtilities; @@ -19,31 +19,31 @@ * and mutate(ObjectClassDefinition) */ public class DropdownMutator { - private List transforms; + private Collection<DropdownTransformer> transforms; private Set<String> attributesToIgnore = new HashSet<String>(); public DropdownMutator() { - transforms = new ArrayList(); + this.transforms = new ArrayList<DropdownTransformer>(); } - public ObjectClassDefinition mutate(ObjectClassDefinition ocd) { + public ObjectClassDefinition mutate(ObjectClassDefinition objectClassDefinition) { return ObjectClassDefinitionTransformer.transform( - ocd, transforms, this.attributesToIgnore); + objectClassDefinition, this.transforms, this.attributesToIgnore); } - public void add(String id, List options, String defaultOption) { + public void add(String id, Collection<String> options, String defaultOption) { add(id, swapToFront(options, defaultOption)); } - public void add(String id, List options) { + public void add(String id, Collection<String> options) { add(id, options, options); } public void add( String id, - List optionLabels, + Collection<String> optionLabels, String defaultOptionLabel, - List optionValues, + Collection<String> optionValues, String defaultOptionValue) { add( id, @@ -51,7 +51,7 @@ swapToFront(optionValues, defaultOptionValue)); } - public void add(String id, List optionLabels, List optionValues) { + public void add(String id, Collection<String> optionLabels, Collection<String> optionValues) { add( id, (String[]) optionLabels.toArray(new String[0]), @@ -81,9 +81,7 @@ } public void add( - final String id, - final String[] optionLabels, - final String[] optionValues) { + final String id, final String[] optionLabels, final String[] optionValues) { if (!shouldIgnore(id)) { transforms.add( new DefaultDropdownTransformer() { @@ -110,8 +108,8 @@ return this.attributesToIgnore.contains(id); } - private static List swapToFront(List list, String target) { - String[] temp = (String[]) list.toArray(new String[]{}); + private static Collection<String> swapToFront(Collection<String> items, String target) { + String[] temp = (String[]) items.toArray(new String[]{}); return Arrays.asList(swapToFront(temp, target)); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
[CIShell-SVN] SF.net SVN: cishell:[1084]
trunk/core/org.cishell.utilities/src/org/cishell /utilities
From: <pat...@us...> - 2010-07-12 21:24:20
|
Revision: 1084 http://cishell.svn.sourceforge.net/cishell/?rev=1084&view=rev Author: pataphil Date: 2010-07-12 21:24:14 +0000 (Mon, 12 Jul 2010) Log Message: ----------- * Continued developing on SWT Utilities. Modified Paths: -------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/StringUtilities.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 Added Paths: ----------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/ExpandableComponentWidget.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUIBuilderUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GridContainer.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/ScrolledComponentFactory.java Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/StringUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/StringUtilities.java 2010-07-09 20:55:18 UTC (rev 1083) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/StringUtilities.java 2010-07-12 21:24:14 UTC (rev 1084) @@ -1,347 +1,352 @@ -package org.cishell.utilities; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.StringTokenizer; - -public class StringUtilities { - // TODO: Make this wrap implodeItems. - public static String implodeStringArray(String[] stringArray, String separator) { - final int stringArrayLength = stringArray.length; - StringBuffer workingResultString = new StringBuffer(); - - for (int ii = 0; ii < stringArrayLength; ii++) { - workingResultString.append(stringArray[ii]); - if (ii != stringArrayLength - 1) { - workingResultString.append(separator); - } - } - - return workingResultString.toString(); - } - - /* TODO: This is a wrapper for implodeItems. All new/updated code should refer to implodeItems - * from now on. - */ - @SuppressWarnings("unchecked") // Raw List. - public static String implodeList(List list, String separator) { - return implodeItems(list, separator); - } - - public static<T> String implodeItems(Collection<T> items, String separator) { - StringBuffer workingResultString = new StringBuffer(); - - for (Iterator<T> it = items.iterator(); it.hasNext(); ) { -// for (int ii = 0; ii < listLength; ii++) { -// workingResultString.append(list.get(ii)); - workingResultString.append(it.next()); - -// boolean isLastElement = (ii == listLength - 1); - boolean isLastElement = !it.hasNext(); - if (!isLastElement) { - workingResultString.append(separator); - } - } - - return workingResultString.toString(); - } - - public static String[] filterStringsByPattern(String[] stringsToFilter, String pattern) { - ArrayList<String> filteredStrings = new ArrayList<String>(); - - for (int ii = 0; ii < stringsToFilter.length; ii++) { - if (!stringsToFilter[ii].matches(pattern)) { - filteredStrings.add(stringsToFilter[ii]); - } - } - - return (String[])filteredStrings.toArray(new String[0]); - } - - public static String[] filterEmptyStrings(String[] stringsToFilter) { - // TODO: This maybe should use filterStringsByPattern? - ArrayList<String> filteredStrings = new ArrayList<String>(); - - for (int ii = 0; ii < stringsToFilter.length; ii++) { - if (!"".equals(stringsToFilter[ii])) { - filteredStrings.add(stringsToFilter[ii]); - } - } - - return (String[])filteredStrings.toArray(new String[0]); - } - - /* - * This method is really meant to simplify working with Prefuse tables. - * Prefuse table columns are typed. If a column contains a null cell, - * Prefuse types that column as an array type, and it then represents - * null values with arrays of length 0. - * To handle this, this method returns: - * null if the object is actually null or array of length 0; - * just the first element of the array; or - * the result of the object's toString method. - */ - // TODO: Rename to interpretAsString. - // TODO: Move these things to TableUtilities. - // TODO: Handle all cases, including all primitive array types and - // perhaps primitive box types (i.e. Integer). - public static String interpretObjectAsString(Object object) { - if (object == null) { - return null; - } else if (object instanceof String[]) { - String[] objectAsStringArray = (String[]) object; - - if (objectAsStringArray.length == 0) { - return null; - } else { - return objectAsStringArray[0]; - } - } else { - return object.toString(); - } - } - - // TODO Think about instead using a Pattern, "\s*". Don't have to though. - public static boolean isEmptyOrWhitespace(String string) { - String trimmed = string.trim(); - - return (trimmed.length() == 0); - } - - 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) { - int count = 0; - - for (int ii = 0; ii < characters.length(); ii++) { - if (characters.charAt(ii) == target) { - count++; - } - } - - return count; - } - - public static String multiply(String target, int count) { - if (count < 1) { - return ""; - } else { - StringBuffer stringInProgress = new StringBuffer(); - - for (int ii = 0; ii < count; ii ++) { - stringInProgress.append(target); - } - - return stringInProgress.toString(); - } - } - - public static String multiplyWithSeparator(String target, String separator, int count) { - String multipliedWithExtraSeparator = multiply(target + separator, count); - - return multipliedWithExtraSeparator.substring( - 0, multipliedWithExtraSeparator.length() - separator.length()); - } - - public static String emptyStringIfNull(Object object) { - if (object == null) { - return ""; - } else { - return object.toString(); - } - } - - public static String simpleClean(String string) { - String guaranteedToNotBeNull = emptyStringIfNull(string); - - return guaranteedToNotBeNull.trim(); - } - - public static final String[] simpleCleanStrings(String[] strings) { - List<String> cleanedStrings = new ArrayList<String>(); - - for (int ii = 0; ii < strings.length; ii ++) { - cleanedStrings.add(StringUtilities.simpleClean(strings[ii])); - } - - 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); - - if (cleanedWord.length() == 0) { - return ""; - } else { - return - Character.toUpperCase(cleanedWord.charAt(0)) + - cleanedWord.substring(1).toLowerCase(); - } - } - - public static int prefixIndex(String target, String[] prefixes) { - /* - * Look for the prefixes in reverse order (so a longer one will win out over a shorter one - * if they both have a beginning in common). - */ - for (int ii = (prefixes.length - 1); ii >= 0; ii--) { - if (target.startsWith(prefixes[ii])) { - return ii; - } - } - - return -1; - } - - /* 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 bothAreEqualOrNull(String string1, String string2) { - if (string1 != null) { - return string1.equals(string2); - } else { - return (string2 == null); - } - } - - 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 (!isNull_Empty_OrWhitespace(string1)) { - if (!isNull_Empty_OrWhitespace(string2)) { - if (string1.length() >= string2.length()) { - return string1; - } else { - return string2; - } - } else { - return string1; - } - } - else if (!isNull_Empty_OrWhitespace(string2)) { - return string2; - } - - return string1; - } - - //TODO: Make this not exist (a check for 'Null Empty or Whitespace' can stay. Use ! for negated cases) - public static Object alternativeIfNotNull_Empty_OrWhitespace( - String string, Object alternative) { - if (!isNull_Empty_OrWhitespace(string)) { - return string; - } else { - return alternative; - } - } - - public static Object alternativeIfNotNull_Empty_OrWhitespace_IgnoreCase( - String string, Object alternative) { - if (!isNull_Empty_OrWhitespace(string)) { - return string.toLowerCase(); - } else { - return alternative; - } - } - - public static String getNthToken( - String originalString, String separator, int index, boolean trim) { - return getAllTokens(originalString, separator, trim)[index]; - } - - public static String[] getAllTokens( - String originalString, String separator, boolean trim) { - String[] tokens = originalString.split(separator); - - if (trim) { - String[] trimmedTokens = new String[tokens.length]; - - for (int ii = 0; ii < tokens.length; ii++) { - trimmedTokens[ii] = tokens[ii].trim(); - } - - return trimmedTokens; - } else { - return tokens; - } - } - - public static String[] tokenizeByWhitespace(String originalString) { - StringTokenizer tokenizer = new StringTokenizer(originalString); - int tokenCount = tokenizer.countTokens(); - String[] tokens = new String[tokenCount]; - - for (int ii = 0; ii < tokenCount; ii++) { - tokens[ii] = tokenizer.nextToken(); - } - - return tokens; - } -} +package org.cishell.utilities; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.StringTokenizer; + +public class StringUtilities { + // TODO: Make this wrap implodeItems. + public static String implodeStringArray(String[] stringArray, String separator) { + final int stringArrayLength = stringArray.length; + StringBuffer workingResultString = new StringBuffer(); + + for (int ii = 0; ii < stringArrayLength; ii++) { + workingResultString.append(stringArray[ii]); + if (ii != stringArrayLength - 1) { + workingResultString.append(separator); + } + } + + return workingResultString.toString(); + } + + /* TODO: This is a wrapper for implodeItems. All new/updated code should refer to implodeItems + * from now on. + */ + @SuppressWarnings("unchecked") // Raw List. + public static String implodeList(List list, String separator) { + return implodeItems(list, separator); + } + + public static<T> String implodeItems(Collection<T> items, String separator) { + StringBuffer workingResultString = new StringBuffer(); + + for (Iterator<T> it = items.iterator(); it.hasNext(); ) { +// for (int ii = 0; ii < listLength; ii++) { +// workingResultString.append(list.get(ii)); + workingResultString.append(it.next()); + +// boolean isLastElement = (ii == listLength - 1); + boolean isLastElement = !it.hasNext(); + if (!isLastElement) { + workingResultString.append(separator); + } + } + + return workingResultString.toString(); + } + + public static String[] filterStringsByPattern(String[] stringsToFilter, String pattern) { + ArrayList<String> filteredStrings = new ArrayList<String>(); + + for (int ii = 0; ii < stringsToFilter.length; ii++) { + if (!stringsToFilter[ii].matches(pattern)) { + filteredStrings.add(stringsToFilter[ii]); + } + } + + return (String[])filteredStrings.toArray(new String[0]); + } + + public static String[] filterEmptyStrings(String[] stringsToFilter) { + // TODO: This maybe should use filterStringsByPattern? + ArrayList<String> filteredStrings = new ArrayList<String>(); + + for (int ii = 0; ii < stringsToFilter.length; ii++) { + if (!"".equals(stringsToFilter[ii])) { + filteredStrings.add(stringsToFilter[ii]); + } + } + + return (String[])filteredStrings.toArray(new String[0]); + } + + /* + * This method is really meant to simplify working with Prefuse tables. + * Prefuse table columns are typed. If a column contains a null cell, + * Prefuse types that column as an array type, and it then represents + * null values with arrays of length 0. + * To handle this, this method returns: + * null if the object is actually null or array of length 0; + * just the first element of the array; or + * the result of the object's toString method. + */ + // TODO: Rename to interpretAsString. + // TODO: Move these things to TableUtilities. + // TODO: Handle all cases, including all primitive array types and + // perhaps primitive box types (i.e. Integer). + public static String interpretObjectAsString(Object object) { + if (object == null) { + return null; + } else if (object instanceof String[]) { + String[] objectAsStringArray = (String[]) object; + + if (objectAsStringArray.length == 0) { + return null; + } else { + return objectAsStringArray[0]; + } + } else { + return object.toString(); + } + } + + // TODO Think about instead using a Pattern, "\s*". Don't have to though. + public static boolean isEmptyOrWhitespace(String string) { + String trimmed = string.trim(); + + return (trimmed.length() == 0); + } + + 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) { + int count = 0; + + for (int ii = 0; ii < characters.length(); ii++) { + if (characters.charAt(ii) == target) { + count++; + } + } + + return count; + } + + public static String multiply(String target, int count) { + if (count < 1) { + return ""; + } else { + StringBuffer stringInProgress = new StringBuffer(); + + for (int ii = 0; ii < count; ii ++) { + stringInProgress.append(target); + } + + return stringInProgress.toString(); + } + } + + public static String multiplyWithSeparator(String target, String separator, int count) { + String multipliedWithExtraSeparator = multiply(target + separator, count); + + return multipliedWithExtraSeparator.substring( + 0, multipliedWithExtraSeparator.length() - separator.length()); + } + + public static String emptyStringIfNull(Object object) { + if (object == null) { + return ""; + } else { + return object.toString(); + } + } + + public static String simpleClean(String string) { + String guaranteedToNotBeNull = emptyStringIfNull(string); + + return guaranteedToNotBeNull.trim(); + } + + public static final String[] simpleCleanStrings(String[] strings) { + List<String> cleanedStrings = new ArrayList<String>(); + + for (int ii = 0; ii < strings.length; ii ++) { + cleanedStrings.add(StringUtilities.simpleClean(strings[ii])); + } + + 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); + + if (cleanedWord.length() == 0) { + return ""; + } else { + return + Character.toUpperCase(cleanedWord.charAt(0)) + + cleanedWord.substring(1).toLowerCase(); + } + } + + public static int prefixIndex(String target, String[] prefixes) { + /* + * Look for the prefixes in reverse order (so a longer one will win out over a shorter one + * if they both have a beginning in common). + */ + for (int ii = (prefixes.length - 1); ii >= 0; ii--) { + if (target.startsWith(prefixes[ii])) { + return ii; + } + } + + return -1; + } + + /* 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 bothAreEqualOrNull(String string1, String string2) { + if (string1 != null) { + return string1.equals(string2); + } else { + return (string2 == null); + } + } + + 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 (!isNull_Empty_OrWhitespace(string1)) { + if (!isNull_Empty_OrWhitespace(string2)) { + if (string1.length() >= string2.length()) { + return string1; + } else { + return string2; + } + } else { + return string1; + } + } + else if (!isNull_Empty_OrWhitespace(string2)) { + return string2; + } + + return string1; + } + + //TODO: Make this not exist (a check for 'Null Empty or Whitespace' can stay. Use ! for negated cases) + public static Object alternativeIfNotNull_Empty_OrWhitespace( + String string, Object alternative) { + if (!isNull_Empty_OrWhitespace(string)) { + return string; + } else { + return alternative; + } + } + + public static Object alternativeIfNotNull_Empty_OrWhitespace_IgnoreCase( + String string, Object alternative) { + if (!isNull_Empty_OrWhitespace(string)) { + return string.toLowerCase(); + } else { + return alternative; + } + } + + public static String getNthToken( + String originalString, String separator, int index, boolean trim) { + return getAllTokens(originalString, separator, trim)[index]; + } + + public static String[] getAllTokens( + String originalString, String separator, boolean trim) { + String[] tokens = originalString.split(separator); + + if (trim) { + String[] trimmedTokens = new String[tokens.length]; + + for (int ii = 0; ii < tokens.length; ii++) { + trimmedTokens[ii] = tokens[ii].trim(); + } + + return trimmedTokens; + } else { + return tokens; + } + } + + public static String[] tokenizeByWhitespace(String originalString) { + StringTokenizer tokenizer = new StringTokenizer(originalString); + int tokenCount = tokenizer.countTokens(); + String[] tokens = new String[tokenCount]; + + for (int ii = 0; ii < tokenCount; ii++) { + tokens[ii] = tokenizer.nextToken(); + } + + return tokens; + } + + // TODO +// public static String escape(String unescaped) { +// return unescaped.replaceAll("\"", "\\\"" +// } +} Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/ExpandableComponentWidget.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/ExpandableComponentWidget.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/ExpandableComponentWidget.java 2010-07-12 21:24:14 UTC (rev 1084) @@ -0,0 +1,246 @@ +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++; + +// Control componentControlHack = (Control) component; +// componentControlHack.setLayoutData(createComponentLayoutData()); + fixSize(); + + this.components.add(component); + + return component; + } + + public void removeComponent(int index) { +// this.components.get(index).dispose(); + 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 Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUIBuilderUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUIBuilderUtilities.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUIBuilderUtilities.java 2010-07-12 21:24:14 UTC (rev 1084) @@ -0,0 +1,78 @@ +package org.cishell.utilities.swt; + +import org.eclipse.swt.SWT; +import org.eclipse.swt.graphics.Point; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Display; +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; + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GridContainer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GridContainer.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GridContainer.java 2010-07-12 21:24:14 UTC (rev 1084) @@ -0,0 +1,92 @@ +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(); + } + } + } +} Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/ScrolledComponentFactory.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/ScrolledComponentFactory.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/ScrolledComponentFactory.java 2010-07-12 21:24:14 UTC (rev 1084) @@ -0,0 +1,15 @@ +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 Modified: 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-07-09 20:55:18 UTC (rev 1083) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModel.java 2010-07-12 21:24:14 UTC (rev 1084) @@ -2,6 +2,7 @@ import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -63,6 +64,7 @@ Composite parent, int style) { java.util.List<String> orderedOptionLabels = new ArrayList<String>(unorderedOptionLabels); + Collections.sort(orderedOptionLabels); Combo dropDown = new Combo(parent, style | SWT.DROP_DOWN); DropDownDataSynchronizer dataSynchronizer = new DropDownDataSynchronizer( dropDown, selectedIndex, orderedOptionLabels, optionValuesByLabels); Modified: 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-07-09 20:55:18 UTC (rev 1083) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModelField.java 2010-07-12 21:24:14 UTC (rev 1084) @@ -28,6 +28,7 @@ if (event.type == GUIModelField.this.dataSynchronizer.swtUpdateListenerCode()) { GUIModelField.this.value = GUIModelField.this.dataSynchronizer.synchronizeFromGUI(); + System.err.println(GUIModelField.this.value); } } }); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
[CIShell-SVN] SF.net SVN: cishell:[1087]
trunk/core/org.cishell.utilities/src/org/cishell /utilities
From: <pat...@us...> - 2010-07-13 18:06:13
|
Revision: 1087 http://cishell.svn.sourceforge.net/cishell/?rev=1087&view=rev Author: pataphil Date: 2010-07-13 18:06:07 +0000 (Tue, 13 Jul 2010) Log Message: ----------- * Fixing build again. Hopefully. Modified Paths: -------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/ExpandableComponentWidget.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/datasynchronizer/DateDataSynchronizer.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/TimeDataSynchronizer.java 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-13 15:13:45 UTC (rev 1086) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java 2010-07-13 18:06:07 UTC (rev 1087) @@ -23,6 +23,7 @@ return workingKeys; } + /* Maps items to themselves in a Map. */ public static<T> Map<T, T> mirror(Collection<T> items) { Map<T, T> mirroredItems = new HashMap<T, T>(); Modified: 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-07-13 15:13:45 UTC (rev 1086) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/ExpandableComponentWidget.java 2010-07-13 18:06:07 UTC (rev 1087) @@ -78,8 +78,6 @@ this, this.scrolledAreaGrid, style, arguments, componentCount, this.uniqueComponentCount); this.uniqueComponentCount++; -// Control componentControlHack = (Control) component; -// componentControlHack.setLayoutData(createComponentLayoutData()); fixSize(); this.components.add(component); @@ -88,7 +86,6 @@ } public void removeComponent(int index) { -// this.components.get(index).dispose(); this.scrolledAreaGrid.removeRow(index); this.components.remove(index); fixSize(); Modified: 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-07-13 15:13:45 UTC (rev 1086) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModel.java 2010-07-13 18:06:07 UTC (rev 1087) @@ -7,12 +7,10 @@ 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.SingleListSelectionDataSynchronizer; import org.cishell.utilities.swt.model.datasynchronizer.TextDataSynchronizer; -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; @@ -78,43 +76,44 @@ // TODO: addMultiSelectionDropDown // TODO: Test this out. - 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); + // 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; +// } - 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); +// 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; +// } - return field; - } - // TODO: addCalendar // TODO: Test this out. Modified: 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 2010-07-13 15:13:45 UTC (rev 1086) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/DateDataSynchronizer.java 2010-07-13 18:06:07 UTC (rev 1087) @@ -1,42 +1,42 @@ -package org.cishell.utilities.swt.model.datasynchronizer; - -import org.eclipse.swt.SWT; - -public class DateDataSynchronizer implements ModelDataSynchronizer<org.joda.time.DateTime> { - private org.eclipse.swt.widgets.DateTime dateSelector; - - public DateDataSynchronizer( - org.eclipse.swt.widgets.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 +//package org.cishell.utilities.swt.model.datasynchronizer; +// +//import org.eclipse.swt.SWT; +// +//public class DateDataSynchronizer implements ModelDataSynchronizer<org.joda.time.DateTime> { +// private org.eclipse.swt.widgets.DateTime dateSelector; +// +// public DateDataSynchronizer( +// org.eclipse.swt.widgets.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 Modified: 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 2010-07-13 15:13:45 UTC (rev 1086) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/TimeDataSynchronizer.java 2010-07-13 18:06:07 UTC (rev 1087) @@ -1,43 +1,43 @@ -package org.cishell.utilities.swt.model.datasynchronizer; - -import org.eclipse.swt.SWT; - -public class TimeDataSynchronizer implements ModelDataSynchronizer<org.joda.time.DateTime> { - private org.eclipse.swt.widgets.DateTime timeSelector; - - public TimeDataSynchronizer( - org.eclipse.swt.widgets.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 +//package org.cishell.utilities.swt.model.datasynchronizer; +// +//import org.eclipse.swt.SWT; +// +//public class TimeDataSynchronizer implements ModelDataSynchronizer<org.joda.time.DateTime> { +// private org.eclipse.swt.widgets.DateTime timeSelector; +// +// public TimeDataSynchronizer( +// org.eclipse.swt.widgets.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. |
[CIShell-SVN] SF.net SVN: cishell:[1088]
trunk/core/org.cishell.utilities/src/org/cishell /utilities
From: <pat...@us...> - 2010-07-13 21:30:28
|
Revision: 1088 http://cishell.svn.sourceforge.net/cishell/?rev=1088&view=rev Author: pataphil Date: 2010-07-13 21:30:22 +0000 (Tue, 13 Jul 2010) Log Message: ----------- * Added ArrayListUtilities.unionCollectionsAsList() * Added CollectionUtilities.get() * Added SWTUtilities.printURL() * Mild, mild cleanup. Modified Paths: -------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayListUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/CollectionUtilities.java 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/model/GUIModel.java Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayListUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayListUtilities.java 2010-07-13 18:06:07 UTC (rev 1087) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayListUtilities.java 2010-07-13 21:30:22 UTC (rev 1088) @@ -31,6 +31,13 @@ return union; } + + public static<T> List<T> unionCollectionsAsList( + Collection<T> items1, + Collection<T> items2, + Collection<T> keysToSkip) { + return new ArrayList<T>(unionCollections(items1, items2, keysToSkip)); + } /* Implodes list to a String with the String.valueOf the elements separated * by separator and where all elements except the first prefixSize and Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/CollectionUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/CollectionUtilities.java 2010-07-13 18:06:07 UTC (rev 1087) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/CollectionUtilities.java 2010-07-13 21:30:22 UTC (rev 1088) @@ -28,4 +28,8 @@ return selectedElements; } + @SuppressWarnings("unchecked") + public static<T> T get(Collection<T> values, int index) { + return (T) values.toArray()[index]; + } } Modified: 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-07-13 18:06:07 UTC (rev 1087) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/SWTUtilities.java 2010-07-13 21:30:22 UTC (rev 1088) @@ -4,6 +4,7 @@ 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 { @@ -95,4 +96,28 @@ 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 Modified: 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-07-13 18:06:07 UTC (rev 1087) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/URLClickedListener.java 2010-07-13 21:30:22 UTC (rev 1088) @@ -10,7 +10,7 @@ import org.eclipse.swt.program.Program; /* - * Listens for clicks on urls and launches a browser appropriately. + * Listens for clicks on urls and launches a browser. */ public class URLClickedListener extends MouseAdapter { private Map<Integer, String> offsetsToURLs = new HashMap<Integer, String>(); Modified: 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-07-13 18:06:07 UTC (rev 1087) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModel.java 2010-07-13 21:30:22 UTC (rev 1088) @@ -53,7 +53,7 @@ return field; } - public GUIModelField<String, Combo, DropDownDataSynchronizer> addSingleSelectionDropDown( + public GUIModelField<String, Combo, DropDownDataSynchronizer> addDropDown( String name, int selectedIndex, Collection<String> unorderedOptionLabels, @@ -117,7 +117,7 @@ // TODO: addCalendar // TODO: Test this out. - public GUIModelField<String, List, SingleListSelectionDataSynchronizer> addSingleSelectionList( + public GUIModelField<String, List, SingleListSelectionDataSynchronizer> addList( String name, int selectedIndex, Collection<String> unorderedOptionLabels, @@ -145,7 +145,7 @@ // TODO: addSpinner // TODO: addStyledText - public GUIModelField<String, Text, TextDataSynchronizer> addUnstyledText( + public GUIModelField<String, Text, TextDataSynchronizer> addText( String name, String value, boolean isMultiLined, This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
[CIShell-SVN] SF.net SVN: cishell:[1089]
trunk/core/org.cishell.utilities/src/org/cishell /utilities
From: <pat...@us...> - 2010-07-15 08:30:33
|
Revision: 1089 http://cishell.svn.sourceforge.net/cishell/?rev=1089&view=rev Author: pataphil Date: 2010-07-15 08:30:27 +0000 (Thu, 15 Jul 2010) Log Message: ----------- * Added ArrayListUtilities.copyAndSort(). * Fixed some GUIModel stuff. Modified Paths: -------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayListUtilities.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/datasynchronizer/DropDownDataSynchronizer.java Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayListUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayListUtilities.java 2010-07-13 21:30:22 UTC (rev 1088) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/ArrayListUtilities.java 2010-07-15 08:30:27 UTC (rev 1089) @@ -2,10 +2,18 @@ import java.util.ArrayList; import java.util.Collection; +import java.util.Collections; import java.util.HashSet; import java.util.List; public class ArrayListUtilities { + public static<T extends Comparable<T>> List<T> copyAndSort(Collection<T> items) { + List<T> copy = new ArrayList<T>(items); + Collections.sort(copy); + + return copy; + } + // TODO: Move this to CollectionUtilities. public static<T> Collection<T> unionCollections( Collection<T> items1, @@ -36,7 +44,25 @@ Collection<T> items1, Collection<T> items2, Collection<T> keysToSkip) { - return new ArrayList<T>(unionCollections(items1, items2, keysToSkip)); + List<T> union = new ArrayList<T>(); + + if (keysToSkip == null) { + keysToSkip = new ArrayList<T>(); + } + + for (T element : items1) { + if (!union.contains(element) && !keysToSkip.contains(element)) { + union.add(element); + } + } + + for (T element : items2) { + if (!union.contains(element) && !keysToSkip.contains(element)) { + union.add(element); + } + } + + return union; } /* Implodes list to a String with the String.valueOf the elements separated Modified: 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-07-13 21:30:22 UTC (rev 1088) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModel.java 2010-07-15 08:30:27 UTC (rev 1089) @@ -2,7 +2,6 @@ import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.Map; @@ -61,13 +60,15 @@ Composite parent, int style) { java.util.List<String> orderedOptionLabels = new ArrayList<String>(unorderedOptionLabels); - Collections.sort(orderedOptionLabels); 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, orderedOptionLabels.get(selectedIndex), dropDown, dataSynchronizer); + name, + optionValuesByLabels.get(orderedOptionLabels.get(selectedIndex)), + dropDown, + dataSynchronizer); addField(field); return field; Modified: 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-07-13 21:30:22 UTC (rev 1088) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModelField.java 2010-07-15 08:30:27 UTC (rev 1089) @@ -8,6 +8,7 @@ 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; @@ -26,9 +27,9 @@ 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(); - System.err.println(GUIModelField.this.value); } } }); @@ -38,6 +39,10 @@ return this.name; } + public T getPreviousValue() { + return this.previousValue; + } + public T getValue() { return this.value; } Modified: 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 2010-07-13 21:30:22 UTC (rev 1088) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/DropDownDataSynchronizer.java 2010-07-15 08:30:27 UTC (rev 1089) @@ -14,7 +14,7 @@ public class DropDownDataSynchronizer implements ModelDataSynchronizer<String> { private Combo dropDown; private BiMap<Integer, String> optionLabels; - private Map<String, String> optionValuesByLabels; + private BiMap<String, String> optionValuesByLabels; public DropDownDataSynchronizer( Combo dropDown, @@ -22,10 +22,8 @@ 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])); + setOptions(optionLabels, optionValuesByLabels); this.dropDown.select(selectedIndex); } @@ -39,11 +37,12 @@ } public String synchronizeFromGUI() { - return this.optionLabels.get(this.dropDown.getSelectionIndex()); + return value(); } public String synchronizeToGUI(String value) { - this.dropDown.select(this.optionLabels.inverse().get(value)); + String label = this.optionValuesByLabels.inverse().get(value); + this.dropDown.select(this.optionLabels.inverse().get(label)); return value(); } @@ -51,4 +50,12 @@ public String reset(String defaultValue) { return synchronizeToGUI(defaultValue); } + + public void setOptions(List<String> optionLabels, Map<String, String> optionValuesByLabels) { + this.optionLabels = HashBiMap.create(MapUtilities.mapIndexToValues(optionLabels)); + this.optionValuesByLabels = HashBiMap.create(optionValuesByLabels); + + this.dropDown.setItems(optionLabels.toArray(new String[0])); + this.dropDown.select(0); + } } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
[CIShell-SVN] SF.net SVN: cishell:[1091]
trunk/core/org.cishell.utilities/src/org/cishell /utilities
From: <pat...@us...> - 2010-07-21 00:47:21
|
Revision: 1091 http://cishell.svn.sourceforge.net/cishell/?rev=1091&view=rev Author: pataphil Date: 2010-07-21 00:47:14 +0000 (Wed, 21 Jul 2010) Log Message: ----------- * Added MapUtilities.valuesByKeys(). * Fixed some SWT GUIModel bugs. Modified Paths: -------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.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/datasynchronizer/TextDataSynchronizer.java 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-16 02:11:57 UTC (rev 1090) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java 2010-07-21 00:47:14 UTC (rev 1091) @@ -63,4 +63,18 @@ return valuesByIndex; } + + public static<K, V> void valuesByKeys( + Map<K, V> items, Collection<K> keys, Collection<V> target) { + for (K key : keys) { + target.add(items.get(key)); + } + } + + public static<K, V> Collection<V> valuesByKeys(Map<K, V> items, Collection<K> keys) { + List<V> values = new ArrayList<V>(); + valuesByKeys(items, keys, values); + + return values; + } } \ No newline at end of file Modified: 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-07-16 02:11:57 UTC (rev 1090) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/GUIModelGroup.java 2010-07-21 00:47:14 UTC (rev 1091) @@ -50,6 +50,8 @@ public<T> void removeField( GUIModelField<T, ? extends Widget, ? extends ModelDataSynchronizer<?>> field) { - this.inputFieldsByName.remove(field); + if (this.inputFieldsByName.containsValue(field)) { + this.inputFieldsByName.remove(field.getName()); + } } } \ No newline at end of file Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/TextDataSynchronizer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/TextDataSynchronizer.java 2010-07-16 02:11:57 UTC (rev 1090) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/model/datasynchronizer/TextDataSynchronizer.java 2010-07-21 00:47:14 UTC (rev 1091) @@ -13,7 +13,7 @@ } public int swtUpdateListenerCode() { - return SWT.Selection; + return SWT.Modify; } public String value() { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
[CIShell-SVN] SF.net SVN: cishell:[1093]
trunk/core/org.cishell.utilities/src/org/cishell /utilities
From: <pat...@us...> - 2010-07-21 03:50:43
|
Revision: 1093 http://cishell.svn.sourceforge.net/cishell/?rev=1093&view=rev Author: pataphil Date: 2010-07-21 03:50:35 +0000 (Wed, 21 Jul 2010) Log Message: ----------- * Added GUIBuilderUtilities.setCancelable(). Modified Paths: -------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUIBuilderUtilities.java Added Paths: ----------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ObjectContainer.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUICanceledException.java Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/ObjectContainer.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ObjectContainer.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/ObjectContainer.java 2010-07-21 03:50:35 UTC (rev 1093) @@ -0,0 +1,12 @@ +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-07-21 03:49:14 UTC (rev 1092) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUIBuilderUtilities.java 2010-07-21 03:50:35 UTC (rev 1093) @@ -1,9 +1,14 @@ package org.cishell.utilities.swt; +import org.cishell.utilities.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 { @@ -75,4 +80,45 @@ 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 Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUICanceledException.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUICanceledException.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/swt/GUICanceledException.java 2010-07-21 03:50:35 UTC (rev 1093) @@ -0,0 +1,21 @@ +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 This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
[CIShell-SVN] SF.net SVN: cishell:[1127]
trunk/core/org.cishell.utilities/src/org/cishell /utilities
From: <pat...@us...> - 2010-08-23 18:06:46
|
Revision: 1127 http://cishell.svn.sourceforge.net/cishell/?rev=1127&view=rev Author: pataphil Date: 2010-08-23 18:06:40 +0000 (Mon, 23 Aug 2010) Log Message: ----------- * Added MapUtilities.keysToCounts(). * Reviewed by Chintan. Modified Paths: -------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/CollectionUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/CollectionUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/CollectionUtilities.java 2010-08-19 17:08:12 UTC (rev 1126) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/CollectionUtilities.java 2010-08-23 18:06:40 UTC (rev 1127) @@ -6,7 +6,6 @@ import java.util.Iterator; public class CollectionUtilities { - /* Return only elements of the Collection which are mapped to true in the * Dictionary */ Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java 2010-08-19 17:08:12 UTC (rev 1126) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java 2010-08-23 18:06:40 UTC (rev 1127) @@ -77,4 +77,18 @@ return values; } + + public static<K> Map<K, Integer> keysToCounts(Collection<K> keys) { + Map<K, Integer> keysToCounts = new HashMap<K, Integer>(); + + for (K key : keys) { + if (keysToCounts.containsKey(key)) { + keysToCounts.put(key, keysToCounts.get(key) + 1); + } else { + keysToCounts.put(key, 1); + } + } + + return keysToCounts; + } } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
[CIShell-SVN] SF.net SVN: cishell:[1188]
trunk/core/org.cishell.utilities/src/org/cishell /utilities
From: <pat...@us...> - 2011-01-06 16:37:15
|
Revision: 1188 http://cishell.svn.sourceforge.net/cishell/?rev=1188&view=rev Author: pataphil Date: 2011-01-06 16:37:08 +0000 (Thu, 06 Jan 2011) Log Message: ----------- * Added NumberUtilities.interpretObjectAsNumber * Minor cleaned-up in NumberUtilities and TableUtilities * Reviewed by Joseph Modified Paths: -------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/NumberUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/TableUtilities.java Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/NumberUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/NumberUtilities.java 2011-01-03 19:46:56 UTC (rev 1187) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/NumberUtilities.java 2011-01-06 16:37:08 UTC (rev 1188) @@ -2,25 +2,120 @@ import java.text.DecimalFormat; import java.text.Format; +import java.text.NumberFormat; +import java.text.ParseException; public class NumberUtilities { public static final String UNROUNDED_DECIMAL_PATTERN = "#.############################"; public static final String NOT_A_NUMBER_PREFIX = "NOT A NUMBER"; + + public static final String EMPTY_CELL_MESSAGE = "An empty number cell was found."; + + public static Number interpretObjectAsNumber(Object object) + throws NumberFormatException, ParseException { + if (object instanceof Number) { + Number number = (Number) object; + + return number; + } else if (object instanceof short[]) { + short[] objectAsShortArray = (short[]) object; + + if (objectAsShortArray.length == 0) { + throw new NumberFormatException(EMPTY_CELL_MESSAGE); + } else { + return new Short(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]; + } + } else if (object instanceof int[]) { + int[] objectAsIntArray = (int[]) object; + + if (objectAsIntArray.length == 0) { + throw new NumberFormatException(EMPTY_CELL_MESSAGE); + } else { + return new Integer(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]; + } + } else if (object instanceof long[]) { + long[] objectAsLongArray = (long[]) object; + + if (objectAsLongArray.length == 0) { + throw new NumberFormatException(EMPTY_CELL_MESSAGE); + } else { + return new Long(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]; + } + } else if (object instanceof float[]) { + float[] objectAsFloatArray = (float[]) object; + + if (objectAsFloatArray.length == 0) { + throw new NumberFormatException(EMPTY_CELL_MESSAGE); + } else { + return new Float(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]; + } + } 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]; + } + } + + NumberFormat numberFormat = NumberFormat.getInstance(); + + return numberFormat.parse(object.toString()); + } 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; + Number number = (Number) object; return new Double(number.doubleValue()); } else if (object instanceof short[]) { - short[] objectAsShortArray = (short[])object; + short[] objectAsShortArray = (short[]) object; if (objectAsShortArray.length == 0) { throw new NumberFormatException(EMPTY_CELL_MESSAGE); @@ -28,7 +123,7 @@ return new Double(objectAsShortArray[0]); } } else if (object instanceof Short[]) { - Short[] objectAsShortArray = (Short[])object; + Short[] objectAsShortArray = (Short[]) object; if (objectAsShortArray.length == 0) { throw new NumberFormatException(EMPTY_CELL_MESSAGE); @@ -36,7 +131,7 @@ return new Double(objectAsShortArray[0].doubleValue()); } } else if (object instanceof int[]) { - int[] objectAsIntArray = (int[])object; + int[] objectAsIntArray = (int[]) object; if (objectAsIntArray.length == 0) { throw new NumberFormatException(EMPTY_CELL_MESSAGE); @@ -44,7 +139,7 @@ return new Double(objectAsIntArray[0]); } } else if (object instanceof Integer[]) { - Integer[] objectAsIntegerArray = (Integer[])object; + Integer[] objectAsIntegerArray = (Integer[]) object; if (objectAsIntegerArray.length == 0) { throw new NumberFormatException(EMPTY_CELL_MESSAGE); @@ -52,7 +147,7 @@ return new Double(objectAsIntegerArray[0].doubleValue()); } } else if (object instanceof long[]) { - long[] objectAsLongArray = (long[])object; + long[] objectAsLongArray = (long[]) object; if (objectAsLongArray.length == 0) { throw new NumberFormatException(EMPTY_CELL_MESSAGE); @@ -60,7 +155,7 @@ return new Double(objectAsLongArray[0]); } } else if (object instanceof Long[]) { - Long[] objectAsLongArray = (Long[])object; + Long[] objectAsLongArray = (Long[]) object; if (objectAsLongArray.length == 0) { throw new NumberFormatException(EMPTY_CELL_MESSAGE); @@ -68,7 +163,7 @@ return new Double(objectAsLongArray[0].doubleValue()); } } else if (object instanceof float[]) { - float[] objectAsFloatArray = (float[])object; + float[] objectAsFloatArray = (float[]) object; if (objectAsFloatArray.length == 0) { throw new NumberFormatException(EMPTY_CELL_MESSAGE); @@ -76,7 +171,7 @@ return new Double(objectAsFloatArray[0]); } } else if (object instanceof Float[]) { - Float[] objectAsFloatArray = (Float[])object; + Float[] objectAsFloatArray = (Float[]) object; if (objectAsFloatArray.length == 0) { throw new NumberFormatException(EMPTY_CELL_MESSAGE); @@ -84,7 +179,7 @@ return new Double(objectAsFloatArray[0].doubleValue()); } } else if (object instanceof double[]) { - double[] objectAsDoubleArray = (double[])object; + double[] objectAsDoubleArray = (double[]) object; if (objectAsDoubleArray.length == 0) { throw new NumberFormatException(EMPTY_CELL_MESSAGE); @@ -92,7 +187,7 @@ return new Double(objectAsDoubleArray[0]); } } else if (object instanceof Double[]) { - Double[] objectAsDoubleArray = (Double[])object; + Double[] objectAsDoubleArray = (Double[]) object; if (objectAsDoubleArray.length == 0) { throw new NumberFormatException(EMPTY_CELL_MESSAGE); Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/TableUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/TableUtilities.java 2011-01-03 19:46:56 UTC (rev 1187) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/TableUtilities.java 2011-01-06 16:37:08 UTC (rev 1188) @@ -11,6 +11,50 @@ import prefuse.util.collections.IntIterator; public class TableUtilities { + public static final Class<?>[] POSSIBLE_NUMBER_CLASSES = { + 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 + }; + + public static final Class<?>[] POSSIBLE_INTEGER_CLASSES = { + int.class, + Integer.class, + int[].class, + Integer[].class + }; + + public static final Class<?>[] POSSIBLE_DATE_CLASSES = { + Date.class, + int.class, + Integer.class, + String.class, + int[].class, + Integer[].class, + String[].class, + }; + public static Table copyTable(Table oldTable) { Schema oldSchema = oldTable.getSchema(); Table newTable = oldSchema.instantiate(); @@ -87,61 +131,17 @@ 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); + return filterSchemaColumnNamesByClasses(table.getSchema(), POSSIBLE_NUMBER_CLASSES); } public static String[] getValidIntegerColumnNamesInTable(Table table) throws ColumnNotFoundException { - Class<?>[] possibleIntegerClasses = { - int.class, - Integer.class, - int[].class, - Integer[].class - }; - - return filterSchemaColumnNamesByClasses(table.getSchema(), possibleIntegerClasses); + return filterSchemaColumnNamesByClasses(table.getSchema(), POSSIBLE_INTEGER_CLASSES); } 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); + return filterSchemaColumnNamesByClasses(table.getSchema(), POSSIBLE_DATE_CLASSES); } public static String[] filterSchemaColumnNamesByClasses( This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
[CIShell-SVN] SF.net SVN: cishell:[1206]
trunk/core/org.cishell.utilities/src/org/cishell /utilities
From: <pat...@us...> - 2011-02-11 13:38:43
|
Revision: 1206 http://cishell.svn.sourceforge.net/cishell/?rev=1206&view=rev Author: pataphil Date: 2011-02-11 13:38:37 +0000 (Fri, 11 Feb 2011) Log Message: ----------- * Added CollectionUtilities.collectionEnumerationElements * Added MapUtilities.mapKeyToIndices * Added ZipIOException and ZipUtilities * Not reviewed. Modified Paths: -------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/CollectionUtilities.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java Added Paths: ----------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ZipIOException.java trunk/core/org.cishell.utilities/src/org/cishell/utilities/ZipUtilities.java Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/CollectionUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/CollectionUtilities.java 2011-02-11 13:37:40 UTC (rev 1205) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/CollectionUtilities.java 2011-02-11 13:38:37 UTC (rev 1206) @@ -3,6 +3,7 @@ import java.util.ArrayList; import java.util.Collection; import java.util.Dictionary; +import java.util.Enumeration; import java.util.Iterator; public class CollectionUtilities { @@ -31,4 +32,13 @@ public static<T> T get(Collection<T> values, int index) { return (T) values.toArray()[index]; } + + public static<T> Collection<T> collectionEnumerationElements( + Enumeration<T> source, Collection<T> target) { + while (source.hasMoreElements()) { + target.add(source.nextElement()); + } + + return target; + } } Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java 2011-02-11 13:37:40 UTC (rev 1205) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/MapUtilities.java 2011-02-11 13:38:37 UTC (rev 1206) @@ -64,6 +64,16 @@ return valuesByIndex; } + public static<K> Map<K, Integer> mapKeyToIndices(List<K> keys) { + Map<K, Integer> indexByKeys = new HashMap<K, Integer>(); + + for (int ii = 0; ii < keys.size(); ii++) { + indexByKeys.put(keys.get(ii), ii); + } + + return indexByKeys; + } + public static<K, V> void valuesByKeys( Map<K, V> items, Collection<K> keys, Collection<V> target) { for (K key : keys) { Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/ZipIOException.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ZipIOException.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/ZipIOException.java 2011-02-11 13:38:37 UTC (rev 1206) @@ -0,0 +1,21 @@ +package org.cishell.utilities; + +public class ZipIOException extends Exception { + private static final long serialVersionUID = 1L; + + public ZipIOException() { + super(); + } + + public ZipIOException(String arg0) { + super(arg0); + } + + public ZipIOException(Throwable arg0) { + super(arg0); + } + + public ZipIOException(String arg0, Throwable arg1) { + super(arg0, arg1); + } +} \ No newline at end of file Added: trunk/core/org.cishell.utilities/src/org/cishell/utilities/ZipUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/ZipUtilities.java (rev 0) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/ZipUtilities.java 2011-02-11 13:38:37 UTC (rev 1206) @@ -0,0 +1,143 @@ +package org.cishell.utilities; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; +import java.util.zip.ZipOutputStream; + +public class ZipUtilities { + static final int BUFFER_SIZE = 2048; + + public static void zipFiles(Collection<File> files, ZipOutputStream zipOut) + throws ZipIOException { + try { + for (File file : files) { + writeFileToZipFile(file, zipOut); + } + + zipOut.close(); + } catch (IOException e) { + throw new ZipIOException(e.getMessage(), e); + } + } + + public static void zipFiles(Collection<File> files, File targetZipFile) + throws ZipIOException { + try { + zipFiles( + files, + new ZipOutputStream( + new BufferedOutputStream(new FileOutputStream(targetZipFile)))); + } catch (FileNotFoundException e) { + throw new ZipIOException(e.getMessage(), e); + } + } + + public static void writeFileToZipFile(File file, ZipOutputStream zipOut) + throws ZipIOException { + try { + byte data[] = new byte[BUFFER_SIZE]; + BufferedInputStream fileInput = + new BufferedInputStream(new FileInputStream(file), BUFFER_SIZE); + ZipEntry entry = new ZipEntry(file.getName()); + zipOut.putNextEntry(entry); + int count; + + while ((count = fileInput.read(data, 0, BUFFER_SIZE)) != -1) { + zipOut.write(data, 0, count); + } + + fileInput.close(); + } catch (FileNotFoundException e) { + throw new ZipIOException(e.getMessage(), e); + } catch (IOException e) { + throw new ZipIOException(e.getMessage(), e); + } + } + + public static File readFileFromZipFile(ZipEntry entry, ZipFile zipFile) throws IOException { + long size = entry.getSize(); + + if (size > 0) { + BufferedInputStream reader = new BufferedInputStream(zipFile.getInputStream(entry)); + String fileName = new File(entry.getName()).getName(); + File outputFile = + FileUtilities.createTemporaryFileInDefaultTemporaryDirectory(fileName, ""); + BufferedOutputStream output = + new BufferedOutputStream(new FileOutputStream(outputFile), BUFFER_SIZE); + + byte readBytes[] = new byte[BUFFER_SIZE]; + int readByteCount; + + while ((readByteCount = reader.read(readBytes, 0, BUFFER_SIZE)) != -1) { + output.write(readBytes, 0, readByteCount); + } + + output.close(); + + return outputFile; + } else { + return null; + } + } + + public static Map<String, ZipEntry> mapFileNamesToEntries( + ZipFile zipFile, boolean includeDirectories) throws IOException { + Collection<ZipEntry> entries = collectEntries(zipFile); + Map<String, ZipEntry> fileNamesToEntries = new HashMap<String, ZipEntry>(); + + for (ZipEntry entry : entries) { + if (includeDirectories) { + if (entry.isDirectory()) { + fileNamesToEntries.put(entry.getName(), entry); + } + } else if (!entry.isDirectory()) { + fileNamesToEntries.put(entry.getName(), entry); + } + } + + return fileNamesToEntries; + } + + @SuppressWarnings("unchecked") + public static Collection<ZipEntry> collectEntries(ZipFile zipFile) throws IOException { + Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>) zipFile.entries(); + + return CollectionUtilities.collectionEnumerationElements( + entries, new ArrayList<ZipEntry>()); + } + + public static void main(String[] args) { + String filePath = + "C:\\Documents and Settings\\pataphil\\Desktop\\org.cishell.utility.swt.zip"; + + try { + ZipFile zipFile = new ZipFile(filePath); + Map<String, ZipEntry> entriesByName = mapFileNamesToEntries(zipFile, false); + + int count = 0; + for (String key : entriesByName.keySet()) { + System.err.println(key + ": " + entriesByName.get(key)); + count++; + + if (count == 2) { + readFileFromZipFile(entriesByName.get(key), zipFile); + } + } + } catch (IOException e) { + System.err.println("Exception: " + e.getMessage()); + e.printStackTrace(); + } + } +} \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |