Added special message for AUTH users
[pithos] / src / gr / ebs / gss / server / ejb / ExternalAPIBean.java
index 5c7e5d8..cc65ee5 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,16 +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.dto.FileBodyDTO;
-import gr.ebs.gss.server.domain.dto.FileHeaderDTO;
-import gr.ebs.gss.server.domain.dto.FolderDTO;
-import gr.ebs.gss.server.domain.dto.GroupDTO;
-import gr.ebs.gss.server.domain.dto.PermissionDTO;
+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;
 
@@ -57,7 +57,6 @@ import java.util.ArrayList;
 import java.util.Date;
 import java.util.Iterator;
 import java.util.LinkedHashSet;
-import java.util.LinkedList;
 import java.util.List;
 import java.util.Locale;
 import java.util.Random;
@@ -87,6 +86,7 @@ import org.apache.commons.lang.StringUtils;
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
 import org.apache.solr.client.solrj.SolrQuery;
+import org.apache.solr.client.solrj.SolrResponse;
 import org.apache.solr.client.solrj.SolrServerException;
 import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
 import org.apache.solr.client.solrj.request.ContentStreamUpdateRequest;
@@ -152,16 +152,22 @@ 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 FolderDTO getRootFolder(Long userId) throws ObjectNotFoundException {
+       public Folder getRootFolder(Long userId) throws ObjectNotFoundException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
                Folder folder = dao.getRootFolder(userId);
-               return folder.getDTO();
+               return folder;
        }
 
        @Override
-       public FolderDTO getFolder(final Long userId, final Long folderId) throws ObjectNotFoundException, InsufficientPermissionsException {
+       public Folder getFolder(final Long userId, final Long folderId) throws ObjectNotFoundException, InsufficientPermissionsException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
                if (folderId == null)
@@ -171,7 +177,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.getDTO();
+               return expandFolder(folder);
        }
 
        @Override
@@ -187,15 +193,15 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
        }
 
        @Override
-       public GroupDTO getGroup(final Long groupId) throws ObjectNotFoundException {
+       public Group getGroup(final Long groupId) throws ObjectNotFoundException {
                if (groupId == null)
                        throw new ObjectNotFoundException("No group specified");
                final Group group = dao.getEntityById(Group.class, groupId);
-               return group.getDTO();
+               return group;
        }
 
        @Override
-       public GroupDTO getGroup(Long userId, String name) throws ObjectNotFoundException {
+       public Group getGroup(Long userId, String name) throws ObjectNotFoundException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
                if (name == null)
@@ -204,23 +210,20 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                List<Group> groups = user.getGroupsSpecified();
                for (Group group: groups)
                        if (group.getName().equals(name))
-                               return group.getDTO();
+                               return group;
                throw new ObjectNotFoundException("Group " + name + " not found");
        }
 
        @Override
-       public List<GroupDTO> getGroups(final Long userId) throws ObjectNotFoundException {
+       public List<Group> getGroups(final Long userId) throws ObjectNotFoundException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
                final List<Group> groups = dao.getGroups(userId);
-               final List<GroupDTO> result = new ArrayList<GroupDTO>();
-               for (final Group g : groups)
-                       result.add(g.getDTO());
-               return result;
+               return groups;
        }
 
        @Override
-       public List<FileHeaderDTO> getFiles(Long userId, Long folderId, boolean ignoreDeleted)
+       public List<FileHeader> getFiles(Long userId, Long folderId, boolean ignoreDeleted)
                        throws ObjectNotFoundException, InsufficientPermissionsException {
                // Validate.
                if (userId == null)
@@ -231,16 +234,12 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                Folder folder = dao.getEntityById(Folder.class, folderId);
                if (!folder.hasReadPermission(user))
                        throw new InsufficientPermissionsException("You don't have the permissions to read this folder");
-               // Do the actual work.
-               List<FileHeaderDTO> result = new ArrayList<FileHeaderDTO>();
                List<FileHeader> files = dao.getFiles(folderId, userId, ignoreDeleted);
-               for (FileHeader f : files)
-                       result.add(f.getDTO());
-               return result;
+               return files;
        }
 
        @Override
-       public List<UserDTO> getUsers(final Long userId, final Long groupId) throws ObjectNotFoundException {
+       public List<User> getUsers(final Long userId, final Long groupId) throws ObjectNotFoundException {
                // Validate.
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
@@ -249,14 +248,11 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
 
                // Do the actual work.
                final List<User> users = dao.getUsers(groupId);
-               final List<UserDTO> result = new ArrayList<UserDTO>();
-               for (final User u : users)
-                       result.add(u.getDTO());
-               return result;
+               return users;
        }
 
        @Override
-       public FolderDTO createFolder(Long userId, Long parentId, String name)
+       public Folder createFolder(Long userId, Long parentId, String name)
                        throws DuplicateNameException, ObjectNotFoundException, InsufficientPermissionsException {
                // Validate.
                if (userId == null)
@@ -294,7 +290,7 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
         * @param creator
         * @return the new folder
         */
-       private FolderDTO createFolder(String name, Folder parent, User creator) {
+       private Folder createFolder(String name, Folder parent, User creator) {
                Folder folder = new Folder();
                folder.setName(name);
                if (parent != null) {
@@ -335,7 +331,7 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                        folder.setReadForAll(parent.isReadForAll());
 
                dao.create(folder);
-               return folder.getDTO();
+               return folder;
        }
 
        @Override
@@ -382,7 +378,7 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
 
        @Override
        @SuppressWarnings("unchecked")
-       public List<FolderDTO> getSubfolders(Long userId, Long folderId)
+       public List<Folder> getSubfolders(Long userId, Long folderId)
                        throws ObjectNotFoundException, InsufficientPermissionsException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
@@ -392,18 +388,18 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                Folder folder = dao.getEntityById(Folder.class, folderId);
                if (!folder.hasReadPermission(user))
                        throw new InsufficientPermissionsException("You don't have the permissions to read this folder");
-               List<FolderDTO> result = new ArrayList<FolderDTO>();
+               List<Folder> result = new ArrayList<Folder>();
                if (folder.hasReadPermission(user))
                        for (Folder f : folder.getSubfolders())
                                if (f.hasReadPermission(user) && !f.isDeleted())
-                                       result.add(f.getDTO());
+                                       result.add(f);
                return result;
        }
 
        @Override
-       public FolderDTO updateFolder(Long userId, Long folderId, String folderName,
+       public Folder updateFolder(Long userId, Long folderId, String folderName,
                                Boolean readForAll,
-                               Set<PermissionDTO> permissions)
+                               Set<Permission> permissions)
                        throws InsufficientPermissionsException, ObjectNotFoundException,
                        DuplicateNameException {
 
@@ -440,9 +436,21 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                folder.getAuditInfo().setModifiedBy(user);
                dao.update(folder);
                touchParentFolders(folder, user, new Date());
-               return folder.getDTO();
+               // 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.
@@ -480,16 +488,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);
@@ -498,7 +503,7 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
        }
 
        @Override
-       public FileHeaderDTO createFile(Long userId, Long folderId, String name, String mimeType, InputStream stream)
+       public FileHeader createFile(Long userId, Long folderId, String name, String mimeType, InputStream stream)
                        throws DuplicateNameException, ObjectNotFoundException, GSSIOException,
                        InsufficientPermissionsException, QuotaExceededException {
                File file = null;
@@ -508,14 +513,17 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                        // Supply a more accurate problem description.
                        throw new GSSIOException("Problem creating file",ioe);
                }
+               finally{
+                       try {
+                               stream.close();
+                       } catch (IOException e) {
+                               logger.error("Unable to close InputStream on FileUpload:",e);
+                       }
+               }
                return createFile(userId, folderId, name, mimeType, file.length(), file.getAbsolutePath());
        }
 
-       /* (non-Javadoc)
-        * @see gr.ebs.gss.server.ejb.ExternalAPIRemote#indexFile(java.lang.Long, boolean)
-        */
-       @Override
-       public void indexFile(Long fileId, boolean delete) {
+       private void indexFile(Long fileId, boolean delete) {
                Connection qConn = null;
                Session session = null;
                MessageProducer sender = null;
@@ -609,7 +617,7 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                        return;
                File file = new File(path);
                if (!file.delete())
-                       logger.error("Could not delete file " + path);
+                       logger.error("Could not delete file " + path + " "+file.exists());
        }
 
        @Override
@@ -638,7 +646,7 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
        @Override
        public void updateFile(Long userId, Long fileId, String name,
                                String tagSet, Date modificationDate, Boolean versioned,
-                               Boolean readForAll,     Set<PermissionDTO> permissions)
+                               Boolean readForAll,     Set<Permission> permissions)
                        throws DuplicateNameException, ObjectNotFoundException, InsufficientPermissionsException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
@@ -716,7 +724,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);
        }
 
@@ -774,7 +782,7 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
        }
 
        @Override
-       public FileHeaderDTO getFile(Long userId, Long fileId) throws ObjectNotFoundException, InsufficientPermissionsException {
+       public FileHeader getFile(Long userId, Long fileId) throws ObjectNotFoundException, InsufficientPermissionsException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
                if (fileId == null)
@@ -783,11 +791,11 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                final FileHeader file = dao.getEntityById(FileHeader.class, fileId);
                if (!file.hasReadPermission(user) && !file.getFolder().hasReadPermission(user))
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
-               return file.getDTO();
+               return file;
        }
 
        @Override
-       public FileBodyDTO getFileBody(Long userId, Long fileId, Long bodyId) throws ObjectNotFoundException, InsufficientPermissionsException {
+       public FileBody getFileBody(Long userId, Long fileId, Long bodyId) throws ObjectNotFoundException, InsufficientPermissionsException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
                if (fileId == null)
@@ -797,7 +805,7 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                if (!file.hasReadPermission(user) && !file.getFolder().hasReadPermission(user))
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
                FileBody body = dao.getEntityById(FileBody.class, bodyId);
-               return body.getDTO();
+               return body;
        }
 
        @Override
@@ -817,10 +825,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);
-               FolderDTO 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");
                }
@@ -828,14 +838,14 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                // Use the lastElement to retrieve the actual resource.
                Object resource = null;
                try {
-                       FileHeaderDTO 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.
-                       FolderDTO 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;
@@ -854,14 +864,14 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
         *             found, with the exception message mentioning the precise
         *             problem
         */
-       private FileHeaderDTO getFile(Long folderId, String name) throws ObjectNotFoundException {
+       private FileHeader getFile(Long folderId, String name) throws ObjectNotFoundException {
                if (folderId == null)
                        throw new ObjectNotFoundException("No parent folder specified");
                if (StringUtils.isEmpty(name))
                        throw new ObjectNotFoundException("No file specified");
 
                FileHeader file = dao.getFile(folderId, name);
-               return file.getDTO();
+               return file;
        }
 
        /**
@@ -875,17 +885,17 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
         *             found, with the exception message mentioning the precise
         *             problem
         */
-       private FolderDTO getFolder(Long parentId, String name) throws ObjectNotFoundException {
+       private Folder getFolder(Long parentId, String name) throws ObjectNotFoundException {
                if (parentId == null)
                        throw new ObjectNotFoundException("No parent folder specified");
                if (StringUtils.isEmpty(name))
                        throw new ObjectNotFoundException("No folder specified");
 
                Folder folder = dao.getFolder(parentId, name);
-               return folder.getDTO();
+               return folder;
        }
 
-       private FileHeaderDTO updateFileContents(Long userId, Long fileId, String mimeType, InputStream resourceInputStream) throws ObjectNotFoundException, GSSIOException, InsufficientPermissionsException, QuotaExceededException {
+       private FileHeader updateFileContents(Long userId, Long fileId, String mimeType, InputStream resourceInputStream) throws ObjectNotFoundException, GSSIOException, InsufficientPermissionsException, QuotaExceededException {
                File file = null;
                try {
                        file = uploadFile(resourceInputStream, userId);
@@ -906,9 +916,9 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                        throw new ObjectNotFoundException("No destination specified");
 
                Object destination = getResourceAtPath(userId, getParentPath(dest), true);
-               if (!(destination instanceof FolderDTO))
+               if (!(destination instanceof Folder))
                        throw new ObjectNotFoundException("Destination parent folder not found");
-               FolderDTO parent = (FolderDTO) destination;
+               Folder parent = (Folder) destination;
                copyFile(userId, fileId, parent.getId(), getLastElement(dest));
        }
 
@@ -924,9 +934,9 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                        throw new ObjectNotFoundException("No destination specified");
 
                Object destination = getResourceAtPath(ownerId, getParentPath(dest), true);
-               if (!(destination instanceof FolderDTO))
+               if (!(destination instanceof Folder))
                        throw new ObjectNotFoundException("Destination parent folder not found");
-               FolderDTO parent = (FolderDTO) destination;
+               Folder parent = (Folder) destination;
                copyFile(userId, fileId, parent.getId(), getLastElement(dest));
        }
 
@@ -983,9 +993,9 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                        throw new ObjectNotFoundException("No destination specified");
 
                Object destination = getResourceAtPath(userId, getParentPath(dest), true);
-               if (!(destination instanceof FolderDTO))
+               if (!(destination instanceof Folder))
                        throw new ObjectNotFoundException("Destination folder not found");
-               FolderDTO parent = (FolderDTO) destination;
+               Folder parent = (Folder) destination;
                copyFolder(userId, folderId, parent.getId(), getLastElement(dest));
        }
 
@@ -1019,9 +1029,9 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                        throw new ObjectNotFoundException("No destination specified");
 
                Object destination = getResourceAtPath(ownerId, getParentPath(dest), true);
-               if (!(destination instanceof FolderDTO))
+               if (!(destination instanceof Folder))
                        throw new ObjectNotFoundException("Destination folder not found");
-               FolderDTO parent = (FolderDTO) destination;
+               Folder parent = (Folder) destination;
                copyFolderStructure(userId, folderId, parent.getId(), getLastElement(dest));
        }
 
@@ -1122,14 +1132,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)
@@ -1142,9 +1155,9 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                        throw new ObjectNotFoundException("No destination specified");
 
                Object destination = getResourceAtPath(ownerId, getParentPath(dest), true);
-               if (!(destination instanceof FolderDTO))
+               if (!(destination instanceof Folder))
                        throw new ObjectNotFoundException("Destination parent folder not found");
-               FolderDTO parent = (FolderDTO) destination;
+               Folder parent = (Folder) destination;
                moveFile(userId, fileId, parent.getId(), getLastElement(dest));
        }
 
@@ -1210,9 +1223,9 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                        throw new ObjectNotFoundException("No destination specified");
 
                Object destination = getResourceAtPath(ownerId, getParentPath(dest), true);
-               if (!(destination instanceof FolderDTO))
+               if (!(destination instanceof Folder))
                        throw new ObjectNotFoundException("Destination parent folder not found");
-               FolderDTO parent = (FolderDTO) destination;
+               Folder parent = (Folder) destination;
                moveFolder(userId, folderId, parent.getId(), getLastElement(dest));
        }
 
@@ -1273,17 +1286,14 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
        }
 
        @Override
-       public List<FileHeaderDTO> getDeletedFiles(Long userId) throws ObjectNotFoundException {
+       public List<FileHeader> getDeletedFiles(Long userId) throws ObjectNotFoundException {
                // Validate.
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
 
                // Do the actual work.
-               final List<FileHeaderDTO> result = new ArrayList<FileHeaderDTO>();
                final List<FileHeader> files = dao.getDeletedFiles(userId);
-               for (final FileHeader f : files)
-                       result.add(f.getDTO());
-               return result;
+               return files;
        }
 
        @Override
@@ -1300,34 +1310,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)
@@ -1338,50 +1353,50 @@ 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<FolderDTO> getDeletedRootFolders(Long userId) throws ObjectNotFoundException {
+       public List<Folder> getDeletedRootFolders(Long userId) throws ObjectNotFoundException {
                List<Folder> folders = dao.getDeletedRootFolders(userId);
-               List<FolderDTO> result = new ArrayList<FolderDTO>();
-               for (Folder folder : folders)
-                       result.add(folder.getDTO());
-               return result;
+               return folders;
        }
 
        @Override
        public void emptyTrash(Long userId) throws ObjectNotFoundException, InsufficientPermissionsException {
-               List<FolderDTO> deletedRootFolders = getDeletedRootFolders(userId);
-               for (FolderDTO fdto : deletedRootFolders)
-                       deleteFolder(userId, fdto.getId());
-               List<FileHeaderDTO> deletedFiles = getDeletedFiles(userId);
-               for (FileHeaderDTO filedto : deletedFiles)
-                       deleteFile(userId, filedto.getId());
+               List<Folder> deletedRootFolders = getDeletedRootFolders(userId);
+               for (Folder folder : deletedRootFolders)
+                       deleteFolder(userId, folder.getId());
+               List<FileHeader> deletedFiles = getDeletedFiles(userId);
+               for (FileHeader file : deletedFiles)
+                       deleteFile(userId, file.getId());
        }
 
        @Override
        public void restoreTrash(Long userId) throws ObjectNotFoundException, InsufficientPermissionsException {
-               List<FolderDTO> deletedRootFolders = getDeletedRootFolders(userId);
-               for (FolderDTO fdto : deletedRootFolders)
-                       removeFolderFromTrash(userId, fdto.getId());
-               List<FileHeaderDTO> deletedFiles = getDeletedFiles(userId);
-               for (FileHeaderDTO filedto : deletedFiles)
-                       removeFileFromTrash(userId, filedto.getId());
+               List<Folder> deletedRootFolders = getDeletedRootFolders(userId);
+               for (Folder folder : deletedRootFolders)
+                       removeFolderFromTrash(userId, folder.getId());
+               List<FileHeader> deletedFiles = getDeletedFiles(userId);
+               for (FileHeader file : deletedFiles)
+                       removeFileFromTrash(userId, file.getId());
        }
 
        @Override
        public User createUser(String username, String name, String mail,
-                               String idp, String idpid) throws ObjectNotFoundException {
+                               String idp, String idpid, String homeOrg) throws ObjectNotFoundException {
                if (username == null)
                        throw new ObjectNotFoundException("No username specified");
                if (name == null)
@@ -1402,6 +1417,7 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                user.generateAuthToken();
                user.generateWebDAVPassword();
                user.setUserClass(getDefaultUserClass());
+        user.setHomeOrganization(homeOrg);
                dao.create(user);
                // Make sure we get an ID in the user object.
                dao.flush();
@@ -1460,7 +1476,7 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
        }
 
        @Override
-       public Set<PermissionDTO> getFolderPermissions(Long userId, Long folderId) throws ObjectNotFoundException, InsufficientPermissionsException {
+       public Set<Permission> getFolderPermissions(Long userId, Long folderId) throws ObjectNotFoundException, InsufficientPermissionsException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
                if (folderId == null)
@@ -1470,14 +1486,14 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                if(!folder.hasReadPermission(user))
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
                Set<Permission> perms = folder.getPermissions();
-               Set<PermissionDTO> result = new LinkedHashSet<PermissionDTO>();
+               Set<Permission> result = new LinkedHashSet<Permission>();
                for (Permission perm : perms)
                        if (perm.getUser() != null && perm.getUser().getId().equals(folder.getOwner().getId()))
-                               result.add(perm.getDTO());
+                               result.add(perm);
                for (Permission perm : perms)
                        if (perm.getUser() != null && perm.getUser().getId().equals(folder.getOwner().getId())) {
                        } else
-                               result.add(perm.getDTO());
+                               result.add(perm);
                return result;
 
        }
@@ -1492,13 +1508,13 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
         * @throws ObjectNotFoundException
         * @throws InsufficientPermissionsException
         */
-       private void setFolderPermissions(User user, Folder folder, Set<PermissionDTO> permissions) throws ObjectNotFoundException, InsufficientPermissionsException {
+       private void setFolderPermissions(User user, Folder folder, Set<Permission> permissions) throws ObjectNotFoundException, InsufficientPermissionsException {
                if (permissions != null && !permissions.isEmpty()) {
                        User owner = folder.getOwner();
-                       PermissionDTO ownerPerm = null;
-                       for (PermissionDTO dto : permissions)
-                               if (dto.getUser() != null && dto.getUser().getId().equals(owner.getId())) {
-                                       ownerPerm = dto;
+                       Permission ownerPerm = null;
+                       for (Permission perm : permissions)
+                               if (perm.getUser() != null && perm.getUser().getId().equals(owner.getId())) {
+                                       ownerPerm = perm;
                                        break;
                                }
                        if (ownerPerm == null || !ownerPerm.hasRead() || !ownerPerm.hasWrite() || !ownerPerm.hasModifyACL())
@@ -1507,10 +1523,10 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                        for (Permission perm: folder.getPermissions())
                                dao.delete(perm);
                        folder.getPermissions().clear();
-                       for (PermissionDTO dto : permissions) {
+                       for (Permission p : permissions) {
                                // Skip 'empty' permission entries.
-                               if (!dto.getRead() && !dto.getWrite() && !dto.getModifyACL()) continue;
-                               folder.addPermission(getPermission(dto));
+                               if (!p.getRead() && !p.getWrite() && !p.getModifyACL()) continue;
+                               folder.addPermission(getPermission(p));
                        }
                        dao.update(folder);
                        for (FileHeader file : folder.getFiles()) {
@@ -1524,18 +1540,18 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                }
        }
 
-       private Permission getPermission(PermissionDTO dto) throws ObjectNotFoundException {
+       private Permission getPermission(Permission perm) throws ObjectNotFoundException {
                Permission res = new Permission();
-               if (dto.getGroup() != null)
-                       res.setGroup(dao.getEntityById(Group.class, dto.getGroup().getId()));
-               else if (dto.getUser() != null)
-                       if (dto.getUser().getId() == null)
-                               res.setUser(dao.getUser(dto.getUser().getUsername()));
+               if (perm.getGroup() != null)
+                       res.setGroup(dao.getEntityById(Group.class, perm.getGroup().getId()));
+               else if (perm.getUser() != null)
+                       if (perm.getUser().getId() == null)
+                               res.setUser(dao.getUser(perm.getUser().getUsername()));
                        else
-                               res.setUser(dao.getEntityById(User.class, dto.getUser().getId()));
-               res.setRead(dto.hasRead());
-               res.setWrite(dto.hasWrite());
-               res.setModifyACL(dto.hasModifyACL());
+                               res.setUser(dao.getEntityById(User.class, perm.getUser().getId()));
+               res.setRead(perm.hasRead());
+               res.setWrite(perm.hasWrite());
+               res.setModifyACL(perm.hasModifyACL());
                return res;
        }
 
@@ -1543,12 +1559,9 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
         * @see gr.ebs.gss.server.ejb.ExternalAPI#getUsersByUserNameLike(java.lang.String)
         */
        @Override
-       public List<UserDTO> getUsersByUserNameLike(String username) {
+       public List<User> getUsersByUserNameLike(String username) {
                List<User> users = dao.getUsersByUserNameLike(username);
-               List<UserDTO> result = new ArrayList<UserDTO>();
-               for (User u : users)
-                       result.add(u.getDTO());
-               return result;
+               return users;
 
        }
 
@@ -1582,15 +1595,15 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
        }
 
        @Override
-       public List<FolderDTO> getSharedRootFolders(Long userId) throws ObjectNotFoundException {
+       public List<Folder> getSharedRootFolders(Long userId) throws ObjectNotFoundException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
                List<Folder> folders = dao.getSharedRootFolders(userId);
-               List<FolderDTO> result = new ArrayList<FolderDTO>();
+               List<Folder> result = new ArrayList<Folder>();
                for (Folder f : folders) {
-                       FolderDTO dto = f.getDTO();
-                       dto.setSubfolders(getSharedSubfolders(userId, f.getId()));
-                       result.add(dto);
+                       Folder lf = f;
+                       lf.setSubfolders(getSharedSubfolders(userId, f.getId()));
+                       result.add(lf);
                }
                return result;
        }
@@ -1614,20 +1627,20 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
        }
 
        @Override
-       public List<UserDTO> getUsersSharingFoldersForUser(Long userId) throws ObjectNotFoundException {
+       public List<User> getUsersSharingFoldersForUser(Long userId) throws ObjectNotFoundException {
                List<User> users = dao.getUsersSharingFoldersForUser(userId);
                List<User> usersFiles = dao.getUsersSharingFilesForUser(userId);
-               List<UserDTO> res = new ArrayList<UserDTO>();
+               List<User> result = new ArrayList<User>();
                for (User u : users)
-                       res.add(u.getDTO());
+                       result.add(u);
                for(User fu : usersFiles)
                        if(!users.contains(fu))
-                               res.add(fu.getDTO());
-               return res;
+                               result.add(fu);
+               return result;
        }
 
        @Override
-       public Set<PermissionDTO> getFilePermissions(Long userId, Long fileId) throws ObjectNotFoundException, InsufficientPermissionsException {
+       public Set<Permission> getFilePermissions(Long userId, Long fileId) throws ObjectNotFoundException, InsufficientPermissionsException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
                if (fileId == null)
@@ -1637,14 +1650,14 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                if(!folder.hasReadPermission(user))
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
                Set<Permission> perms = folder.getPermissions();
-               Set<PermissionDTO> result = new LinkedHashSet<PermissionDTO>();
+               Set<Permission> result = new LinkedHashSet<Permission>();
                for (Permission perm : perms)
                        if (perm.getUser() != null && perm.getUser().getId().equals(folder.getOwner().getId()))
-                               result.add(perm.getDTO());
+                               result.add(perm);
                for (Permission perm : perms)
                        if (perm.getUser() != null && perm.getUser().getId().equals(folder.getOwner().getId())) {
                        } else
-                               result.add(perm.getDTO());
+                               result.add(perm);
                return result;
        }
 
@@ -1659,13 +1672,13 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
         * @throws InsufficientPermissionsException
         */
        private void setFilePermissions(FileHeader file,
-                               Set<PermissionDTO> permissions)
+                               Set<Permission> permissions)
                        throws ObjectNotFoundException, InsufficientPermissionsException {
                if (permissions != null && !permissions.isEmpty()) {
-                       PermissionDTO ownerPerm = null;
-                       for (PermissionDTO dto : permissions)
-                               if (dto.getUser() != null && dto.getUser().getId().equals(file.getOwner().getId())) {
-                                       ownerPerm = dto;
+                       Permission ownerPerm = null;
+                       for (Permission perm : permissions)
+                               if (perm.getUser() != null && perm.getUser().getId().equals(file.getOwner().getId())) {
+                                       ownerPerm = perm;
                                        break;
                                }
                        if (ownerPerm == null || !ownerPerm.hasRead() || !ownerPerm.hasWrite() || !ownerPerm.hasModifyACL())
@@ -1674,96 +1687,84 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                        for (Permission perm: file.getPermissions())
                                dao.delete(perm);
                        file.getPermissions().clear();
-                       for (PermissionDTO dto : permissions) {
+                       for (Permission perm : permissions) {
                                // Skip 'empty' permission entries.
-                               if (!dto.getRead() && !dto.getWrite() && !dto.getModifyACL()) continue;
-                               file.addPermission(getPermission(dto));
+                               if (!perm.getRead() && !perm.getWrite() && !perm.getModifyACL()) continue;
+                               file.addPermission(getPermission(perm));
                        }
                        dao.flush();
                }
        }
 
        @Override
-       public List<FileHeaderDTO> getSharedFilesNotInSharedFolders(Long userId) throws ObjectNotFoundException {
+       public List<FileHeader> getSharedFilesNotInSharedFolders(Long userId) throws ObjectNotFoundException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
                List<FileHeader> files = dao.getSharedFilesNotInSharedFolders(userId);
-               List<FileHeaderDTO> result = new ArrayList<FileHeaderDTO>();
-               for (FileHeader f : files)
-                       result.add(f.getDTO());
-               return result;
+               return files;
        }
 
        @Override
-       public List<FileHeaderDTO> getSharedFiles(Long userId) throws ObjectNotFoundException {
+       public List<FileHeader> getSharedFiles(Long userId) throws ObjectNotFoundException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
                List<FileHeader> files = dao.getSharedFiles(userId);
-               List<FileHeaderDTO> result = new ArrayList<FileHeaderDTO>();
-               for (FileHeader f : files)
-                       result.add(f.getDTO());
-               return result;
+               return files;
        }
 
        @Override
-       public List<FolderDTO> getSharedFolders(Long userId) throws ObjectNotFoundException {
+       public List<Folder> getSharedFolders(Long userId) throws ObjectNotFoundException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
                List<Folder> folders = dao.getSharedFolders(userId);
-               List<FolderDTO> result = new ArrayList<FolderDTO>();
-               for (Folder f : folders)
-                       result.add(f.getDTO());
-               return result;
+               return folders;
        }
 
        @Override
-       public List<FileHeaderDTO> getSharedFiles(Long ownerId, Long callingUserId) throws ObjectNotFoundException {
+       public List<FileHeader> getSharedFiles(Long ownerId, Long callingUserId) throws ObjectNotFoundException {
                if (ownerId == null)
                        throw new ObjectNotFoundException("No owner specified");
                if (callingUserId == null)
                        throw new ObjectNotFoundException("No calling user specified");
                List<FileHeader> folders = dao.getSharedFiles(ownerId, callingUserId);
-               List<FileHeaderDTO> result = new ArrayList<FileHeaderDTO>();
-               for (FileHeader f : folders)
-                       result.add(f.getDTO());
-               return result;
+               return folders;
        }
 
        @Override
-       public List<FolderDTO> getSharedRootFolders(Long ownerId, Long callingUserId) throws ObjectNotFoundException {
+       public List<Folder> getSharedRootFolders(Long ownerId, Long callingUserId) throws ObjectNotFoundException {
                if (ownerId == null)
                        throw new ObjectNotFoundException("No owner specified");
                if (callingUserId == null)
                        throw new ObjectNotFoundException("No calling user specified");
                List<Folder> folders = dao.getSharedRootFolders(ownerId, callingUserId);
-               List<FolderDTO> result = new ArrayList<FolderDTO>();
+               List<Folder> result = new ArrayList<Folder>();
                for (Folder f : folders) {
-                       FolderDTO dto = f.getDTO();
-                       dto.setSubfolders(getSharedSubfolders(ownerId, callingUserId, f.getId()));
-                       result.add(dto);
+                       Folder lf = f;
+                       lf.setSubfolders(getSharedSubfolders(ownerId, callingUserId, f.getId()));
+                       result.add(lf);
                }
                return result;
 
        }
 
        @Override
-       public List<FolderDTO> getSharedSubfolders(Long userId, Long folderId) throws ObjectNotFoundException {
+       public List<Folder> getSharedSubfolders(Long userId, Long folderId) throws ObjectNotFoundException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
                if (folderId == null)
                        throw new ObjectNotFoundException("No folder specified");
                User user = dao.getEntityById(User.class, userId);
                Folder folder = dao.getEntityById(Folder.class, folderId);
-               List<FolderDTO> result = new ArrayList<FolderDTO>();
+               List<Folder> result = new ArrayList<Folder>();
                if (folder.isShared(user) || folder.isReadForAll())
                        for (Folder f : folder.getSubfolders())
                                if ((f.isShared(user) || f.isReadForAll()) && !f.isDeleted())
-                                       result.add(f.getDTO());
+                                       result.add(f);
                return result;
        }
 
        @Override
-       public List<FolderDTO> getSharedSubfolders(Long userId, Long callingUserId, Long folderId) throws ObjectNotFoundException {
+       public List<Folder> getSharedSubfolders(Long userId, Long callingUserId, Long folderId) throws ObjectNotFoundException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
                if (callingUserId == null)
@@ -1772,20 +1773,20 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                        throw new ObjectNotFoundException("No folder specified");
                User user = dao.getEntityById(User.class, callingUserId);
                Folder folder = dao.getEntityById(Folder.class, folderId);
-               List<FolderDTO> result = new ArrayList<FolderDTO>();
+               List<Folder> result = new ArrayList<Folder>();
                if (folder.isSharedForOtherUser(user))
                        for (Folder f : folder.getSubfolders())
                                if (f.isSharedForOtherUser(user) && !f.isDeleted()){
-                                       FolderDTO dto = f.getDTO();
-                                       dto.setSubfolders(getSharedSubfolders(userId, callingUserId, dto.getId()));
-                                       result.add(dto);
+                                       Folder lf = f;
+                                       lf.setSubfolders(getSharedSubfolders(userId, callingUserId, lf.getId()));
+                                       result.add(lf);
                                }
                return result;
 
        }
 
        @Override
-       public List<FileHeaderDTO> searchFiles(Long userId, String query) throws ObjectNotFoundException {
+       public List<FileHeader> searchFiles(Long userId, String query) throws ObjectNotFoundException {
         long startTime = System.currentTimeMillis();
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
@@ -1793,15 +1794,10 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                if (query == null)
                        throw new ObjectNotFoundException("No query specified");
                List<FileHeader> files = search(user.getId(), query);
-        long startTime2 = System.currentTimeMillis();
-               List<FileHeaderDTO> res = new ArrayList<FileHeaderDTO>();
-               for(FileHeader f : files)
-                       res.add(f.getDTO());
-        long stopTime2 = System.currentTimeMillis();
-        logger.info("DTO time: " + (stopTime2 - startTime2));
+               
         long stopTime = System.currentTimeMillis();
         logger.info("Total time: " + (stopTime - startTime));
-               return res;
+               return files;
        }
 
        /**
@@ -1816,7 +1812,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);
@@ -1834,14 +1843,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);
@@ -1875,52 +1883,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");
@@ -1971,51 +1933,6 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
        }
 
        @Override
-       public List<FileBodyDTO> getVersions(Long userId, Long fileId) throws ObjectNotFoundException, InsufficientPermissionsException {
-               if (userId == null)
-                       throw new ObjectNotFoundException("No user specified");
-               if (fileId == null)
-                       throw new ObjectNotFoundException("No file specified");
-               User user = dao.getEntityById(User.class, userId);
-               FileHeader header = dao.getEntityById(FileHeader.class, fileId);
-               if(!header.hasReadPermission(user))
-                       throw new InsufficientPermissionsException("You don't have the necessary permissions");
-               List<FileBodyDTO> result = new LinkedList<FileBodyDTO>();
-               for(int i = header.getBodies().size()-1 ; i>=0; i--)
-                       result.add(header.getBodies().get(i).getDTO());
-               return result;
-       }
-
-       @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");
@@ -2096,9 +2013,14 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
             logger.info("Total of " + fileIds.size() + " will be indexed");
             int i = 0;
                        for (Long id : fileIds) {
-                               postFileToSolr(solr, id);
+                try {
+                    postFileToSolr(solr, id);
+                }
+                catch (ObjectNotFoundException e) {
+                    logger.error("Indexing of file id " + id + " failed.", e);
+                }
                 i++;
-                if (i % 100 == 0) {
+                if (i % 10 == 0) {
                     solr.commit();
                     logger.info("Sent commit to solr at file " + i);
                 }
@@ -2121,16 +2043,23 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                        CommonsHttpSolrServer solr = new CommonsHttpSolrServer(getConfiguration().getString("solr.url"));
                        
                        List<Long> fileIds = dao.getAllFileIds();
-            logger.info("Total of " + fileIds.size() + " will be indexed");
+            logger.info("Total of " + fileIds.size() + " will be checked");
             int i = 0;
                        for (Long id : fileIds) {
-                               postFileToSolr(solr, id);
+                if (!fileIsInSolr(solr, id)) {
+                    try {
+                        postFileToSolr(solr, id);
+                    }
+                    catch (ObjectNotFoundException e) {
+                       logger.error("Indexing of file id " + id + " failed.", e);
+                    }
+                }
                 i++;
+                if (i % 10 == 0) {
+                    solr.commit();
+                    logger.info("Sent commit to solr at file " + i);
+                }
                        }
-            if (i % 100 == 0) {
-                solr.commit();
-                logger.debug("Sent commit to solr at file " + i);
-            }
                        solr.optimize();
                        solr.commit();
             logger.info("Finished indexing of " + i + " files");
@@ -2142,8 +2071,20 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                }
        }
 
-       @Override
-       public FileHeaderDTO createFile(Long userId, Long folderId, String name, String mimeType, long fileSize, String filePath)
+    private boolean fileIsInSolr(CommonsHttpSolrServer solr, Long id) {
+        try {
+            SolrQuery query = new SolrQuery("id:" + id);
+            QueryResponse response = solr.query(query);
+            return !(response.getResults().size() == 0);
+        }
+        catch (SolrServerException e) {
+            logger.warn("Exception while checking file " + id, e);
+            return false;
+        }
+    }
+
+    @Override
+       public FileHeader createFile(Long userId, Long folderId, String name, String mimeType, long fileSize, String filePath)
                        throws DuplicateNameException, ObjectNotFoundException, GSSIOException,
                        InsufficientPermissionsException, QuotaExceededException {
                // Validate.
@@ -2209,11 +2150,11 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                dao.flush();
                indexFile(file.getId(), false);
 
-               return file.getDTO();
+               return file;
        }
 
        @Override
-       public FileHeaderDTO updateFileContents(Long userId, Long fileId, String mimeType, long fileSize, String filePath) throws ObjectNotFoundException, GSSIOException, InsufficientPermissionsException, QuotaExceededException {
+       public FileHeader updateFileContents(Long userId, Long fileId, String mimeType, long fileSize, String filePath) throws ObjectNotFoundException, GSSIOException, InsufficientPermissionsException, QuotaExceededException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
                if (fileId == null)
@@ -2246,7 +2187,7 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                touchParentFolders(parent, owner, new Date());
 
                indexFile(fileId, false);
-               return file.getDTO();
+               return file;
        }
 
        /**
@@ -2416,45 +2357,7 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
        }
 
        @Override
-       public FolderDTO getFolderWithSubfolders(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");
-               final User user = dao.getEntityById(User.class, userId);
-               final Folder folder = dao.getEntityById(Folder.class, folderId);
-               // Check permissions
-               if (!folder.hasReadPermission(user))
-                       throw new InsufficientPermissionsException("You don't have the permissions to read this folder");
-               List<FolderDTO> subfolders = new ArrayList<FolderDTO>();
-               if (folder.hasReadPermission(user))
-                       for (Folder f : folder.getSubfolders())
-                               if (f.hasReadPermission(user) && !f.isDeleted())
-                                       subfolders.add(f.getDTO());
-               FolderDTO result = folder.getDTO();
-               result.setSubfolders(subfolders);
-               return folder.getDTO();
-       }
-
-       @Override
-       public FolderDTO getFolderWithSubfolders(Long userId, Long callingUserId, Long folderId) throws ObjectNotFoundException, InsufficientPermissionsException {
-               if (userId == null)
-                       throw new ObjectNotFoundException("No user specified");
-               if (folderId == null)
-                       throw new ObjectNotFoundException("No folder specified");
-               User user = dao.getEntityById(User.class, callingUserId);
-               Folder folder = dao.getEntityById(Folder.class, folderId);
-               // Check permissions
-               if (!folder.hasReadPermission(user))
-                       throw new InsufficientPermissionsException("You don't have the permissions to read this folder");
-
-               FolderDTO result = folder.getDTO();
-               result.setSubfolders(getSharedSubfolders(userId, callingUserId, folder.getId()));
-               return result;
-       }
-
-       @Override
-       public FileBodyDTO getFileVersion(Long userId, Long fileId, int version)
+       public FileBody getFileVersion(Long userId, Long fileId, int version)
                        throws ObjectNotFoundException, InsufficientPermissionsException {
                if (userId == null)
                        throw new ObjectNotFoundException("No user specified");
@@ -2467,7 +2370,7 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                if (!file.hasReadPermission(user) && !file.getFolder().hasReadPermission(user))
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
                FileBody body = dao.getFileVersion(fileId, version);
-               return body.getDTO();
+               return body;
        }
 
        @Override
@@ -2562,26 +2465,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.
         *
@@ -2605,9 +2488,43 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
                }
 
        }
+               
+       /**
+        * Update the userLogin with the values from the supplied object.
+        */
+       
+       public void addUserLogin(UserLogin userLogin) {
+               dao.update(userLogin);          
 
-       @Override
-       public void postFileToSolr(CommonsHttpSolrServer solr, Long id) {
+       }
+               
+       /**
+        * 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;
+       }
+       
+
+    public void postFileToSolr(Long id) throws IOException, SolrServerException, ObjectNotFoundException {
+        CommonsHttpSolrServer solr = new CommonsHttpSolrServer(getConfiguration().getString("solr.url"));
+        postFileToSolr(solr, id);
+        solr.commit();
+    }
+
+       private void postFileToSolr(CommonsHttpSolrServer solr, Long id) throws ObjectNotFoundException {
                try {
                        FileHeader file = dao.getFileForIndexing(id);
                        FileBody body = file.getCurrentBody();
@@ -2631,32 +2548,39 @@ 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);
                                }
                        }
                } catch (MalformedURLException e) {
                        throw new EJBException(e);
-               } catch (ObjectNotFoundException e) {
-                       logger.error("Indexing of file id " + id + " failed.", e);
                } catch (SolrServerException e) {
                        throw new EJBException(e);
                } catch (IOException e) {
@@ -2671,6 +2595,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);
        }
 
@@ -2696,4 +2630,185 @@ public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
        private String escapeCharacters(String text) {
                return text.replaceAll(":", "\\\\:");
        }
+       
+       /*** NEW METHODS IN ORDER TO AVOID LAZY loading exception in json render 
+        ****/
+       @Override
+       public Folder expandFolder(Folder folder) throws ObjectNotFoundException{
+               Folder result = dao.getEntityById(Folder.class, folder.getId());
+               result.getSubfolders().size();
+               result.getFiles().size();
+               result.getPermissions().size();
+               return result;
+}
+
+       @Override
+       public FileHeader expandFile(FileHeader folder) throws ObjectNotFoundException{
+               FileHeader result = dao.getEntityById(FileHeader.class, folder.getId());
+               result.getFolder();
+               result.getPermissions().size();
+               result.getFileTags().size();
+               return result;
+       }
+       
+       @Override
+       public Group expandGroup(Group folder) throws ObjectNotFoundException{
+               Group result = dao.getEntityById(Group.class, folder.getId());
+               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);
+       }
 }