Merge with 2ad3c504ee5d73982c0ef23336276dc1fc9e165f
[pithos] / src / gr / ebs / gss / server / ejb / ExternalAPIBean.java
index fd2c57c..88059a0 100644 (file)
@@ -19,6 +19,8 @@
 package gr.ebs.gss.server.ejb;
 
 import static gr.ebs.gss.server.configuration.GSSConfigurationFactory.getConfiguration;
+
+import gr.ebs.gss.admin.client.ui.UsersTable;
 import gr.ebs.gss.client.exceptions.DuplicateNameException;
 import gr.ebs.gss.client.exceptions.GSSIOException;
 import gr.ebs.gss.client.exceptions.InsufficientPermissionsException;
@@ -32,11 +34,14 @@ import gr.ebs.gss.server.domain.FileTag;
 import gr.ebs.gss.server.domain.FileUploadStatus;
 import gr.ebs.gss.server.domain.Folder;
 import gr.ebs.gss.server.domain.Group;
+import gr.ebs.gss.server.domain.FileLock;
 import gr.ebs.gss.server.domain.Invitation;
 import gr.ebs.gss.server.domain.Nonce;
 import gr.ebs.gss.server.domain.Permission;
 import gr.ebs.gss.server.domain.User;
 import gr.ebs.gss.server.domain.UserClass;
+import gr.ebs.gss.server.domain.UserLogin;
+import gr.ebs.gss.server.domain.WebDavNonce;
 import gr.ebs.gss.server.domain.dto.StatsDTO;
 import gr.ebs.gss.server.domain.dto.UserDTO;
 
@@ -146,6 +151,12 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                }
        }
 
+       private Long getRootFolderId(Long userId) throws ObjectNotFoundException {
+               if (userId == null)
+                       throw new ObjectNotFoundException("No user specified");
+               return dao.getRootFolderId(userId);
+       }
+       
        @Override
        public Folder getRootFolder(Long userId) throws ObjectNotFoundException {
                if (userId == null)
@@ -165,7 +176,7 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                // Check permissions
                if (!folder.hasReadPermission(user))
                        throw new InsufficientPermissionsException("You don't have the permissions to read this folder");
-               return folder;
+               return expandFolder(folder);
        }
 
        @Override
@@ -424,9 +435,21 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                folder.getAuditInfo().setModifiedBy(user);
                dao.update(folder);
                touchParentFolders(folder, user, new Date());
+               // Re-index the folder contents if it was modified.
+               if ((permissions != null && !permissions.isEmpty()) || readForAll != null) {
+            indexFolder(folder);
+        }
+
                return folder;
        }
 
+    private void indexFolder(Folder folder) {
+        for (FileHeader fh : folder.getFiles())
+            indexFile(fh.getId(), false);
+        for (Folder f : folder.getSubfolders())
+            indexFolder(f);
+    }
+
        @Override
        public void createGroup(final Long userId, final String name) throws ObjectNotFoundException, DuplicateNameException {
                // Validate.
@@ -464,16 +487,13 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                        List<Folder> folders = dao.getFoldersPermittedForGroup(userId, groupId);
                        for (Folder f : folders){
                                f.getPermissions().removeAll(group.getPermissions());
-                               touchFolder(f, owner, now);
                                for(FileHeader file : f.getFiles()){
                                        file.getPermissions().removeAll(group.getPermissions());
-                                       touchFile(file, owner, now);
                                }
                        }
                        List<FileHeader> files = dao.getFilesPermittedForGroup(userId, groupId);
                        for(FileHeader h : files){
                                h.getPermissions().removeAll(group.getPermissions());
-                               touchFile(h, owner, now);
                        }
                        owner.removeSpecifiedGroup(group);
                        dao.delete(group);
@@ -700,7 +720,7 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                touchParentFolders(parent, user, new Date());
 
                // Re-index the file if it was modified.
-               if (name != null || tagSet != null)
+               if (name != null || tagSet != null || (permissions != null && !permissions.isEmpty()) || readForAll != null)
                        indexFile(fileId, false);
        }
 
@@ -801,10 +821,12 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                        return getRootFolder(owner.getId());
                // Store the last element, since it requires special handling.
                String lastElement = pathElements.remove(pathElements.size() - 1);
-               Folder cursor = getRootFolder(owner.getId());
+               
+               Folder cursor = null;
+               Long rootFolderId = getRootFolderId(owner.getId());
                // Traverse and verify the specified folder path.
                for (String pathElement : pathElements) {
-                       cursor = getFolder(cursor.getId(), pathElement);
+                       cursor = getFolder(cursor==null ? rootFolderId : cursor.getId(), pathElement);
                        if (cursor.isDeleted())
                                throw new ObjectNotFoundException("Folder " + cursor.getPath() + " not found");
                }
@@ -812,18 +834,17 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                // Use the lastElement to retrieve the actual resource.
                Object resource = null;
                try {
-                       FileHeader file = getFile(cursor.getId(), lastElement);
+                       FileHeader file = getFile(cursor==null ? rootFolderId : cursor.getId(), lastElement);
                        if (ignoreDeleted && file.isDeleted())
                                throw new ObjectNotFoundException("Resource not found");
                        resource = file;
                } catch (ObjectNotFoundException e) {
                        // Perhaps the requested resource is not a file, so
                        // check for folders as well.
-                       Folder folder = getFolder(cursor.getId(), lastElement);
+                       Folder folder = getFolder(cursor==null ? rootFolderId : cursor.getId(), lastElement);
                        if (ignoreDeleted && folder.isDeleted())
                                throw new ObjectNotFoundException("Resource not found");
                        resource = folder;
-                       
                }
                return resource;
        }
@@ -1107,14 +1128,17 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                if (parent == null)
                        throw new ObjectNotFoundException("The specified file has no parent folder");
                User user = dao.getEntityById(User.class, userId);
-               if (!file.hasDeletePermission(user))
-                       throw new InsufficientPermissionsException("User " + user.getId() + " cannot delete file " + file.getName() + "(" + file.getId() + ")");
-
-               file.setDeleted(true);
-               dao.update(file);
-               touchParentFolders(parent, user, new Date());
+        trashFile(user, file);
+        touchParentFolders(parent, user, new Date());
        }
 
+    private void trashFile(User user, FileHeader file) throws InsufficientPermissionsException {
+        if (!file.hasDeletePermission(user))
+            throw new InsufficientPermissionsException("User " + user.getId() + " cannot delete file " + file.getName() + "(" + file.getId() + ")");
+
+        file.setDeleted(true);
+    }
+
        @Override
        public void moveFileToPath(Long userId, Long ownerId, Long fileId, String dest) throws ObjectNotFoundException, InsufficientPermissionsException, QuotaExceededException {
                if (userId == null)
@@ -1282,34 +1306,39 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                if (parent == null)
                        throw new ObjectNotFoundException("The specified file has no parent folder");
                User user = dao.getEntityById(User.class, userId);
-               if (!file.hasDeletePermission(user))
-                       throw new InsufficientPermissionsException("User " + user.getUsername() +
-                                               " cannot restore file " + file.getName());
-
-               file.setDeleted(false);
-               dao.update(file);
+        untrashFile(user, file);
                touchParentFolders(parent, user, new Date());
        }
 
+    private void untrashFile(User user, FileHeader file) throws InsufficientPermissionsException {
+        if (!file.hasDeletePermission(user))
+            throw new InsufficientPermissionsException("User " + user.getUsername() +
+                        " cannot restore file " + file.getName());
+
+        file.setDeleted(false);
+    }
+
        @Override
        public void moveFolderToTrash(Long userId, Long folderId) throws ObjectNotFoundException, InsufficientPermissionsException {
-               if (userId == null)
-                       throw new ObjectNotFoundException("No user specified");
-               if (folderId == null)
-                       throw new ObjectNotFoundException("No folder specified");
-               Folder folder = dao.getEntityById(Folder.class, folderId);
-               User user = dao.getEntityById(User.class, userId);
-               if (!folder.hasDeletePermission(user))
-                       throw new InsufficientPermissionsException("You don't have the necessary permissions");
-               folder.setDeleted(true);
-               dao.update(folder);
-               touchParentFolders(folder, user, new Date());
-               for (FileHeader file : folder.getFiles())
-                       moveFileToTrash(userId, file.getId());
-               for (Folder subFolder : folder.getSubfolders())
-                       moveFolderToTrash(userId, subFolder.getId());
-
-       }
+        if (userId == null)
+            throw new ObjectNotFoundException("No user specified");
+        if (folderId == null)
+            throw new ObjectNotFoundException("No folder specified");
+        Folder folder = dao.getEntityById(Folder.class, folderId);
+        User user = dao.getEntityById(User.class, userId);
+        trashFolder(user, folder);
+        touchParentFolders(folder, user, new Date());
+       }
+
+    private void trashFolder(User user, Folder folder) throws ObjectNotFoundException, InsufficientPermissionsException {
+        if (!folder.hasDeletePermission(user))
+            throw new InsufficientPermissionsException("You don't have the necessary permissions");
+        folder.setDeleted(true);
+        for (FileHeader file : folder.getFiles())
+            trashFile(user, file);
+        for (Folder subFolder : folder.getSubfolders())
+            trashFolder(user, subFolder);
+    }
 
        @Override
        public void removeFolderFromTrash(Long userId, Long folderId)
@@ -1320,18 +1349,21 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                        throw new ObjectNotFoundException("No folder specified");
                Folder folder = dao.getEntityById(Folder.class, folderId);
                User user = dao.getEntityById(User.class, userId);
-               if (!folder.hasDeletePermission(user))
-                       throw new InsufficientPermissionsException("User " + user.getUsername() +
-                                               " cannot restore folder " + folder.getName());
-               folder.setDeleted(false);
-               for (FileHeader file : folder.getFiles())
-                       removeFileFromTrash(userId, file.getId());
-               for (Folder subFolder : folder.getSubfolders())
-                       removeFolderFromTrash(userId, subFolder.getId());
-               dao.update(folder);
+        untrashFolder(user, folder);
                touchParentFolders(folder, user, new Date());
        }
 
+    private void untrashFolder(User user, Folder folder) throws ObjectNotFoundException, InsufficientPermissionsException {
+        if (!folder.hasDeletePermission(user))
+            throw new InsufficientPermissionsException("User " + user.getUsername() +
+                        " cannot restore folder " + folder.getName());
+        folder.setDeleted(false);
+        for (FileHeader file : folder.getFiles())
+            untrashFile(user, file);
+        for (Folder subFolder : folder.getSubfolders())
+            untrashFolder(user, subFolder);
+    }
+
        @Override
        public List<Folder> getDeletedRootFolders(Long userId) throws ObjectNotFoundException {
                List<Folder> folders = dao.getDeletedRootFolders(userId);
@@ -1775,7 +1807,20 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                List<FileHeader> result = new ArrayList<FileHeader>();
                try {
                        CommonsHttpSolrServer solr = new CommonsHttpSolrServer(getConfiguration().getString("solr.url"));
-                       SolrQuery solrQuery = new SolrQuery(escapeCharacters(normalizeSearchQuery(query)));
+            List<Group> groups = dao.getGroupsContainingUser(userId);
+            String constructedQuery = escapeCharacters(normalizeSearchQuery(query)) + " AND (public: true OR ureaders: " + userId;
+            if (!groups.isEmpty()) {
+                constructedQuery += " OR (";
+                for (int i=0; i<groups.size(); i++) {
+                    Group g = groups.get(i);
+                    constructedQuery += "greaders :" + g.getId();
+                    if (i < groups.size() - 1)
+                        constructedQuery += " OR ";
+                }
+                constructedQuery += ")";
+            }
+            constructedQuery += ")";
+                       SolrQuery solrQuery = new SolrQuery(constructedQuery);
             solrQuery.setRows(maxRows);
             long startTime = System.currentTimeMillis();
                        QueryResponse response = solr.query(solrQuery);
@@ -1793,14 +1838,13 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                                Long id = Long.valueOf((String) d.getFieldValue("id"));
                                try {
                                        FileHeader f = dao.getEntityById(FileHeader.class, id);
-                                       if (f.hasReadPermission(user))
-                                               result.add(f);
+                                       result.add(f);
                                } catch (ObjectNotFoundException e) {
                                        logger.warn("Search result id " + id + " cannot be found", e);
                                }
                        }
             stopTime = System.currentTimeMillis();
-            logger.info("Permission checks: " + (stopTime - startTime));
+            logger.info("File loads: " + (stopTime - startTime));
                } catch (MalformedURLException e) {
                        logger.error(e);
                        throw new EJBException(e);
@@ -1834,52 +1878,6 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
        }
 
        @Override
-       public void deleteFiles(Long userId, List<Long> fileIds) throws ObjectNotFoundException, InsufficientPermissionsException {
-               if (userId == null)
-                       throw new ObjectNotFoundException("No user specified");
-               final User user = dao.getEntityById(User.class, userId);
-               List<String> filesToRemove = new ArrayList<String>();
-               //first delete database objects
-               for(Long fileId : fileIds){
-                       if (fileId == null)
-                               throw new ObjectNotFoundException("No file specified");
-                       final FileHeader file = dao.getEntityById(FileHeader.class, fileId);
-                       final Folder parent = file.getFolder();
-                       if (parent == null)
-                               throw new ObjectNotFoundException("The specified file has no parent folder");
-                       if (!file.hasDeletePermission(user))
-                               throw new InsufficientPermissionsException("User " + user.getId() + " cannot delete file " + file.getName() + "(" + file.getId() + ")");
-
-                       parent.removeFile(file);
-                       for (final FileBody body : file.getBodies())
-                               filesToRemove.add(body.getStoredFilePath());
-                       dao.delete(file);
-                       touchParentFolders(parent, user, new Date());
-               }
-               //then remove physical files if everything is ok
-               for(String physicalFileName : filesToRemove)
-                       deleteActualFile(physicalFileName);
-               //then unindex deleted files
-               for(Long fileId : fileIds)
-                       indexFile(fileId, true);
-
-       }
-
-       @Override
-       public void moveFilesToTrash(Long userId, List<Long> fileIds) throws ObjectNotFoundException, InsufficientPermissionsException {
-               for(Long l : fileIds)
-                       moveFileToTrash(userId, l);
-
-       }
-
-       @Override
-       public void removeFilesFromTrash(Long userId, List<Long> fileIds) throws ObjectNotFoundException, InsufficientPermissionsException {
-               for(Long l : fileIds)
-                       removeFileFromTrash(userId, l);
-
-       }
-
-       @Override
        public Nonce createNonce(Long userId) throws ObjectNotFoundException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
@@ -1930,35 +1928,6 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
        }
 
        @Override
-       public void removeVersion(Long userId, Long fileId, Long bodyId) throws ObjectNotFoundException, InsufficientPermissionsException {
-               if (userId == null)
-                       throw new ObjectNotFoundException("No user specified");
-               if (fileId == null)
-                       throw new ObjectNotFoundException("No file specified");
-               if (bodyId == null)
-                       throw new ObjectNotFoundException("No body specified");
-               User user = dao.getEntityById(User.class, userId);
-               FileHeader header = dao.getEntityById(FileHeader.class, fileId);
-               if(!header.hasWritePermission(user))
-                       throw new InsufficientPermissionsException("You don't have the necessary permissions");
-               FileBody body = dao.getEntityById(FileBody.class, bodyId);
-               if(body.equals(header.getCurrentBody())){
-
-                       if(header.getBodies().size() == 1)
-                               throw new InsufficientPermissionsException("You cant delete this version, Delete file instead!");
-                       for(FileBody b : header.getBodies())
-                               if(b.getVersion() == body.getVersion()-1)
-                                       header.setCurrentBody(b);
-               }
-               deleteActualFile(body.getStoredFilePath());
-               header.getBodies().remove(body);
-
-               Folder parent = header.getFolder();
-               touchParentFolders(parent, user, new Date());
-
-       }
-
-       @Override
        public void restoreVersion(Long userId, Long fileId, int version) throws ObjectNotFoundException, InsufficientPermissionsException,  GSSIOException, QuotaExceededException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
@@ -2041,7 +2010,7 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                        for (Long id : fileIds) {
                                postFileToSolr(solr, id);
                 i++;
-                if (i % 100 == 0) {
+                if (i % 10 == 0) {
                     solr.commit();
                     logger.info("Sent commit to solr at file " + i);
                 }
@@ -2070,9 +2039,9 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                                postFileToSolr(solr, id);
                 i++;
                        }
-            if (i % 100 == 0) {
+            if (i % 10 == 0) {
                 solr.commit();
-                logger.debug("Sent commit to solr at file " + i);
+                logger.info("Sent commit to solr at file " + i);
             }
                        solr.optimize();
                        solr.commit();
@@ -2467,26 +2436,6 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
        }
 
        /**
-        * Mark the folder as modified from the specified user and change it's modification date.
-        */
-       private void touchFolder(Folder f, User _user, Date now){
-               final AuditInfo auditInfo = f.getAuditInfo();
-               auditInfo.setModificationDate(now);
-               auditInfo.setModifiedBy(_user);
-               f.setAuditInfo(auditInfo);
-       }
-
-       /**
-        * Mark the file as modified from the specified user and change it's modification date.
-        */
-       private void touchFile(FileHeader f, User _user, Date now){
-               final AuditInfo auditInfo = f.getAuditInfo();
-               auditInfo.setModificationDate(now);
-               auditInfo.setModifiedBy(_user);
-               f.setAuditInfo(auditInfo);
-       }
-
-       /**
         * Set the provided readForAll as the new readforAll value of the specified
         * folder and sub-folders.
         *
@@ -2510,6 +2459,35 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                }
 
        }
+               
+       /**
+        * Update the userLogin with the values from the supplied object.
+        */
+       
+       public void addUserLogin(UserLogin userLogin) {
+               dao.update(userLogin);          
+
+       }
+               
+       /**
+        * Retrieves the current session user login and the user's last login
+        * 
+        * @param userId
+        * @return a list of last two user logins
+        * @throws ObjectNotFoundException 
+        */
+       
+       public List<UserLogin> getLastUserLogins(Long userId) throws ObjectNotFoundException{
+               List<UserLogin> userLoginResults = new ArrayList<UserLogin>();          
+               userLoginResults = dao.getLoginsForUser(userId);        
+               if(userLoginResults.size() == 0)
+                       throw new ObjectNotFoundException("No userlogin found for the user");
+               //if the user logins for the first time lastLoginDate = currentLoginDate
+               if(userLoginResults.size()==1)
+                       userLoginResults.add(userLoginResults.get(0));
+               return userLoginResults;
+       }
+       
 
        @Override
        public void postFileToSolr(CommonsHttpSolrServer solr, Long id) {
@@ -2536,24 +2514,33 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                                for (FileTag t : file.getFileTags()) {
                                        solrRequest.getParams().add("literal.tag", t.getTag());
                                }
+                for (Permission p : file.getPermissions()) {
+                    if (p.getRead()) {
+                        if (p.getUser() != null)
+                            solrRequest.getParams().add("literal.ureaders", p.getUser().getId().toString());
+                        else if (p.getGroup() != null)
+                            solrRequest.getParams().add("literal.greaders", p.getGroup().getId().toString());
+                    }
+                }
+                solrRequest.setParam("literal.owner", file.getOwner().getId().toString());
+                solrRequest.setParam("literal.public", String.valueOf(file.isReadForAll()));
                 File fsFile = new File(body.getStoredFilePath());
                                solrRequest.addFile(fsFile);
-//                             solrRequest.setAction(AbstractUpdateRequest.ACTION.COMMIT, true, true);
                                try {
                                        solr.request(solrRequest);
                                }
                                catch (SolrException e) {
-                                       logger.warn("File " + id + " failed with " + e.getLocalizedMessage() + ". Retrying without the file");
+                                       logger.warn("File " + id + " failed with SolrException: " + e.getLocalizedMessage() + ". Retrying without the file");
                                        //Let 's try without the file
                                        sendMetaDataOnly(solr, file);
                                }
                                catch (NullPointerException e) {
-                                       logger.warn("File " + id + " failed with " + e.getLocalizedMessage() + ". Retrying without the file");
+                                       logger.warn("File " + id + " failed with NullPointerException: " + e.getLocalizedMessage() + ". Retrying without the file");
                                        //Let 's try without the file
                                        sendMetaDataOnly(solr, file);
                                }
                                catch (SolrServerException e) {
-                                       logger.warn("File " + id + " failed with " + e.getLocalizedMessage() + ". Retrying without the file");
+                                       logger.warn("File " + id + " failed with SolrServerException: " + e.getLocalizedMessage() + ". Retrying without the file");
                                        //Let 's try without the file
                                        sendMetaDataOnly(solr, file);
                                }
@@ -2576,6 +2563,16 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                for (FileTag t : file.getFileTags()) {
                        solrDoc.addField("tag", t.getTag());
                }
+        for (Permission p : file.getPermissions()) {
+            if (p.getRead()) {
+                if (p.getUser() != null)
+                    solrDoc.addField("ureaders", p.getUser().getId());
+                else if (p.getGroup() != null)
+                    solrDoc.addField("greaders", p.getGroup().getId());
+            }
+        }
+        solrDoc.addField("owner", file.getOwner().getId());
+        solrDoc.addField("public", file.isReadForAll());
                solr.add(solrDoc);
        }
 
@@ -2611,8 +2608,8 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                result.getFiles().size();
                result.getPermissions().size();
                return result;
-       }
-       
+}
+
        @Override
        public FileHeader expandFile(FileHeader folder) throws ObjectNotFoundException{
                FileHeader result = dao.getEntityById(FileHeader.class, folder.getId());
@@ -2628,4 +2625,168 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                result.getMembers().size();
                return result;
        }
+
+       /* (non-Javadoc)
+        * @see gr.ebs.gss.server.ejb.ExternalAPI#getUsersByUserNameLike(java.lang.String)
+        */
+       @Override
+       public User getUserByUserName(String username) {
+               User result = dao.getUserByUserName(username);
+               return result;
+       }
+       
+       /*WEBDAV CREATE EMPTY FILE*/
+       @Override
+       public FileHeader createEmptyFile(Long userId, Long folderId, String name)
+                       throws DuplicateNameException, ObjectNotFoundException, GSSIOException,
+                       InsufficientPermissionsException, QuotaExceededException {
+               // Validate.
+               if (userId == null)
+                       throw new ObjectNotFoundException("No user specified");
+               if (folderId == null)
+                       throw new ObjectNotFoundException("No folder specified");
+               String contentType = DEFAULT_MIME_TYPE;
+               if (StringUtils.isEmpty(name))
+                       throw new ObjectNotFoundException("No file name specified");
+               if (dao.existsFolderOrFile(folderId, name))
+                       throw new DuplicateNameException("A folder or file with the name '" + name +
+                                               "' already exists at this level");
+
+               // Do the actual work.
+               Folder parent = null;
+               try {
+                       parent = dao.getEntityById(Folder.class, folderId);
+               } catch (final ObjectNotFoundException onfe) {
+                       // Supply a more accurate problem description.
+                       throw new ObjectNotFoundException("Parent folder not found");
+               }
+               final User owner = dao.getEntityById(User.class, userId);
+               if (!parent.hasWritePermission(owner))
+                       throw new InsufficientPermissionsException("You don't have the permissions to write to this folder");
+               final FileHeader file = new FileHeader();
+               file.setName(name);
+               parent.addFile(file);
+               // set file owner to folder owner
+               file.setOwner(parent.getOwner());
+               //set file's readForAll value according to parent folder readForAll value
+               file.setReadForAll(parent.isReadForAll());
+
+               final Date now = new Date();
+               final AuditInfo auditInfo = new AuditInfo();
+               auditInfo.setCreatedBy(owner);
+               auditInfo.setCreationDate(now);
+               auditInfo.setModifiedBy(owner);
+               auditInfo.setModificationDate(now);
+               file.setAuditInfo(auditInfo);
+               // TODO set the proper versioning flag on creation
+               file.setVersioned(false);
+
+               for (final Permission p : parent.getPermissions()) {
+                       final Permission permission = new Permission();
+                       permission.setGroup(p.getGroup());
+                       permission.setUser(p.getUser());
+                       permission.setRead(p.getRead());
+                       permission.setWrite(p.getWrite());
+                       permission.setModifyACL(p.getModifyACL());
+                       file.addPermission(permission);
+               }
+               // Create the file body.
+               try {
+                       createEmptyFileBody(name, contentType, 0,  file, auditInfo);
+               } catch (FileNotFoundException e) {
+                       throw new GSSIOException(e);
+               }
+               touchParentFolders(parent, owner, new Date());
+               dao.flush();
+               return file;
+       }
+       
+       private void createEmptyFileBody(String name, String mimeType, long fileSize, 
+                               FileHeader header, AuditInfo auditInfo)
+                       throws FileNotFoundException, QuotaExceededException, ObjectNotFoundException {
+
+               long currentTotalSize = 0;
+               if (!header.isVersioned() && header.getCurrentBody() != null && header.getBodies() != null)
+                       currentTotalSize = header.getTotalSize();
+               Long quotaLeft = getQuotaLeft(header.getOwner().getId());
+               
+
+               FileBody body = new FileBody();
+
+               // if no mime type or the generic mime type is defined by the client, then try to identify it from the filename extension
+               if (StringUtils.isEmpty(mimeType) || "application/octet-stream".equals(mimeType)
+                                       || "application/download".equals(mimeType) || "application/force-download".equals(mimeType)
+                                       || "octet/stream".equals(mimeType) || "application/unknown".equals(mimeType))
+                       body.setMimeType(identifyMimeType(name));
+               else
+                       body.setMimeType(mimeType);
+               body.setAuditInfo(auditInfo);
+               body.setFileSize(fileSize);
+               body.setOriginalFilename(name);
+               body.setStoredFilePath(generateRepositoryFilePath());
+               //CLEAR OLD VERSION IF FILE IS NOT VERSIONED AND GETS UPDATED
+               if(!header.isVersioned() && header.getCurrentBody() != null){
+                       header.setCurrentBody(null);
+                       if (header.getBodies() != null) {
+                               Iterator<FileBody> it = header.getBodies().iterator();
+                               while(it.hasNext()){
+                                       FileBody bo = it.next();
+                                       deleteActualFile(bo.getStoredFilePath());
+                                       it.remove();
+                                       dao.delete(bo);
+                               }
+                       }
+               }
+
+               dao.flush();
+               header.addBody(body);
+               header.setAuditInfo(auditInfo);
+
+               dao.create(body);
+       }
+       /*** WEBDAV LOCK **/
+       @Override
+       public FileLock getLockById(String id) {
+               return dao.getLockById(id);
+       }
+
+       @Override
+       public FileLock getLockByToken(String tokenId) {
+               return dao.getLockByToken(tokenId);
+       }
+
+       @Override
+       public void removeLock(FileLock lock) {
+               dao.removeLock(lock);           
+       }
+
+       @Override
+       public FileLock saveOrUpdateLock(FileLock lock) {
+               return dao.saveOrUpdateLock(lock);
+       }
+       
+       @Override
+       public WebDavNonce getWebDavNonce(String tokenId) {
+               return dao.getWebDavNonce(tokenId);
+       }
+
+       @Override
+       public void removeWebDavNonce(WebDavNonce nonce) {
+               dao.removeWebDavNonce(nonce);           
+       }
+
+       @Override
+       public WebDavNonce saveOrUpdateWebDavNonce(WebDavNonce nonce) {
+               return dao.saveOrUpdateWebDavNonce(nonce);
+       }
+       
+       /* (non-Javadoc)
+        * @see gr.ebs.gss.server.ejb.ExternalAPI#getUsersByUserNameLike(java.lang.String)
+        */
+       @Override
+       public UserDTO getUserByUserName(String username) {
+               User result = dao.getUserByUserName(username);
+               return result.getDTO();
+       }
+       
 }