From: <pat...@us...> - 2010-05-28 18:53:09
|
Revision: 1068 http://cishell.svn.sourceforge.net/cishell/?rev=1068&view=rev Author: pataphil Date: 2010-05-28 18:53:00 +0000 (Fri, 28 May 2010) Log Message: ----------- * Refactored File Load code to not suck so bad. * Reviewed by Joseph. Modified Paths: -------------- trunk/clients/gui/org.cishell.reference.gui.brand.cishell/extra-files/configuration/default_menu.xml trunk/clients/gui/org.cishell.reference.gui.persistence/OSGI-INF/load.properties trunk/clients/gui/org.cishell.reference.gui.persistence/OSGI-INF/load.xml trunk/clients/gui/org.cishell.reference.gui.persistence/OSGI-INF/metatype/METADATA.XML trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileFormatSelector.java trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileLoadFactory.java trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/viewwith/FileViewWithFactory.java Added Paths: ----------- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileLoadAlgorithm.java trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileLoadUserInputRunnable.java trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileValidator.java Removed Paths: ------------- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileLoad.java Modified: trunk/clients/gui/org.cishell.reference.gui.brand.cishell/extra-files/configuration/default_menu.xml =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.brand.cishell/extra-files/configuration/default_menu.xml 2010-05-28 18:18:24 UTC (rev 1067) +++ trunk/clients/gui/org.cishell.reference.gui.brand.cishell/extra-files/configuration/default_menu.xml 2010-05-28 18:53:00 UTC (rev 1068) @@ -2,7 +2,7 @@ <!-- <?xml version="1.0" encoding="ISO-8859-1" ?> --> <menu_layout> <top_menu name="File"> - <menu name="Load..." pid= "org.cishell.reference.gui.persistence.load.FileLoad "/> + <menu name="Load..." pid= "org.cishell.reference.gui.persistence.load.FileLoadAlgorithm "/> <menu type="break"/> <menu name="Save..." pid= "org.cishell.reference.gui.persistence.save.Save"/> <menu type="break"/> Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/OSGI-INF/load.properties =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/OSGI-INF/load.properties 2010-05-28 18:18:24 UTC (rev 1067) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/OSGI-INF/load.properties 2010-05-28 18:53:00 UTC (rev 1068) @@ -4,7 +4,7 @@ description=This allows users to select file from the file system and load it to Data Model window in_data=null out_data=java.lang.Object -service.pid=org.cishell.reference.gui.persistence.load.FileLoad +service.pid=org.cishell.reference.gui.persistence.load.FileLoadAlgorithm remoteable=true prefs_published=local receive_prefs=true Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/OSGI-INF/load.xml =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/OSGI-INF/load.xml 2010-05-28 18:18:24 UTC (rev 1067) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/OSGI-INF/load.xml 2010-05-28 18:53:00 UTC (rev 1068) @@ -1,5 +1,5 @@ <?xml version="1.0" encoding="UTF-8"?> -<component name="org.cishell.reference.gui.persistence.load.FileLoad.component" immediate="false"> +<component name="org.cishell.reference.gui.persistence.load.FileLoadAlgorithm.component" immediate="false"> <implementation class="org.cishell.reference.gui.persistence.load.FileLoadFactory"/> <properties entry="OSGI-INF/load.properties"/> <reference name="LOG" interface="org.osgi.service.log.LogService"/> Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/OSGI-INF/metatype/METADATA.XML =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/OSGI-INF/metatype/METADATA.XML 2010-05-28 18:18:24 UTC (rev 1067) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/OSGI-INF/metatype/METADATA.XML 2010-05-28 18:53:00 UTC (rev 1068) @@ -1,6 +1,6 @@ <?xml version="1.0" encoding="UTF-8"?> <metatype:MetaData xmlns:metatype="http://www.osgi.org/xmlns/metatype/v1.0.0"> - <OCD name="File Load" id="org.cishell.reference.gui.persistence.load.FileLoad.prefs.local.OCD" + <OCD name="File Load" id="org.cishell.reference.gui.persistence.load.FileLoadAlgorithm.prefs.local.OCD" description=" "> <AD name="Default load directory" id="loadDir" type="String" default="directory:sampledata/"/> </OCD> @@ -8,8 +8,8 @@ description=" "> <AD name="View With" id="viewWith" type="String" default=""/> </OCD> - <Designate pid="org.cishell.reference.gui.persistence.load.FileLoad.prefs.local"> - <Object ocdref="org.cishell.reference.gui.persistence.load.FileLoad.prefs.local.OCD" /> + <Designate pid="org.cishell.reference.gui.persistence.load.FileLoadAlgorithm.prefs.local"> + <Object ocdref="org.cishell.reference.gui.persistence.load.FileLoadAlgorithm.prefs.local.OCD" /> </Designate> <Designate pid="org.cishell.reference.gui.persistence.viewwith.FileViewWith"> <Object ocdref="org.cishell.reference.gui.persistence.viewwith.FileViewWith.OCD" /> Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileFormatSelector.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileFormatSelector.java 2010-05-28 18:18:24 UTC (rev 1067) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileFormatSelector.java 2010-05-28 18:53:00 UTC (rev 1068) @@ -6,13 +6,7 @@ */ package org.cishell.reference.gui.persistence.load; -import java.io.File; -import java.util.ArrayList; - -import org.cishell.framework.CIShellContext; import org.cishell.framework.algorithm.AlgorithmFactory; -import org.cishell.framework.data.BasicData; -import org.cishell.framework.data.Data; import org.cishell.framework.data.DataProperty; import org.cishell.reference.gui.common.AbstractDialog; import org.eclipse.swt.SWT; @@ -30,17 +24,12 @@ import org.eclipse.swt.widgets.Shell; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; -import org.osgi.service.log.LogService; public class FileFormatSelector extends AbstractDialog { - private File selectedFile; - private LogService logger; - private ServiceReference[] persisterArray; - private List persisterList; -// private StyledText detailPane; - private CIShellContext ciShellContext; private BundleContext bundleContext; - private ArrayList returnList; + private AlgorithmFactory validator; + private ServiceReference[] validatorReferences; + private List validatorList; // private static final String[] DETAILS_ITEM_KEY = // {"format_name", "supported_file_extension", "format_description" }; @@ -59,19 +48,12 @@ public FileFormatSelector( String title, - File selectedFile, Shell parent, - CIShellContext ciShellContext, - BundleContext bundleContext, - ServiceReference[] persisterArray, - ArrayList returnList) { + BundleContext bundleContext, + ServiceReference[] validatorReferences) { super(parent, title, AbstractDialog.QUESTION); - this.ciShellContext = ciShellContext; this.bundleContext = bundleContext; - this.persisterArray = persisterArray; - this.returnList = returnList; - this.selectedFile = selectedFile; - this.logger = (LogService)ciShellContext.getService(LogService.class.getName()); + this.validatorReferences = validatorReferences; // Shall this part be moved out of the code? setDescription( @@ -82,8 +64,12 @@ "This dialog allows the user to choose among all available " + "formats for loading the selected data model. Choose any of the formats " + "to continue loading the dataset."); - } + } + public AlgorithmFactory getValidator() { + return this.validator; + } + private Composite initializeGUI(Composite parent) { Composite content = new Composite(parent, SWT.NONE); @@ -91,18 +77,18 @@ layout.numColumns = 1; content.setLayout(layout); - Group persisterGroup = new Group(content, SWT.NONE); + Group validatorGroup = new Group(content, SWT.NONE); // Shall this label be moved out of the code? - persisterGroup.setText("Load as..."); - persisterGroup.setLayout(new FillLayout()); - GridData persisterListGridData = new GridData(GridData.FILL_BOTH); - persisterListGridData.widthHint = 200; - persisterGroup.setLayoutData(persisterListGridData); + validatorGroup.setText("Load as..."); + validatorGroup.setLayout(new FillLayout()); + GridData validatorListGridData = new GridData(GridData.FILL_BOTH); + validatorListGridData.widthHint = 200; + validatorGroup.setLayoutData(validatorListGridData); - this.persisterList = new List(persisterGroup, SWT.H_SCROLL |SWT.V_SCROLL | SWT.SINGLE); + this.validatorList = new List(validatorGroup, SWT.H_SCROLL |SWT.V_SCROLL | SWT.SINGLE); // initPersisterArray(); initializePersisterList(); - this.persisterList.addMouseListener(new MouseAdapter() { + this.validatorList.addMouseListener(new MouseAdapter() { public void mouseDoubleClick(MouseEvent mouseEvent) { List list = (List)mouseEvent.getSource(); int selection = list.getSelectionIndex(); @@ -113,109 +99,70 @@ } }); - this.persisterList.addSelectionListener(new SelectionAdapter() { + this.validatorList.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent selectionEvent) { List list = (List)selectionEvent.getSource(); int selection = list.getSelectionIndex(); if (selection != -1) { - // updateDetailPane(persisterArray[selection]); + // updateDetailPane(validatorReferences[selection]); } } }); - persisterList.setSelection(0); + validatorList.setSelection(0); - /* Group detailsGroup = new Group(content, SWT.NONE); - // Shall this label be moved out of the code? - detailsGroup.setText("Details"); - detailsGroup.setLayout(new FillLayout()); - GridData detailsGridData = new GridData(GridData.FILL_BOTH); - detailsGridData.widthHint = 200; - detailsGroup.setLayoutData(detailsGridData); - - detailPane = initDetailPane(detailsGroup); - - persisterList.setSelection(0); - updateDetailPane(persisterArray[0]); */ - return content; } private void initializePersisterList() { - for (int ii = 0; ii < this.persisterArray.length; ++ii) { - String name = (String)this.persisterArray[ii].getProperty("label"); + for (int ii = 0; ii < this.validatorReferences.length; ++ii) { + String name = (String)this.validatorReferences[ii].getProperty("label"); /* * If someone was sloppy enough to not provide a name, then use the name of the * class instead. */ if (name == null || name.length() == 0) { - name = this.persisterArray[ii].getClass().getName(); + name = this.validatorReferences[ii].getClass().getName(); } - this.persisterList.add(name); + this.validatorList.add(name); } } - - /* private StyledText initDetailPane(Group detailsGroup) { - StyledText detailPane = new StyledText(detailsGroup, SWT.H_SCROLL | SWT.V_SCROLL); - detailPane.setEditable(false); - detailPane.getCaret().setVisible(false); - - return detailPane; - }*/ - - /* private void updateDetailPane(ServiceReference persister) { - - detailPane.setText(""); - - for (int ii = 0; ii < DETAILS_ITEM_KEY.length; ii++){ - String val = (String)persister.getProperty(DETAILS_ITEM_KEY[ii]); - - StyleRange styleRange = new StyleRange(); - styleRange.start = detailPane.getText().length(); - detailPane.append(DETAILS_ITEM_KEY_DISPLAY_VALUE[ii] + ":\n"); - styleRange.length = DETAILS_ITEM_KEY[ii].length() + 1; - styleRange.fontStyle = SWT.BOLD; - detailPane.setStyleRange(styleRange); - - detailPane.append(val + "\n"); - } - } */ - private void selectionMade(int selectedIndex) { - AlgorithmFactory persister = - (AlgorithmFactory)this.bundleContext.getService(this.persisterArray[selectedIndex]); - Data[] data = null; - boolean loadSuccess = false; - - try { - data = - new Data[] { new BasicData(this.selectedFile.getPath(), String.class.getName()) }; - data = persister.createAlgorithm(data, null, this.ciShellContext).execute(); - loadSuccess = true; - } catch (Throwable exception) { - this.logger.log( - LogService.LOG_ERROR, "Error occurred while executing selection", exception); - exception.printStackTrace(); - loadSuccess = false; - } - - if ((data != null) && loadSuccess) { - this.logger.log(LogService.LOG_INFO, "Loaded: " + this.selectedFile.getPath()); - - for (int ii = 0; ii < data.length; ii++) { - Data dataItem = data[ii]; - FileLoad.relabelWithFilename(dataItem, selectedFile); - this.returnList.add(dataItem); - } - - close(true); - } else { - this.logger.log(LogService.LOG_ERROR, "Unable to load with selected loader"); - } + this.validator = + (AlgorithmFactory)this.bundleContext.getService(this.validatorReferences[selectedIndex]); + close(true); +// AlgorithmFactory validator = +// (AlgorithmFactory)this.bundleContext.getService(this.persisterArray[selectedIndex]); +// Data[] data = null; +// boolean loadSuccess = false; +// +// try { +// data = +// new Data[] { new BasicData(this.selectedFile.getPath(), String.class.getName()) }; +// data = validator.createAlgorithm(data, null, this.ciShellContext).execute(); +// loadSuccess = true; +// } catch (Throwable exception) { +// this.logger.log( +// LogService.LOG_ERROR, "Error occurred while executing selection", exception); +// exception.printStackTrace(); +// loadSuccess = false; +// } +// +// if ((data != null) && loadSuccess) { +// this.logger.log(LogService.LOG_INFO, "Loaded: " + this.selectedFile.getPath()); +// +// for (int ii = 0; ii < data.length; ii++) { +// this.returnList.add(data[ii]); +// } +// +// close(true); +// } else { +// this.logger.log(LogService.LOG_ERROR, "Unable to load with selected loader"); +// } } public void createDialogButtons(Composite parent) { @@ -223,7 +170,7 @@ select.setText("Select"); select.addSelectionListener(new SelectionAdapter(){ public void widgetSelected(SelectionEvent selectionEvent) { - int index = FileFormatSelector.this.persisterList.getSelectionIndex(); + int index = FileFormatSelector.this.validatorList.getSelectionIndex(); if (index != -1) { selectionMade(index); Deleted: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileLoad.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileLoad.java 2010-05-28 18:18:24 UTC (rev 1067) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileLoad.java 2010-05-28 18:53:00 UTC (rev 1068) @@ -1,302 +0,0 @@ -package org.cishell.reference.gui.persistence.load; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Dictionary; - -import org.cishell.framework.CIShellContext; -import org.cishell.framework.algorithm.Algorithm; -import org.cishell.framework.algorithm.AlgorithmExecutionException; -import org.cishell.framework.algorithm.AlgorithmFactory; -import org.cishell.framework.data.BasicData; -import org.cishell.framework.data.Data; -import org.cishell.framework.data.DataProperty; -import org.eclipse.swt.SWT; -import org.eclipse.swt.widgets.Display; -import org.eclipse.swt.widgets.FileDialog; -import org.eclipse.ui.IWorkbenchWindow; -import org.eclipse.ui.PlatformUI; -import org.osgi.framework.BundleContext; -import org.osgi.framework.InvalidSyntaxException; -import org.osgi.framework.ServiceReference; -import org.osgi.service.log.LogService; - -public class FileLoad implements Algorithm { - - private final LogService logger; - - private BundleContext bundleContext; - private CIShellContext ciShellContext; - private static String defaultLoadDirectory; - - public FileLoad(CIShellContext ciContext, BundleContext bContext, - Dictionary prefProperties) { - this.ciShellContext = ciContext; - this.bundleContext = bContext; - logger = (LogService) ciContext.getService(LogService.class.getName()); - - // unpack preference properties - if (defaultLoadDirectory == null) { - - /* - * get the default load directory from preferences, - * if it has been set. - */ - Object result = prefProperties.get("loadDir"); - if (result != null) { - defaultLoadDirectory = (String) result; - } else { - defaultLoadDirectory = ""; - } - } - } - - protected static void relabelWithFilename(Data data, File file) { - File absoluteFile; - try { - absoluteFile = file.getCanonicalFile(); - } catch (IOException e) { - absoluteFile = file.getAbsoluteFile(); - } - File parent; - try { - parent = absoluteFile.getParentFile().getCanonicalFile(); - } catch (IOException e) { - parent = absoluteFile.getParentFile().getAbsoluteFile(); - } - String prefix; - String parentName = parent.getName(); - if(parentName.trim().length() == 0) { - prefix = File.separator; - } else { - prefix = "..." + File.separator + parentName + File.separator; - } - data.getMetadata().put(DataProperty.LABEL, prefix + absoluteFile.getName()); - } - - public Data[] execute() throws AlgorithmExecutionException { - // prepare to run load dialog in GUI thread - - IWorkbenchWindow window = getFirstWorkbenchWindow(); - Display display = PlatformUI.getWorkbench().getDisplay(); - FileLoadRunnable fileLoader = new FileLoadRunnable(window); - - // run load dialog in gui thread. - - if (Thread.currentThread() != display.getThread()) { - display.syncExec(fileLoader); - } else { - fileLoader.run(); - } - - // return loaded file data - - Data[] loadedFileData = extractLoadedFileData(fileLoader); - return loadedFileData; - } - - final class FileLoadRunnable implements Runnable { - boolean loadFileSuccess = false; - IWorkbenchWindow window; - - // this is how we return values from the runnable - public ArrayList loadedFiles_ReturnParameter = new ArrayList(); - - FileLoadRunnable(IWorkbenchWindow window) { - this.window = window; - } - - /* - * Let the user chose which file to load, - * Let the user choose the file type (if it is ambiguous), - * and then actually load and validate the file. - */ - public void run() { - try { - // Prepare to ask the user which file to load. - - FileDialog dialog = new FileDialog(window.getShell(), SWT.OPEN); - File currentDir = new File(defaultLoadDirectory); - String absolutePath = currentDir.getAbsolutePath(); - dialog.setFilterPath(absolutePath); - dialog.setText("Select a File"); - - // Determine which file to load. - - String nameOfFileToLoad = dialog.open(); - if (nameOfFileToLoad == null) { - return; - } - - // Actually load the file. - - File file = new File(nameOfFileToLoad); - - if (file.isDirectory()) { - defaultLoadDirectory = file.getAbsolutePath(); - } else { - defaultLoadDirectory = file.getParentFile().getAbsolutePath(); - } - - //Validate the loaded file, "casting" it to a certain MIME type. - - // Extract the file's file extension. - - String fileExtension = getFileExtension(file).toLowerCase(); - - // Get all the validators which support this file extension... - - ServiceReference[] supportingValidators = getSupportingValidators(fileExtension); - - // If there are no supporting validators... - if (supportingValidators.length == 0) { - // Let the user choose from all the validators available. - - ServiceReference[] allValidators = getAllValidators(); - - new FileFormatSelector("Load", file, window.getShell(), - ciShellContext, bundleContext, allValidators, - loadedFiles_ReturnParameter).open(); - } - - // If there is just one supporting validator... - if (supportingValidators.length == 1) { - // Just use that validator to validate the file. - - ServiceReference onlyPossibleValidator = supportingValidators[0]; - AlgorithmFactory selectedValidatorExecutor = (AlgorithmFactory) bundleContext - .getService(onlyPossibleValidator); - Data[] outputDataAfterValidation; - Data[] inputDataForValidation = new Data[] { new BasicData( - file.getPath(), String.class.getName()) }; - outputDataAfterValidation = selectedValidatorExecutor - .createAlgorithm(inputDataForValidation, null, - ciShellContext).execute(); - - /* - * outputDataAfterValidation = null implies that file - * was not loaded properly. - */ - - if (outputDataAfterValidation != null) { - loadFileSuccess = true; - logger.log(LogService.LOG_INFO, "Loaded: " - + file.getPath()); - for (int i = 0; i < outputDataAfterValidation.length; i++) { - Data data = outputDataAfterValidation[i]; - relabelWithFilename(data, file); - loadedFiles_ReturnParameter.add(data); - } - } - } - - // If there is more than one supporting validator... - if (supportingValidators.length > 1) { - // Let the user choose which validator they want to use. - - new FileFormatSelector("Load", file, window.getShell(), - ciShellContext, bundleContext, supportingValidators, - loadedFiles_ReturnParameter).open(); - } - - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - - - private ServiceReference[] getSupportingValidators(String fileExtension) { - try { - String ldapQuery = "(& (type=validator)" + - "(|" + - "(in_data=file-ext:" + fileExtension + ")" + - "(also_validates=" + fileExtension + ")" + - "))"; - - ServiceReference[] supportingValidators = - bundleContext.getAllServiceReferences( - AlgorithmFactory.class.getName(), - ldapQuery); - - - if (supportingValidators == null) { - //(better to return a list of length zero than null) - supportingValidators = new ServiceReference[]{}; - } - - return supportingValidators; - - - } catch (InvalidSyntaxException e) { - e.printStackTrace(); - return new ServiceReference[]{}; - } - } - - private ServiceReference[] getAllValidators() { - try { - ServiceReference[] allValidators = - bundleContext.getAllServiceReferences( - AlgorithmFactory.class.getName(), - "(&(type=validator)(in_data=file-ext:*))"); - - if (allValidators == null) { - //(better to return a list of length zero than null) - allValidators = new ServiceReference[]{}; - } - - return allValidators; - - } catch (InvalidSyntaxException e) { - e.printStackTrace(); - return new ServiceReference[]{}; - } - } - - public String getFileExtension(File theFile) { - String fileName = theFile.getName(); - String extension; - if (fileName.lastIndexOf(".") != -1) - extension = fileName.substring(fileName.lastIndexOf(".") + 1); - else - extension = ""; - return extension; - } - } - - private IWorkbenchWindow getFirstWorkbenchWindow() - throws AlgorithmExecutionException { - final IWorkbenchWindow[] windows = PlatformUI.getWorkbench() - .getWorkbenchWindows(); - if (windows.length == 0) { - throw new AlgorithmExecutionException( - "Cannot obtain workbench window needed to open dialog."); - } else { - return windows[0]; - } - } - - private Data[] extractLoadedFileData(FileLoadRunnable dataUpdater) - throws AlgorithmExecutionException { - Data[] loadedFileData; - try { - if (!dataUpdater.loadedFiles_ReturnParameter.isEmpty()) { - int size = dataUpdater.loadedFiles_ReturnParameter.size(); - loadedFileData = new Data[size]; - for (int index = 0; index < size; index++) { - loadedFileData[index] = (Data) dataUpdater.loadedFiles_ReturnParameter - .get(index); - } - return loadedFileData; - } else { - this.logger - .log(LogService.LOG_WARNING, "File loading canceled"); - return new Data[0]; - } - } catch (Throwable e2) { - throw new AlgorithmExecutionException(e2); - } - } -} \ No newline at end of file Copied: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileLoadAlgorithm.java (from rev 1041, trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileLoad.java) =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileLoadAlgorithm.java (rev 0) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileLoadAlgorithm.java 2010-05-28 18:53:00 UTC (rev 1068) @@ -0,0 +1,98 @@ +package org.cishell.reference.gui.persistence.load; + +import java.io.File; +import java.util.Collection; +import java.util.Dictionary; + +import org.cishell.framework.CIShellContext; +import org.cishell.framework.algorithm.Algorithm; +import org.cishell.framework.algorithm.AlgorithmExecutionException; +import org.cishell.framework.algorithm.AlgorithmFactory; +import org.cishell.framework.algorithm.ProgressMonitor; +import org.cishell.framework.algorithm.ProgressTrackable; +import org.cishell.framework.data.Data; +import org.cishell.utilities.StringUtilities; +import org.eclipse.swt.widgets.Display; +import org.eclipse.ui.IWorkbenchWindow; +import org.eclipse.ui.PlatformUI; +import org.osgi.framework.BundleContext; +import org.osgi.service.log.LogService; + +public class FileLoadAlgorithm implements Algorithm, ProgressTrackable { + public static final String LOAD_DIRECTORY_PREFERENCE_KEY = "loadDir"; + + public static String defaultLoadDirectory; + + private final LogService logger; + private BundleContext bundleContext; + private CIShellContext ciShellContext; + private ProgressMonitor progressMonitor = ProgressMonitor.NULL_MONITOR; + + public FileLoadAlgorithm( + CIShellContext ciShellContext, + BundleContext bundleContext, + Dictionary<String, Object> preferences) { + this.logger = (LogService)ciShellContext.getService(LogService.class.getName()); + this.ciShellContext = ciShellContext; + this.bundleContext = bundleContext; + + // This is not done upon declaration because the preference service may not have started. + if (FileLoadAlgorithm.defaultLoadDirectory == null) { + FileLoadAlgorithm.defaultLoadDirectory = determineDefaultLoadDirectory(preferences); + } + } + + public Data[] execute() throws AlgorithmExecutionException { + // Prepare to run load dialog in GUI thread. + + IWorkbenchWindow window = getFirstWorkbenchWindow(); + Display display = PlatformUI.getWorkbench().getDisplay(); + FileLoadUserInputRunnable userInputGetter = new FileLoadUserInputRunnable( + window, this.bundleContext, this.ciShellContext); + + // Run load dialog in GUI thread. + + if (Thread.currentThread() != display.getThread()) { + display.syncExec(userInputGetter); + } else { + userInputGetter.run(); + } + + // Return loaded file data. + + File file = userInputGetter.getFile(); + AlgorithmFactory validator = userInputGetter.getValidator(); + + if ((file == null) || (validator == null)) { + String logMessage = "File loading canceled"; + this.logger.log(LogService.LOG_WARNING, logMessage); + + return null; + } else { + return FileValidator.validateFile(file, validator, this.ciShellContext, this.logger); + } + } + + public ProgressMonitor getProgressMonitor() { + return this.progressMonitor; + } + + public void setProgressMonitor(ProgressMonitor progressMonitor) { + this.progressMonitor = progressMonitor; + } + + private static String determineDefaultLoadDirectory(Dictionary<String, Object> preferences) { + return StringUtilities.emptyStringIfNull(preferences.get(LOAD_DIRECTORY_PREFERENCE_KEY)); + } + + private static IWorkbenchWindow getFirstWorkbenchWindow() throws AlgorithmExecutionException { + final IWorkbenchWindow[] windows = PlatformUI.getWorkbench().getWorkbenchWindows(); + + if (windows.length == 0) { + throw new AlgorithmExecutionException( + "Cannot obtain workbench window needed to open dialog."); + } else { + return windows[0]; + } + } +} \ No newline at end of file Property changes on: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileLoadAlgorithm.java ___________________________________________________________________ Added: svn:mergeinfo + Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileLoadFactory.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileLoadFactory.java 2010-05-28 18:18:24 UTC (rev 1067) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileLoadFactory.java 2010-05-28 18:53:00 UTC (rev 1068) @@ -12,19 +12,17 @@ import org.osgi.service.cm.ManagedService; import org.osgi.service.component.ComponentContext; -/* - * @author Weixia(Bonnie) Huang (hu...@in...) - */ public class FileLoadFactory implements AlgorithmFactory, ManagedService { - private BundleContext bcontext; + private BundleContext bundleContext; private Dictionary properties = new Hashtable(); - protected void activate(ComponentContext ctxt) { - bcontext = ctxt.getBundleContext(); + protected void activate(ComponentContext componentContext) { + bundleContext = componentContext.getBundleContext(); } - public Algorithm createAlgorithm(Data[] data, Dictionary parameters, CIShellContext context) { - return new FileLoad(context, bcontext, properties); + public Algorithm createAlgorithm( + Data[] data, Dictionary parameters, CIShellContext ciShellContext) { + return new FileLoadAlgorithm(ciShellContext, this.bundleContext, this.properties); } public void updated(Dictionary properties) throws ConfigurationException { @@ -35,18 +33,18 @@ } // private void printPreferences(Dictionary properties) { -// System.out.println(" Preferences are as follows for File Load:"); -// if (properties == null) { -// System.out.println(" Dictionary is null!"); -// } else { -// Enumeration propertiesKeys = properties.keys(); +// System.out.println(" Preferences are as follows for File Load:"); +// if (properties == null) { +// System.out.println(" Dictionary is null!"); +// } else { +// Enumeration propertiesKeys = properties.keys(); +// +// while (propertiesKeys.hasMoreElements()) { +// String propertiesKey = (String) propertiesKeys.nextElement(); // -// while (propertiesKeys.hasMoreElements()) { -// String propertiesKey = (String) propertiesKeys.nextElement(); -// -// Object propertiesValue = properties.get(propertiesKey); -// System.out.println(" " + propertiesKey + ":" + propertiesValue); -// } +// Object propertiesValue = properties.get(propertiesKey); +// System.out.println(" " + propertiesKey + ":" + propertiesValue); // } // } +// } } \ No newline at end of file Added: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileLoadUserInputRunnable.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileLoadUserInputRunnable.java (rev 0) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileLoadUserInputRunnable.java 2010-05-28 18:53:00 UTC (rev 1068) @@ -0,0 +1,147 @@ +package org.cishell.reference.gui.persistence.load; + +import java.io.File; + +import org.cishell.framework.CIShellContext; +import org.cishell.framework.algorithm.AlgorithmFactory; +import org.cishell.utilities.FileUtilities; +import org.eclipse.swt.SWT; +import org.eclipse.swt.widgets.FileDialog; +import org.eclipse.ui.IWorkbenchWindow; +import org.osgi.framework.BundleContext; +import org.osgi.framework.InvalidSyntaxException; +import org.osgi.framework.ServiceReference; + +public final class FileLoadUserInputRunnable implements Runnable { + private IWorkbenchWindow window; + private BundleContext bundleContext; + private CIShellContext ciShellContext; + private File file; + private AlgorithmFactory validator; + + public FileLoadUserInputRunnable( + IWorkbenchWindow window, BundleContext bundleContext, CIShellContext ciShellContext) { + this.window = window; + this.bundleContext = bundleContext; + this.ciShellContext = ciShellContext; + } + + public File getFile() { + return this.file; + } + + public AlgorithmFactory getValidator() { + return this.validator; + } + + public void run() { + this.file = getFileFromUser(); + + if (file == null) { + return; + } else if (this.file.isDirectory()) { + FileLoadAlgorithm.defaultLoadDirectory = this.file.getAbsolutePath(); + } else { + FileLoadAlgorithm.defaultLoadDirectory = this.file.getParentFile().getAbsolutePath(); + } + + // Validate the loaded file, "casting" it to a certain MIME type. + + // Extract the file's file extension. + + String fileExtension = + FileUtilities.getFileExtension(this.file).toLowerCase().substring(1); + + // TODO split here? + + // Get all the validators which support this file extension... + + ServiceReference[] supportingValidators = getSupportingValidators(fileExtension); + + // If there are no supporting validators... + if (supportingValidators.length == 0) { + // Let the user choose from all the validators available. + + ServiceReference[] allValidators = getAllValidators(); + + FileFormatSelector validatorSelector = new FileFormatSelector( + "Load", window.getShell(), this.bundleContext, allValidators); + validatorSelector.open(); + this.validator = validatorSelector.getValidator(); + } else if (supportingValidators.length == 1) { + ServiceReference onlyPossibleValidator = supportingValidators[0]; + this.validator = + (AlgorithmFactory)this.bundleContext.getService(onlyPossibleValidator); + } + + if (supportingValidators.length > 1) { + FileFormatSelector validatorSelector = new FileFormatSelector( + "Load", window.getShell(), this.bundleContext, supportingValidators); + validatorSelector.open(); + this.validator = validatorSelector.getValidator(); + } + } + + private File getFileFromUser() { + FileDialog fileDialog = createFileDialog(); + String fileName = fileDialog.open(); + + if (fileName == null) { + return null; + } else { + return new File(fileName); + } + } + + private FileDialog createFileDialog() { + File currentDirectory = new File(FileLoadAlgorithm.defaultLoadDirectory); + String absolutePath = currentDirectory.getAbsolutePath(); + FileDialog fileDialog = new FileDialog(this.window.getShell(), SWT.OPEN); + fileDialog.setFilterPath(absolutePath); + fileDialog.setText("Select a File"); + + return fileDialog; + } + + private ServiceReference[] getSupportingValidators(String fileExtension) { + try { + String validatorsQuery = + "(& (type=validator)" + + "(|" + + "(in_data=file-ext:" + fileExtension + ")" + + "(also_validates=" + fileExtension + ")" + + "))"; + + ServiceReference[] supportingValidators = this.bundleContext.getAllServiceReferences( + AlgorithmFactory.class.getName(), validatorsQuery); + + if (supportingValidators == null) { + return new ServiceReference[0]; + } else { + return supportingValidators; + } + } catch (InvalidSyntaxException e) { + e.printStackTrace(); + + return new ServiceReference[]{}; + } + } + + private ServiceReference[] getAllValidators() { + try { + String validatorsQuery = "(&(type=validator)(in_data=file-ext:*))"; + ServiceReference[] allValidators = this.bundleContext.getAllServiceReferences( + AlgorithmFactory.class.getName(), validatorsQuery); + + if (allValidators == null) { + return new ServiceReference[0]; + } else { + return allValidators; + } + } catch (InvalidSyntaxException e) { + e.printStackTrace(); + + return new ServiceReference[0]; + } + } +} \ No newline at end of file Added: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileValidator.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileValidator.java (rev 0) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileValidator.java 2010-05-28 18:53:00 UTC (rev 1068) @@ -0,0 +1,36 @@ +package org.cishell.reference.gui.persistence.load; + +import java.io.File; + +import org.cishell.framework.CIShellContext; +import org.cishell.framework.algorithm.AlgorithmExecutionException; +import org.cishell.framework.algorithm.AlgorithmFactory; +import org.cishell.framework.data.BasicData; +import org.cishell.framework.data.Data; +import org.osgi.service.log.LogService; + +public final class FileValidator { + public static Data[] validateFile( + File file, + AlgorithmFactory validator, + CIShellContext ciShellContext, + LogService logger) throws AlgorithmExecutionException { + Data[] validationData = + new Data[] { new BasicData(file.getPath(), String.class.getName()) }; + Data[] validatedData = validator.createAlgorithm( + validationData, null, ciShellContext).execute(); + + if (validatedData != null) { + logger.log(LogService.LOG_INFO, "Loaded: " + file.getPath()); + } + + return validatedData; +// } catch (AlgorithmExecutionException e) { +// String logMessage = +// "An error occurred while attempting to load your file " + +// "with the format you chose."; +// this.logger.log(LogService.LOG_ERROR, logMessage, e); +// this.thrownException = e; +// } + } +} \ No newline at end of file Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/viewwith/FileViewWithFactory.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/viewwith/FileViewWithFactory.java 2010-05-28 18:18:24 UTC (rev 1067) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/viewwith/FileViewWithFactory.java 2010-05-28 18:53:00 UTC (rev 1068) @@ -69,13 +69,8 @@ programCsv = Program.findProgram("csv"); }}); - - //TODO: what the hell? - System.err.println(definition.getID()); String[] defValStringArray = null; //doesn't actually work yet... - //String[] myOptionLabels = new String[] {programTxt.getName(),programDoc.getName(),programHtml.getName()}; - //String[] myOptionValues = new String[] {"txt","doc","html"}; int possiblePrograms = 0; int counter = 0; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |