|
What this is
Other links
The source code/* * Sun Public License Notice * * The contents of this file are subject to the Sun Public License * Version 1.0 (the "License"). You may not use this file except in * compliance with the License. A copy of the License is available at * http://www.sun.com/ * * The Original Code is NetBeans. The Initial Developer of the Original * Code is Sun Microsystems, Inc. Portions Copyright 1997-2003 Sun * Microsystems, Inc. All Rights Reserved. */ package org.netbeans.modules.tasklist.core.translators; import java.io.*; import java.text.MessageFormat; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; import javax.swing.plaf.basic.BasicFileChooserUI; import org.openide.ErrorManager; import org.openide.NotifyDescriptor; import org.openide.NotifyDescriptor.Confirmation; import org.openide.NotifyDescriptor.Message; import org.openide.filesystems.FileObject; import org.openide.util.NbBundle; import org.openide.DialogDisplayer; import org.netbeans.modules.tasklist.core.TaskList; /** * This class implements the FormatTranslator interface and provides * some common useful functionality, like the code for asking the * user for a filename, checking if the file exists and warning (during * export) or bailing (during import). * * @author Tor Norbye */ public abstract class AbstractTranslator implements FormatTranslator { /** * Returns description for the default extension. It will be used in * FileFilter during export. * @return description */ protected String getExtensionDesc() { return getExportName(); } /** * Returns default extension for files created with this Translator. * @return default extension without the dot. * null means no default extension. */ protected String getDefaultExtension() { return null; } /** Provide a title to place on the file chooser when exporting */ abstract protected String getExportDialogTitle(); /** Provide a title to place on the file chooser when importing */ abstract protected String getImportDialogTitle(); /** * Do the actual export of the list into the stream * * @param list The tasklist to read into * @param out target byte stream (do not forget to flush wrapper writer etc.) * @param interactive Whether or not the user should be kept informed * @param dir May be null, or a directory where the writer is * going to write the tasklist. Exporters may for example * write additional files in this directory. * @return true iff the list was successfully written */ /* TODO: for tests */ public abstract boolean writeList(TaskList list, OutputStream out, boolean interactive, File dir) throws IOException; /** Only do backups once per session - that way if something goes wrong and we save twice the user has lost the data */ private static boolean backedUp = false; /** Write a tasklist into the given file location @param list The tasklist to export @param folder The FileObject for the folder in which a file named name should be created. @param folderPath The folder path to use, in case file is null. This is because of user mounts, some paths may not be accessible through the filesystems API. @param interactive When false, don't prompt the user. When true, provide user feedback etc. @param backup Save backup file */ public boolean write(TaskList list, FileObject folder, String name, File folderPath, boolean interactive, boolean backup) { if (interactive && (folder == null) && (folderPath == null)) { // Put up a file chooser JFileChooser chooser = new JFileChooser(); chooser.setDialogTitle(getExportDialogTitle()); chooser.setApproveButtonText(NbBundle.getMessage(AbstractTranslator.class, "Export")); // NOI18N chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setMultiSelectionEnabled(false); chooser.setDialogType(JFileChooser.SAVE_DIALOG); if(getDefaultExtension() != null) { final String ext = "." + getDefaultExtension(); chooser.setSelectedFile(new File("tasklist" + ext)); chooser.addChoosableFileFilter(new FileFilter() { public String getDescription() { return getExtensionDesc(); } public boolean accept(File pathname) { return pathname.isDirectory() || pathname.getName().endsWith(ext); } }); } // XXX pick a decent default here? At least a mounted directory? // chooser.setCurrentDirectory(dir); // XXX perhaps pick a better approve text - // use chooser.showDialog(null, approveText) instead int returnVal = chooser.showSaveDialog(null); if (returnVal == JFileChooser.APPROVE_OPTION) { File f = chooser.getSelectedFile(); if ((f == null) && (chooser.getUI() instanceof BasicFileChooserUI)) { // HACK // Hack which lets me type in a path in the text field // (in the Swing file chooser) without pressing return // and having that string be used. BasicFileChooserUI ui = (BasicFileChooserUI)chooser.getUI(); f = new File(ui.getFileName()); } if (f == null) { return false; } if (f.isFile()) { // Check if the user wants to replace the file NotifyDescriptor nd = new NotifyDescriptor.Confirmation ( NbBundle.getMessage(AbstractTranslator.class, "LBL_fileexists"), // NOI18N NotifyDescriptor.YES_NO_OPTION ); Object result = DialogDisplayer.getDefault().notify(nd); if (NotifyDescriptor.YES_OPTION != result) { return false; // Don't overwrite } } folderPath = f.getParentFile(); if (!folderPath.isDirectory()) { // Parent directory does not exist String msg = MessageFormat.format( NbBundle.getMessage(AbstractTranslator.class, "NoParent"), // NOI18N new String[] { folderPath.getPath(), f.getPath() }); DialogDisplayer.getDefault().notify( new NotifyDescriptor.Message(msg, NotifyDescriptor.ERROR_MESSAGE)); return false; } /* TODO Figure out how to use File objects later FileObject[] pos = FileUtil.fromFile(folderPath); if ((pos != null) && pos.length > 0) { folder = pos[0]; } else { // Parent directory does not exist String msg = MessageFormat.format( NbBundle.getMessage(AbstractTranslator.class, "ToFileError"), // NOI18N new String[] { folderPath.getPath() }); DialogDisplayer.getDefault().notify( new NotifyDescriptor.Message(msg, NotifyDescriptor.ERROR_MESSAGE)); return false; } */ // Determine the basename name = f.getPath().substring(folderPath.getPath().length()+1); } else { // User cancelled return false; } } else if ((folder == null) && (folderPath == null)) { return false; } File file = null; boolean success = false; OutputStream out = null; try { file = new File(folderPath.getPath()+File.separatorChar+name); if (file.exists()) { if (!backedUp && backup) { // Save backup File oldFile = new File(file.getPath()+'~'); if (oldFile.exists()) { oldFile.delete(); } file.renameTo(oldFile); backedUp = true; } else { file.delete(); } } file.createNewFile(); out = new BufferedOutputStream(new FileOutputStream(file)); success = writeList(list, out, interactive, file.getParentFile()); } catch (IOException ioe) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message( ioe, NotifyDescriptor.ERROR_MESSAGE)); } finally { if (out != null) { try { out.close(); } catch (IOException e) { } } } if (success) { exportDone(file); } return success; /* TODO Figure out how to use File objects later FileObject file = folder.getFileObject(name); if (file == null) { // The file does not already exist; create it // XXX find parent folder try { file = folder.createData(name, ""); } catch (java.io.IOException e) { ErrorManager.getDefault().notify(e); return false; } } else if (!backedUp && backup) { // Save backup files backedUp = true; // Check if FILENAME~ exists; if so delete it, // and then rename the curren String backupName = name + "~"; // TODO Is this configurable? // Get rid of the old backup FileObject oldbackup = folder.getFileObject(backupName); if (oldbackup != null) { try { oldbackup.delete(); } catch (java.io.IOException e) { ErrorManager.getDefault().notify(e); } } FileLock lock = null; boolean renamed = false; try { lock = file.lock(); // GRRRRRRRrrrrrrrr There is no rename(FileLock, String) // method - I have to specify a file "extension". // This does not work: // file.rename(lock, backupName, ""); // because the system inserts a "." for me // So we have to fake it file.rename(lock, file.getName(), file.getExt() + "~"); renamed = true; } catch (java.io.IOException e) { ErrorManager.getDefault().notify(e); } finally { if (lock != null) { lock.releaseLock(); } } if (renamed) { try { file = folder.createData(name, ""); } catch (java.io.IOException e) { ErrorManager.getDefault().notify(e); return false; } } } // TODO Run as FileSystem.AtomicAction ?? //final FileSystem fs = folder.getFileSystem(); //fs.runAtomicAction(new FileSystem.AtomicAction() { // public void run() throws IOException { boolean success = false; BufferedWriter writer = null; FileLock lock = null; try { lock = file.lock(); writer = new BufferedWriter( new OutputStreamWriter(file.getOutputStream(lock), "UTF-8")); // NOI18N success = writeList(list, writer, interactive, ... what here? ...); } catch (java.io.IOException ioe) { DialogDisplayer.getDefault().notify(new NotifyDescriptor.Message( ioe, NotifyDescriptor.ERROR_MESSAGE)); } finally { if (writer != null) { try { writer.close(); } catch (java.io.IOException e) { } } if (lock != null) { lock.releaseLock(); } } if (success) { exportDone(file); } return success; */ } /** Called when export is done; after the export each filter may want to do some action, like showing the exported file */ protected void exportDone(FileObject file) { } /** Called when export is done; after the export each filter may want to do some action, like showing the exported file */ protected void exportDone(File file) { } /** Called when import is done; after the import each filter may want to do some action, like showing the imported results */ protected void importDone(TaskList list) { } /** Read a file into the given tasklist @param list The tasklist to read into @param file The FileObject for the file to be read @param path The file path to use, in case file is null. This is because of user mounts, some paths may not be accessible through the filesystems API. @param interactive When false, don't prompt the user. When true, provide user feedback etc. */ public boolean read(TaskList list, FileObject file, File path, final boolean interactive) throws UnknownFormatException { if (interactive && (file == null) && (path == null)) { String name = ""; // Put up a file chooser JFileChooser chooser = new JFileChooser(); // String name = null; chooser.setDialogTitle(getImportDialogTitle()); chooser.setApproveButtonText(NbBundle.getMessage(AbstractTranslator.class, "Import")); // NOI18N chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.setDialogType(JFileChooser.OPEN_DIALOG); chooser.setMultiSelectionEnabled(false); // XXX pick a decent default here? At least a mounted directory? // chooser.setCurrentDirectory(dir); int returnVal = chooser.showOpenDialog(null); // XXX perhaps pick a better approve text - use chooser.showDialog(null, approveText) instead if (returnVal == JFileChooser.APPROVE_OPTION) { path = chooser.getSelectedFile(); if ((path == null) && (chooser.getUI() instanceof BasicFileChooserUI)) { // HACK // Hack which lets me type in a path in the text field // (in the Swing file chooser) without pressing return // and having that string be used. BasicFileChooserUI ui = (BasicFileChooserUI)chooser.getUI(); path = new File(ui.getFileName()); } if ((path == null) || !path.isFile()) { // No such file -- tell user if (path != null) { name = path.getPath(); } String msg = MessageFormat.format( NbBundle.getMessage(AbstractTranslator.class, "NoSuchFile"), // NOI18N new String[] { name }); DialogDisplayer.getDefault().notify( new NotifyDescriptor.Message(msg, NotifyDescriptor.ERROR_MESSAGE)); return false; } /* TODO Figure out some way to deal with File Objects name = null; if (path != null) { name = path.getAbsolutePath(); FileObject[] fos = FileUtil.fromFile(f); if ((fos != null) && fos.length > 0) { file = fos[0]; } } else if (chooser.getUI() instanceof BasicFileChooserUI) { // HACK // Hack which lets me type in a path in the text field // (in the Swing file chooser) without pressing return // and having that string be used. BasicFileChooserUI ui = (BasicFileChooserUI)chooser.getUI(); name = ui.getFileName(); f = new File(name); if (!f.isFile()) { // No such file -- tell user String msg = MessageFormat.format( NbBundle.getMessage(AbstractTranslator.class, "NoSuchFile"), // NOI18N new String[] { name }); DialogDisplayer.getDefault().notify( new NotifyDescriptor.Message(msg, NotifyDescriptor.ERROR_MESSAGE)); return false; } FileObject[] fos = FileUtil.fromFile(f); if ((fos != null) && fos.length > 0) { file = fos[0]; } } if (file == null) { // Some kind of problem if (f != null) { name = f.getPath(); } String msg = MessageFormat.format( NbBundle.getMessage(AbstractTranslator.class, "ToFileError"), // NOI18N new String[] { name }); DialogDisplayer.getDefault().notify( new NotifyDescriptor.Message(msg, NotifyDescriptor.ERROR_MESSAGE)); return false; } */ } else { // User cancelled return false; } } else if ((file == null) && (path == null)) { return false; } // TODO Run as FileSystem.AtomicAction ?? //final FileSystem fs = folder.getFileSystem(); //fs.runAtomicAction(new FileSystem.AtomicAction() { // public void run() throws IOException { boolean success; try { if (path != null) { success = readList(list, path, interactive); } else if (file != null) { success = readList(list, file, interactive); } else { // XXX And???? success = false; } } catch (IOException e) { ErrorManager.getDefault().notify( ErrorManager.INFORMATIONAL, e); success = false; } if (success) { // it should be handled by the list //list.getRoot().updatedStructure(); importDone(list); // Make sure the list is saved list.markChanged(); } return success; } /** Alternative to implementing readList(TaskList, FileObject); provides a file stream so you don't have to deal with the FileObject directly. @param list The tasklist to be imported into @param reader An input stream to read the import data from @param interactive Whether or not the user should be kept informed @return True iff the list was read successfully */ /* TODO: for tests*/ public boolean readList(TaskList list, InputStream reader, boolean interactive) throws IOException, UnknownFormatException { // Default implementation does nothing return false; } /** Do the actual reading of the tasklist @param list The tasklist to be imported into @param file The file object for the file to be imported @param interactive Whether or not the user should be kept informed @return True iff the list was read successfully The default implementation will create the reader object, if the child implementation is not interested in doing it (e.g. it needs closer access to the FileObject) and will call readList(TaskList, Reader) to do the actual work. */ protected final boolean readList(TaskList list, FileObject file, boolean interactive) throws IOException, UnknownFormatException { boolean success; InputStream is = null; try { is = file.getInputStream(); success = readList(list, is, interactive); } catch (FileNotFoundException e) { // Should not happen, we checked for file existence before // opening it success = false; } catch (IOException e) { ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e); success = false; } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } return success; } /** Do the actual reading of the tasklist @param list The tasklist to be imported into @param file The file path for the file to be imported @param interactive Whether or not the user should be kept informed @return True iff the list was read successfully The default implementation will create the reader object, if the child implementation is not interested in doing it (e.g. it needs closer access to the FileObject) and will call readList(TaskList, Reader) to do the actual work. */ protected final boolean readList(TaskList list, File file, boolean interactive) throws IOException, UnknownFormatException { InputStream is = null; boolean success; try { is = new FileInputStream(file); success = readList(list, is, interactive); } catch (FileNotFoundException e) { // Should not happen, we checked for file existence before // opening it success = false; } catch (IOException e) { ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, e); success = false; } finally { if (is != null) { try { is.close(); } catch (IOException e) { } } } return success; } } |
... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.