/**
* OverEncrypt project hosted by Università degli Studi di Bergamo
* -> for PrimeLife project {@link http://www.primelife.eu/}
*/
package unibg.overencrypt.utility;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import unibg.overencrypt.protocol.TokenStruct;
import unibg.overencrypt.server.ServerConfiguration;
import unibg.overencrypt.server.managers.SessionManager;
/**
* Class that allows to simply manage all .tokens files.
* Can create a reference to this abstract (WebDAV) files with constructor,
* can save new token and retrieve token informations through folder name.
*
* @author Flavio Giovarruscio & Riccardo Tribbia
* @version 1.0
* @see TokenStruct
*/
public class TokensResource {
/** Logger for this class. */
private static final Logger LOGGER = Logger.getLogger(TokensResource.class);
/** Private field that identifies xml document. */
private Document xmlDocument;
/** Private field that identifies File object. */
public File tokensFile = null;
/**
* Build a TokenResource from URI .tokens file's parent.
*
* @param parentPath path of the parent folder of .tokens file
*/
public TokensResource(String parentPath){
//Root element
Element rootEl = new Element("Tokens");
LOGGER.debug(".tokens path: " + parentPath);
tokensFile = new File(parentPath + "/.tokens");
if(tokensFile != null && tokensFile.exists()){
SAXBuilder sb = new SAXBuilder();
try {
this.xmlDocument = sb.build(tokensFile);
} catch (JDOMException e) {
LOGGER.error("JDOM error while building tokens from xml .tokens file",e);
} catch (IOException e) {
LOGGER.error("IO error while building tokens from xml .tokens file",e);
}
}else{
this.xmlDocument = new Document(rootEl);
}
}
/**
* Return TokenStruct from xml .tokens
*
* @param folderName the folder name of .tokens file
* @return data structure of token
*/
public TokenStruct getTokens(String folderName){
TokenStruct token = null;
Element root = xmlDocument.getRootElement();
@SuppressWarnings("unchecked")
List<Element> children = root.getChildren("Folder");
if( children != null){
for (Iterator<Element> iterator = children.iterator(); iterator.hasNext();) {
Element element = (Element) iterator.next();
if(element.getChildText("folderName").equals(folderName)){
token = new TokenStruct();
token.folderIdDB = element.getChildText("folderIdDB");
token.folderIdGraph = element.getChildText("folderIdGraph");
token.folderName = element.getChildText("folderName");
token.ownerID = element.getChildText("ownerID");
token.cryptedAclBEL = element.getChildText("cryptedAclBEL");
token.cryptedAclSEL = element.getChildText("cryptedAclSEL");
token.hasSEL = Boolean.parseBoolean(element.getChildText("hasSEL"));
}
}
}
return token;
}
public static String getLockedPath(String tokensPath, HashMap<String, Integer> lockMap, String ownerOfSharedFolder){
String pathToReturn = "";
File tempTokensFile = new File(tokensPath);
LOGGER.debug("temp tokens file path: " + tempTokensFile.getPath());
//Se la cartella padre del file .tokens che si sta considerando è la root del server, allora
//devo ciclare tutte le folder degli utenti connessi
if (tempTokensFile.getParent().equals(ServerConfiguration.getWebDAVrootPath())) {
LOGGER.debug("Il token considerato ha come parent path la root del server");
//Ciclo tutte le cartelle di tutti gli utenti connessi
Set<String> usersIdInSession = SessionManager.getIdInSession();
boolean pathFound = false;
for (Iterator<String> iterator1 = usersIdInSession.iterator(); iterator1.hasNext();) {
String user = (String) iterator1.next();
File file = new File(ServerConfiguration.getWebDAVrootPath() + "/" + user);
if (lockMap.containsValue(Integer.parseInt(file.getName()))) {
LOGGER.debug("La lock map contiene almeno un record dell'utente la cui root è quella presa in considerazione (" + file.getName() + ")");
//Se la mappa che contiene le path in stato di lock ne contiene almeno una
//relativa all'utente la quale root è quella presa in considerazione
//cerco se ha eseguito un lock su una (o più) subfolder della propria root folder.
Set<String> lockedPaths = lockMap.keySet();
for (Iterator<String> iterator = lockedPaths.iterator(); iterator
.hasNext();) {
String lockedPath = (String) iterator.next();
if (lockMap.get(lockedPath) == Integer.parseInt(file.getName())) {
LOGGER.debug("La map contiene questa path locked relativa all'utente: " + lockedPath);
File temp = new File(lockedPath);
if (temp.getParent().equals(ServerConfiguration.getWebDAVrootPath() + "/" + file.getName())) {
TokensResource tokenResource = new TokensResource(file.getPath());
LOGGER.debug("il token che ora vado a controllare ha path: " + file.getPath() + "/.tokens");
TokenStruct token = tokenResource.getTokens(temp.getName());
if (token != null) {
pathToReturn = ServerConfiguration.getWebDAVrootPath() + "/" + file.getName() + "/.tokens";
LOGGER.debug("Ci siamo - la path che ritorna è: " + pathToReturn);
pathFound = true;
break;
}
}
}
}
}
}
if (!pathFound) {
LOGGER.error("path non trovata.. ERRORE");
}
}else{
LOGGER.debug("Il token considerato NON ha come parent path la root del server");
//Ciclo tutte le path lockate
Set<String> pathsLocked = lockMap.keySet();
for (Iterator<String> iterator = pathsLocked.iterator(); iterator.hasNext();) {
String pathLocked = (String) iterator.next();
//Estrapolo l'utente proprietario della path locked
LOGGER.debug("path Locked: " + pathLocked);
if (pathLocked.length() < 1) {
break;
}
String ownerIdFromPathLocked = pathLocked.replace(ServerConfiguration.getWebDAVrootPath() + "/", "");
ownerIdFromPathLocked = ownerIdFromPathLocked.substring(0, ownerIdFromPathLocked.indexOf("/"));
LOGGER.debug("ownerIdFromPathLocked: " + ownerIdFromPathLocked);
//Ricompongo la path del file .tokens con questo user id
String newTokensPath = "";
if (ownerOfSharedFolder == null) {
newTokensPath = tokensPath.replace(ServerConfiguration.getWebDAVrootPath() + "/", "");
newTokensPath = ServerConfiguration.getWebDAVrootPath() + "/" + ownerIdFromPathLocked + "/" + newTokensPath;
}else{
newTokensPath = tokensPath.replace(ServerConfiguration.getWebDAVrootPath() + "/" + ownerIdFromPathLocked + "/", "");
newTokensPath = ServerConfiguration.getWebDAVrootPath() + "/" + ownerIdFromPathLocked + "/" + newTokensPath;
}
LOGGER.debug("new Tokens path: " + newTokensPath);
File tokens = new File(newTokensPath);
File locked = new File(pathLocked);
//Se la cartella che contiene il file .tokens è cartella padre del percorso salvato
//nella mappa dei percorsi locked
if (locked.getParent().equals(tokens.getParent())) {
LOGGER.debug("locked.getParent().equals(tokens.getParent()): TRUE");
//Controllo se esiste effettivamente
if (locked.getParentFile().exists() && tokens.exists()) {
if (ownerOfSharedFolder == null) {
LOGGER.debug("SIAMO IN UNA CARTELLA SHARED");
pathToReturn = ServerConfiguration.getWebDAVrootPath() + "/" + ownerIdFromPathLocked + "/";
String relativePath = tokens.getPath().replace(ServerConfiguration.getWebDAVrootPath() + "/" + ownerIdFromPathLocked + "/", "");
pathToReturn = pathToReturn + "/Shared/" + ownerOfSharedFolder + "/" + relativePath;
}else{
pathToReturn = tokensPath;
}
LOGGER.debug("Path to return: " + pathToReturn);
}
}
}
}
LOGGER.debug("path returned: " + pathToReturn);
return pathToReturn;
}
}