From: <mwl...@us...> - 2008-08-15 19:01:00
|
Revision: 799 http://cishell.svn.sourceforge.net/cishell/?rev=799&view=rev Author: mwlinnem Date: 2008-08-15 19:00:54 +0000 (Fri, 15 Aug 2008) Log Message: ----------- Files opened with "View..." will now have a name based on their label in the DataManager, and should usually have the correct extension (.nwb, or .net, or whatever), instead of always being .txt Modified Paths: -------------- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/FileSaver.java trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/FileView.java trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/ViewDataChooser.java Added Paths: ----------- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/FileUtil.java Added: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/FileUtil.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/FileUtil.java (rev 0) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/FileUtil.java 2008-08-15 19:00:54 UTC (rev 799) @@ -0,0 +1,99 @@ +package org.cishell.reference.gui.persistence; + +import java.io.File; +import java.io.IOException; + +import org.osgi.service.log.LogService; + +public class FileUtil { + + private static int uniqueIntForTempFile = 1; + + public static File getTempFile(String fileName, String extension, LogService logger){ + File tempFile; + + if (fileName == null || fileName.equals("")) { + fileName = "unknown"; + } + + if (extension == null || extension.equals("")) { + extension = ".txt"; + } + + if (!extension.startsWith(".")) { + extension = extension + "."; + } + + String tempPath = System.getProperty("java.io.tmpdir"); + File tempDir = new File(tempPath+File.separator+"nwb"); + if(!tempDir.exists()) + tempDir.mkdir(); + try{ + tempFile = File.createTempFile(fileName, extension, tempDir); + + }catch (IOException e1){ + //failed with given file name and extension. Let's use a standard one. + logger.log(LogService.LOG_WARNING, "Failed to create temp file with provided name and extension '" + fileName + extension + "'. Trying a generic name and extension instead.", e1); + try { + tempFile = File.createTempFile("unknown", ".txt", tempDir); + } catch (IOException e2) { + //looks like it doesn't even like that. We'll have to just make a file directly. + tempFile = new File (tempPath+File.separator+"nwb"+File.separator+"unknown" + uniqueIntForTempFile + ".txt"); + uniqueIntForTempFile++; + + logger.log(LogService.LOG_ERROR, "Failed to create temp file twice..."); + logger.log(LogService.LOG_ERROR, "First Try... \r\n " + e1.toString()); + logger.log(LogService.LOG_ERROR, "Second Try... \r\n " + e2.toString()); + } + } + return tempFile; + } + + public static String extractExtension(String format) { + String extension = ""; + //TODO: We should really have explicit piece of metadata that says what the extension is, + //TODO: as this method is not guaranteed to yield the correct extension + if (format.startsWith("file:text/")) { + extension = "." + format.substring("file:text/".length()); + } else if (format.startsWith("file-ext:")) { + extension = "." + format.substring("file-ext:".length()); + } + + extension = extension.replace('+', '.'); + + return extension; + } + + public static String extractFileName(String fileLabel) { + + //index variables will be -1 if index is not found. + int descriptionEndIndex = fileLabel.lastIndexOf(":"); + int filePathEndIndex = fileLabel.lastIndexOf(File.separator); + + //doesn't matter if either variable is -1, since startIndex will be + //zero and none of the string will be cut off the front. + int startIndex = Math.max(descriptionEndIndex, filePathEndIndex) + 1; + + String fileNameWithExtension = fileLabel.substring(startIndex); + + + //find the first character of the file name extension. + int extensionBeginIndex = fileNameWithExtension.lastIndexOf("."); + + int endIndex; + + if (extensionBeginIndex != -1) { + //we found a period in the file name. + endIndex = extensionBeginIndex; //cut off everything after + //first period. + } else { + //we didn't find an extension on the file name. + endIndex = fileNameWithExtension.length(); // don't cut any off the end. + } + + String fileNameWithoutExtension = fileNameWithExtension.substring(0, endIndex); + + String fileName = fileNameWithoutExtension; + return fileName; + } +} Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/FileSaver.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/FileSaver.java 2008-08-13 17:14:47 UTC (rev 798) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/FileSaver.java 2008-08-15 19:00:54 UTC (rev 799) @@ -13,6 +13,7 @@ import org.cishell.framework.algorithm.AlgorithmProperty; import org.cishell.framework.data.Data; import org.cishell.framework.data.DataProperty; +import org.cishell.reference.gui.persistence.FileUtil; import org.cishell.service.conversion.ConversionException; import org.cishell.service.conversion.Converter; import org.cishell.service.guibuilder.GUIBuilderService; @@ -112,7 +113,7 @@ dialog.setText("Choose File"); String fileLabel = (String)data.getMetadata().get(DataProperty.LABEL); - String suggestedFileName = getFileName(fileLabel); + String suggestedFileName = FileUtil.extractFileName(fileLabel); dialog.setFileName(suggestedFileName + "." + ext); // if (fileLabel == null) { @@ -185,36 +186,5 @@ } } - private String getFileName(String fileLabel) { - - //index variables will be -1 if index is not found. - int descriptionEndIndex = fileLabel.lastIndexOf(":"); - int filePathEndIndex = fileLabel.lastIndexOf(File.separator); - - //doesn't matter if either variable is -1, since startIndex will be - //zero and none of the string will be cut off the front. - int startIndex = Math.max(descriptionEndIndex, filePathEndIndex) + 1; - - String fileNameWithExtension = fileLabel.substring(startIndex); - - - //find the first character of the file name extension. - int extensionBeginIndex = fileNameWithExtension.lastIndexOf("."); - - int endIndex; - - if (extensionBeginIndex != -1) { - //we found a period in the file name. - endIndex = extensionBeginIndex; //cut off everything after - //first period. - } else { - //we didn't find an extension on the file name. - endIndex = fileNameWithExtension.length(); // don't cut any off the end. - } - - String fileNameWithoutExtension = fileNameWithExtension.substring(0, endIndex); - - String fileName = fileNameWithoutExtension; - return fileName; - } + } \ No newline at end of file Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/FileView.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/FileView.java 2008-08-13 17:14:47 UTC (rev 798) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/FileView.java 2008-08-15 19:00:54 UTC (rev 799) @@ -11,10 +11,11 @@ import org.cishell.framework.algorithm.Algorithm; import org.cishell.framework.algorithm.AlgorithmExecutionException; import org.cishell.framework.data.Data; +import org.cishell.framework.data.DataProperty; +import org.cishell.reference.gui.persistence.FileUtil; import org.cishell.service.conversion.ConversionException; import org.cishell.service.conversion.Converter; import org.cishell.service.conversion.DataConversionService; -import org.cishell.service.guibuilder.GUIBuilderService; import org.eclipse.swt.program.Program; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; @@ -45,87 +46,55 @@ logger = (LogService)context.getService(LogService.class.getName()); } - - public File getTempFile(){ - File tempFile; - - String tempPath = System.getProperty("java.io.tmpdir"); - File tempDir = new File(tempPath+File.separator+"temp"); - if(!tempDir.exists()) - tempDir.mkdir(); - try{ - tempFile = File.createTempFile("xxx-Session-", ".txt", tempDir); - - }catch (IOException e){ - logger.log(LogService.LOG_ERROR, e.toString()); - tempFile = new File (tempPath+File.separator+"temp"+File.separator+"temp.txt"); - } - return tempFile; - } - - public File getTempFileCSV(){ //TC181 - File tempFile; - - String tempPath = System.getProperty("java.io.tmpdir"); - File tempDir = new File(tempPath+File.separator+"temp"); - if(!tempDir.exists()) - tempDir.mkdir(); - try{ - tempFile = File.createTempFile("xxx-Session-", ".csv", tempDir); - - }catch (IOException e){ - logger.log(LogService.LOG_ERROR, e.toString()); - tempFile = new File (tempPath+File.separator+"temp"+File.separator+"temp.csv"); - - } - return tempFile; - } - + //show the contents of a file to the user public Data[] execute() throws AlgorithmExecutionException { try { boolean lastSaveSuccessful = false; - boolean isCSVFile = false;//TC181 + boolean isCSVFile = false; String format; - Display display; - IWorkbenchWindow[] windows; - final Shell parentShell; + //tempFile = getTempFile(); TC181 - windows = PlatformUI.getWorkbench().getWorkbenchWindows(); - if (windows.length == 0){ - throw new AlgorithmExecutionException("Cannot get workbench window."); - } - parentShell = windows[0].getShell(); - display = PlatformUI.getWorkbench().getDisplay(); - //tempFile = getTempFile(); TC181 + //for each data item we want to view... for (int i = 0; i < data.length; i++){ Object theData = data[i].getData(); format = data[i].getFormat(); + String label = (String) data[i].getMetadata().get(DataProperty.LABEL); + //if it is a text file... if (theData instanceof File || format.startsWith("file:text/") || format.startsWith("file-ext:")){ + //if it is a csv text file... if (format.startsWith("file:text/csv") || format.startsWith("file-ext:csv")) { + //prepare to open it like a csv file tempFile = getTempFileCSV(); isCSVFile = true; } - else - { - tempFile = getTempFile(); + else //it is just a regular text file + { + //prepare to open it like a normal text file + String fileName = FileUtil.extractFileName(label); + String extension = FileUtil.extractExtension(format); + tempFile = FileUtil.getTempFile(fileName, extension, logger); } + + //copy out data into the temp file we just created. copy((File)data[i].getData(), tempFile); lastSaveSuccessful = true; - }else{ + }else {//the data item is in an in-memory format, and must be converted to a file format before the user can see it + final Converter[] convertersCSV = conversionManager.findConverters(data[i], "file-ext:csv"); - //logger.log(LogService.LOG_ERROR, "convertersCSV's length = " + convertersCSV.length); + + //if the data item can be converted to a csv file ... do it. if (convertersCSV.length == 1) { Data newDataCSV = convertersCSV[0].convert(data[i]); @@ -146,41 +115,69 @@ isCSVFile = true; copy((File)newDataCSV.getData(), tempFile); lastSaveSuccessful = true; - } - else{ + } else { //it cannot be converted to a .csv + + //try to convert it to any other file format + final Converter[] converters = conversionManager.findConverters(data[i], "file-ext:*"); + //if it can't be converted to any file format... if (converters.length < 1) { + //throw an error throw new AlgorithmExecutionException("No valid converters for data type: " + data[i].getData().getClass().getName() + ". Please install a plugin that will save the data type to a file"); } - else if (converters.length == 1){ - //If length=1, use the unique path to save it directly - //and bring the text editor. - Data newData = converters[0].convert(data[i]); - tempFile = getTempFile(); + else if (converters.length == 1){ //if there is only file format it can be converted to + //go ahead and convert the data item to that format + Data newData = converters[0].convert(data[i]); + + String fileName = FileUtil.extractFileName(label); + String extension = FileUtil.extractExtension(newData.getFormat()); + tempFile = FileUtil.getTempFile(fileName, extension, logger); copy((File)newData.getData(), tempFile); lastSaveSuccessful = true; } - else { + else { //there is more than one format that the data item could be converted to + + //let the user choose + + //(get some eclipse UI stuff that we need to open the data viewer) + + Display display; + IWorkbenchWindow[] windows; + final Shell parentShell; + + windows = PlatformUI.getWorkbench().getWorkbenchWindows(); + if (windows.length == 0){ + throw new AlgorithmExecutionException("Cannot get workbench window."); + } + parentShell = windows[0].getShell(); + display = PlatformUI.getWorkbench().getDisplay(); + + //(open the data viewer, which lets the user choose which format they want to see the data item in.) + if (!parentShell.isDisposed()) { DataViewer dataViewer = new DataViewer(parentShell, data[i], converters); display.syncExec(dataViewer); lastSaveSuccessful = dataViewer.isSaved; - tempFile = dataViewer.theFile; + tempFile = dataViewer.outputFile; } } } } + + //if it's a CSV file if (isCSVFile){//TC181 + //prepare to open the file with the default csv program Display.getDefault().syncExec(new Runnable() { public void run() { program = Program.findProgram("csv"); }}); - }else - { + }else + {//it's any other file + //prepare to open it with the standard text editor. Display.getDefault().syncExec(new Runnable() { public void run() { program = Program.findProgram("txt"); @@ -201,14 +198,18 @@ } */ + + //if we can't find any program to open the file... if (program == null) { + //throw an error throw new AlgorithmExecutionException( "No valid text viewer for the .txt file. " + "The file is located at: "+tempFile.getAbsolutePath() + ". Unable to open default text viewer. File is located at: "+ tempFile.getAbsolutePath()); } - else { + else {//we found a program to open the file + //open it, for real. if (lastSaveSuccessful == true) { Display.getDefault().syncExec(new Runnable() { public void run() { @@ -216,9 +217,6 @@ }}); } } - - - } return null; } catch (ConversionException e1) { @@ -228,6 +226,24 @@ } } + public File getTempFileCSV(){ //TC181 + File tempFile; + + String tempPath = System.getProperty("java.io.tmpdir"); + File tempDir = new File(tempPath+File.separator+"temp"); + if(!tempDir.exists()) + tempDir.mkdir(); + try{ + tempFile = File.createTempFile("xxx-Session-", ".csv", tempDir); + + }catch (IOException e){ + logger.log(LogService.LOG_ERROR, e.toString()); + tempFile = new File (tempPath+File.separator+"temp"+File.separator+"temp.csv"); + + } + return tempFile; + } + public static boolean copy(File in, File out) throws AlgorithmExecutionException{ try { FileInputStream fis = new FileInputStream(in); @@ -250,8 +266,8 @@ final class DataViewer implements Runnable { Shell shell; boolean isSaved; + File outputFile; Data theData; - File theFile = getTempFile(); Converter[] theConverters; DataViewer (Shell parentShell, Data data, Converter[] converters){ @@ -262,10 +278,11 @@ public void run() { // lots of persisters found, return the chooser - ViewDataChooser vdc = new ViewDataChooser("View", theFile, shell, - theData, theConverters, context); + ViewDataChooser vdc = new ViewDataChooser("View", shell, + theData, theConverters, context, logger); vdc.open(); isSaved = vdc.isSaved(); + outputFile = vdc.outputFile; } } Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/ViewDataChooser.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/ViewDataChooser.java 2008-08-13 17:14:47 UTC (rev 798) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/ViewDataChooser.java 2008-08-15 19:00:54 UTC (rev 799) @@ -4,25 +4,29 @@ import org.cishell.framework.CIShellContext; import org.cishell.framework.data.Data; +import org.cishell.framework.data.DataProperty; +import org.cishell.reference.gui.persistence.FileUtil; import org.cishell.reference.gui.persistence.save.SaveDataChooser; import org.cishell.service.conversion.Converter; import org.eclipse.swt.widgets.Shell; +import org.osgi.service.log.LogService; /* * @author Weixia(Bonnie) Huang (hu...@in...) * */ public class ViewDataChooser extends SaveDataChooser { - private File tempFile; boolean isSaved = false; + LogService logger; Data theData; + File outputFile; - public ViewDataChooser(String title, File tempFile, Shell parent, - Data data, Converter[] converters, CIShellContext context){ + public ViewDataChooser(String title, Shell parent, + Data data, Converter[] converters, CIShellContext context, LogService logger){ super (data, parent, converters, title, context); - this.tempFile = tempFile; this.theData = data; + this.logger = logger; } protected void selectionMade(int selectedIndex){ @@ -30,7 +34,12 @@ getShell().setVisible(false); final Converter converter = converterArray[selectedIndex]; Data newData = converter.convert(theData); + String label = (String) newData.getMetadata().get(DataProperty.LABEL); + String fileName = FileUtil.extractFileName(label); + String extension = FileUtil.extractExtension(newData.getFormat()); + File tempFile = FileUtil.getTempFile(fileName, extension, logger); isSaved = FileView.copy((File)newData.getData(), tempFile); + outputFile = tempFile; close(true); } catch (Exception e) { throw new RuntimeException(e); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pat...@us...> - 2009-11-30 23:33:44
|
Revision: 987 http://cishell.svn.sourceforge.net/cishell/?rev=987&view=rev Author: pataphil Date: 2009-11-30 23:33:35 +0000 (Mon, 30 Nov 2009) Log Message: ----------- * The load file format selection window now selects the first option by default. * The Select buttons in the load and save file format selection windows is now focused by default, so the user can just hit enter to use the default option. * Cleaned up SavedataChooser a bit. * Users can now double-click options in the save file format selection window to choose it (similarly to the load file format selection window in a previous commit.) Modified Paths: -------------- 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/save/FileSaver.java trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/Save.java trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/SaveDataChooser.java trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/SaveFactory.java trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/core/ViewDataChooser.java 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 2009-11-30 22:24:29 UTC (rev 986) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/load/FileFormatSelector.java 2009-11-30 23:33:35 UTC (rev 987) @@ -15,8 +15,8 @@ import org.cishell.framework.data.Data; import org.cishell.reference.gui.common.AbstractDialog; import org.eclipse.swt.SWT; +import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; -import org.eclipse.swt.events.MouseListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.layout.FillLayout; @@ -100,19 +100,14 @@ this.persisterList = new List(persisterGroup, SWT.H_SCROLL |SWT.V_SCROLL | SWT.SINGLE); // initPersisterArray(); - initPersisterList(); - this.persisterList.addMouseListener(new MouseListener() { - public void mouseUp(MouseEvent mouseEvent) { - } - - public void mouseDown(MouseEvent mouseEvent) { - } - + initializePersisterList(); + this.persisterList.addMouseListener(new MouseAdapter() { public void mouseDoubleClick(MouseEvent mouseEvent) { - int index = FileFormatSelector.this.persisterList.getSelectionIndex(); + List list = (List)mouseEvent.getSource(); + int selection = list.getSelectionIndex(); - if (index != -1) { - selectionMade(index); + if (selection != -1) { + selectionMade(selection); } } }); @@ -127,6 +122,8 @@ } } }); + + persisterList.setSelection(0); /* Group detailsGroup = new Group(content, SWT.NONE); // Shall this label be moved out of the code? @@ -144,7 +141,7 @@ return content; } - private void initPersisterList() { + private void initializePersisterList() { for (int ii = 0; ii < this.persisterArray.length; ++ii) { String name = (String)this.persisterArray[ii].getProperty("label"); @@ -230,6 +227,7 @@ } } }); + select.setFocus(); Button cancel = new Button(parent, SWT.NONE); cancel.setText("Cancel"); Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/FileSaver.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/FileSaver.java 2009-11-30 22:24:29 UTC (rev 986) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/FileSaver.java 2009-11-30 23:33:35 UTC (rev 987) @@ -42,7 +42,7 @@ * Initializes services to output messages * * @param parent - * @param context + * @param ciShellContext */ public FileSaver(Shell parent, CIShellContext context){ this.parent = parent; Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/Save.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/Save.java 2009-11-30 22:24:29 UTC (rev 986) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/Save.java 2009-11-30 23:33:35 UTC (rev 987) @@ -37,7 +37,7 @@ * * @param data The data array to persist * @param parameters Parameters for the algorithm - * @param context Provides services to CIShell services + * @param ciShellContext Provides services to CIShell services */ public Save(Data[] data, Dictionary parameters, CIShellContext context) { this.data = data; Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/SaveDataChooser.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/SaveDataChooser.java 2009-11-30 22:24:29 UTC (rev 986) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/SaveDataChooser.java 2009-11-30 23:33:35 UTC (rev 987) @@ -21,6 +21,8 @@ import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; +import org.eclipse.swt.events.MouseAdapter; +import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.graphics.Image; @@ -37,36 +39,39 @@ /** * SaveDataChooser is a simple user interface to allow for selection - * among several Persisters that support the selected model, in the event + * among several persisters that support the selected model, in the event * that more than one is found. - * - * @author Team IVC */ public class SaveDataChooser extends AbstractDialog implements AlgorithmProperty { + public static final Image QUESTION_ICON = + Display.getCurrent().getSystemImage(SWT.ICON_QUESTION); + protected Data data; - protected Converter[] converterArray; - private List converterList; + protected Converter[] converters; + private List converterListComponent; private StyledText detailPane; - //private Shell parent; - CIShellContext context; - public static final Image QUESTION = Display.getCurrent().getSystemImage(SWT.ICON_QUESTION); + CIShellContext ciShellContext; /** * Creates a new SaveChooser object. * * @param data The data object to save * @param parent The parent shell - * @param converterArray The array of converters to persist the data + * @param converters The array of converters to persist the data * @param title Title of the Window * @param brandPluginID The plugin that supplies the branding - * @param context The CIShellContext to retrieve available services + * @param ciShellContext The CIShellContext to retrieve available services */ - public SaveDataChooser(Data data, Shell parent, Converter[] converterArray, - String title, CIShellContext context) { - super(parent, title, QUESTION); + public SaveDataChooser( + Data data, + Shell parent, + Converter[] converters, + String title, + CIShellContext ciShellContext) { + super(parent, title, QUESTION_ICON); this.data = data; - this.converterArray = alphabetizeConverters(filterConverters(converterArray)); - this.context = context; + this.converters = alphabetizeConverters(filterConverters(converters)); + this.ciShellContext = ciShellContext; } /** @@ -74,12 +79,11 @@ * @param parent The parent window * @return The new window containing the chooser */ - private Composite initGUI(Composite parent) { + private Composite initializeGUI(Composite parent) { Composite content = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; content.setLayout(layout); - //parent.setLayout(layout); Group converterGroup = new Group(content, SWT.NONE); converterGroup.setText("Pick the Output Data Type"); @@ -88,18 +92,29 @@ persisterData.widthHint = 200; converterGroup.setLayoutData(persisterData); - converterList = new List(converterGroup, SWT.H_SCROLL | SWT.V_SCROLL | SWT.SINGLE); - initConverterList(); - converterList.addSelectionListener(new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - List list = (List) e.getSource(); - int selection = list.getSelectionIndex(); + converterListComponent = + new List(converterGroup, SWT.H_SCROLL | SWT.V_SCROLL | SWT.SINGLE); + initializeConverterListComponent(); + converterListComponent.addMouseListener(new MouseAdapter() { + public void mouseDoubleClick(MouseEvent mouseEvent) { + List list = (List)mouseEvent.getSource(); + int selection = list.getSelectionIndex(); + + if (selection != -1) { + selectionMade(selection); + } + } + }); + converterListComponent.addSelectionListener(new SelectionAdapter() { + public void widgetSelected(SelectionEvent selectionEvent) { + List list = (List)selectionEvent.getSource(); + int selection = list.getSelectionIndex(); - if (selection != -1) { - updateDetailPane(converterArray[selection]); - } - } - }); + if (selection != -1) { + updateDetailPane(converters[selection]); + } + } + }); Group detailsGroup = new Group(content, SWT.NONE); detailsGroup.setText("Details"); @@ -107,45 +122,47 @@ GridData detailsData = new GridData(GridData.FILL_BOTH); detailsData.widthHint = 200; detailsGroup.setLayoutData(detailsData); - - detailPane = initDetailPane(detailsGroup); - //select the first item by default - converterList.setSelection(0); - updateDetailPane(converterArray[0]); - + detailPane = initializeDetailPane(detailsGroup); + + // Select the first item by default. + converterListComponent.setSelection(0); + updateDetailPane(converters[0]); + return content; } /** * Initialize the Listbox of Persisters using the stored Persister array */ - private void initConverterList() { - for (int i = 0; i < converterArray.length; ++i) { - if (converterArray[i] != null) { - Dictionary dict = converterArray[i].getProperties(); + private void initializeConverterListComponent() { + for (int ii = 0; ii < converters.length; ii++) { + if (converters[ii] != null) { + Dictionary converterProperties = converters[ii].getProperties(); - // get the name of the persister from the property map + // Get the name of the persister from the property map. String outData = null; - ServiceReference[] refs = converterArray[i].getConverterChain(); - if (refs != null && refs.length > 0) { - outData = (String) refs[refs.length-1].getProperty( - AlgorithmProperty.LABEL); + ServiceReference[] serviceReferences = converters[ii].getConverterChain(); + + if ((serviceReferences != null) && (serviceReferences.length > 0)) { + outData = (String)serviceReferences[serviceReferences.length - 1].getProperty( + AlgorithmProperty.LABEL); } - + if (outData == null) { - outData = (String) dict.get(AlgorithmProperty.LABEL); + outData = (String)converterProperties.get(AlgorithmProperty.LABEL); } - // if someone was sloppy enough to not provide a name, then use - // the - // name of the class instead. + /* + * If someone was sloppy enough to not provide a name, then use the name of the + * class instead. + */ if ((outData == null) || (outData.length() == 0)) { - outData = converterArray[i].getClass().getName(); + outData = converters[ii].getClass().getName(); } - converterList.add(outData); + converterListComponent.add(outData); } } } @@ -158,7 +175,7 @@ * The detail pane to init * @return A style of the text */ - private StyledText initDetailPane(Group detailsGroup) { + private StyledText initializeDetailPane(Group detailsGroup) { StyledText detailPane = new StyledText(detailsGroup, SWT.H_SCROLL | SWT.V_SCROLL); detailPane.setEditable(false); detailPane.getCaret().setVisible(false); @@ -172,14 +189,14 @@ * @param converter A converter that contains the properties for the detail pane */ private void updateDetailPane(Converter converter) { - Dictionary dict = converter.getProperties(); - Enumeration keysEnum = dict.keys(); + Dictionary converterProperties = converter.getProperties(); + Enumeration converterPropertiesKeys = converterProperties.keys(); detailPane.setText(""); - while (keysEnum.hasMoreElements()) { - Object key = keysEnum.nextElement(); - Object val = dict.get(key); + while (converterPropertiesKeys.hasMoreElements()) { + Object key = converterPropertiesKeys.nextElement(); + Object value = converterProperties.get(key); StyleRange styleRange = new StyleRange(); styleRange.start = detailPane.getText().length(); @@ -188,7 +205,7 @@ styleRange.fontStyle = SWT.BOLD; detailPane.setStyleRange(styleRange); - detailPane.append(val + "\n"); + detailPane.append(value + "\n"); } } @@ -209,26 +226,23 @@ private Converter[] filterConverters(Converter[] allConverters) { Map lastInDataToConverter = new HashMap(); - for (int i = 0; i < allConverters.length; i++) { - Converter converter = allConverters[i]; - - - - //for .xml files, to uniquely identify it - //we need to know what kind of xml it was - //so we look at the in_data type of the - //last converter - String lastInData = getLastConverterInData(converter); - - //if we already have a converter with this out data type... - if (lastInDataToConverter.containsKey(lastInData)) { - Converter alreadyStoredConverter = (Converter) lastInDataToConverter.get(lastInData); - - Converter chosenConverter = returnPreferredConverter(converter,alreadyStoredConverter); - - lastInDataToConverter.put(lastInData, chosenConverter); + for (int ii = 0; ii < allConverters.length; ii++) { + Converter converter = allConverters[ii]; + + /* + * To uniquely identify an XML file, we need to know what kind of XML it was so we look + * at the input data type of the last converter. + */ + String lastInputData = getLastConverterInData(converter); + + if (lastInDataToConverter.containsKey(lastInputData)) { + Converter alreadyStoredConverter = + (Converter)lastInDataToConverter.get(lastInputData); + Converter chosenConverter = + returnPreferredConverter(converter, alreadyStoredConverter); + lastInDataToConverter.put(lastInputData, chosenConverter); } else { - lastInDataToConverter.put(lastInData, converter); + lastInDataToConverter.put(lastInputData, converter); } } @@ -237,11 +251,11 @@ private String getLastConverterInData(Converter converter) { ServiceReference[] convChain = converter.getConverterChain(); + if (convChain.length >= 1) { - ServiceReference lastConv = convChain[convChain.length - 1]; - - String lastInData = (String) lastConv.getProperty("in_data"); - + ServiceReference lastConverter = convChain[convChain.length - 1]; + String lastInData = (String) lastConverter.getProperty("in_data"); + return lastInData; } else { return ""; @@ -251,87 +265,88 @@ /** * Returns whichever converter is better to show to the user in the chooser, * based on lossiness, and length of converter chain - * @param c1 A converter with the same out_data type as the other - * @param c2 A converter with the same out_data type as the other + * @param converter1 A converter with the same out_data type as the other + * @param converter2 A converter with the same out_data type as the other * @return The preferred converter of the two */ - private Converter returnPreferredConverter(Converter c1, Converter c2) { - Dictionary c1Dict = c1.getProperties(); - String c1Lossiness = (String) c1Dict.get(CONVERSION); - int c1Quality = determineQuality(c1Lossiness); + private Converter returnPreferredConverter(Converter converter1, Converter converter2) { + Dictionary converter1Properties = converter1.getProperties(); + String converter1Lossiness = (String)converter1Properties.get(CONVERSION); + int converter1Quality = determineQuality(converter1Lossiness); + + Dictionary converter2Properties = converter2.getProperties(); + String converter2Lossiness = (String)converter2Properties.get(CONVERSION); + int converter2Quality = determineQuality(converter2Lossiness); - - - Dictionary c2Dict = c2.getProperties(); - String c2Lossiness = (String) c2Dict.get(CONVERSION); - int c2Quality = determineQuality(c2Lossiness); - - if (c1Quality > c2Quality) { - return c1; - } else if (c2Quality > c1Quality) { - return c2; + if (converter1Quality > converter2Quality) { + return converter1; + } else if (converter2Quality > converter1Quality) { + return converter2; } else { - //they are tied. Look at converter chain length + // They are tied. Look at converter chain length. - int c1Length = c1.getConverterChain().length; - int c2Length = c2.getConverterChain().length; - //return the shortest - if (c1Length > c2Length) { - return c2; - } else if (c2Length > c1Length) { - return c1; + int converter1Length = converter1.getConverterChain().length; + int converter2Length = converter2.getConverterChain().length; + + if (converter1Length > converter2Length) { + return converter2; + } else if (converter2Length > converter1Length) { + return converter1; } else { - //both have the same lossiness and same length - //arbitrary pick the first - return c1; + /* + * Both have the same lossiness and same length. + * Arbitrary pick the first. + */ + return converter1; } } } - + private int determineQuality(String lossiness) { if (lossiness == LOSSY) { return 0; } else if (lossiness == null) { return 1; - } else { //lossiness == LOSSLESS + // Lossiness == LOSSLESS. + } else { return 2; } } - - private Converter[] alphabetizeConverters(Converter[] cs) { - Arrays.sort(cs, new CompareAlphabetically()); - return cs; + + private Converter[] alphabetizeConverters(Converter[] converters) { + Arrays.sort(converters, new CompareAlphabetically()); + + return converters; } /** * When a Persister is chosen to Persist this model, this method handles the job * of opening the FileSaver and saving the model. - * @param selectedIndex The chosen converter + * @param selectedIndex The chosen converter. */ protected void selectionMade(int selectedIndex) { try { getShell().setVisible(false); - final Converter converter = converterArray[selectedIndex]; - final FileSaver saver = new FileSaver(getShell(), context); + final Converter converter = converters[selectedIndex]; + final FileSaver saver = new FileSaver(getShell(), ciShellContext); close(saver.save(converter, data)); - } catch (Exception e) { - throw new RuntimeException(e); + } catch (Exception exception) { + throw new RuntimeException(exception); } } /** - * Create the buttons for either cancelling or continuing with - * the save + * Create the buttons for either cancelling or continuing with the save. * - * @param parent The GUI to place the buttons + * @param parent The GUI to place the buttons. */ public void createDialogButtons(Composite parent) { Button select = new Button(parent, SWT.PUSH); select.setText("Select"); select.addSelectionListener( new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { - int index = converterList.getSelectionIndex(); + public void widgetSelected(SelectionEvent selectionEvent) { + int index = converterListComponent.getSelectionIndex(); if (index != -1) { selectionMade(index); @@ -339,12 +354,13 @@ } } ); + select.setFocus(); Button cancel = new Button(parent, SWT.NONE); cancel.setText("Cancel"); cancel.addSelectionListener( new SelectionAdapter() { - public void widgetSelected(SelectionEvent e) { + public void widgetSelected(SelectionEvent selectionEvent) { close(false); } } @@ -352,55 +368,53 @@ } /** - * Checks for the number of file savers. If there is one - * converter then it will save directly, otherwise initialize the chooser. + * Checks for the number of file savers. If there is one converter then it will save directly, + * otherwise initialize the chooser. * * @param parent The parent GUI for new dialog windows. */ public Composite createContent(Composite parent) { - if (converterArray.length == 1) { - final FileSaver saver = new FileSaver((Shell) parent, context); - close(saver.save(converterArray[0], data)); + if (converters.length == 1) { + final FileSaver saver = new FileSaver((Shell) parent, ciShellContext); + close(saver.save(converters[0], data)); + return parent; } else { - return initGUI(parent); + return initializeGUI(parent); } } private class CompareAlphabetically implements Comparator { - public int compare(Object o1, Object o2) { - if (o1 instanceof Converter && o2 instanceof Converter) { - Converter c1 = (Converter) o1; - String c1Label = getLabel(c1); + public int compare(Object object1, Object object2) { + if ((object1 instanceof Converter) && (object2 instanceof Converter)) { + Converter converter1 = (Converter)object1; + String converter1Label = getLabel(converter1); - Converter c2 = (Converter) o2; - String c2Label = getLabel(c2); + Converter converter2 = (Converter)object2; + String converter2Label = getLabel(converter2); - if (c1Label != null && c2Label != null) { - return c1Label.compareTo(c2Label); - } else if (c1Label == null) { - //c1 > c2 + if ((converter1Label != null) && (converter2Label != null)) { + return converter1Label.compareTo(converter2Label); + } else if (converter1Label == null) { return 1; - } else if (c2Label == null) { - //c1 < c2 + } else if (converter2Label == null) { return -1; } else { - //c1 == c2 return 0; } } else { - throw new IllegalArgumentException("Can only " + - "compare Converters"); + throw new IllegalArgumentException("Can only compare Converters"); } } - - private String getLabel(Converter c) { - String label = ""; - ServiceReference[] refs = c.getConverterChain(); - if (refs != null && refs.length > 0) { - label = (String) refs[refs.length-1].getProperty( - AlgorithmProperty.LABEL); + + private String getLabel(Converter converter) { + String label = ""; + ServiceReference[] serviceReferences = converter.getConverterChain(); + + if ((serviceReferences != null) && (serviceReferences.length > 0)) { + label = (String)serviceReferences[serviceReferences.length - 1].getProperty( + AlgorithmProperty.LABEL); } return label; Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/SaveFactory.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/SaveFactory.java 2009-11-30 22:24:29 UTC (rev 986) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/SaveFactory.java 2009-11-30 23:33:35 UTC (rev 987) @@ -20,8 +20,8 @@ private CIShellContext ciShellContext; /** - * Create a local CIShell context - * @param componentContext The current CIShell context + * Create a local CIShell ciShellContext + * @param componentContext The current CIShell ciShellContext */ protected void activate(ComponentContext componentContext) { ciShellContext = Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/core/ViewDataChooser.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/core/ViewDataChooser.java 2009-11-30 22:24:29 UTC (rev 986) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/core/ViewDataChooser.java 2009-11-30 23:33:35 UTC (rev 987) @@ -21,7 +21,7 @@ protected void selectionMade(int selectedIndex) { getShell().setVisible(false); - this.selectedConverter = converterArray[selectedIndex]; + this.selectedConverter = converters[selectedIndex]; close(true); } This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fu...@us...> - 2010-03-26 18:08:41
|
Revision: 1063 http://cishell.svn.sourceforge.net/cishell/?rev=1063&view=rev Author: fugu13 Date: 2010-03-26 18:08:35 +0000 (Fri, 26 Mar 2010) Log Message: ----------- Uses the ones in FileUtilities now. Modified Paths: -------------- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/FileSaver.java trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/core/FileViewer.java Removed Paths: ------------- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/FileUtil.java Deleted: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/FileUtil.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/FileUtil.java 2010-03-26 18:03:14 UTC (rev 1062) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/FileUtil.java 2010-03-26 18:08:35 UTC (rev 1063) @@ -1,138 +0,0 @@ -package org.cishell.reference.gui.persistence; - -import java.io.File; -import java.io.IOException; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; - -import org.osgi.service.log.LogService; - -public class FileUtil { - public static final char FILENAME_CHARACTER_REPLACEMENT = '#'; - - /* Attempt to enumerate characters which cannot be used to name a file. - * For our purposes, this should be as aggressive as sensible. - * This includes all such characters for modern Windows systems, plus %. - * Please add any others. - */ - public static final Collection INVALID_FILENAME_CHARACTERS; - static { - Collection s = new HashSet(); - s.add(new Character('\\')); - s.add(new Character('/')); - s.add(new Character(':')); - s.add(new Character('*')); - s.add(new Character('?')); - s.add(new Character('"')); - s.add(new Character('<')); - s.add(new Character('>')); - s.add(new Character('|')); - s.add(new Character('%')); - INVALID_FILENAME_CHARACTERS = Collections.unmodifiableCollection(s); - } - - private static int uniqueIntForTempFile = 1; - - public static File getTempFile(String fileName, String extension, LogService logger) { - File tempFile; - - if (fileName == null || fileName.equals("")) { - fileName = "unknown"; - } - - if (extension == null || extension.equals("")) { - extension = ".txt"; - } - - if (!extension.startsWith(".")) { - extension = extension + "."; - } - - String tempPath = System.getProperty("java.io.tmpdir"); - File tempDir = new File(tempPath+File.separator+"nwb"); - if(!tempDir.exists()) - tempDir.mkdir(); - try{ - tempFile = File.createTempFile(fileName, extension, tempDir); - - }catch (IOException e1){ - //failed with given file name and extension. Let's use a standard one. - logger.log(LogService.LOG_WARNING, "Failed to create temp file with provided name and extension '" + fileName + extension + "'. Trying a generic name and extension instead.", e1); - try { - tempFile = File.createTempFile("unknown", ".txt", tempDir); - } catch (IOException e2) { - //looks like it doesn't even like that. We'll have to just make a file directly. - tempFile = new File (tempPath+File.separator+"nwb"+File.separator+"unknown" + uniqueIntForTempFile + ".txt"); - uniqueIntForTempFile++; - - logger.log(LogService.LOG_ERROR, "Failed to create temp file twice..."); - logger.log(LogService.LOG_ERROR, "First Try... \r\n " + e1.toString()); - logger.log(LogService.LOG_ERROR, "Second Try... \r\n " + e2.toString()); - } - } - return tempFile; - } - - public static String extractExtension(String format) { - String extension = ""; - /* TODO: We should really have explicit piece of metadata that says what - * the extension is, as this method is not guaranteed to yield the - * correct extension. - */ - if (format.startsWith("file:text/")) { - extension = "." + format.substring("file:text/".length()); - } else if (format.startsWith("file-ext:")) { - extension = "." + format.substring("file-ext:".length()); - } - - extension = extension.replace('+', '.'); - - return extension; - } - - public static String replaceInvalidFilenameCharacters(String filename) { - String cleanedFilename = filename; - - for (Iterator invalidCharacters = INVALID_FILENAME_CHARACTERS.iterator(); - invalidCharacters.hasNext();) { - char invalidCharacter = ((Character) invalidCharacters.next()).charValue(); - - cleanedFilename = - cleanedFilename.replace(invalidCharacter, FILENAME_CHARACTER_REPLACEMENT); - } - - return cleanedFilename; - } - - public static String extractFileName(String fileLabel) { - //index variables will be -1 if index is not found. - int descriptionEndIndex = fileLabel.lastIndexOf(":"); - int filePathEndIndex = fileLabel.lastIndexOf(File.separator); - - //doesn't matter if either variable is -1, since startIndex will be - //zero and none of the string will be cut off the front. - int startIndex = Math.max(descriptionEndIndex, filePathEndIndex) + 1; - - String fileNameWithExtension = fileLabel.substring(startIndex); - - //find the first character of the file name extension. - int extensionBeginIndex = fileNameWithExtension.lastIndexOf("."); - - int endIndex; - - if (extensionBeginIndex != -1) { - //we found a period in the file name. - endIndex = extensionBeginIndex; //cut off everything after - //first period. - } else { - //we didn't find an extension on the file name. - endIndex = fileNameWithExtension.length(); // don't cut any off the end. - } - - String fileNameWithoutExtension = fileNameWithExtension.substring(0, endIndex); - - return fileNameWithoutExtension; - } -} Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/FileSaver.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/FileSaver.java 2010-03-26 18:03:14 UTC (rev 1062) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/FileSaver.java 2010-03-26 18:08:35 UTC (rev 1063) @@ -13,10 +13,10 @@ import org.cishell.framework.algorithm.AlgorithmProperty; import org.cishell.framework.data.Data; import org.cishell.framework.data.DataProperty; -import org.cishell.reference.gui.persistence.FileUtil; import org.cishell.service.conversion.ConversionException; import org.cishell.service.conversion.Converter; import org.cishell.service.guibuilder.GUIBuilderService; +import org.cishell.utilities.FileUtilities; import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.widgets.Shell; @@ -118,9 +118,9 @@ dialog.setText("Choose File"); String fileLabel = (String)data.getMetadata().get(DataProperty.LABEL); - String suggestedFileName = FileUtil.extractFileName(fileLabel); + String suggestedFileName = FileUtilities.extractFileName(fileLabel); String cleanedSuggestedFileName = - FileUtil.replaceInvalidFilenameCharacters(suggestedFileName); + FileUtilities.replaceInvalidFilenameCharacters(suggestedFileName); dialog.setFileName(cleanedSuggestedFileName + "." + ext); // if (fileLabel == null) { Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/core/FileViewer.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/core/FileViewer.java 2010-03-26 18:03:14 UTC (rev 1062) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/core/FileViewer.java 2010-03-26 18:08:35 UTC (rev 1063) @@ -6,7 +6,6 @@ import org.cishell.framework.CIShellContext; import org.cishell.framework.data.Data; import org.cishell.framework.data.DataProperty; -import org.cishell.reference.gui.persistence.FileUtil; import org.cishell.reference.gui.persistence.view.core.exceptiontypes.ConvertDataForViewingException; import org.cishell.reference.gui.persistence.view.core.exceptiontypes.FileViewingException; import org.cishell.reference.gui.persistence.view.core.exceptiontypes.NoProgramFoundException; @@ -251,7 +250,7 @@ FILE_EXTENSION_MIME_TYPE_PREFIX + fileExtension; File convertedFile = convertToFile( originalData, fileExtensionMimeType, converterManager); - String fileName = FileUtil.extractFileName(dataLabel); + String fileName = FileUtilities.extractFileName(dataLabel); return FileUtilities.createTemporaryFileCopy( convertedFile, fileName, fileExtension); @@ -279,8 +278,8 @@ String dataLabel = (String)originalData.getMetadata().get(DataProperty.LABEL); String dataFormat = originalData.getFormat(); - String fileName = FileUtil.extractFileName(dataLabel); - String fileExtension = FileUtil.extractExtension(dataFormat); + String fileName = FileUtilities.extractFileName(dataLabel); + String fileExtension = FileUtilities.extractExtension(dataFormat); try { File fileToView = FileUtilities. This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pat...@us...> - 2011-01-07 18:41:55
|
Revision: 1189 http://cishell.svn.sourceforge.net/cishell/?rev=1189&view=rev Author: pataphil Date: 2011-01-07 18:41:48 +0000 (Fri, 07 Jan 2011) Log Message: ----------- * http://cns-jira.slis.indiana.edu/browse/SCISQUARED-360 * Also cleaned up code a little, as I read through it. * Reviewed by Joseph. Modified Paths: -------------- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/FileSaver.java trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/Save.java trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/SaveFactory.java trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/FileView.java trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/FileViewFactory.java trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/core/FileViewer.java Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/FileSaver.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/FileSaver.java 2011-01-06 16:37:08 UTC (rev 1188) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/FileSaver.java 2011-01-07 18:41:48 UTC (rev 1189) @@ -22,11 +22,6 @@ import org.eclipse.swt.widgets.Shell; import org.osgi.service.log.LogService; -/** - * Persist the file to disk for the user - * - * @author Team - */ public class FileSaver { public static final String FILE_EXTENSION_PREFIX = "file-ext:"; @@ -37,17 +32,11 @@ private GUIBuilderService guiBuilder; private LogService log; - - /** - * Initializes services to output messages - * - * @param parent - * @param ciShellContext - */ - public FileSaver(Shell parent, CIShellContext context){ + public FileSaver(Shell parent, CIShellContext ciShellContext) { this.parent = parent; - this.guiBuilder = (GUIBuilderService)context.getService(GUIBuilderService.class.getName()); - this.log = (LogService) context.getService(LogService.class.getName()); + this.guiBuilder = + (GUIBuilderService) ciShellContext.getService(GUIBuilderService.class.getName()); + this.log = (LogService) ciShellContext.getService(LogService.class.getName()); } /** @@ -69,15 +58,17 @@ */ private boolean isSaveFileValid(File file) { boolean valid = false; + if (file.isDirectory()) { String message = "Destination cannot be a directory. Please choose a file"; guiBuilder.showError("Invalid Destination", message, ""); valid = false; } else if (file.exists()) { valid = confirmFileOverwrite(file); + } else { + valid = true; } - else - valid = true ; + return valid; } @@ -89,10 +80,10 @@ * @return Whether or not the save was successful */ public boolean save(Converter converter, Data data) { - String outDataStr = - (String) converter.getProperties().get(AlgorithmProperty.OUT_DATA); + String outDataStr = (String) converter.getProperties().get(AlgorithmProperty.OUT_DATA); String ext = ""; + if (outDataStr.startsWith(FILE_EXTENSION_PREFIX)) { ext = outDataStr.substring(FILE_EXTENSION_PREFIX.length()); } @@ -103,14 +94,13 @@ } FileDialog dialog = new FileDialog(parent, SWT.SAVE); - + if (currentDir == null) { - currentDir = new File(System.getProperty("user.home") + File.separator - + "anything"); + currentDir = new File(System.getProperty("user.home") + File.separator + "anything"); } + dialog.setFilterPath(currentDir.getPath()); - - + if (ext != null && !ext.equals("*")) { dialog.setFilterExtensions(new String[]{"*." + ext}); } Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/Save.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/Save.java 2011-01-06 16:37:08 UTC (rev 1188) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/Save.java 2011-01-07 18:41:48 UTC (rev 1189) @@ -1,7 +1,5 @@ package org.cishell.reference.gui.persistence.save; -import java.util.Dictionary; - import org.cishell.framework.CIShellContext; import org.cishell.framework.algorithm.Algorithm; import org.cishell.framework.algorithm.AlgorithmExecutionException; @@ -11,60 +9,43 @@ import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.PlatformUI; -/** - * Save algorithm for persisting a data object - * - * @author bmarkine - */ + public class Save implements Algorithm { public static final String ANY_FILE_EXTENSION = "file-ext:*"; public static final String SAVE_DIALOG_TITLE = "Save"; - private Data[] data; - private CIShellContext context; + private Data data; + private CIShellContext ciShellContext; + private Shell parentShell; private DataConversionService conversionManager; - - /** - * Sets up default services for the algorithm - * - * @param data The data array to persist - * @param parameters Parameters for the algorithm - * @param ciShellContext Provides services to CIShell services - */ - public Save(Data[] data, Dictionary parameters, CIShellContext context) { + + public Save( + Data data, CIShellContext ciShellContext, DataConversionService conversionManager) { this.data = data; - this.context = context; + this.ciShellContext = ciShellContext; - this.conversionManager = (DataConversionService) - context.getService(DataConversionService.class.getName()); + this.conversionManager = conversionManager; } - /** - * @return Null when successful - */ public Data[] execute() throws AlgorithmExecutionException { - Data outData = data[0]; - - tryToSave(outData, ANY_FILE_EXTENSION); + tryToSave(this.data, ANY_FILE_EXTENSION); return null; } private void tryToSave(final Data outData, String outFormat) throws AlgorithmExecutionException { - final Converter[] converters = - conversionManager.findConverters(outData, outFormat); + final Converter[] converters = conversionManager.findConverters(outData, outFormat); + if (converters.length == 0) { - throw new AlgorithmExecutionException( - "Error: Calculated an empty converter chain."); + throw new AlgorithmExecutionException("Error: Calculated an empty converter chain."); } - - parentShell = - PlatformUI.getWorkbench().getWorkbenchWindows()[0].getShell(); - if (parentShell.isDisposed()) { - throw new AlgorithmExecutionException( - "Attempted to use disposed parent shell."); + + this.parentShell = PlatformUI.getWorkbench().getWorkbenchWindows()[0].getShell(); + + if (this.parentShell.isDisposed()) { + throw new AlgorithmExecutionException("Attempted to use disposed parent shell."); } try { @@ -73,18 +54,17 @@ if (converters.length == 1) { // Only one possible choice in how to save data. Do it. Converter onlyConverter = converters[0]; - final FileSaver saver = - new FileSaver(parentShell, context); + FileSaver saver = new FileSaver(Save.this.parentShell, ciShellContext); saver.save(onlyConverter, outData); } else { // Multiple ways to save the data. Let user choose. - SaveDataChooser saveChooser = - new SaveDataChooser(outData, - parentShell, - converters, - SAVE_DIALOG_TITLE, - context); - saveChooser.createContent(new Shell(parentShell)); + SaveDataChooser saveChooser = new SaveDataChooser( + outData, + Save.this.parentShell, + converters, + SAVE_DIALOG_TITLE, + Save.this.ciShellContext); + saveChooser.createContent(new Shell(Save.this.parentShell)); saveChooser.open(); } } @@ -98,7 +78,7 @@ if (Thread.currentThread() == Display.getDefault().getThread()) { run.run(); } else { - parentShell.getDisplay().syncExec(run); + this.parentShell.getDisplay().syncExec(run); } } } \ No newline at end of file Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/SaveFactory.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/SaveFactory.java 2011-01-06 16:37:08 UTC (rev 1188) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/save/SaveFactory.java 2011-01-07 18:41:48 UTC (rev 1189) @@ -3,13 +3,10 @@ import java.util.Dictionary; import org.cishell.framework.CIShellContext; -import org.cishell.framework.LocalCIShellContext; import org.cishell.framework.algorithm.Algorithm; import org.cishell.framework.algorithm.AlgorithmFactory; import org.cishell.framework.data.Data; -import org.osgi.service.cm.ConfigurationException; -import org.osgi.service.cm.ManagedService; -import org.osgi.service.component.ComponentContext; +import org.cishell.service.conversion.DataConversionService; /** * Create a Save object @@ -18,32 +15,14 @@ * no final file:X->file-ext:* converter. * */ -public class SaveFactory implements AlgorithmFactory, ManagedService { - private CIShellContext ciShellContext; +public class SaveFactory implements AlgorithmFactory { + public Algorithm createAlgorithm( + Data[] data, Dictionary<String, Object> parameters, CIShellContext ciShellContext) { + Data inputData = data[0]; + DataConversionService conversionManager = + (DataConversionService) ciShellContext.getService( + DataConversionService.class.getName()); - /** - * Create a local CIShell ciShellContext - * @param componentContext The current CIShell ciShellContext - */ - protected void activate(ComponentContext componentContext) { - ciShellContext = - new LocalCIShellContext(componentContext.getBundleContext()); + return new Save(inputData, ciShellContext, conversionManager); } - - public void updated(Dictionary properties) throws ConfigurationException { - } - - /** - * Create a Save algorithm - * @param data The data objects to save - * @param parameters The parameters for the algorithm - * @param ciShellContext Reference to services provided by CIShell - * @return An instance of the Save algorithm - */ - public Algorithm createAlgorithm(Data[] data, - Dictionary parameters, - CIShellContext ciShellContext) { - this.ciShellContext = ciShellContext; - return new Save(data, parameters, ciShellContext); - } } \ No newline at end of file Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/FileView.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/FileView.java 2011-01-06 16:37:08 UTC (rev 1188) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/FileView.java 2011-01-07 18:41:48 UTC (rev 1189) @@ -1,7 +1,5 @@ package org.cishell.reference.gui.persistence.view; -import java.util.Dictionary; - import org.cishell.framework.CIShellContext; import org.cishell.framework.algorithm.Algorithm; import org.cishell.framework.algorithm.AlgorithmExecutionException; @@ -19,27 +17,25 @@ private LogService logger; public FileView( - Data[] data, Dictionary parameters, CIShellContext context) { + Data[] data, + CIShellContext ciShellContext, + DataConversionService conversionManager, + LogService logger) { this.dataToView = data; - this.ciShellContext = context; - - this.conversionManager = (DataConversionService)context.getService( - DataConversionService.class.getName()); - this.logger = (LogService)context.getService(LogService.class.getName()); + this.ciShellContext = ciShellContext; + this.conversionManager = conversionManager; + this.logger = logger; } public Data[] execute() throws AlgorithmExecutionException { - for (int ii = 0; ii < this.dataToView.length; ii++) { + for (Data data : this.dataToView) { try { - FileViewer.viewDataFile(this.dataToView[ii], - this.ciShellContext, - this.conversionManager, - this.logger); + FileViewer.viewDataFile( + data, this.ciShellContext, this.conversionManager, this.logger); } catch (FileViewingException fileViewingException) { - String logMessage = - "Error: Unable to view data \"" + - this.dataToView[ii].getMetadata().get(DataProperty.LABEL) + - "\"."; + String logMessage = String.format( + "Error: Unable to view data \"%s\".", + data.getMetadata().get(DataProperty.LABEL)); this.logger.log(LogService.LOG_ERROR, logMessage); } Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/FileViewFactory.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/FileViewFactory.java 2011-01-06 16:37:08 UTC (rev 1188) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/FileViewFactory.java 2011-01-07 18:41:48 UTC (rev 1189) @@ -6,12 +6,18 @@ import org.cishell.framework.algorithm.Algorithm; import org.cishell.framework.algorithm.AlgorithmFactory; import org.cishell.framework.data.Data; +import org.cishell.service.conversion.DataConversionService; +import org.osgi.service.log.LogService; public class FileViewFactory implements AlgorithmFactory { - public Algorithm createAlgorithm(Data[] data, - Dictionary parameters, - CIShellContext ciShellContext) { - return new FileView(data, parameters, ciShellContext); + public Algorithm createAlgorithm( + Data[] data, Dictionary<String, Object> parameters, CIShellContext ciShellContext) { + DataConversionService conversionManager = + (DataConversionService) ciShellContext.getService( + DataConversionService.class.getName()); + LogService logger = (LogService) ciShellContext.getService(LogService.class.getName()); + + return new FileView(data, ciShellContext, conversionManager, logger); } } \ No newline at end of file Modified: trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/core/FileViewer.java =================================================================== --- trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/core/FileViewer.java 2011-01-06 16:37:08 UTC (rev 1188) +++ trunk/clients/gui/org.cishell.reference.gui.persistence/src/org/cishell/reference/gui/persistence/view/core/FileViewer.java 2011-01-07 18:41:48 UTC (rev 1189) @@ -2,8 +2,11 @@ import java.io.File; import java.io.IOException; +import java.util.Dictionary; +import java.util.Enumeration; import org.cishell.framework.CIShellContext; +import org.cishell.framework.data.BasicData; import org.cishell.framework.data.Data; import org.cishell.framework.data.DataProperty; import org.cishell.reference.gui.persistence.view.core.exceptiontypes.ConvertDataForViewingException; @@ -36,11 +39,11 @@ public static final String ANY_FILE_FORMAT_PATTERN = "(file:.*)|(file-ext:.*)"; - public static void viewDataFile(Data data, - CIShellContext ciShellContext, - DataConversionService conversionManager, - LogService logger) - throws FileViewingException { + public static void viewDataFile( + Data data, + CIShellContext ciShellContext, + DataConversionService conversionManager, + LogService logger) throws FileViewingException { viewDataFileWithProgram(data, "", ciShellContext, conversionManager, logger); } @@ -49,11 +52,9 @@ String customFileExtension, CIShellContext ciShellContext, DataConversionService converterManager, - LogService logger) - throws FileViewingException { - FileWithExtension fileWithExtension = - convertDataForViewing(data, ciShellContext, converterManager, - logger); + LogService logger) throws FileViewingException { + FileWithExtension fileWithExtension = convertDataForViewing( + data, ciShellContext, converterManager, logger); viewFileWithExtension(fileWithExtension, customFileExtension); } @@ -64,16 +65,18 @@ LogService logger) throws FileViewingException { try { String dataFormat = data.getFormat(); - //TODO: Add image viewing support here (shouldn't be too hard) + // TODO: Add image viewing support here (shouldn't be too hard). if (dataIsDB(data, converterManager)) { try { - Data genericDBData = converterManager.convert(data, Database.GENERIC_DB_MIME_TYPE); - Database genericDatabase = (Database) genericDBData.getData(); + Data genericDBData = + converterManager.convert(data, Database.GENERIC_DB_MIME_TYPE); + Database genericDatabase = (Database) genericDBData.getData(); + + File dbSchemaOverview = + DatabaseSchemaOverviewGenerator.generateDatabaseSchemaOverview( + genericDatabase); - File dbSchemaOverview = - DatabaseSchemaOverviewGenerator.generateDatabaseSchemaOverview(genericDatabase); - - return new FileWithExtension(dbSchemaOverview, TXT_FILE_EXTENSION); + return new FileWithExtension(dbSchemaOverview, TXT_FILE_EXTENSION); } catch (ConversionException e) { //continue attempts to view for other formats } catch (Exception e) { @@ -85,13 +88,12 @@ } if (isCSVFormat(data)) { /* - * The data is already a CSV file, so it just needs to - * be copied. + * The data is already a CSV file, so it just needs to be copied. */ try { File csvFileForViewing = FileUtilities.createTemporaryFileCopy( - (File)data.getData(), + (File) data.getData(), TEMPORARY_CSV_FILE_NAME, CSV_FILE_EXTENSION); @@ -110,16 +112,14 @@ File preparedFileForViewing = prepareFileForViewing( data, CSV_FILE_EXTENSION, converterManager); - return new FileWithExtension( - preparedFileForViewing, CSV_FILE_EXTENSION); + return new FileWithExtension(preparedFileForViewing, CSV_FILE_EXTENSION); } else if (dataIsFile(data, dataFormat)) { /* * The data is already a text-based file, so it just needs to * be copied to a temporary file for viewing in the default * text-viewing program. */ - return new FileWithExtension( - prepareTextFileForViewing(data), TXT_FILE_EXTENSION); + return new FileWithExtension(prepareTextFileForViewing(data), TXT_FILE_EXTENSION); } else if (convertersExist( data, ANY_FILE_EXTENSION_FILTER, converterManager)) { /* @@ -128,29 +128,24 @@ * text-viewing program. */ return new FileWithExtension( - convertDataToTextFile( - data, converterManager, ciShellContext), + convertDataToTextFile(data, converterManager, ciShellContext), "txt"); } else { - String exceptionMessage = - "No converters exist for the data \"" + - data.getMetadata().get(DataProperty.LABEL) + - "\"."; - + String exceptionMessage = String.format( + "No converters exist for the data \"%s\".", + data.getMetadata().get(DataProperty.LABEL)); + throw new ConvertDataForViewingException(exceptionMessage); } - } catch (ConvertDataForViewingException - convertDataForViewingException) { - String exceptionMessage = - "There was a problem when preparing the data \"" + - data.getMetadata().get(DataProperty.LABEL) + - "\" for viewing."; + } catch (ConvertDataForViewingException e) { + String exceptionMessage = String.format( + "There was a problem when preparing the data \"%s\" for viewing.", + data.getMetadata().get(DataProperty.LABEL)); - throw new FileViewingException( - exceptionMessage, convertDataForViewingException); + throw new FileViewingException(exceptionMessage, e); } } - + private static void viewFileWithExtension( FileWithExtension fileWithExtension, String customFileExtension) throws FileViewingException { @@ -160,47 +155,33 @@ executeProgramWithFile(program, fileWithExtension.file); } catch (NoProgramFoundException noProgramFoundException) { - String exceptionMessage = - "Could not view the file \"" + - fileWithExtension.file.getAbsolutePath() + - "\" because no viewing program could be found for it."; + String exceptionMessage = String.format( + "Could not view the file \"%s\" because no viewing program could be found for it.", + fileWithExtension.file.getAbsolutePath()); - throw new FileViewingException( - exceptionMessage, noProgramFoundException); + throw new FileViewingException(exceptionMessage, noProgramFoundException); } } - + private static boolean isCSVFormat(Data data) { String dataFormat = data.getFormat(); - if (dataFormat.startsWith(CSV_MIME_TYPE) || - dataFormat.startsWith(CSV_FILE_EXT)) { + if (dataFormat.startsWith(CSV_MIME_TYPE) || dataFormat.startsWith(CSV_FILE_EXT)) { return true; } else { return false; } } - - /*private static boolean dataIsCSVCompatibleFile( - Data data, - DataConversionService converterManager) { - return convertersExist(data, CSV_FILE_EXT, converterManager); - }*/ - - private static boolean dataIsCSVCompatible( - Data data, - DataConversionService converterManager) { - if (isCSVFormat(data) || - convertersExist(data, CSV_FILE_EXT, converterManager)) { + + private static boolean dataIsCSVCompatible(Data data, DataConversionService converterManager) { + if (isCSVFormat(data) || convertersExist(data, CSV_FILE_EXT, converterManager)) { return true; } else { return false; } } - - private static boolean dataIsDB ( - Data data, - DataConversionService converterManager) { + + private static boolean dataIsDB(Data data, DataConversionService converterManager) { if (has_DB_MimeType_Prefix(data) || convertersExist(data, Database.GENERIC_DB_MIME_TYPE, converterManager)) { return true; @@ -208,11 +189,11 @@ return false; } } - + private static boolean has_DB_MimeType_Prefix(Data data) { return data.getFormat().startsWith(Database.DB_MIME_TYPE_PREFIX); } - + private static boolean dataIsFile(Data data, String dataFormat) { if (data.getData() instanceof File || dataFormat.startsWith(ANY_MIME_TYPE) || @@ -222,51 +203,45 @@ return false; } } - + private static boolean convertersExist( - Data data, - String targetFormat, - DataConversionService conversionManager) { - final Converter[] converters = - conversionManager.findConverters(data, targetFormat); - + Data data, String targetFormat, DataConversionService conversionManager) { + final Converter[] converters = conversionManager.findConverters(data, targetFormat); + if (converters.length > 0) { return true; } else { return false; } } - + private static File prepareFileForViewing( Data originalData, String fileExtension, - DataConversionService converterManager) - throws ConvertDataForViewingException { - String dataLabel = - (String)originalData.getMetadata().get(DataProperty.LABEL); - + DataConversionService converterManager) throws ConvertDataForViewingException { + String dataLabel = (String) originalData.getMetadata().get(DataProperty.LABEL); + try { - String fileExtensionMimeType = - FILE_EXTENSION_MIME_TYPE_PREFIX + fileExtension; + String fileExtensionMimeType = FILE_EXTENSION_MIME_TYPE_PREFIX + fileExtension; File convertedFile = convertToFile( originalData, fileExtensionMimeType, converterManager); String fileName = FileUtilities.extractFileName(dataLabel); + String cleanedFileName = FileUtilities.replaceInvalidFilenameCharacters(fileName); return FileUtilities.createTemporaryFileCopy( - convertedFile, fileName, fileExtension); - } catch (ConversionException convertingDataToFileException) { - String exceptionMessage = - "A ConversionException occurred when converting the data \"" + - dataLabel + - "\" to " + fileExtension + "."; + convertedFile, cleanedFileName, fileExtension); + } catch (ConversionException e) { + String exceptionMessage = String.format( + "A ConversionException occurred when converting the data \"%s\" to %s.", + dataLabel, + fileExtension); - throw new ConvertDataForViewingException( - exceptionMessage, convertingDataToFileException); + throw new ConvertDataForViewingException(exceptionMessage, e); } catch (FileCopyingException temporaryFileCopyingException) { - String exceptionMessage = - "A FileCopyingException occurred when converting the data \"" + - dataLabel + - "\" to " + fileExtension + "."; + String exceptionMessage = String.format( + "A FileCopyingException occurred when converting the data \"%s\" to %s.", + dataLabel, + fileExtension); throw new ConvertDataForViewingException( exceptionMessage, temporaryFileCopyingException); @@ -275,8 +250,7 @@ private static File prepareTextFileForViewing(Data originalData) throws ConvertDataForViewingException { - String dataLabel = - (String)originalData.getMetadata().get(DataProperty.LABEL); + String dataLabel = (String)originalData.getMetadata().get(DataProperty.LABEL); String dataFormat = originalData.getFormat(); String suggestedFileName = FileUtilities.extractFileName(dataLabel); String cleanedSuggestedFileName = @@ -284,9 +258,8 @@ String fileExtension = FileUtilities.extractExtension(dataFormat); try { - File fileToView = FileUtilities. - createTemporaryFileInDefaultTemporaryDirectory( - cleanedSuggestedFileName, fileExtension); + File fileToView = FileUtilities.createTemporaryFileInDefaultTemporaryDirectory( + cleanedSuggestedFileName, fileExtension); FileUtilities.copyFile((File)originalData.getData(), fileToView); return fileToView; @@ -306,8 +279,7 @@ private static File convertDataToTextFile( Data originalData, DataConversionService converterManager, - CIShellContext ciShellContext) - throws ConvertDataForViewingException { + CIShellContext ciShellContext) throws ConvertDataForViewingException { final Converter[] converters = converterManager.findConverters( originalData, ANY_FILE_EXTENSION_FILTER); @@ -317,20 +289,15 @@ * the conversion. */ try { - return convertToFile( - originalData, converters[0]); - } - catch (ConversionException - convertDataToFileAndPrepareForViewingException) { - String exceptionMessage = - "A ConversionException occurred when converting the " + - "data \"" + - originalData.getMetadata().get(DataProperty.LABEL) + - "\" to a file format."; + return convertToFile(originalData, converters[0]); + } catch (ConversionException e) { + String format = + "A ConversionException occurred when converting the data \"%s\" " + + "to a file format."; + String exceptionMessage = String.format( + format, originalData.getMetadata().get(DataProperty.LABEL)); - throw new ConvertDataForViewingException( - exceptionMessage, - convertDataToFileAndPrepareForViewingException); + throw new ConvertDataForViewingException(exceptionMessage, e); } } else { /* @@ -341,25 +308,20 @@ return convertDataBasedOffUserChosenConverter( originalData, converters, ciShellContext); } catch (ConversionException conversionException) { - String exceptionMessage = - "A ConversionException occurred when converting the " + - "data \"" + - originalData.getMetadata().get(DataProperty.LABEL) + - "\"."; + String exceptionMessage = String.format( + "A ConversionException occurred when converting the data \"%s\".", + originalData.getMetadata().get(DataProperty.LABEL)); - throw new ConvertDataForViewingException( - exceptionMessage, conversionException); - } catch (UserCanceledDataViewSelectionException - userCanceledDataViewSelectionException) { - String exceptionMessage = + throw new ConvertDataForViewingException(exceptionMessage, conversionException); + } catch (UserCanceledDataViewSelectionException e) { + String format = "A UserCanceledDataViewSelectionException occurred " + "when the user did not choose a converter for the " + - "data \"" + - originalData.getMetadata().get(DataProperty.LABEL) + - "\"."; + "data \"%s\"."; + String exceptionMessage = String.format( + format, originalData.getMetadata().get(DataProperty.LABEL)); - throw new ConvertDataForViewingException( - exceptionMessage, userCanceledDataViewSelectionException); + throw new ConvertDataForViewingException(exceptionMessage, e); } } } @@ -432,10 +394,11 @@ } - private static File convertToFile(Data data, Converter converter) - throws ConversionException { - Data newData = converter.convert(data); - return (File)newData.getData(); + private static File convertToFile(Data data, Converter converter) throws ConversionException { + Data dataWithCleanedLabelForConversion = cloneDataWithCleanedLabelForConversion(data); + Data newData = converter.convert(dataWithCleanedLabelForConversion); + + return (File) newData.getData(); } private static File convertDataBasedOffUserChosenConverter( @@ -527,6 +490,25 @@ this.selectedConverter = viewDataChooser.getSelectedConverter(); } } + + private static Data cloneDataWithCleanedLabelForConversion(Data originalData) { + Data clonedData = new BasicData(originalData.getData(), originalData.getFormat()); + Dictionary<String, Object> originalMetadata = originalData.getMetadata(); + Dictionary<String, Object> clonedMetadata = clonedData.getMetadata(); + + for (Enumeration<String> keys = originalMetadata.keys(); keys.hasMoreElements();) { + String key = keys.nextElement(); + + if (DataProperty.LABEL.equals(key)) { + clonedMetadata.put(key, FileUtilities.replaceInvalidFilenameCharacters( + (String) originalMetadata.get(key))); + } else { + clonedMetadata.put(key, originalMetadata.get(key)); + } + } + + return clonedData; + } private static class FileWithExtension { public final File file; This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |