net.sf.gluebooster.java.booster.basic.resources.FileResourceSystem Maven / Gradle / Ivy
package net.sf.gluebooster.java.booster.basic.resources;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import net.sf.gluebooster.java.booster.essentials.container.ResourceSystem;
import net.sf.gluebooster.java.booster.essentials.utils.Check;
/**
* A resource system using the file system.
*
* @author CBauer
*
*/
public class FileResourceSystem implements ResourceSystem {
/**
* If this file is set, all relative paths are relative to this directory
*/
private File rootDirectory = null;
public FileResourceSystem() {
}
public FileResourceSystem(File rootDirectory) {
this.rootDirectory = rootDirectory;
}
@Override
public OutputStream getOutputStream(Object resourceID) throws Exception {
File file = asFile( resourceID);
file.getParentFile().mkdirs(); //to prevent exceptions if no parent exists
return new FileOutputStream(file);
}
@Override
public InputStream getInputStream(Object resourceID) throws Exception {
File file = asFile( resourceID);
return new FileInputStream(file);
}
/**
* Convert a to a file.
*
* @param resourceID
* must be a file or a filename
* @return the converted id
*/
private File asFile(Object resourceID){
File result;
if (resourceID == null) {
result = null;
} else if (resourceID instanceof File) {
result = (File) resourceID;
} else {
result = new File(resourceID.toString());
}
if (result != null && rootDirectory != null) {
if (!result.toString().startsWith(rootDirectory.toString())) {
result = new File(rootDirectory, result.toString());
}
}
return result;
}
/**
* Supported are File and String.
*/
@Override
public boolean isResourceIDSupported(Object resourceID) {
return resourceID instanceof File || resourceID instanceof String;
}
@Override
public URL getUrl(Object resourceID)throws Exception{
return asFile(resourceID).toURL();
}
@Override
public boolean isWritable() {
return true;
}
@Override
public Object createDirectory(Object parentResourceId, Object newResourceId)
throws Exception {
Check.notNull(newResourceId, "newResourceId");
File result = null;
File parentFile = null;
if (parentResourceId != null) {
parentFile = asFile(parentResourceId);
if (newResourceId instanceof String)
if (parentFile != null)
result = new File(parentFile, (String) newResourceId);
else
result = new File((String) newResourceId);
} else {
result = asFile(newResourceId);
}
result.mkdirs();
return result;
}
}