/*
*Returns a existing file if the filename given has already been used in a folder/root
**/
public FileResource getConflictedFile(String fileName, String licenseKey, Long parentDirectoryId){
return FileResource.withCriteria(uniqueResult:true){
ilike("name","%"+fileName+"%")
eq("licenseKey",licenseKey)
if(parentDirectoryId){
parentDirectory{
eq("id",parentDirectoryId)
}
}
else{
isNull("parentDirectory")
}
fetchMode("parentDirectory",FM.EAGER)
}
}
public String createUniqueFileNameInFolder(String fileName, String licenseKey, Long parentDirectoryId){
def file = getConflictedFile(fileName, licenseKey, parentDirectoryId)
if( file ){
def fName = file.name
int dotPos = fName.lastIndexOf(".")
def name = fName.substring(0,dotPos);
def fileExt = fName.substring(dotPos+1);
//check if there is a _numeric at the end of the file name
if( name.lastIndexOf("_")==-1 ){
fName = name+"_1."+fileExt;
}
else{
int usPos = name.lastIndexOf("_");
def copyNumber = name.substring( usPos+1 )
if( copyNumber.isLong() ){
copyNumber = copyNumber.toLong()+1
name = name.substring(0,usPos)
fName = name+"_"+copyNumber+"."+fileExt;
}
else{
fName = name+"_1."+fileExt;
}
}
//if yes then extract, increment, append and rerun again until no conflicts
return createUniqueFileNameInFolder(fName,licenseKey,parentDirectoryId)
}
else{
return fileName;
}
}
Friday, May 7, 2010
Resolving filename conflict
In case i forget
Subscribe to:
Comments (Atom)