10) Create a File Renaming Policy. |
A renaming policy is used by Xload to initially rename files on the server when they are initially written to disk during an upload and NOT when copying or moving files. A rename policy can be as complex or as simple as you wish but must adhere to a few simple rules. This facility is very powerful as it allows a whole bespoke naming strategy to be implemented by the application. To implement a renaming policy you simply implement an interface called XloadFileRename. This interface has only one method, rename() which when implemented must adhere to a certain set of rules. The rename() method should:
1. Create an empty file on the file system based on some form of policy and the File object submitted as the argument to the rename() method.
2. Create the file in a thread safe and atomic manner (for example, when renaming a file you could be using statically stored resources requiring thread safe programming).
3. Only alter the file name (if altering is required at all).
4. Return a File object even if it could not be created. Any IOException that is thrown when renaming should be handled and ignored by the rename method, as Xload will handle the lack of an existing file itself.
Xload provides two, inbuilt, ready to use renaming policies. The default renaming policy, XloadIncrementalFileRename, that is used unless another renaming policy is specified using the appropriate XloadManager constructor, tries to create a file on the server using the files original (or 'remote') name. If a name clash occurs then (1) is added to the name and an attempt is made again. If this fails then (2) is added to the file name and the process is repeated until a unique name is found. The other type of renaming policy available, XloadCounterFileRename, renames every file deployment to an arbitrary number (e.g. 265637.jpg) and if that file name already exists within the directory, increments the number by one and repeats the process until a unique file name is found. Using this policy it is not guaranteed to produce a sequential numbering of files within a given directory.
A simple example is to rename a file by prefixing with a fixed string value. This example does not expect any name clashes to occur (as an example) but shows how to create a renaming policy.
import com.gubutech.xload.*; import java.io.*;
public class ExampleFileRename implements XloadFileRename{
public ExampleFileRename() { }
public File rename(File file){ String name = file.getName(); name = "name_prefix_" + name; File newFile = new File(file.getParent(), name); try{ newFile.createNewFile(); }catch(IOException e){ //do nothing here, let Xload handle this exception later } return newFile; } }
|
The appropriate XloadManager constructor is then used to insert a bespoke renaming policy.
XloadManager xman = new XloadManager(request, new ExampleFileRename());
|
© Gubutech(Xload) 2006 (v1.2)