/**
* OverEncrypt project hosted by Università degli Studi di Bergamo
* -> for PrimeLife project {@link http://www.primelife.eu/}
*/
package unibg.overencrypt.domain;
import java.io.File;
import java.util.Date;
import org.apache.log4j.Logger;
import unibg.overencrypt.core.User;
import unibg.overencrypt.server.ServerConfiguration;
import unibg.overencrypt.server.managers.SessionManager;
import unibg.overencrypt.utility.Utils;
import com.bradmcevoy.http.Auth;
import com.bradmcevoy.http.CollectionResource;
import com.bradmcevoy.http.LockInfo;
import com.bradmcevoy.http.LockResult;
import com.bradmcevoy.http.LockTimeout;
import com.bradmcevoy.http.LockToken;
import com.bradmcevoy.http.Request;
import com.bradmcevoy.http.Resource;
import com.bradmcevoy.http.Request.Method;
import com.bradmcevoy.http.exceptions.NotAuthorizedException;
import com.bradmcevoy.http.http11.auth.DigestResponse;
/**
* Manages the OverEncrypted resource.
*
* @author Flavio Giovarruscio & Riccardo Tribbia
* @version 1.0
*/
public abstract class OverEncryptedResource extends OverEncryptedAbstractResource {
/** Logger for this class. */
private static Logger LOGGER = Logger.getLogger(OverEncryptedResource.class);
/** The OverEncrypt factory. */
protected final OverEncryptResourceFactory factory;
/** The hostname of the client. */
protected final String host;
/** The is owner. */
protected boolean isOwner;
/** Verify is user is the owner of the resource. */
protected int ownerId;
/** The real file. */
protected File realFile;
/** The relative user path. */
protected String relativeUserPath;
/**
* Instantiates a new over encrypted resource.
*
* @param host the hostname of the client
* @param factory the OverEncrypt resource factory
* @param file the file
* @param ownerid the owner id
* @param isOwner true if user is the owner of the file
*/
public OverEncryptedResource(String host, OverEncryptResourceFactory factory, File file, int ownerid, boolean isOwner) {
this.host = host;
this.factory = factory;
this.realFile = file;
this.isOwner = isOwner;
//Cut webdav root path
String s = realFile.getAbsolutePath().replace(ServerConfiguration.getWebDAVrootPath(), "");
//extract only path after user id
if(!s.isEmpty()){
s = s.substring(1);
if(s.indexOf("/") != 0){
s = s.substring(s.indexOf("/") + 1);
}else{
s = "";
}
}
this.relativeUserPath = s;
LOGGER.debug("relative user path : "+ relativeUserPath);
//Retrieve owner user
if(ownerid == 0){
try{
this.ownerId = Utils.retrieveUserID(realFile.getAbsolutePath());
} catch (NumberFormatException e) {
LOGGER.error("Error when retrieving id from realFile.getAbsolutePath",e);
}
}
}
/**
* Gets the real file.
*
* @return the real file
*/
public File getRealFile(){
return this.realFile;
}
/* (non-Javadoc)
* @see com.bradmcevoy.http.MoveableResource#moveTo(com.bradmcevoy.http.CollectionResource, java.lang.String)
*/
public void moveTo(CollectionResource newParent, String newName) {
if (isOwner) {
if( newParent instanceof OverEncryptedFolderResource ) {
OverEncryptedFolderResource newFsParent = (OverEncryptedFolderResource) newParent;
File dest = new File(newFsParent.getRealFile(), newName);
boolean ok = this.realFile.renameTo(dest);
if( !ok ) throw new RuntimeException("Failed to move to: " + dest.getAbsolutePath());
this.realFile = dest;
} else {
throw new RuntimeException("Destination is an unknown type. Must be a OverEncryptFolderResource, is a: " + newParent.getClass());
}
}else{
throw new RuntimeException("Move this resource is not permitted because user isn't its owner.");
}
}
/**
* Gets the creation date.
*
* @return tthe creation date
*/
public Date getCreateDate() {
return null;
}
/* (non-Javadoc)
* @see com.bradmcevoy.http.CopyableResource#copyTo(com.bradmcevoy.http.CollectionResource, java.lang.String)
*/
public void copyTo(CollectionResource newParent, String newName) {
if (isOwner) {
if( newParent instanceof OverEncryptedFolderResource ) {
OverEncryptedFolderResource newFsParent = (OverEncryptedFolderResource) newParent;
File dest = new File(newFsParent.getRealFile(), newName);
doCopy(dest);
} else {
throw new RuntimeException("Destination is an unknown type. Must be a OverEncryptedFolderResource, is a: " + newParent.getClass());
}
}else{
throw new RuntimeException("Copy this resource is not permitted because user isn't its owner.");
}
}
/**
* Executes the copy of the resource.
*
* @param dest the destination of copy
*/
protected abstract void doCopy(File dest);
/**
* Deletes the resource.
*/
public void delete() {
if (isOwner) {
boolean ok = realFile.delete();
if( !ok ) throw new RuntimeException("Failed to delete");
}else{
throw new RuntimeException("Delete this resource is not permitted because user isn't its owner.");
}
}
/* (non-Javadoc)
* @see com.bradmcevoy.http.LockableResource#lock(com.bradmcevoy.http.LockTimeout, com.bradmcevoy.http.LockInfo)
*/
public LockResult lock(LockTimeout timeout, LockInfo lockInfo) throws NotAuthorizedException {
return factory.getLockManager().lock(timeout, lockInfo, this);
}
/* (non-Javadoc)
* @see com.bradmcevoy.http.LockableResource#refreshLock(java.lang.String)
*/
public LockResult refreshLock(String token) throws NotAuthorizedException {
return factory.getLockManager().refresh(token, this);
}
/* (non-Javadoc)
* @see com.bradmcevoy.http.LockableResource#unlock(java.lang.String)
*/
public void unlock(String tokenId) throws NotAuthorizedException {
factory.getLockManager().unlock(tokenId, this);
}
/* (non-Javadoc)
* @see com.bradmcevoy.http.LockableResource#getCurrentLock()
*/
public LockToken getCurrentLock() {
if( factory.getLockManager() != null ) {
return factory.getLockManager().getCurrentToken( this );
} else {
LOGGER.warn("getCurrentLock called, but no lock manager: file: " + realFile.getAbsolutePath());
return null;
}
}
/* (non-Javadoc)
* @see com.bradmcevoy.http.Resource#authenticate(java.lang.String, java.lang.String)
*/
public Object authenticate(String user, String password) {
LOGGER.debug("OVER ENCRYPTED RESOURCE - user: " + user + " psw: " + password);
int userId = Utils.retrieveUserID(realFile.getAbsolutePath());
LOGGER.debug("OVER ENCRYPTED RESOURCE - userID: " + userId);
if(SessionManager.isAlreadyInSession(String.valueOf(userId))) {
LOGGER.debug("OVER ENCRYPTED RESOURCE - is already in session");
return user;
} else {
LOGGER.debug("OVER ENCRYPTED RESOURCE - 12131");
return factory.getSecurityManager().authenticate(user, password);
}
}
/* (non-Javadoc)
* @see com.bradmcevoy.http.DigestResource#authenticate(com.bradmcevoy.http.http11.auth.DigestResponse)
*/
public Object authenticate( DigestResponse digestRequest ) {
LOGGER.debug("OVER ENCRYPTED RESOURCE - DIGEST ");
int userId = Utils.retrieveUserID(realFile.getAbsolutePath());
if(SessionManager.isAlreadyInSession(String.valueOf(userId))){
return digestRequest;
} else {
return factory.getSecurityManager().authenticate(digestRequest);
}
}
/**
* Checks if is digest allowed.
*
* @return true, if is digest allowed
*/
public boolean isDigestAllowed() {
return true;
}
/* (non-Javadoc)
* @see com.bradmcevoy.http.Resource#authorise(com.bradmcevoy.http.Request, com.bradmcevoy.http.Request.Method, com.bradmcevoy.http.Auth)
*/
public boolean authorise(Request request, Method method, Auth auth) {
if(Utils.retrieveUserID(realFile.getAbsolutePath()) != 0) return true;
else return factory.getSecurityManager().authorise(request, method, auth, this);
}
/* (non-Javadoc)
* @see com.bradmcevoy.http.Resource#checkRedirect(com.bradmcevoy.http.Request)
*/
@Override
public String checkRedirect(Request arg0) {
LOGGER.debug("CHECK REDIRECT CALLED");
return null;
}
/* (non-Javadoc)
* @see com.bradmcevoy.http.Resource#getModifiedDate()
*/
@Override
public Date getModifiedDate() {
return new Date(realFile.lastModified());
}
/* (non-Javadoc)
* @see com.bradmcevoy.http.Resource#getName()
*/
@Override
public String getName() {
String name = realFile.getName();
if(realFile.getAbsolutePath().equals(factory.root.getAbsolutePath())){
int userID = Utils.retrieveUserID(realFile.getAbsolutePath());
User loggedUser = new User(String.valueOf(userID));
name = loggedUser.getName() + " " + loggedUser.getSurname() + "'s OverEncrypted root folder";
}
return name;
}
/* (non-Javadoc)
* @see com.bradmcevoy.http.Resource#getRealm()
*/
@Override
public String getRealm() {
return ServerConfiguration.getREALM();
}
/* (non-Javadoc)
* @see com.bradmcevoy.http.Resource#getUniqueId()
*/
@Override
public String getUniqueId() {
String s = realFile.lastModified() + "_" + realFile.length();
return s.hashCode() + "";
}
/**
* Compares two resources.
*
* @param o the resource to be compared
* @return the value 0 if the argument resource is equal to this resource; a value less than 0 if this resource is lexicographically less than the resource argument; and a value greater than 0 if this resource is lexicographically greater than the resource argument.
*/
public int compareTo(Resource o) {
return this.getName().compareTo(o.getName());
}
}