From: <fu...@us...> - 2010-03-26 18:03:21
|
Revision: 1062 http://cishell.svn.sourceforge.net/cishell/?rev=1062&view=rev Author: fugu13 Date: 2010-03-26 18:03:14 +0000 (Fri, 26 Mar 2010) Log Message: ----------- Move some stuff here from persistence. Modified Paths: -------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java 2010-03-26 16:30:23 UTC (rev 1061) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java 2010-03-26 18:03:14 UTC (rev 1062) @@ -15,9 +15,15 @@ import java.net.URI; import java.net.URL; import java.nio.channels.FileChannel; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; import javax.imageio.ImageIO; +import org.osgi.service.log.LogService; + public class FileUtilities { public static final int READ_TEXT_FILE_BUFFER_SIZE = 1024; public static final String DEFAULT_STREAM_TO_FILE_NAME = "stream_"; @@ -301,4 +307,130 @@ return directory; } + +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; + } } \ No newline at end of file This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <fu...@us...> - 2010-05-26 16:41:53
|
Revision: 1066 http://cishell.svn.sourceforge.net/cishell/?rev=1066&view=rev Author: fugu13 Date: 2010-05-26 16:41:47 +0000 (Wed, 26 May 2010) Log Message: ----------- Eliminate spaces at the beginnings (and ends) of filenames for saving. Modified Paths: -------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java 2010-03-26 20:32:48 UTC (rev 1065) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java 2010-05-26 16:41:47 UTC (rev 1066) @@ -431,7 +431,7 @@ String fileNameWithoutExtension = fileNameWithExtension.substring(0, endIndex); - return fileNameWithoutExtension; + return fileNameWithoutExtension.trim(); //no spaces on either end } public static String extractFileNameWithExtension(String fileLabel) { This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <pat...@us...> - 2010-10-28 22:15:17
|
Revision: 1145 http://cishell.svn.sourceforge.net/cishell/?rev=1145&view=rev Author: pataphil Date: 2010-10-28 22:15:11 +0000 (Thu, 28 Oct 2010) Log Message: ----------- * Implemented FileUtilities.writeEntireStreamToTemporaryFileInDirectory * Fixed a small bug in ensureDirectoryExists * Reviewed by Joseph. Modified Paths: -------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java 2010-10-22 18:08:52 UTC (rev 1144) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java 2010-10-28 22:15:11 UTC (rev 1145) @@ -33,12 +33,13 @@ * temporaryDirectoryPath, creating the directory if it doesn't * already exist. */ - private static File createTemporaryDirectory( - String temporaryDirectoryPath) { - return ensureDirectoryExists( - temporaryDirectoryPath + File.separator + "temp"); + public static File createTemporaryDirectory(String temporaryDirectoryPath) { + String fullDirectoryPath = + String.format("%s%stemp", temporaryDirectoryPath, File.separator); + + return ensureDirectoryExists(fullDirectoryPath); } - + // Attempt to create a temporary file on disk whose name is passed in. public static File createTemporaryFile(File temporaryDirectory, String temporaryDirectoryPath, @@ -282,6 +283,27 @@ return temporaryFile; } + + public static File writeEntireStreamToTemporaryFileInDirectory( + InputStream input, File directory, String fileName, String fileExtension) + throws IOException { + File temporaryFile = + createTemporaryFile(directory, directory.getAbsolutePath(), fileName, fileExtension); + OutputStream output = new FileOutputStream(temporaryFile); + // TODO: Use READ_TEXT_FILE_BUFFER_SIZE. + byte[] readCharacters = new byte[1]; + int readCharacterCount = input.read(readCharacters); + + while (readCharacterCount > 0) { + output.write(readCharacters, 0, readCharacterCount); + readCharacterCount = input.read(readCharacters); + } + + output.close(); + input.close(); + + return temporaryFile; + } public static String getFileExtension(File file) { return getFileExtension(file.getAbsolutePath()); @@ -301,14 +323,14 @@ File directory = new File(directoryPath); if (!directory.exists()) { - directory.mkdir(); + directory.mkdirs(); directory.deleteOnExit(); } return directory; } -public static final char FILENAME_CHARACTER_REPLACEMENT = '#'; + 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 was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <jrb...@us...> - 2010-12-22 17:32:25
|
Revision: 1183 http://cishell.svn.sourceforge.net/cishell/?rev=1183&view=rev Author: jrbibers Date: 2010-12-22 17:32:19 +0000 (Wed, 22 Dec 2010) Log Message: ----------- Updating FileUtilities.extractExtension(String format). Previously it attempted to derive the extension from the MIME type assuming it began with "file:text/". For a type like "file:application/pajeknet" it would return an empty string. We attempt to handle this better now with a Map from MIME types to extensions (excluding the case "file:text/foo" -> "foo" as we default to this). Reviewed by Patrick. Modified Paths: -------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java 2010-12-21 22:59:56 UTC (rev 1182) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java 2010-12-22 17:32:19 UTC (rev 1183) @@ -24,10 +24,28 @@ import org.osgi.service.log.LogService; +import com.google.common.collect.ImmutableMap; + public class FileUtilities { public static final int READ_TEXT_FILE_BUFFER_SIZE = 1024; public static final String DEFAULT_STREAM_TO_FILE_NAME = "stream_"; + /** Don't bother with "file:text/foo" -> "foo", we can find those automatically. */ + public static final ImmutableMap<String, String> MIME_TYPE_TO_FILE_EXTENSION = + new ImmutableMap.Builder<String, String>() + .put("file:application/pajekmat", "mat") + .put("file:application/pajeknet", "net") + .put("file:application/parvis", "stf") // TODO: This is a guess. + .put("file:text/bibtex", "bib") + .put("file:text/compartmentalmodel", "mdl") + .put("file:text/coord", "nwb") + .put("file:text/grace", "grace.dat") + .put("file:text/intsim", "int") + .put("file:text/plain", "txt") + .put("file:text/plot", "plot.dat") + .put("file:text/referbib", "refer") + .build(); + /* * Return a File pointing to the directory specified in * temporaryDirectoryPath, creating the directory if it doesn't @@ -395,16 +413,28 @@ return tempFile; } + /* 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. + */ 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()); + + if (format.startsWith("file-ext:")) { + extension = format.substring("file-ext:".length()); + } else if (format.startsWith("file:")) { + if (MIME_TYPE_TO_FILE_EXTENSION.containsKey(format)) { + // Unless explicitly set.. + extension = MIME_TYPE_TO_FILE_EXTENSION.get(format); + } else { + if (format.contains("/")) { + // Whatever follows "/" + extension = format.substring(format.indexOf("/") + 1); + } else { + // Whatever follows "file:" + extension = format.substring("file:".length()); + } + } } extension = extension.replace('+', '.'); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |
From: <dav...@us...> - 2012-02-01 15:41:38
|
Revision: 1304 http://cishell.svn.sourceforge.net/cishell/?rev=1304&view=rev Author: david-coe Date: 2012-02-01 15:41:27 +0000 (Wed, 01 Feb 2012) Log Message: ----------- Added some nice features such as getting a tempdirectory given a prefix for the directory name and reading a stream into a file. Reviewed by Thomas. Modified Paths: -------------- trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java Modified: trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java =================================================================== --- trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java 2012-01-30 23:56:55 UTC (rev 1303) +++ trunk/core/org.cishell.utilities/src/org/cishell/utilities/FileUtilities.java 2012-02-01 15:41:27 UTC (rev 1304) @@ -58,6 +58,36 @@ return ensureDirectoryExists(fullDirectoryPath); } + /** + * Adapted from Google Guava. + * + * This will attempt to return you a temp directory in Java's temp + * directory. This method assumes that the temporary volume is writable, has + * free inodes and free blocks, and that it will not be called thousands of + * times per second. + * + * @param prefix + * A string that will appear at the beginning of a directories + * name. + */ + public static File createTempDirectory(String prefix) { + final int TEMP_DIR_ATTEMPTS = 1000; + File baseDir = new File(getDefaultTemporaryDirectory()); + String baseName = prefix + "-" + System.currentTimeMillis() + "-"; + + for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) { + File tempDir = new File(baseDir, baseName + counter); + if (tempDir.mkdir()) { + return tempDir; + } + } + throw new IllegalStateException("Failed to create directory within " + + TEMP_DIR_ATTEMPTS + " attempts (tried " + + baseName + "0 to " + baseName + (TEMP_DIR_ATTEMPTS - 1) + ')'); + + } + + // Attempt to create a temporary file on disk whose name is passed in. public static File createTemporaryFile(File temporaryDirectory, String temporaryDirectoryPath, @@ -91,6 +121,10 @@ throw new RuntimeException(e2); } + /* + * FIXME this is very very very bad if the machine will be left running for long periods of time... + * See: http://www.pongasoft.com/blog/yan/java/2011/05/17/file-dot-deleteOnExit-is-evil/ + */ temporaryFile.deleteOnExit(); } } @@ -307,22 +341,29 @@ throws IOException { File temporaryFile = createTemporaryFile(directory, directory.getAbsolutePath(), fileName, fileExtension); - OutputStream output = new FileOutputStream(temporaryFile); - // TODO: Use READ_TEXT_FILE_BUFFER_SIZE. - byte[] readCharacters = new byte[1]; - int readCharacterCount = input.read(readCharacters); - - while (readCharacterCount > 0) { - output.write(readCharacters, 0, readCharacterCount); - readCharacterCount = input.read(readCharacters); - } - - output.close(); - input.close(); - - return temporaryFile; + return writeStreamToFile(input, temporaryFile); } + /** + * Read the input stream into the output file and return the file. + */ + public static File writeStreamToFile(InputStream input, File outputFile) + throws IOException { + OutputStream output = new FileOutputStream(outputFile); + // TODO: Use READ_TEXT_FILE_BUFFER_SIZE. + byte[] readCharacters = new byte[1]; + int readCharacterCount = input.read(readCharacters); + + while (readCharacterCount > 0) { + output.write(readCharacters, 0, readCharacterCount); + readCharacterCount = input.read(readCharacters); + } + + output.close(); + input.close(); + return outputFile; + } + public static String getFileExtension(File file) { return getFileExtension(file.getAbsolutePath()); } @@ -455,7 +496,7 @@ return cleanedFilename; } - + public static String extractFileName(String fileLabel) { //index variables will be -1 if index is not found. int descriptionEndIndex = fileLabel.lastIndexOf(":"); This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |