Statistics
| Branch: | Tag: | Revision:

root / src / gr / ebs / gss / server / ejb / ExternalAPIBean.java @ a0dde818

History | View | Annotate | Download (94.2 kB)

1 14ad7326 pastith
/*
2 14ad7326 pastith
 * Copyright 2007, 2008, 2009 Electronic Business Systems Ltd.
3 14ad7326 pastith
 *
4 14ad7326 pastith
 * This file is part of GSS.
5 14ad7326 pastith
 *
6 14ad7326 pastith
 * GSS is free software: you can redistribute it and/or modify
7 14ad7326 pastith
 * it under the terms of the GNU General Public License as published by
8 14ad7326 pastith
 * the Free Software Foundation, either version 3 of the License, or
9 14ad7326 pastith
 * (at your option) any later version.
10 14ad7326 pastith
 *
11 14ad7326 pastith
 * GSS is distributed in the hope that it will be useful,
12 14ad7326 pastith
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 14ad7326 pastith
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 14ad7326 pastith
 * GNU General Public License for more details.
15 14ad7326 pastith
 *
16 14ad7326 pastith
 * You should have received a copy of the GNU General Public License
17 14ad7326 pastith
 * along with GSS.  If not, see <http://www.gnu.org/licenses/>.
18 14ad7326 pastith
 */
19 14ad7326 pastith
package gr.ebs.gss.server.ejb;
20 14ad7326 pastith
21 bde4eafb pastith
import static gr.ebs.gss.server.configuration.GSSConfigurationFactory.getConfiguration;
22 14ad7326 pastith
import gr.ebs.gss.client.exceptions.DuplicateNameException;
23 14ad7326 pastith
import gr.ebs.gss.client.exceptions.GSSIOException;
24 14ad7326 pastith
import gr.ebs.gss.client.exceptions.InsufficientPermissionsException;
25 14ad7326 pastith
import gr.ebs.gss.client.exceptions.ObjectNotFoundException;
26 14ad7326 pastith
import gr.ebs.gss.client.exceptions.QuotaExceededException;
27 14ad7326 pastith
import gr.ebs.gss.server.domain.AuditInfo;
28 14ad7326 pastith
import gr.ebs.gss.server.domain.FileBody;
29 14ad7326 pastith
import gr.ebs.gss.server.domain.FileHeader;
30 14ad7326 pastith
import gr.ebs.gss.server.domain.FileTag;
31 14ad7326 pastith
import gr.ebs.gss.server.domain.FileUploadStatus;
32 14ad7326 pastith
import gr.ebs.gss.server.domain.Folder;
33 14ad7326 pastith
import gr.ebs.gss.server.domain.Group;
34 14ad7326 pastith
import gr.ebs.gss.server.domain.Nonce;
35 14ad7326 pastith
import gr.ebs.gss.server.domain.Permission;
36 14ad7326 pastith
import gr.ebs.gss.server.domain.User;
37 2f2da9c7 pastith
import gr.ebs.gss.server.domain.dto.FileBodyDTO;
38 2f2da9c7 pastith
import gr.ebs.gss.server.domain.dto.FileHeaderDTO;
39 2f2da9c7 pastith
import gr.ebs.gss.server.domain.dto.FolderDTO;
40 2f2da9c7 pastith
import gr.ebs.gss.server.domain.dto.GroupDTO;
41 2f2da9c7 pastith
import gr.ebs.gss.server.domain.dto.PermissionDTO;
42 2f2da9c7 pastith
import gr.ebs.gss.server.domain.dto.StatsDTO;
43 2f2da9c7 pastith
import gr.ebs.gss.server.domain.dto.UserDTO;
44 14ad7326 pastith
45 14ad7326 pastith
import java.io.File;
46 14ad7326 pastith
import java.io.FileInputStream;
47 14ad7326 pastith
import java.io.FileNotFoundException;
48 14ad7326 pastith
import java.io.FileOutputStream;
49 14ad7326 pastith
import java.io.IOException;
50 14ad7326 pastith
import java.io.InputStream;
51 14ad7326 pastith
import java.io.StringWriter;
52 14ad7326 pastith
import java.io.UnsupportedEncodingException;
53 14ad7326 pastith
import java.util.ArrayList;
54 14ad7326 pastith
import java.util.Date;
55 14ad7326 pastith
import java.util.Iterator;
56 14ad7326 pastith
import java.util.LinkedHashSet;
57 14ad7326 pastith
import java.util.LinkedList;
58 14ad7326 pastith
import java.util.List;
59 f3f7bdf3 Fotis Stamatelopoulos
import java.util.Locale;
60 14ad7326 pastith
import java.util.Random;
61 14ad7326 pastith
import java.util.Set;
62 14ad7326 pastith
import java.util.StringTokenizer;
63 14ad7326 pastith
64 14ad7326 pastith
import javax.ejb.EJB;
65 14ad7326 pastith
import javax.ejb.EJBException;
66 14ad7326 pastith
import javax.ejb.Stateless;
67 14ad7326 pastith
import javax.ejb.TransactionAttribute;
68 14ad7326 pastith
import javax.ejb.TransactionAttributeType;
69 14ad7326 pastith
import javax.jms.Connection;
70 14ad7326 pastith
import javax.jms.ConnectionFactory;
71 14ad7326 pastith
import javax.jms.JMSException;
72 14ad7326 pastith
import javax.jms.MapMessage;
73 14ad7326 pastith
import javax.jms.MessageProducer;
74 14ad7326 pastith
import javax.jms.Queue;
75 14ad7326 pastith
import javax.jms.QueueConnectionFactory;
76 14ad7326 pastith
import javax.jms.Session;
77 14ad7326 pastith
import javax.jws.WebMethod;
78 14ad7326 pastith
import javax.naming.Context;
79 14ad7326 pastith
import javax.naming.InitialContext;
80 14ad7326 pastith
import javax.naming.NamingException;
81 14ad7326 pastith
import javax.xml.parsers.DocumentBuilder;
82 14ad7326 pastith
import javax.xml.parsers.DocumentBuilderFactory;
83 14ad7326 pastith
import javax.xml.parsers.ParserConfigurationException;
84 14ad7326 pastith
import javax.xml.transform.OutputKeys;
85 14ad7326 pastith
import javax.xml.transform.Transformer;
86 14ad7326 pastith
import javax.xml.transform.TransformerConfigurationException;
87 14ad7326 pastith
import javax.xml.transform.TransformerException;
88 14ad7326 pastith
import javax.xml.transform.TransformerFactory;
89 14ad7326 pastith
import javax.xml.transform.dom.DOMSource;
90 14ad7326 pastith
import javax.xml.transform.stream.StreamResult;
91 14ad7326 pastith
92 14ad7326 pastith
import org.apache.commons.httpclient.HttpClient;
93 14ad7326 pastith
import org.apache.commons.httpclient.HttpException;
94 14ad7326 pastith
import org.apache.commons.httpclient.NameValuePair;
95 14ad7326 pastith
import org.apache.commons.httpclient.methods.GetMethod;
96 14ad7326 pastith
import org.apache.commons.httpclient.methods.PostMethod;
97 14ad7326 pastith
import org.apache.commons.httpclient.methods.StringRequestEntity;
98 14ad7326 pastith
import org.apache.commons.lang.StringUtils;
99 14ad7326 pastith
import org.apache.commons.logging.Log;
100 14ad7326 pastith
import org.apache.commons.logging.LogFactory;
101 14ad7326 pastith
import org.w3c.dom.DOMException;
102 14ad7326 pastith
import org.w3c.dom.Document;
103 14ad7326 pastith
import org.w3c.dom.Node;
104 14ad7326 pastith
import org.w3c.dom.NodeList;
105 14ad7326 pastith
import org.xml.sax.SAXException;
106 14ad7326 pastith
107 14ad7326 pastith
/**
108 14ad7326 pastith
 * The concrete implementation of the ExternalAPI interface.
109 14ad7326 pastith
 *
110 14ad7326 pastith
 * @author past
111 14ad7326 pastith
 */
112 14ad7326 pastith
@Stateless
113 14ad7326 pastith
public class ExternalAPIBean implements ExternalAPI, ExternalAPIRemote {
114 14ad7326 pastith
        /**
115 14ad7326 pastith
         * The default MIME type for files without an explicit one.
116 14ad7326 pastith
         */
117 14ad7326 pastith
        private static final String DEFAULT_MIME_TYPE = "application/octet-stream";
118 14ad7326 pastith
119 14ad7326 pastith
        /**
120 14ad7326 pastith
         * The size of the buffer that is used to temporarily store chunks of
121 14ad7326 pastith
         * uploaded files, while storing them to the file repository.
122 14ad7326 pastith
         */
123 14ad7326 pastith
        private static final int UPLOAD_BUFFER_SIZE = 1024 * 4;
124 14ad7326 pastith
125 14ad7326 pastith
        /**
126 14ad7326 pastith
         * The logger.
127 14ad7326 pastith
         */
128 14ad7326 pastith
        private static Log logger = LogFactory.getLog(ExternalAPIBean.class);
129 14ad7326 pastith
130 14ad7326 pastith
        /**
131 14ad7326 pastith
         * Injected reference to the GSSDAO data access facade.
132 14ad7326 pastith
         */
133 14ad7326 pastith
        @EJB
134 14ad7326 pastith
        private GSSDAO dao;
135 14ad7326 pastith
136 09051786 droutsis
137 14ad7326 pastith
        /**
138 14ad7326 pastith
         * A cached random number generator for creating unique filenames.
139 14ad7326 pastith
         */
140 14ad7326 pastith
        private static Random random = new Random();
141 14ad7326 pastith
142 68410d59 pastith
        @Override
143 68410d59 pastith
        public FolderDTO getRootFolder(Long userId) throws ObjectNotFoundException {
144 14ad7326 pastith
                if (userId == null)
145 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
146 68410d59 pastith
                Folder folder = dao.getRootFolder(userId);
147 14ad7326 pastith
                return folder.getDTO();
148 14ad7326 pastith
        }
149 14ad7326 pastith
150 14ad7326 pastith
        /*
151 14ad7326 pastith
         * (non-Javadoc)
152 14ad7326 pastith
         *
153 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#getFolder(java.lang.Long)
154 14ad7326 pastith
         */
155 14ad7326 pastith
        public FolderDTO getFolder(final Long userId, final Long folderId) throws ObjectNotFoundException, InsufficientPermissionsException {
156 14ad7326 pastith
                if (userId == null)
157 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
158 14ad7326 pastith
                if (folderId == null)
159 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
160 14ad7326 pastith
                final User user = dao.getEntityById(User.class, userId);
161 14ad7326 pastith
                final Folder folder = dao.getEntityById(Folder.class, folderId);
162 14ad7326 pastith
                // Check permissions
163 14ad7326 pastith
                if (!folder.hasReadPermission(user))
164 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the permissions to read this folder");
165 14ad7326 pastith
                return folder.getDTO();
166 14ad7326 pastith
        }
167 14ad7326 pastith
168 14ad7326 pastith
        /* (non-Javadoc)
169 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#getUser(java.lang.Long)
170 14ad7326 pastith
         */
171 14ad7326 pastith
        public User getUser(Long userId) throws ObjectNotFoundException {
172 14ad7326 pastith
                if (userId == null)
173 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
174 14ad7326 pastith
                return dao.getEntityById(User.class, userId);
175 14ad7326 pastith
        }
176 14ad7326 pastith
177 14ad7326 pastith
        /* (non-Javadoc)
178 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#getUserDTO(java.lang.Long)
179 14ad7326 pastith
         */
180 14ad7326 pastith
        public UserDTO getUserDTO(final Long userId) throws ObjectNotFoundException {
181 14ad7326 pastith
                return getUser(userId).getDTO();
182 14ad7326 pastith
        }
183 14ad7326 pastith
184 14ad7326 pastith
        /*
185 14ad7326 pastith
         * (non-Javadoc)
186 14ad7326 pastith
         *
187 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#getGroup(java.lang.Long)
188 14ad7326 pastith
         */
189 14ad7326 pastith
        public GroupDTO getGroup(final Long groupId) throws ObjectNotFoundException {
190 14ad7326 pastith
                if (groupId == null)
191 14ad7326 pastith
                        throw new ObjectNotFoundException("No group specified");
192 14ad7326 pastith
                final Group group = dao.getEntityById(Group.class, groupId);
193 14ad7326 pastith
                return group.getDTO();
194 14ad7326 pastith
        }
195 14ad7326 pastith
196 14ad7326 pastith
        @Override
197 14ad7326 pastith
        public GroupDTO getGroup(Long userId, String name) throws ObjectNotFoundException {
198 14ad7326 pastith
                if (userId == null)
199 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
200 14ad7326 pastith
                if (name == null)
201 14ad7326 pastith
                        throw new ObjectNotFoundException("No group specified");
202 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
203 14ad7326 pastith
                List<Group> groups = user.getGroupsSpecified();
204 14ad7326 pastith
                for (Group group: groups)
205 14ad7326 pastith
                        if (group.getName().equals(name))
206 14ad7326 pastith
                                return group.getDTO();
207 14ad7326 pastith
                throw new ObjectNotFoundException("Group " + name + " not found");
208 14ad7326 pastith
        }
209 14ad7326 pastith
210 14ad7326 pastith
        /*
211 14ad7326 pastith
         * (non-Javadoc)
212 14ad7326 pastith
         *
213 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#getGroups(java.lang.Long)
214 14ad7326 pastith
         */
215 14ad7326 pastith
        public List<GroupDTO> getGroups(final Long userId) throws ObjectNotFoundException {
216 14ad7326 pastith
                if (userId == null)
217 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
218 14ad7326 pastith
                final List<Group> groups = dao.getGroups(userId);
219 14ad7326 pastith
                final List<GroupDTO> result = new ArrayList<GroupDTO>();
220 14ad7326 pastith
                for (final Group g : groups)
221 14ad7326 pastith
                        result.add(g.getDTO());
222 14ad7326 pastith
                return result;
223 14ad7326 pastith
        }
224 14ad7326 pastith
225 14ad7326 pastith
        @Override
226 3d1b9329 koutsoub
        public List<FileHeaderDTO> getFiles(Long userId, Long folderId, boolean ignoreDeleted)
227 14ad7326 pastith
                        throws ObjectNotFoundException, InsufficientPermissionsException {
228 14ad7326 pastith
                // Validate.
229 14ad7326 pastith
                if (userId == null)
230 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
231 14ad7326 pastith
                if (folderId == null)
232 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
233 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
234 14ad7326 pastith
                Folder folder = dao.getEntityById(Folder.class, folderId);
235 14ad7326 pastith
                if (!folder.hasReadPermission(user))
236 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the permissions to read this folder");
237 14ad7326 pastith
                // Do the actual work.
238 14ad7326 pastith
                List<FileHeaderDTO> result = new ArrayList<FileHeaderDTO>();
239 cc154eca droutsis
                List<FileHeader> files = dao.getFiles(folderId, userId, ignoreDeleted);
240 14ad7326 pastith
                for (FileHeader f : files)
241 14ad7326 pastith
                        result.add(f.getDTO());
242 14ad7326 pastith
                return result;
243 14ad7326 pastith
        }
244 14ad7326 pastith
245 14ad7326 pastith
        /*
246 14ad7326 pastith
         * (non-Javadoc)
247 14ad7326 pastith
         *
248 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#getUsers(java.lang.Long,
249 14ad7326 pastith
         *      java.lang.Long)
250 14ad7326 pastith
         */
251 14ad7326 pastith
        public List<UserDTO> getUsers(final Long userId, final Long groupId) throws ObjectNotFoundException {
252 14ad7326 pastith
                // Validate.
253 14ad7326 pastith
                if (userId == null)
254 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
255 14ad7326 pastith
                if (groupId == null)
256 14ad7326 pastith
                        throw new ObjectNotFoundException("No group specified");
257 14ad7326 pastith
258 14ad7326 pastith
                // Do the actual work.
259 14ad7326 pastith
                final List<User> users = dao.getUsers(groupId);
260 14ad7326 pastith
                final List<UserDTO> result = new ArrayList<UserDTO>();
261 14ad7326 pastith
                for (final User u : users)
262 14ad7326 pastith
                        result.add(u.getDTO());
263 14ad7326 pastith
                return result;
264 14ad7326 pastith
        }
265 14ad7326 pastith
266 14ad7326 pastith
        @Override
267 a0dde818 Panagiotis Astithas
        public FolderDTO createFolder(Long userId, Long parentId, String name)
268 14ad7326 pastith
                        throws DuplicateNameException, ObjectNotFoundException, InsufficientPermissionsException {
269 14ad7326 pastith
                // Validate.
270 14ad7326 pastith
                if (userId == null)
271 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
272 14ad7326 pastith
                if (StringUtils.isEmpty(name))
273 14ad7326 pastith
                        throw new ObjectNotFoundException("New folder name is empty");
274 14ad7326 pastith
                if (parentId == null)
275 14ad7326 pastith
                        throw new ObjectNotFoundException("No parent specified");
276 14ad7326 pastith
                if (dao.existsFolderOrFile(parentId, name))
277 14ad7326 pastith
                        throw new DuplicateNameException("A folder or file with the name '" +
278 14ad7326 pastith
                                                name + "' already exists at this level");
279 14ad7326 pastith
280 14ad7326 pastith
                User creator = dao.getEntityById(User.class, userId);
281 14ad7326 pastith
282 14ad7326 pastith
                Folder parent = null;
283 14ad7326 pastith
                try {
284 14ad7326 pastith
                        parent = dao.getEntityById(Folder.class, parentId);
285 14ad7326 pastith
                } catch (ObjectNotFoundException onfe) {
286 14ad7326 pastith
                        // Supply a more accurate problem description.
287 14ad7326 pastith
                        throw new ObjectNotFoundException("Parent folder not found");
288 14ad7326 pastith
                }
289 14ad7326 pastith
                if (!parent.hasWritePermission(creator))
290 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the permissions" +
291 14ad7326 pastith
                                        " to write to this folder");
292 14ad7326 pastith
293 14ad7326 pastith
                // Do the actual work.
294 a0dde818 Panagiotis Astithas
                return createFolder(name, parent, creator);
295 14ad7326 pastith
        }
296 14ad7326 pastith
297 14ad7326 pastith
        /**
298 14ad7326 pastith
         * Create a new folder with the provided name, parent and owner.
299 14ad7326 pastith
         *
300 14ad7326 pastith
         * @param name
301 14ad7326 pastith
         * @param parent
302 14ad7326 pastith
         * @param creator
303 a0dde818 Panagiotis Astithas
         * @return the new folder
304 14ad7326 pastith
         */
305 a0dde818 Panagiotis Astithas
        private FolderDTO createFolder(String name, Folder parent, User creator) {
306 14ad7326 pastith
                Folder folder = new Folder();
307 14ad7326 pastith
                folder.setName(name);
308 14ad7326 pastith
                if (parent != null) {
309 14ad7326 pastith
                        parent.addSubfolder(folder);
310 14ad7326 pastith
                        folder.setOwner(parent.getOwner());
311 14ad7326 pastith
                } else
312 14ad7326 pastith
                        folder.setOwner(creator);
313 14ad7326 pastith
314 14ad7326 pastith
                Date now = new Date();
315 14ad7326 pastith
                AuditInfo auditInfo = new AuditInfo();
316 14ad7326 pastith
                auditInfo.setCreatedBy(creator);
317 14ad7326 pastith
                auditInfo.setCreationDate(now);
318 14ad7326 pastith
                auditInfo.setModifiedBy(creator);
319 14ad7326 pastith
                auditInfo.setModificationDate(now);
320 14ad7326 pastith
                folder.setAuditInfo(auditInfo);
321 14ad7326 pastith
322 14ad7326 pastith
                if (parent != null)
323 14ad7326 pastith
                        for (Permission p : parent.getPermissions()) {
324 14ad7326 pastith
                                Permission permission = new Permission();
325 14ad7326 pastith
                                permission.setGroup(p.getGroup());
326 14ad7326 pastith
                                permission.setUser(p.getUser());
327 14ad7326 pastith
                                permission.setRead(p.getRead());
328 14ad7326 pastith
                                permission.setWrite(p.getWrite());
329 14ad7326 pastith
                                permission.setModifyACL(p.getModifyACL());
330 14ad7326 pastith
                                folder.addPermission(permission);
331 14ad7326 pastith
                        }
332 14ad7326 pastith
                else {
333 14ad7326 pastith
                        Permission permission = new Permission();
334 14ad7326 pastith
                        permission.setUser(creator);
335 14ad7326 pastith
                        permission.setRead(true);
336 14ad7326 pastith
                        permission.setWrite(true);
337 14ad7326 pastith
                        permission.setModifyACL(true);
338 14ad7326 pastith
                        folder.addPermission(permission);
339 14ad7326 pastith
                }
340 14ad7326 pastith
                dao.create(folder);
341 a0dde818 Panagiotis Astithas
                return folder.getDTO();
342 14ad7326 pastith
        }
343 14ad7326 pastith
344 14ad7326 pastith
        /*
345 4d737770 Fotis Stamatelopoulos
         * Deletes the given folder and all its subfolders and files
346 4d737770 Fotis Stamatelopoulos
         * Only the permissions for top folder are checked
347 14ad7326 pastith
         *
348 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#deleteFolder(java.lang.Long,
349 14ad7326 pastith
         *      java.lang.Long)
350 14ad7326 pastith
         */
351 14ad7326 pastith
        public void deleteFolder(final Long userId, final Long folderId) throws InsufficientPermissionsException, ObjectNotFoundException {
352 14ad7326 pastith
                // Validate.
353 14ad7326 pastith
                if (userId == null)
354 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
355 14ad7326 pastith
                if (folderId == null)
356 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
357 14ad7326 pastith
358 14ad7326 pastith
                // Do the actual work.
359 14ad7326 pastith
                final Folder folder = dao.getEntityById(Folder.class, folderId);
360 14ad7326 pastith
                final Folder parent = folder.getParent();
361 14ad7326 pastith
                if (parent == null)
362 14ad7326 pastith
                        throw new ObjectNotFoundException("Deleting the root folder is not allowed");
363 14ad7326 pastith
                final User user = dao.getEntityById(User.class, userId);
364 14ad7326 pastith
                if (!folder.hasDeletePermission(user)) {
365 14ad7326 pastith
                        logger.info("User " + user.getId() + " cannot delete folder " + folder.getName() + "(" + folder.getId() + ")");
366 14ad7326 pastith
                        throw new InsufficientPermissionsException("User " + user.getId() + " cannot delete folder " + folder.getName() + "(" + folder.getId() + ")");
367 14ad7326 pastith
                }
368 4d737770 Fotis Stamatelopoulos
                removeSubfolderFiles(folder);
369 14ad7326 pastith
                parent.removeSubfolder(folder);
370 14ad7326 pastith
                dao.delete(folder);
371 14ad7326 pastith
        }
372 14ad7326 pastith
373 4d737770 Fotis Stamatelopoulos
        /**
374 4d737770 Fotis Stamatelopoulos
         * Traverses the folder and deletes all actual files (file system)
375 4d737770 Fotis Stamatelopoulos
         * regardless of permissions
376 4d737770 Fotis Stamatelopoulos
         *
377 4d737770 Fotis Stamatelopoulos
         * @param folder
378 4d737770 Fotis Stamatelopoulos
         */
379 4d737770 Fotis Stamatelopoulos
        private void removeSubfolderFiles(Folder folder) {
380 4d737770 Fotis Stamatelopoulos
                //remove files for all subfolders
381 4d737770 Fotis Stamatelopoulos
                for (Folder subfolder:folder.getSubfolders())
382 4d737770 Fotis Stamatelopoulos
                        removeSubfolderFiles(subfolder);
383 4d737770 Fotis Stamatelopoulos
                //remove this folder's file bodies (actual files)
384 4d737770 Fotis Stamatelopoulos
                for (FileHeader file:folder.getFiles()) {
385 4d737770 Fotis Stamatelopoulos
                        for (FileBody body:file.getBodies())
386 4d737770 Fotis Stamatelopoulos
                                deleteActualFile(body.getStoredFilePath());
387 4d737770 Fotis Stamatelopoulos
                        indexFile(file.getId(), true);
388 4d737770 Fotis Stamatelopoulos
                }
389 4d737770 Fotis Stamatelopoulos
        }
390 4d737770 Fotis Stamatelopoulos
391 14ad7326 pastith
        @SuppressWarnings("unchecked")
392 68410d59 pastith
        public List<FolderDTO> getSubfolders(Long userId, Long folderId)
393 68410d59 pastith
                        throws ObjectNotFoundException, InsufficientPermissionsException {
394 14ad7326 pastith
                if (userId == null)
395 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
396 14ad7326 pastith
                if (folderId == null)
397 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
398 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
399 14ad7326 pastith
                Folder folder = dao.getEntityById(Folder.class, folderId);
400 14ad7326 pastith
                if (!folder.hasReadPermission(user))
401 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the permissions to read this folder");
402 14ad7326 pastith
                List<FolderDTO> result = new ArrayList<FolderDTO>();
403 14ad7326 pastith
                if (folder.hasReadPermission(user))
404 14ad7326 pastith
                        for (Folder f : folder.getSubfolders())
405 14ad7326 pastith
                                if (f.hasReadPermission(user) && !f.isDeleted())
406 14ad7326 pastith
                                        result.add(f.getDTO());
407 14ad7326 pastith
                return result;
408 14ad7326 pastith
        }
409 14ad7326 pastith
410 afdfbc24 pastith
        @Override
411 77dcb3f1 Panagiotis Astithas
        public FolderDTO modifyFolder(Long userId, Long folderId, String folderName)
412 afdfbc24 pastith
                        throws InsufficientPermissionsException, ObjectNotFoundException, DuplicateNameException {
413 14ad7326 pastith
414 14ad7326 pastith
                // Validate.
415 14ad7326 pastith
                if (userId == null)
416 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
417 14ad7326 pastith
                if (folderId == null)
418 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
419 14ad7326 pastith
                if (StringUtils.isEmpty(folderName))
420 14ad7326 pastith
                        throw new ObjectNotFoundException("New folder name is empty");
421 afdfbc24 pastith
422 afdfbc24 pastith
                Folder folder = dao.getEntityById(Folder.class, folderId);
423 afdfbc24 pastith
                User user = dao.getEntityById(User.class, userId);
424 14ad7326 pastith
                if (!folder.hasWritePermission(user))
425 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
426 afdfbc24 pastith
427 afdfbc24 pastith
                Folder parent = folder.getParent();
428 afdfbc24 pastith
                if (parent != null)
429 afdfbc24 pastith
                        if (!folder.getName().equals(folderName) && dao.existsFolderOrFile(parent.getId(), folderName))
430 afdfbc24 pastith
                                throw new DuplicateNameException("A folder or file with the name '" + folderName + "' already exists at this level");
431 14ad7326 pastith
432 14ad7326 pastith
                // Do the actual modification.
433 14ad7326 pastith
                folder.setName(folderName);
434 14ad7326 pastith
                dao.update(folder);
435 77dcb3f1 Panagiotis Astithas
                return folder.getDTO();
436 14ad7326 pastith
        }
437 14ad7326 pastith
438 14ad7326 pastith
        /*
439 14ad7326 pastith
         * (non-Javadoc)
440 14ad7326 pastith
         *
441 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#createGroup(java.lang.Long,
442 14ad7326 pastith
         *      java.lang.String)
443 14ad7326 pastith
         */
444 14ad7326 pastith
        public void createGroup(final Long userId, final String name) throws ObjectNotFoundException, DuplicateNameException {
445 14ad7326 pastith
                // Validate.
446 14ad7326 pastith
                if (userId == null)
447 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
448 14ad7326 pastith
                if (StringUtils.isEmpty(name))
449 14ad7326 pastith
                        throw new ObjectNotFoundException("New group name is empty");
450 14ad7326 pastith
                if (dao.existsGroup(userId, name))
451 14ad7326 pastith
                        throw new DuplicateNameException("A group with the name '" + name + "' already exists");
452 14ad7326 pastith
453 14ad7326 pastith
                // TODO: Check permissions
454 14ad7326 pastith
455 14ad7326 pastith
                final User owner = dao.getEntityById(User.class, userId);
456 14ad7326 pastith
457 14ad7326 pastith
                // Do the actual work.
458 14ad7326 pastith
                owner.createGroup(name);
459 14ad7326 pastith
        }
460 14ad7326 pastith
461 14ad7326 pastith
        /*
462 14ad7326 pastith
         * (non-Javadoc)
463 14ad7326 pastith
         *
464 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#deleteGroup(java.lang.Long,
465 14ad7326 pastith
         *      java.lang.Long)
466 14ad7326 pastith
         */
467 14ad7326 pastith
        public void deleteGroup(final Long userId, final Long groupId) throws ObjectNotFoundException, InsufficientPermissionsException {
468 14ad7326 pastith
                // Validate.
469 14ad7326 pastith
                if (userId == null)
470 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
471 14ad7326 pastith
                if (groupId == null)
472 14ad7326 pastith
                        throw new ObjectNotFoundException("No group specified");
473 14ad7326 pastith
474 14ad7326 pastith
                // Do the actual work.
475 14ad7326 pastith
                final User owner = dao.getEntityById(User.class, userId);
476 14ad7326 pastith
                final Group group = dao.getEntityById(Group.class, groupId);
477 14ad7326 pastith
                // Only delete the group if actually owned by the user.
478 14ad7326 pastith
                if (group.getOwner().equals(owner)) {
479 14ad7326 pastith
                        List<Folder> folders = dao.getFoldersPermittedForGroup(userId, groupId);
480 14ad7326 pastith
                        for (Folder f : folders){
481 14ad7326 pastith
                                f.getPermissions().removeAll(group.getPermissions());
482 14ad7326 pastith
                                for(FileHeader file : f.getFiles())
483 14ad7326 pastith
                                        file.getPermissions().removeAll(group.getPermissions());
484 14ad7326 pastith
                        }
485 14ad7326 pastith
                        List<FileHeader> files = dao.getSharedFilesNotInSharedFolders(userId);
486 14ad7326 pastith
                        for(FileHeader h : files)
487 14ad7326 pastith
                                h.getPermissions().removeAll(group.getPermissions());
488 14ad7326 pastith
                        owner.removeSpecifiedGroup(group);
489 14ad7326 pastith
                        dao.delete(group);
490 14ad7326 pastith
                }
491 14ad7326 pastith
                else throw new InsufficientPermissionsException("You are not the owner of this group");
492 14ad7326 pastith
        }
493 14ad7326 pastith
494 14ad7326 pastith
        @Override
495 8f128261 droutsis
        public FileHeaderDTO createFile(Long userId, Long folderId, String name, String mimeType, InputStream stream)
496 14ad7326 pastith
                        throws DuplicateNameException, ObjectNotFoundException, GSSIOException,
497 14ad7326 pastith
                        InsufficientPermissionsException, QuotaExceededException {
498 14ad7326 pastith
                File file = null;
499 14ad7326 pastith
                try {
500 14ad7326 pastith
                        file = uploadFile(stream, userId);
501 14ad7326 pastith
                } catch ( IOException ioe) {
502 14ad7326 pastith
                        // Supply a more accurate problem description.
503 14ad7326 pastith
                        throw new GSSIOException("Problem creating file",ioe);
504 14ad7326 pastith
                }
505 4d737770 Fotis Stamatelopoulos
                return createFile(userId, folderId, name, mimeType, file.length(), file.getAbsolutePath());
506 14ad7326 pastith
        }
507 14ad7326 pastith
508 14ad7326 pastith
        /* (non-Javadoc)
509 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPIRemote#indexFile(java.lang.Long, boolean)
510 14ad7326 pastith
         */
511 14ad7326 pastith
        public void indexFile(Long fileId, boolean delete) {
512 14ad7326 pastith
                Connection qConn = null;
513 14ad7326 pastith
                Session session = null;
514 14ad7326 pastith
                MessageProducer sender = null;
515 14ad7326 pastith
                try {
516 14ad7326 pastith
                        Context jndiCtx = new InitialContext();
517 14ad7326 pastith
                        ConnectionFactory factory = (QueueConnectionFactory) jndiCtx.lookup("java:/JmsXA");
518 14ad7326 pastith
                        Queue queue = (Queue) jndiCtx.lookup("queue/gss-indexingQueue");
519 14ad7326 pastith
                        qConn = factory.createConnection();
520 14ad7326 pastith
                        session = qConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
521 14ad7326 pastith
                        sender = session.createProducer(queue);
522 14ad7326 pastith
523 14ad7326 pastith
                        MapMessage map = session.createMapMessage();
524 14ad7326 pastith
                        map.setObject("id", fileId);
525 14ad7326 pastith
                        map.setBoolean("delete", delete);
526 14ad7326 pastith
                        sender.send(map);
527 14ad7326 pastith
                }
528 14ad7326 pastith
                catch (NamingException e) {
529 14ad7326 pastith
                        logger.error("Index was not updated: ", e);
530 14ad7326 pastith
                }
531 14ad7326 pastith
                catch (JMSException e) {
532 14ad7326 pastith
                        logger.error("Index was not updated: ", e);
533 14ad7326 pastith
                }
534 14ad7326 pastith
                finally {
535 14ad7326 pastith
                        try {
536 14ad7326 pastith
                                if (sender != null)
537 14ad7326 pastith
                                        sender.close();
538 14ad7326 pastith
                                if (session != null)
539 14ad7326 pastith
                                        session.close();
540 14ad7326 pastith
                                if (qConn != null)
541 14ad7326 pastith
                                        qConn.close();
542 14ad7326 pastith
                        }
543 14ad7326 pastith
                        catch (JMSException e) {
544 14ad7326 pastith
                                logger.warn(e);
545 14ad7326 pastith
                        }
546 14ad7326 pastith
                }
547 14ad7326 pastith
        }
548 14ad7326 pastith
549 14ad7326 pastith
550 14ad7326 pastith
551 14ad7326 pastith
        /**
552 14ad7326 pastith
         * A helper method that generates a unique file path for a stored file. The
553 14ad7326 pastith
         * files are stored using random hash names that are distributed evenly in
554 14ad7326 pastith
         * a 2-level tree of subdirectories named after the first two hex characters
555 14ad7326 pastith
         * in the name. For example, file ab1234cd5769f will be stored in the path
556 14ad7326 pastith
         * /file-repository-root/a/b/ab1234cd5769f. The directories will be created
557 14ad7326 pastith
         * if they don't already exist.
558 14ad7326 pastith
         *
559 14ad7326 pastith
         * @return a unique new file path
560 14ad7326 pastith
         */
561 14ad7326 pastith
        private String generateRepositoryFilePath() {
562 14ad7326 pastith
                String filename = Long.toHexString(random.nextLong());
563 bde4eafb pastith
                String fileRepositoryPath = getConfiguration().getString("fileRepositoryPath","/tmp");
564 14ad7326 pastith
                File root = new File(fileRepositoryPath);
565 14ad7326 pastith
                if (!root.exists())
566 14ad7326 pastith
                        root.mkdirs();
567 14ad7326 pastith
                File firstFolder = new File(root + File.separator + filename.substring(0, 1));
568 14ad7326 pastith
                if (!firstFolder.exists())
569 14ad7326 pastith
                        firstFolder.mkdir();
570 14ad7326 pastith
                File secondFolder = new File(firstFolder + File.separator + filename.substring(1, 2));
571 14ad7326 pastith
                if (!secondFolder.exists())
572 14ad7326 pastith
                        secondFolder.mkdir();
573 14ad7326 pastith
                return secondFolder + File.separator + filename;
574 14ad7326 pastith
        }
575 14ad7326 pastith
576 14ad7326 pastith
        /*
577 14ad7326 pastith
         * (non-Javadoc)
578 14ad7326 pastith
         *
579 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#deleteFile(java.lang.Long,
580 14ad7326 pastith
         *      java.lang.Long)
581 14ad7326 pastith
         */
582 14ad7326 pastith
        public void deleteFile(final Long userId, final Long fileId) throws ObjectNotFoundException, InsufficientPermissionsException {
583 14ad7326 pastith
                // Validate.
584 14ad7326 pastith
                if (userId == null)
585 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
586 14ad7326 pastith
                if (fileId == null)
587 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
588 14ad7326 pastith
589 14ad7326 pastith
                // Do the actual work.
590 14ad7326 pastith
                final FileHeader file = dao.getEntityById(FileHeader.class, fileId);
591 14ad7326 pastith
                final Folder parent = file.getFolder();
592 14ad7326 pastith
                if (parent == null)
593 14ad7326 pastith
                        throw new ObjectNotFoundException("The specified file has no parent folder");
594 14ad7326 pastith
                final User user = dao.getEntityById(User.class, userId);
595 14ad7326 pastith
                if (!file.hasDeletePermission(user))
596 14ad7326 pastith
                        throw new InsufficientPermissionsException("User " + user.getId() + " cannot delete file " + file.getName() + "(" + file.getId() + ")");
597 4d737770 Fotis Stamatelopoulos
                for (final FileBody body : file.getBodies())
598 4d737770 Fotis Stamatelopoulos
                        deleteActualFile(body.getStoredFilePath());
599 14ad7326 pastith
                dao.delete(file);
600 14ad7326 pastith
                indexFile(fileId, true);
601 14ad7326 pastith
        }
602 14ad7326 pastith
603 4d737770 Fotis Stamatelopoulos
        private void deleteActualFile(String filePath) {
604 4d737770 Fotis Stamatelopoulos
                if (filePath == null)
605 4d737770 Fotis Stamatelopoulos
                        return;
606 4d737770 Fotis Stamatelopoulos
                File file = new File(filePath);
607 4d737770 Fotis Stamatelopoulos
                if (!file.delete())
608 4d737770 Fotis Stamatelopoulos
                        logger.error("Could not delete file " + filePath);
609 4d737770 Fotis Stamatelopoulos
        }
610 4d737770 Fotis Stamatelopoulos
611 14ad7326 pastith
        /*
612 14ad7326 pastith
         * (non-Javadoc)
613 14ad7326 pastith
         *
614 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#createTag(java.lang.Long,
615 14ad7326 pastith
         *      java.lang.Long, java.lang.String)
616 14ad7326 pastith
         */
617 14ad7326 pastith
        public void createTag(final Long userId, final Long fileHeaderId, final String tag) throws ObjectNotFoundException {
618 14ad7326 pastith
                if (userId == null)
619 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
620 14ad7326 pastith
                if (fileHeaderId == null)
621 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
622 14ad7326 pastith
                if (StringUtils.isEmpty(tag))
623 14ad7326 pastith
                        throw new ObjectNotFoundException("Tag is empty");
624 14ad7326 pastith
625 14ad7326 pastith
                final User user = dao.getEntityById(User.class, userId);
626 14ad7326 pastith
                final FileHeader fh = dao.getEntityById(FileHeader.class, fileHeaderId);
627 14ad7326 pastith
                user.addTag(fh, tag);
628 14ad7326 pastith
        }
629 14ad7326 pastith
630 14ad7326 pastith
        /* (non-Javadoc)
631 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#getUserTags(java.lang.Long)
632 14ad7326 pastith
         */
633 14ad7326 pastith
        @WebMethod(operationName = "getUserTags")
634 14ad7326 pastith
        public Set<String> getUserTags(final Long userId) throws ObjectNotFoundException {
635 14ad7326 pastith
                return dao.getUserTags(userId);
636 14ad7326 pastith
        }
637 14ad7326 pastith
638 14ad7326 pastith
        /* (non-Javadoc)
639 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#updateFile(java.lang.Long, java.lang.Long, java.lang.String, java.util.Set)
640 14ad7326 pastith
         */
641 14ad7326 pastith
        public void updateFile(Long userId, Long fileId, String name, String tagSet) throws ObjectNotFoundException, InsufficientPermissionsException {
642 14ad7326 pastith
                if (userId == null)
643 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
644 14ad7326 pastith
                if (fileId == null)
645 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
646 14ad7326 pastith
                FileHeader file = dao.getEntityById(FileHeader.class, fileId);
647 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
648 14ad7326 pastith
                if (!file.hasWritePermission(user))
649 14ad7326 pastith
                        throw new InsufficientPermissionsException("User " + user.getId() + " cannot update file " + file.getName() + "(" + file.getId() + ")");
650 14ad7326 pastith
651 14ad7326 pastith
                if (name != null)
652 14ad7326 pastith
                        file.setName(name);
653 14ad7326 pastith
                List<FileTag> tags = file.getFileTags();
654 14ad7326 pastith
655 14ad7326 pastith
                if (tagSet != null) {
656 14ad7326 pastith
                        Iterator<FileTag> i = tags.iterator();
657 14ad7326 pastith
                        while (i.hasNext()) {
658 14ad7326 pastith
                                FileTag tag = i.next();
659 14ad7326 pastith
                                i.remove();
660 14ad7326 pastith
                                tag.setFile(null);
661 14ad7326 pastith
                                user.removeTag(tag);
662 14ad7326 pastith
                                dao.delete(tag);
663 14ad7326 pastith
                        }
664 14ad7326 pastith
                        dao.flush();
665 14ad7326 pastith
                        StringTokenizer st = new StringTokenizer(tagSet, ",");
666 14ad7326 pastith
                        while (st.hasMoreTokens())
667 14ad7326 pastith
                                new FileTag(user, file, st.nextToken().trim());
668 14ad7326 pastith
                }
669 14ad7326 pastith
670 14ad7326 pastith
                // Re-index the file if it was modified.
671 14ad7326 pastith
                if (name != null || tagSet != null)
672 14ad7326 pastith
                        indexFile(fileId, false);
673 14ad7326 pastith
        }
674 14ad7326 pastith
675 14ad7326 pastith
        @Override
676 14ad7326 pastith
        public InputStream getFileContents(Long userId, Long fileId)
677 14ad7326 pastith
                        throws ObjectNotFoundException, InsufficientPermissionsException {
678 14ad7326 pastith
                if (userId == null)
679 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
680 14ad7326 pastith
                if (fileId == null)
681 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
682 14ad7326 pastith
683 14ad7326 pastith
                FileHeader header = dao.getEntityById(FileHeader.class, fileId);
684 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
685 14ad7326 pastith
                if (!header.hasReadPermission(user)) {
686 14ad7326 pastith
                        logger.info("User " + user.getId() + " cannot read file " + header.getName() + "(" + fileId + ")");
687 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
688 14ad7326 pastith
                }
689 14ad7326 pastith
690 14ad7326 pastith
                File f = new File(header.getCurrentBody().getStoredFilePath());
691 14ad7326 pastith
                try {
692 14ad7326 pastith
                        return new FileInputStream(f);
693 14ad7326 pastith
                } catch (FileNotFoundException e) {
694 14ad7326 pastith
                        logger.error("Could not locate the contents of file " + f.getAbsolutePath());
695 14ad7326 pastith
                        throw new ObjectNotFoundException("The file contents could not be located");
696 14ad7326 pastith
                }
697 14ad7326 pastith
        }
698 14ad7326 pastith
699 14ad7326 pastith
        /* (non-Javadoc)
700 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#getFileContents(java.lang.Long, java.lang.Long, java.lang.Long)
701 14ad7326 pastith
         */
702 14ad7326 pastith
        public InputStream getFileContents(Long userId, Long fileId, Long bodyId) throws ObjectNotFoundException, InsufficientPermissionsException {
703 14ad7326 pastith
                if (userId == null)
704 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
705 14ad7326 pastith
                if (fileId == null)
706 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
707 14ad7326 pastith
                if (bodyId == null)
708 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
709 14ad7326 pastith
710 14ad7326 pastith
                final FileHeader header = dao.getEntityById(FileHeader.class, fileId);
711 14ad7326 pastith
                final FileBody body = dao.getEntityById(FileBody.class, bodyId);
712 14ad7326 pastith
                final User user = dao.getEntityById(User.class, userId);
713 14ad7326 pastith
                if (!header.hasReadPermission(user)) {
714 14ad7326 pastith
                        logger.info("User " + user.getId() + " cannot read file " + header.getName() + "(" + fileId + ")");
715 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
716 14ad7326 pastith
                }
717 14ad7326 pastith
718 14ad7326 pastith
                File f = new File(body.getStoredFilePath());
719 14ad7326 pastith
                try {
720 14ad7326 pastith
                        return new FileInputStream(f);
721 14ad7326 pastith
                } catch (FileNotFoundException e) {
722 14ad7326 pastith
                        logger.error("Could not locate the contents of file " + f.getAbsolutePath());
723 14ad7326 pastith
                        throw new ObjectNotFoundException("The file contents could not be located");
724 14ad7326 pastith
                }
725 14ad7326 pastith
        }
726 14ad7326 pastith
727 14ad7326 pastith
        /* (non-Javadoc)
728 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#getFile(java.lang.Long, java.lang.Long)
729 14ad7326 pastith
         */
730 14ad7326 pastith
        public FileHeaderDTO getFile(Long userId, Long fileId) throws ObjectNotFoundException, InsufficientPermissionsException {
731 14ad7326 pastith
                if (userId == null)
732 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
733 14ad7326 pastith
                if (fileId == null)
734 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
735 14ad7326 pastith
                final User user = dao.getEntityById(User.class, userId);
736 14ad7326 pastith
                final FileHeader file = dao.getEntityById(FileHeader.class, fileId);
737 14ad7326 pastith
                if (!file.hasReadPermission(user) && !file.getFolder().hasReadPermission(user))
738 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
739 14ad7326 pastith
                return file.getDTO();
740 14ad7326 pastith
        }
741 14ad7326 pastith
742 14ad7326 pastith
        @Override
743 14ad7326 pastith
        public FileBodyDTO getFileBody(Long userId, Long fileId, Long bodyId) throws ObjectNotFoundException, InsufficientPermissionsException {
744 14ad7326 pastith
                if (userId == null)
745 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
746 14ad7326 pastith
                if (fileId == null)
747 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
748 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
749 14ad7326 pastith
                FileHeader file = dao.getEntityById(FileHeader.class, fileId);
750 14ad7326 pastith
                if (!file.hasReadPermission(user) && !file.getFolder().hasReadPermission(user))
751 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
752 14ad7326 pastith
                FileBody body = dao.getEntityById(FileBody.class, bodyId);
753 14ad7326 pastith
                return body.getDTO();
754 14ad7326 pastith
        }
755 14ad7326 pastith
756 14ad7326 pastith
        @Override
757 68410d59 pastith
        public Object getResourceAtPath(Long ownerId, String path, boolean ignoreDeleted)
758 68410d59 pastith
                        throws ObjectNotFoundException {
759 14ad7326 pastith
                if (ownerId == null)
760 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
761 14ad7326 pastith
                if (StringUtils.isEmpty(path))
762 14ad7326 pastith
                        throw new ObjectNotFoundException("No path specified");
763 14ad7326 pastith
764 14ad7326 pastith
                User owner = dao.getEntityById(User.class, ownerId);
765 14ad7326 pastith
                List<String> pathElements = new ArrayList<String>();
766 14ad7326 pastith
                StringTokenizer st = new StringTokenizer(path, "/");
767 14ad7326 pastith
                while (st.hasMoreTokens())
768 14ad7326 pastith
                        pathElements.add(st.nextToken());
769 14ad7326 pastith
                if (pathElements.size() < 1)
770 14ad7326 pastith
                        return getRootFolder(owner.getId());
771 14ad7326 pastith
                // Store the last element, since it requires special handling.
772 14ad7326 pastith
                String lastElement = pathElements.remove(pathElements.size() - 1);
773 14ad7326 pastith
                FolderDTO cursor = getRootFolder(owner.getId());
774 14ad7326 pastith
                // Traverse and verify the specified folder path.
775 68410d59 pastith
                for (String pathElement : pathElements) {
776 14ad7326 pastith
                        cursor = getFolder(cursor.getId(), pathElement);
777 68410d59 pastith
                        if (cursor.isDeleted())
778 68410d59 pastith
                                throw new ObjectNotFoundException("Folder " + cursor.getPath() + " not found");
779 68410d59 pastith
                }
780 14ad7326 pastith
781 14ad7326 pastith
                // Use the lastElement to retrieve the actual resource.
782 14ad7326 pastith
                Object resource = null;
783 14ad7326 pastith
                try {
784 14ad7326 pastith
                        FileHeaderDTO file = getFile(cursor.getId(), lastElement);
785 68410d59 pastith
                        if (ignoreDeleted && file.isDeleted())
786 14ad7326 pastith
                                throw new ObjectNotFoundException("Resource not found");
787 14ad7326 pastith
                        resource = file;
788 14ad7326 pastith
                } catch (ObjectNotFoundException e) {
789 14ad7326 pastith
                        // Perhaps the requested resource is not a file, so
790 14ad7326 pastith
                        // check for folders as well.
791 14ad7326 pastith
                        FolderDTO folder = getFolder(cursor.getId(), lastElement);
792 68410d59 pastith
                        if (ignoreDeleted && folder.isDeleted())
793 14ad7326 pastith
                                throw new ObjectNotFoundException("Resource not found");
794 14ad7326 pastith
                        resource = folder;
795 14ad7326 pastith
                }
796 14ad7326 pastith
                return resource;
797 14ad7326 pastith
        }
798 14ad7326 pastith
799 14ad7326 pastith
        /**
800 14ad7326 pastith
         * Retrieve a file for the specified user that has the specified name and
801 14ad7326 pastith
         * its parent folder has id equal to folderId.
802 14ad7326 pastith
         *
803 14ad7326 pastith
         * @param userId the ID of the current user
804 14ad7326 pastith
         * @param folderId the ID of the parent folder
805 14ad7326 pastith
         * @param name the name of the requested file
806 14ad7326 pastith
         * @return the file found
807 14ad7326 pastith
         * @throws ObjectNotFoundException if the specified folder or file was not
808 14ad7326 pastith
         *             found, with the exception message mentioning the precise
809 14ad7326 pastith
         *             problem
810 14ad7326 pastith
         */
811 14ad7326 pastith
        private FileHeaderDTO getFile(Long folderId, String name) throws ObjectNotFoundException {
812 14ad7326 pastith
                if (folderId == null)
813 14ad7326 pastith
                        throw new ObjectNotFoundException("No parent folder specified");
814 14ad7326 pastith
                if (StringUtils.isEmpty(name))
815 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
816 14ad7326 pastith
817 14ad7326 pastith
                FileHeader file = dao.getFile(folderId, name);
818 14ad7326 pastith
                return file.getDTO();
819 14ad7326 pastith
        }
820 14ad7326 pastith
821 14ad7326 pastith
        /**
822 14ad7326 pastith
         * Retrieve a folder for the specified user that has the specified name and
823 14ad7326 pastith
         * its parent folder has id equal to parentId.
824 14ad7326 pastith
         *
825 14ad7326 pastith
         * @param parentId the ID of the parent folder
826 14ad7326 pastith
         * @param name the name of the requested folder
827 14ad7326 pastith
         * @return the folder found
828 14ad7326 pastith
         * @throws ObjectNotFoundException if the specified folder or parent was not
829 14ad7326 pastith
         *             found, with the exception message mentioning the precise
830 14ad7326 pastith
         *             problem
831 14ad7326 pastith
         */
832 14ad7326 pastith
        private FolderDTO getFolder(Long parentId, String name) throws ObjectNotFoundException {
833 14ad7326 pastith
                if (parentId == null)
834 14ad7326 pastith
                        throw new ObjectNotFoundException("No parent folder specified");
835 14ad7326 pastith
                if (StringUtils.isEmpty(name))
836 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
837 14ad7326 pastith
838 14ad7326 pastith
                Folder folder = dao.getFolder(parentId, name);
839 14ad7326 pastith
                return folder.getDTO();
840 14ad7326 pastith
        }
841 14ad7326 pastith
842 b13aae04 pastith
        private FileHeaderDTO updateFileContents(Long userId, Long fileId, String mimeType, InputStream resourceInputStream) throws ObjectNotFoundException, GSSIOException, InsufficientPermissionsException, QuotaExceededException {
843 14ad7326 pastith
                File file = null;
844 14ad7326 pastith
                try {
845 14ad7326 pastith
                        file = uploadFile(resourceInputStream, userId);
846 14ad7326 pastith
                } catch ( IOException ioe) {
847 14ad7326 pastith
                        // Supply a more accurate problem description.
848 14ad7326 pastith
                        throw new GSSIOException("Problem creating file",ioe);
849 14ad7326 pastith
                }
850 4d737770 Fotis Stamatelopoulos
                return updateFileContents(userId, fileId, mimeType, file.length(), file.getAbsolutePath());
851 14ad7326 pastith
        }
852 14ad7326 pastith
853 14ad7326 pastith
        @Override
854 14ad7326 pastith
        public void copyFile(Long userId, Long fileId, String dest) throws ObjectNotFoundException, DuplicateNameException, GSSIOException, InsufficientPermissionsException, QuotaExceededException {
855 14ad7326 pastith
                if (userId == null)
856 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
857 14ad7326 pastith
                if (fileId == null)
858 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
859 14ad7326 pastith
                if (StringUtils.isEmpty(dest))
860 14ad7326 pastith
                        throw new ObjectNotFoundException("No destination specified");
861 14ad7326 pastith
862 68410d59 pastith
                Object destination = getResourceAtPath(userId, getParentPath(dest), true);
863 14ad7326 pastith
                if (!(destination instanceof FolderDTO))
864 14ad7326 pastith
                        throw new ObjectNotFoundException("Destination parent folder not found");
865 14ad7326 pastith
                FolderDTO parent = (FolderDTO) destination;
866 14ad7326 pastith
                copyFile(userId, fileId, parent.getId(), getLastElement(dest));
867 14ad7326 pastith
        }
868 14ad7326 pastith
869 14ad7326 pastith
        @Override
870 14ad7326 pastith
        public void copyFileToPath(Long userId, Long ownerId, Long fileId, String dest) throws ObjectNotFoundException, DuplicateNameException, GSSIOException, InsufficientPermissionsException, QuotaExceededException {
871 14ad7326 pastith
                if (userId == null)
872 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
873 14ad7326 pastith
                if (ownerId == null)
874 14ad7326 pastith
                        throw new ObjectNotFoundException("No owner specified");
875 14ad7326 pastith
                if (fileId == null)
876 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
877 14ad7326 pastith
                if (StringUtils.isEmpty(dest))
878 14ad7326 pastith
                        throw new ObjectNotFoundException("No destination specified");
879 14ad7326 pastith
880 68410d59 pastith
                Object destination = getResourceAtPath(ownerId, getParentPath(dest), true);
881 14ad7326 pastith
                if (!(destination instanceof FolderDTO))
882 14ad7326 pastith
                        throw new ObjectNotFoundException("Destination parent folder not found");
883 14ad7326 pastith
                FolderDTO parent = (FolderDTO) destination;
884 14ad7326 pastith
                copyFile(userId, fileId, parent.getId(), getLastElement(dest));
885 14ad7326 pastith
        }
886 14ad7326 pastith
887 14ad7326 pastith
        @Override
888 14ad7326 pastith
        public void copyFile(Long userId, Long fileId, Long destId, String destName) throws ObjectNotFoundException, DuplicateNameException, GSSIOException, InsufficientPermissionsException, QuotaExceededException {
889 14ad7326 pastith
                if (userId == null)
890 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
891 14ad7326 pastith
                if (fileId == null)
892 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
893 14ad7326 pastith
                if (destId == null)
894 14ad7326 pastith
                        throw new ObjectNotFoundException("No destination specified");
895 14ad7326 pastith
                if (StringUtils.isEmpty(destName))
896 14ad7326 pastith
                        throw new ObjectNotFoundException("No destination file name specified");
897 14ad7326 pastith
898 14ad7326 pastith
                FileHeader file = dao.getEntityById(FileHeader.class, fileId);
899 14ad7326 pastith
                Folder destination = dao.getEntityById(Folder.class, destId);
900 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
901 14ad7326 pastith
                if (!file.hasReadPermission(user) || !destination.hasWritePermission(user))
902 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
903 2be5f35d Dimitris Routsis
                boolean versioned = file.isVersioned();
904 14ad7326 pastith
                int versionsNumber = file.getBodies().size();
905 14ad7326 pastith
                FileBody oldestBody = file.getBodies().get(0);
906 14ad7326 pastith
                assert oldestBody != null;
907 14ad7326 pastith
                File contents = new File(oldestBody.getStoredFilePath());
908 14ad7326 pastith
                try {
909 14ad7326 pastith
                        createFile(user.getId(), destination.getId(), destName, oldestBody.getMimeType(), new FileInputStream(contents));
910 14ad7326 pastith
                        FileHeader copiedFile = dao.getFile(destination.getId(), destName);
911 2be5f35d Dimitris Routsis
                        copiedFile.setVersioned(versioned);
912 14ad7326 pastith
                        dao.flush();
913 14ad7326 pastith
                        if (versionsNumber > 1)
914 14ad7326 pastith
                                for (int i = 1; i < versionsNumber; i++) {
915 14ad7326 pastith
                                        FileBody body = file.getBodies().get(i);
916 14ad7326 pastith
                                        assert body != null;
917 14ad7326 pastith
                                        contents = new File(body.getStoredFilePath());
918 14ad7326 pastith
                                        updateFileContents(user.getId(), copiedFile.getId(), body.getMimeType(), new FileInputStream(contents));
919 14ad7326 pastith
                                }
920 14ad7326 pastith
                        List<FileTag> tags = file.getFileTags();
921 14ad7326 pastith
                        for (FileTag tag : tags)
922 14ad7326 pastith
                                createTag(userId, copiedFile.getId(), tag.getTag());
923 14ad7326 pastith
924 14ad7326 pastith
                } catch (FileNotFoundException e) {
925 14ad7326 pastith
                        throw new ObjectNotFoundException("File contents not found for file " + contents.getAbsolutePath());
926 14ad7326 pastith
                }
927 14ad7326 pastith
928 14ad7326 pastith
        }
929 14ad7326 pastith
930 14ad7326 pastith
        @Override
931 14ad7326 pastith
        public void copyFolder(Long userId, Long folderId, String dest) throws ObjectNotFoundException, DuplicateNameException, InsufficientPermissionsException {
932 14ad7326 pastith
                if (userId == null)
933 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
934 14ad7326 pastith
                if (folderId == null)
935 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
936 14ad7326 pastith
                if (StringUtils.isEmpty(dest))
937 14ad7326 pastith
                        throw new ObjectNotFoundException("No destination specified");
938 14ad7326 pastith
939 68410d59 pastith
                Object destination = getResourceAtPath(userId, getParentPath(dest), true);
940 14ad7326 pastith
                if (!(destination instanceof FolderDTO))
941 14ad7326 pastith
                        throw new ObjectNotFoundException("Destination folder not found");
942 14ad7326 pastith
                FolderDTO parent = (FolderDTO) destination;
943 14ad7326 pastith
                copyFolder(userId, folderId, parent.getId(), getLastElement(dest));
944 14ad7326 pastith
        }
945 14ad7326 pastith
946 14ad7326 pastith
        @Override
947 14ad7326 pastith
        public void copyFolder(Long userId, Long folderId, Long destId, String destName) throws ObjectNotFoundException, DuplicateNameException, InsufficientPermissionsException {
948 14ad7326 pastith
                if (userId == null)
949 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
950 14ad7326 pastith
                if (folderId == null)
951 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
952 14ad7326 pastith
                if (destId == null)
953 14ad7326 pastith
                        throw new ObjectNotFoundException("No destination specified");
954 14ad7326 pastith
                if (StringUtils.isEmpty(destName))
955 14ad7326 pastith
                        throw new ObjectNotFoundException("No destination folder name specified");
956 14ad7326 pastith
                Folder folder = dao.getEntityById(Folder.class, folderId);
957 14ad7326 pastith
                Folder destination = dao.getEntityById(Folder.class, destId);
958 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
959 14ad7326 pastith
                if (!destination.hasWritePermission(user) || !folder.hasReadPermission(user))
960 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
961 14ad7326 pastith
                createFolder(user.getId(), destination.getId(), destName);
962 14ad7326 pastith
        }
963 14ad7326 pastith
964 14ad7326 pastith
        @Override
965 14ad7326 pastith
        public void copyFolderStructureToPath(Long userId, Long ownerId, Long folderId, String dest) throws ObjectNotFoundException, DuplicateNameException, InsufficientPermissionsException, GSSIOException, QuotaExceededException {
966 14ad7326 pastith
                if (userId == null)
967 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
968 14ad7326 pastith
                if (ownerId == null)
969 14ad7326 pastith
                        throw new ObjectNotFoundException("No owner specified");
970 14ad7326 pastith
                if (folderId == null)
971 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
972 14ad7326 pastith
                if (StringUtils.isEmpty(dest))
973 14ad7326 pastith
                        throw new ObjectNotFoundException("No destination specified");
974 14ad7326 pastith
975 68410d59 pastith
                Object destination = getResourceAtPath(ownerId, getParentPath(dest), true);
976 14ad7326 pastith
                if (!(destination instanceof FolderDTO))
977 14ad7326 pastith
                        throw new ObjectNotFoundException("Destination folder not found");
978 14ad7326 pastith
                FolderDTO parent = (FolderDTO) destination;
979 14ad7326 pastith
                copyFolderStructure(userId, folderId, parent.getId(), getLastElement(dest));
980 14ad7326 pastith
        }
981 14ad7326 pastith
982 14ad7326 pastith
        @Override
983 14ad7326 pastith
        public void copyFolderStructure(Long userId, Long folderId, Long destId, String destName) throws ObjectNotFoundException, DuplicateNameException, InsufficientPermissionsException, GSSIOException, QuotaExceededException {
984 14ad7326 pastith
                if (userId == null)
985 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
986 14ad7326 pastith
                if (folderId == null)
987 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
988 14ad7326 pastith
                if (destId == null)
989 14ad7326 pastith
                        throw new ObjectNotFoundException("No destination specified");
990 14ad7326 pastith
                if (StringUtils.isEmpty(destName))
991 14ad7326 pastith
                        throw new ObjectNotFoundException("No destination folder name specified");
992 14ad7326 pastith
993 14ad7326 pastith
                Folder folder = dao.getEntityById(Folder.class, folderId);
994 14ad7326 pastith
                Folder destination = dao.getEntityById(Folder.class, destId);
995 14ad7326 pastith
                final User user = dao.getEntityById(User.class, userId);
996 14ad7326 pastith
                // XXX: quick fix need to copy only visible items to user (Source
997 14ad7326 pastith
                // for bugs)
998 14ad7326 pastith
                if (!folder.getOwner().getId().equals(userId) && !folder.hasReadPermission(user))
999 14ad7326 pastith
                        return;
1000 14ad7326 pastith
                if(folder.isDeleted())//do not copy trashed folder and contents
1001 14ad7326 pastith
                        return;
1002 14ad7326 pastith
                if (!destination.hasWritePermission(user) || !folder.hasReadPermission(user))
1003 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
1004 14ad7326 pastith
                createFolder(user.getId(), destination.getId(), destName);
1005 14ad7326 pastith
                Folder createdFolder = dao.getFolder(destination.getId(), destName);
1006 14ad7326 pastith
                List<FileHeader> files = folder.getFiles();
1007 14ad7326 pastith
                if (files != null)
1008 14ad7326 pastith
                        for (FileHeader file : files)
1009 14ad7326 pastith
                                if(!file.isDeleted())
1010 14ad7326 pastith
                                        copyFile(userId, file.getId(), createdFolder.getId(), file.getName());
1011 14ad7326 pastith
                List<Folder> subFolders = folder.getSubfolders();
1012 14ad7326 pastith
                if (subFolders != null)
1013 14ad7326 pastith
                        for (Folder sub : subFolders)
1014 15ad8af3 koutsoub
                                if(!sub.getId().equals(createdFolder.getId()))
1015 15ad8af3 koutsoub
                                        copyFolderStructure(userId, sub.getId(), createdFolder.getId(), sub.getName());
1016 14ad7326 pastith
1017 14ad7326 pastith
        }
1018 14ad7326 pastith
1019 14ad7326 pastith
        /**
1020 14ad7326 pastith
         * For a provided path, remove the last element and return the rest, that is
1021 14ad7326 pastith
         * the path of the parent folder.
1022 14ad7326 pastith
         *
1023 14ad7326 pastith
         * @param path the specified path
1024 14ad7326 pastith
         * @return the path of the parent folder
1025 14ad7326 pastith
         * @throws ObjectNotFoundException if the provided string contains no path
1026 14ad7326 pastith
         *             delimiters
1027 14ad7326 pastith
         */
1028 14ad7326 pastith
        private String getParentPath(String path) throws ObjectNotFoundException {
1029 14ad7326 pastith
                int lastDelimiter = path.lastIndexOf('/');
1030 14ad7326 pastith
                if (lastDelimiter == 0)
1031 14ad7326 pastith
                        return "/";
1032 14ad7326 pastith
                if (lastDelimiter == -1)
1033 14ad7326 pastith
                        // No path found.
1034 14ad7326 pastith
                        throw new ObjectNotFoundException("There is no parent in the path: " + path);
1035 14ad7326 pastith
                else if (lastDelimiter < path.length() - 1)
1036 14ad7326 pastith
                        // Return the part before the delimiter.
1037 14ad7326 pastith
                        return path.substring(0, lastDelimiter);
1038 14ad7326 pastith
                else {
1039 14ad7326 pastith
                        // Remove the trailing delimiter and then recurse.
1040 14ad7326 pastith
                        String strippedTrail = path.substring(0, lastDelimiter);
1041 14ad7326 pastith
                        return getParentPath(strippedTrail);
1042 14ad7326 pastith
                }
1043 14ad7326 pastith
        }
1044 14ad7326 pastith
1045 14ad7326 pastith
        /**
1046 14ad7326 pastith
         * Get the last element in a path that denotes the file or folder name.
1047 14ad7326 pastith
         *
1048 14ad7326 pastith
         * @param path the provided path
1049 14ad7326 pastith
         * @return the last element in the path
1050 14ad7326 pastith
         */
1051 14ad7326 pastith
        private String getLastElement(String path) {
1052 14ad7326 pastith
                int lastDelimiter = path.lastIndexOf('/');
1053 14ad7326 pastith
                if (lastDelimiter == -1)
1054 14ad7326 pastith
                        // No path found.
1055 14ad7326 pastith
                        return path;
1056 14ad7326 pastith
                else if (lastDelimiter < path.length() - 1)
1057 14ad7326 pastith
                        // Return the part after the delimiter.
1058 14ad7326 pastith
                        return path.substring(lastDelimiter + 1);
1059 14ad7326 pastith
                else {
1060 14ad7326 pastith
                        // Remove the trailing delimiter and then recurse.
1061 14ad7326 pastith
                        String strippedTrail = path.substring(0, lastDelimiter);
1062 14ad7326 pastith
                        return getLastElement(strippedTrail);
1063 14ad7326 pastith
                }
1064 14ad7326 pastith
        }
1065 14ad7326 pastith
1066 14ad7326 pastith
        @Override
1067 14ad7326 pastith
        public void moveFileToTrash(Long userId, Long fileId) throws ObjectNotFoundException, InsufficientPermissionsException {
1068 14ad7326 pastith
                if (userId == null)
1069 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1070 14ad7326 pastith
                if (fileId == null)
1071 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
1072 14ad7326 pastith
1073 14ad7326 pastith
                // Do the actual work.
1074 14ad7326 pastith
                FileHeader file = dao.getEntityById(FileHeader.class, fileId);
1075 14ad7326 pastith
                Folder parent = file.getFolder();
1076 14ad7326 pastith
                if (parent == null)
1077 14ad7326 pastith
                        throw new ObjectNotFoundException("The specified file has no parent folder");
1078 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
1079 14ad7326 pastith
                if (!file.hasDeletePermission(user))
1080 14ad7326 pastith
                        throw new InsufficientPermissionsException("User " + user.getId() + " cannot delete file " + file.getName() + "(" + file.getId() + ")");
1081 14ad7326 pastith
1082 14ad7326 pastith
                file.setDeleted(true);
1083 14ad7326 pastith
                dao.update(file);
1084 14ad7326 pastith
        }
1085 14ad7326 pastith
1086 14ad7326 pastith
        @Override
1087 4684df80 Fotis Stamatelopoulos
        public void moveFileToPath(Long userId, Long ownerId, Long fileId, String dest) throws ObjectNotFoundException, InsufficientPermissionsException, QuotaExceededException {
1088 14ad7326 pastith
                if (userId == null)
1089 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1090 14ad7326 pastith
                if (ownerId == null)
1091 14ad7326 pastith
                        throw new ObjectNotFoundException("No owner specified");
1092 14ad7326 pastith
                if (fileId == null)
1093 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
1094 14ad7326 pastith
                if (StringUtils.isEmpty(dest))
1095 14ad7326 pastith
                        throw new ObjectNotFoundException("No destination specified");
1096 14ad7326 pastith
1097 68410d59 pastith
                Object destination = getResourceAtPath(ownerId, getParentPath(dest), true);
1098 14ad7326 pastith
                if (!(destination instanceof FolderDTO))
1099 14ad7326 pastith
                        throw new ObjectNotFoundException("Destination parent folder not found");
1100 14ad7326 pastith
                FolderDTO parent = (FolderDTO) destination;
1101 14ad7326 pastith
                moveFile(userId, fileId, parent.getId(), getLastElement(dest));
1102 14ad7326 pastith
        }
1103 14ad7326 pastith
1104 14ad7326 pastith
        @Override
1105 4d737770 Fotis Stamatelopoulos
        public void moveFile(Long userId, Long fileId, Long destId, String destName) throws InsufficientPermissionsException, ObjectNotFoundException, QuotaExceededException {
1106 14ad7326 pastith
                if (userId == null)
1107 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1108 14ad7326 pastith
                if (fileId == null)
1109 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
1110 14ad7326 pastith
                if (destId == null)
1111 14ad7326 pastith
                        throw new ObjectNotFoundException("No destination specified");
1112 14ad7326 pastith
                if (StringUtils.isEmpty(destName))
1113 14ad7326 pastith
                        throw new ObjectNotFoundException("No destination file name specified");
1114 14ad7326 pastith
1115 14ad7326 pastith
                FileHeader file = dao.getEntityById(FileHeader.class, fileId);
1116 14ad7326 pastith
                Folder destination = dao.getEntityById(Folder.class, destId);
1117 14ad7326 pastith
1118 14ad7326 pastith
                User owner = dao.getEntityById(User.class, userId);
1119 14ad7326 pastith
                if (!file.hasDeletePermission(owner) || !destination.hasWritePermission(owner))
1120 14ad7326 pastith
                        throw new InsufficientPermissionsException("User " + owner.getId() + " cannot move file " + file.getName() + "(" + file.getId() + ")");
1121 14ad7326 pastith
1122 4d737770 Fotis Stamatelopoulos
                // if the destination folder belongs to another user:
1123 4d737770 Fotis Stamatelopoulos
                if (!file.getOwner().equals(destination.getOwner())) {
1124 4d737770 Fotis Stamatelopoulos
                        // (a) check if the destination quota allows the move
1125 4d737770 Fotis Stamatelopoulos
                        if(getQuotaLeft(destination.getOwner().getId()) < file.getTotalSize())
1126 4d737770 Fotis Stamatelopoulos
                                throw new QuotaExceededException("Not enough free space available");
1127 4d737770 Fotis Stamatelopoulos
                        User newOwner = destination.getOwner();
1128 4d737770 Fotis Stamatelopoulos
                        // (b) if quota OK, change the owner of the file
1129 4d737770 Fotis Stamatelopoulos
                        file.setOwner(newOwner);
1130 4d737770 Fotis Stamatelopoulos
                        // if the file has no permission for the new owner, add it
1131 4d737770 Fotis Stamatelopoulos
                        Permission ownerPermission = null;
1132 4d737770 Fotis Stamatelopoulos
                        for (final Permission p : file.getPermissions())
1133 4d737770 Fotis Stamatelopoulos
                                if (p.getUser() != null)
1134 4d737770 Fotis Stamatelopoulos
                                        if (p.getUser().equals(newOwner)) {
1135 4d737770 Fotis Stamatelopoulos
                                                ownerPermission = p;
1136 4d737770 Fotis Stamatelopoulos
                                                break;
1137 4d737770 Fotis Stamatelopoulos
                                        }
1138 4d737770 Fotis Stamatelopoulos
                        if (ownerPermission == null) {
1139 4d737770 Fotis Stamatelopoulos
                                ownerPermission = new Permission();
1140 4d737770 Fotis Stamatelopoulos
                                ownerPermission.setUser(newOwner);
1141 4d737770 Fotis Stamatelopoulos
                                file.addPermission(ownerPermission);
1142 4d737770 Fotis Stamatelopoulos
                        }
1143 4d737770 Fotis Stamatelopoulos
                        ownerPermission.setRead(true);
1144 4d737770 Fotis Stamatelopoulos
                        ownerPermission.setWrite(true);
1145 4d737770 Fotis Stamatelopoulos
                        ownerPermission.setModifyACL(true);
1146 4d737770 Fotis Stamatelopoulos
                }
1147 4d737770 Fotis Stamatelopoulos
                // move the file to the destination folder
1148 4d737770 Fotis Stamatelopoulos
                file.setFolder(destination);
1149 14ad7326 pastith
        }
1150 14ad7326 pastith
1151 14ad7326 pastith
        @Override
1152 14ad7326 pastith
        public void moveFolderToPath(Long userId, Long ownerId, Long folderId, String dest) throws ObjectNotFoundException, DuplicateNameException, InsufficientPermissionsException, GSSIOException, QuotaExceededException {
1153 14ad7326 pastith
                if (userId == null)
1154 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1155 14ad7326 pastith
                if (ownerId == null)
1156 14ad7326 pastith
                        throw new ObjectNotFoundException("No owner specified");
1157 14ad7326 pastith
                if (folderId == null)
1158 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
1159 14ad7326 pastith
                if (StringUtils.isEmpty(dest))
1160 14ad7326 pastith
                        throw new ObjectNotFoundException("No destination specified");
1161 14ad7326 pastith
1162 68410d59 pastith
                Object destination = getResourceAtPath(ownerId, getParentPath(dest), true);
1163 14ad7326 pastith
                if (!(destination instanceof FolderDTO))
1164 14ad7326 pastith
                        throw new ObjectNotFoundException("Destination parent folder not found");
1165 14ad7326 pastith
                FolderDTO parent = (FolderDTO) destination;
1166 14ad7326 pastith
                moveFolder(userId, folderId, parent.getId(), getLastElement(dest));
1167 14ad7326 pastith
        }
1168 14ad7326 pastith
1169 14ad7326 pastith
        @Override
1170 14ad7326 pastith
        public void moveFolder(Long userId, Long folderId, Long destId, String destName) throws ObjectNotFoundException, DuplicateNameException, InsufficientPermissionsException, GSSIOException, QuotaExceededException {
1171 14ad7326 pastith
                // TODO Simple Move and delete of original folder, in production
1172 14ad7326 pastith
                // scenario we must first check individual files and folders permissions
1173 14ad7326 pastith
                copyFolderStructure(userId, folderId, destId, destName);
1174 14ad7326 pastith
                deleteFolder(userId, folderId);
1175 14ad7326 pastith
        }
1176 14ad7326 pastith
1177 14ad7326 pastith
        /* (non-Javadoc)
1178 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#getDeletedFiles(java.lang.Long)
1179 14ad7326 pastith
         */
1180 14ad7326 pastith
        public List<FileHeaderDTO> getDeletedFiles(Long userId) throws ObjectNotFoundException {
1181 14ad7326 pastith
                // Validate.
1182 14ad7326 pastith
                if (userId == null)
1183 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1184 14ad7326 pastith
1185 14ad7326 pastith
                // Do the actual work.
1186 14ad7326 pastith
                final List<FileHeaderDTO> result = new ArrayList<FileHeaderDTO>();
1187 14ad7326 pastith
                final List<FileHeader> files = dao.getDeletedFiles(userId);
1188 14ad7326 pastith
                for (final FileHeader f : files)
1189 14ad7326 pastith
                        result.add(f.getDTO());
1190 14ad7326 pastith
                return result;
1191 14ad7326 pastith
        }
1192 14ad7326 pastith
1193 14ad7326 pastith
        @Override
1194 14ad7326 pastith
        public void removeFileFromTrash(Long userId, Long fileId)
1195 14ad7326 pastith
                        throws ObjectNotFoundException, InsufficientPermissionsException {
1196 14ad7326 pastith
                if (userId == null)
1197 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1198 14ad7326 pastith
                if (fileId == null)
1199 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
1200 14ad7326 pastith
1201 14ad7326 pastith
                // Do the actual work.
1202 14ad7326 pastith
                FileHeader file = dao.getEntityById(FileHeader.class, fileId);
1203 14ad7326 pastith
                Folder parent = file.getFolder();
1204 14ad7326 pastith
                if (parent == null)
1205 14ad7326 pastith
                        throw new ObjectNotFoundException("The specified file has no parent folder");
1206 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
1207 14ad7326 pastith
                if (!file.hasDeletePermission(user))
1208 14ad7326 pastith
                        throw new InsufficientPermissionsException("User " + user.getUsername() +
1209 14ad7326 pastith
                                                " cannot restore file " + file.getName());
1210 14ad7326 pastith
1211 14ad7326 pastith
                file.setDeleted(false);
1212 14ad7326 pastith
                dao.update(file);
1213 14ad7326 pastith
        }
1214 14ad7326 pastith
1215 14ad7326 pastith
        @Override
1216 14ad7326 pastith
        public void moveFolderToTrash(Long userId, Long folderId) throws ObjectNotFoundException, InsufficientPermissionsException {
1217 14ad7326 pastith
                if (userId == null)
1218 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1219 14ad7326 pastith
                if (folderId == null)
1220 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
1221 14ad7326 pastith
                Folder folder = dao.getEntityById(Folder.class, folderId);
1222 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
1223 14ad7326 pastith
                if (!folder.hasDeletePermission(user))
1224 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
1225 14ad7326 pastith
                folder.setDeleted(true);
1226 14ad7326 pastith
                dao.update(folder);
1227 14ad7326 pastith
                for (FileHeader file : folder.getFiles())
1228 14ad7326 pastith
                        moveFileToTrash(userId, file.getId());
1229 14ad7326 pastith
                for (Folder subFolder : folder.getSubfolders())
1230 14ad7326 pastith
                        moveFolderToTrash(userId, subFolder.getId());
1231 14ad7326 pastith
1232 14ad7326 pastith
        }
1233 14ad7326 pastith
1234 14ad7326 pastith
        @Override
1235 14ad7326 pastith
        public void removeFolderFromTrash(Long userId, Long folderId)
1236 14ad7326 pastith
                        throws ObjectNotFoundException, InsufficientPermissionsException {
1237 14ad7326 pastith
                if (userId == null)
1238 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1239 14ad7326 pastith
                if (folderId == null)
1240 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
1241 14ad7326 pastith
                Folder folder = dao.getEntityById(Folder.class, folderId);
1242 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
1243 14ad7326 pastith
                if (!folder.hasDeletePermission(user))
1244 14ad7326 pastith
                        throw new InsufficientPermissionsException("User " + user.getUsername() +
1245 14ad7326 pastith
                                                " cannot restore folder " + folder.getName());
1246 14ad7326 pastith
                folder.setDeleted(false);
1247 14ad7326 pastith
                for (FileHeader file : folder.getFiles())
1248 14ad7326 pastith
                        removeFileFromTrash(userId, file.getId());
1249 14ad7326 pastith
                for (Folder subFolder : folder.getSubfolders())
1250 14ad7326 pastith
                        removeFolderFromTrash(userId, subFolder.getId());
1251 14ad7326 pastith
                dao.update(folder);
1252 14ad7326 pastith
        }
1253 14ad7326 pastith
1254 14ad7326 pastith
        @Override
1255 14ad7326 pastith
        public List<FolderDTO> getDeletedRootFolders(Long userId) throws ObjectNotFoundException {
1256 14ad7326 pastith
                List<Folder> folders = dao.getDeletedRootFolders(userId);
1257 14ad7326 pastith
                List<FolderDTO> result = new ArrayList<FolderDTO>();
1258 14ad7326 pastith
                for (Folder folder : folders)
1259 68410d59 pastith
                        result.add(folder.getDTO());
1260 14ad7326 pastith
                return result;
1261 14ad7326 pastith
        }
1262 14ad7326 pastith
1263 68410d59 pastith
        @Override
1264 14ad7326 pastith
        public void emptyTrash(Long userId) throws ObjectNotFoundException, InsufficientPermissionsException {
1265 14ad7326 pastith
                List<FolderDTO> deletedRootFolders = getDeletedRootFolders(userId);
1266 14ad7326 pastith
                for (FolderDTO fdto : deletedRootFolders)
1267 14ad7326 pastith
                        deleteFolder(userId, fdto.getId());
1268 14ad7326 pastith
                List<FileHeaderDTO> deletedFiles = getDeletedFiles(userId);
1269 14ad7326 pastith
                for (FileHeaderDTO filedto : deletedFiles)
1270 14ad7326 pastith
                        deleteFile(userId, filedto.getId());
1271 14ad7326 pastith
        }
1272 14ad7326 pastith
1273 14ad7326 pastith
        @Override
1274 14ad7326 pastith
        public void restoreTrash(Long userId) throws ObjectNotFoundException, InsufficientPermissionsException {
1275 14ad7326 pastith
                List<FolderDTO> deletedRootFolders = getDeletedRootFolders(userId);
1276 14ad7326 pastith
                for (FolderDTO fdto : deletedRootFolders)
1277 14ad7326 pastith
                        removeFolderFromTrash(userId, fdto.getId());
1278 14ad7326 pastith
                List<FileHeaderDTO> deletedFiles = getDeletedFiles(userId);
1279 14ad7326 pastith
                for (FileHeaderDTO filedto : deletedFiles)
1280 14ad7326 pastith
                        removeFileFromTrash(userId, filedto.getId());
1281 14ad7326 pastith
        }
1282 14ad7326 pastith
1283 14ad7326 pastith
        @Override
1284 14ad7326 pastith
        public User createUser(String username, String name, String mail) throws ObjectNotFoundException {
1285 14ad7326 pastith
                if (username == null)
1286 14ad7326 pastith
                        throw new ObjectNotFoundException("No username specified");
1287 14ad7326 pastith
                if (name == null)
1288 14ad7326 pastith
                        throw new ObjectNotFoundException("No name specified");
1289 14ad7326 pastith
1290 14ad7326 pastith
                User user = new User();
1291 14ad7326 pastith
                user.setUsername(username);
1292 14ad7326 pastith
                user.setName(name);
1293 14ad7326 pastith
                user.setEmail(mail);
1294 14ad7326 pastith
                Date now = new Date();
1295 14ad7326 pastith
                AuditInfo auditInfo = new AuditInfo();
1296 14ad7326 pastith
                auditInfo.setCreationDate(now);
1297 14ad7326 pastith
                auditInfo.setModificationDate(now);
1298 14ad7326 pastith
                user.setAuditInfo(auditInfo);
1299 14ad7326 pastith
                user.generateAuthToken();
1300 3ef7b691 Dimitris Routsis
                user.generateWebDAVPassword();
1301 14ad7326 pastith
                dao.create(user);
1302 14ad7326 pastith
                // Make sure we get an ID in the user object.
1303 14ad7326 pastith
                dao.flush();
1304 14ad7326 pastith
                // Create the root folder for the user.
1305 14ad7326 pastith
                createFolder(user.getName(), null, user);
1306 14ad7326 pastith
                return user;
1307 14ad7326 pastith
        }
1308 14ad7326 pastith
1309 14ad7326 pastith
        @Override
1310 3eaf782f pastith
        public User findUserByEmail(String email) {
1311 3eaf782f pastith
                return dao.findUserByEmail(email);
1312 3eaf782f pastith
        }
1313 3eaf782f pastith
1314 3eaf782f pastith
        @Override
1315 3eaf782f pastith
        public void updateUser(User user) {
1316 3eaf782f pastith
                dao.update(user);
1317 3eaf782f pastith
        }
1318 3eaf782f pastith
1319 3eaf782f pastith
        @Override
1320 14ad7326 pastith
        public User updateUser(String username, String name, String mail) throws ObjectNotFoundException {
1321 14ad7326 pastith
                if (username == null)
1322 14ad7326 pastith
                        throw new ObjectNotFoundException("No username specified");
1323 14ad7326 pastith
1324 14ad7326 pastith
                User user = dao.getUser(username);
1325 14ad7326 pastith
                user.setName(name);
1326 14ad7326 pastith
                user.setEmail(mail);
1327 14ad7326 pastith
                return user;
1328 14ad7326 pastith
        }
1329 14ad7326 pastith
1330 14ad7326 pastith
        @Override
1331 14ad7326 pastith
        public User findUser(String username) {
1332 14ad7326 pastith
                if (username == null)
1333 14ad7326 pastith
                        return null;
1334 14ad7326 pastith
                return dao.findUser(username);
1335 14ad7326 pastith
        }
1336 14ad7326 pastith
1337 14ad7326 pastith
        @Override
1338 14ad7326 pastith
        public User updateUserToken(Long userId) throws ObjectNotFoundException {
1339 14ad7326 pastith
                if (userId == null)
1340 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1341 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
1342 14ad7326 pastith
                user.generateAuthToken();
1343 14ad7326 pastith
                return user;
1344 14ad7326 pastith
        }
1345 14ad7326 pastith
1346 14ad7326 pastith
        /* (non-Javadoc)
1347 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#getFolderPermissions(java.lang.Long, java.lang.Long)
1348 14ad7326 pastith
         */
1349 14ad7326 pastith
        @Override
1350 14ad7326 pastith
        public Set<PermissionDTO> getFolderPermissions(Long userId, Long folderId) throws ObjectNotFoundException, InsufficientPermissionsException {
1351 14ad7326 pastith
                if (userId == null)
1352 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1353 14ad7326 pastith
                if (folderId == null)
1354 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
1355 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
1356 14ad7326 pastith
                Folder folder = dao.getEntityById(Folder.class, folderId);
1357 14ad7326 pastith
                if(!folder.hasReadPermission(user))
1358 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
1359 14ad7326 pastith
                Set<Permission> perms = folder.getPermissions();
1360 14ad7326 pastith
                Set<PermissionDTO> result = new LinkedHashSet<PermissionDTO>();
1361 14ad7326 pastith
                for (Permission perm : perms)
1362 14ad7326 pastith
                        if (perm.getUser() != null && perm.getUser().getId().equals(folder.getOwner().getId()))
1363 14ad7326 pastith
                                result.add(perm.getDTO());
1364 14ad7326 pastith
                for (Permission perm : perms)
1365 14ad7326 pastith
                        if (perm.getUser() != null && perm.getUser().getId().equals(folder.getOwner().getId())) {
1366 14ad7326 pastith
                        } else
1367 14ad7326 pastith
                                result.add(perm.getDTO());
1368 14ad7326 pastith
                return result;
1369 14ad7326 pastith
1370 14ad7326 pastith
        }
1371 14ad7326 pastith
1372 14ad7326 pastith
        /* (non-Javadoc)
1373 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#setFolderPermissions(java.lang.Long, java.lang.Long, java.util.Set)
1374 14ad7326 pastith
         */
1375 14ad7326 pastith
        @Override
1376 14ad7326 pastith
        public void setFolderPermissions(Long userId, Long folderId, Set<PermissionDTO> permissions) throws ObjectNotFoundException, InsufficientPermissionsException {
1377 14ad7326 pastith
                if (userId == null)
1378 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1379 14ad7326 pastith
                if (folderId == null)
1380 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
1381 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
1382 14ad7326 pastith
                Folder folder = dao.getEntityById(Folder.class, folderId);
1383 14ad7326 pastith
                if(!folder.hasModifyACLPermission(user))
1384 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
1385 66c7511a Dimitris Routsis
                // Delete previous entries
1386 66c7511a Dimitris Routsis
                for (Permission perm: folder.getPermissions())
1387 66c7511a Dimitris Routsis
                        dao.delete(perm);
1388 14ad7326 pastith
                folder.getPermissions().clear();
1389 3da65b2c droutsis
                for (PermissionDTO dto : permissions) {
1390 3da65b2c droutsis
                        if (dto.getUser()!=null && dto.getUser().getId().equals(folder.getOwner().getId()) && (!dto.hasRead() || !dto.hasWrite() || !dto.hasModifyACL()))
1391 3da65b2c droutsis
                                        throw new InsufficientPermissionsException("Can't remove permissions from owner");
1392 66c7511a Dimitris Routsis
                        // Don't include 'empty' permission
1393 66c7511a Dimitris Routsis
                        if (!dto.getRead() && !dto.getWrite() && !dto.getModifyACL()) continue;
1394 14ad7326 pastith
                        folder.addPermission(getPermission(dto));
1395 3da65b2c droutsis
                }
1396 14ad7326 pastith
                dao.update(folder);
1397 14ad7326 pastith
                for (FileHeader fh : folder.getFiles())
1398 14ad7326 pastith
                        setFilePermissions(userId, fh.getId(), fh.isReadForAll(), permissions);
1399 14ad7326 pastith
                for (Folder sub : folder.getSubfolders())
1400 14ad7326 pastith
                        setFolderPermissions(userId, sub.getId(), permissions);
1401 14ad7326 pastith
        }
1402 14ad7326 pastith
1403 14ad7326 pastith
        private Permission getPermission(PermissionDTO dto) throws ObjectNotFoundException {
1404 14ad7326 pastith
                Permission res = new Permission();
1405 14ad7326 pastith
                if (dto.getGroup() != null)
1406 14ad7326 pastith
                        res.setGroup(dao.getEntityById(Group.class, dto.getGroup().getId()));
1407 14ad7326 pastith
                else if (dto.getUser() != null)
1408 14ad7326 pastith
                        if (dto.getUser().getId() == null)
1409 14ad7326 pastith
                                res.setUser(dao.getUser(dto.getUser().getUsername()));
1410 14ad7326 pastith
                        else
1411 14ad7326 pastith
                                res.setUser(dao.getEntityById(User.class, dto.getUser().getId()));
1412 14ad7326 pastith
                res.setRead(dto.hasRead());
1413 14ad7326 pastith
                res.setWrite(dto.hasWrite());
1414 14ad7326 pastith
                res.setModifyACL(dto.hasModifyACL());
1415 14ad7326 pastith
                return res;
1416 14ad7326 pastith
        }
1417 14ad7326 pastith
1418 14ad7326 pastith
        /* (non-Javadoc)
1419 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#getUsersByUserNameLike(java.lang.String)
1420 14ad7326 pastith
         */
1421 14ad7326 pastith
        @Override
1422 14ad7326 pastith
        public List<UserDTO> getUsersByUserNameLike(String username) {
1423 14ad7326 pastith
                List<User> users = dao.getUsersByUserNameLike(username);
1424 14ad7326 pastith
                List<UserDTO> result = new ArrayList<UserDTO>();
1425 14ad7326 pastith
                for (User u : users)
1426 14ad7326 pastith
                        result.add(u.getDTO());
1427 14ad7326 pastith
                return result;
1428 14ad7326 pastith
1429 14ad7326 pastith
        }
1430 14ad7326 pastith
1431 14ad7326 pastith
        /* (non-Javadoc)
1432 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#addUserToGroup(java.lang.Long, java.lang.Long, java.lang.Long)
1433 14ad7326 pastith
         */
1434 14ad7326 pastith
        @Override
1435 14ad7326 pastith
        public void addUserToGroup(Long userId, Long groupId, Long userToAddId) throws ObjectNotFoundException, DuplicateNameException, InsufficientPermissionsException {
1436 14ad7326 pastith
                if (userId == null)
1437 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1438 14ad7326 pastith
                if (groupId == null)
1439 14ad7326 pastith
                        throw new ObjectNotFoundException("No group specified");
1440 14ad7326 pastith
                if (userToAddId == null)
1441 14ad7326 pastith
                        throw new ObjectNotFoundException("No user to add specified");
1442 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
1443 14ad7326 pastith
                Group group = dao.getEntityById(Group.class, groupId);
1444 14ad7326 pastith
                if (!group.getOwner().equals(user))
1445 14ad7326 pastith
                        throw new InsufficientPermissionsException();
1446 14ad7326 pastith
                User userToAdd = dao.getEntityById(User.class, userToAddId);
1447 14ad7326 pastith
                if (group.contains(userToAdd))
1448 14ad7326 pastith
                        throw new DuplicateNameException("User already exists in group");
1449 14ad7326 pastith
                group.getMembers().add(userToAdd);
1450 14ad7326 pastith
                dao.update(group);
1451 14ad7326 pastith
1452 14ad7326 pastith
        }
1453 14ad7326 pastith
1454 14ad7326 pastith
        @Override
1455 14ad7326 pastith
        public void invalidateUserToken(Long userId) throws ObjectNotFoundException {
1456 14ad7326 pastith
                if (userId == null)
1457 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1458 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
1459 14ad7326 pastith
                user.invalidateAuthToken();
1460 14ad7326 pastith
                return;
1461 14ad7326 pastith
        }
1462 14ad7326 pastith
1463 14ad7326 pastith
        @Override
1464 14ad7326 pastith
        public List<FolderDTO> getSharedRootFolders(Long userId) throws ObjectNotFoundException {
1465 14ad7326 pastith
                if (userId == null)
1466 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1467 14ad7326 pastith
                List<Folder> folders = dao.getSharedRootFolders(userId);
1468 14ad7326 pastith
                List<FolderDTO> result = new ArrayList<FolderDTO>();
1469 68410d59 pastith
                for (Folder f : folders) {
1470 68410d59 pastith
                        FolderDTO dto = f.getDTO();
1471 68410d59 pastith
                        dto.setSubfolders(getSharedSubfolders(userId, f.getId()));
1472 68410d59 pastith
                        result.add(dto);
1473 68410d59 pastith
                }
1474 14ad7326 pastith
                return result;
1475 14ad7326 pastith
        }
1476 14ad7326 pastith
1477 14ad7326 pastith
        /* (non-Javadoc)
1478 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#removeMemberFromGroup(java.lang.Long, java.lang.Long, java.lang.Long)
1479 14ad7326 pastith
         */
1480 14ad7326 pastith
        @Override
1481 14ad7326 pastith
        public void removeMemberFromGroup(Long userId, Long groupId, Long memberId) throws ObjectNotFoundException, InsufficientPermissionsException {
1482 14ad7326 pastith
                if (userId == null)
1483 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1484 14ad7326 pastith
                if (groupId == null)
1485 14ad7326 pastith
                        throw new ObjectNotFoundException("No group specified");
1486 14ad7326 pastith
                if (memberId == null)
1487 14ad7326 pastith
                        throw new ObjectNotFoundException("No member specified");
1488 14ad7326 pastith
                User owner = dao.getEntityById(User.class, userId);
1489 14ad7326 pastith
                Group group = dao.getEntityById(Group.class, groupId);
1490 14ad7326 pastith
                User member = dao.getEntityById(User.class, memberId);
1491 14ad7326 pastith
                if (!group.getOwner().equals(owner))
1492 14ad7326 pastith
                        throw new InsufficientPermissionsException("User is not the owner of the group");
1493 14ad7326 pastith
                group.removeMemberFromGroup(member);
1494 14ad7326 pastith
                dao.update(group);
1495 14ad7326 pastith
1496 14ad7326 pastith
        }
1497 14ad7326 pastith
1498 14ad7326 pastith
        /* (non-Javadoc)
1499 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#getUsersSharingFoldersForUser(java.lang.Long)
1500 14ad7326 pastith
         */
1501 14ad7326 pastith
        @Override
1502 14ad7326 pastith
        public List<UserDTO> getUsersSharingFoldersForUser(Long userId) throws ObjectNotFoundException {
1503 14ad7326 pastith
                List<User> users = dao.getUsersSharingFoldersForUser(userId);
1504 14ad7326 pastith
                List<User> usersFiles = dao.getUsersSharingFilesForUser(userId);
1505 14ad7326 pastith
                List<UserDTO> res = new ArrayList<UserDTO>();
1506 14ad7326 pastith
                for (User u : users)
1507 14ad7326 pastith
                        res.add(u.getDTO());
1508 14ad7326 pastith
                for(User fu : usersFiles)
1509 14ad7326 pastith
                        if(!users.contains(fu))
1510 14ad7326 pastith
                                res.add(fu.getDTO());
1511 14ad7326 pastith
                return res;
1512 14ad7326 pastith
        }
1513 14ad7326 pastith
1514 14ad7326 pastith
        /* (non-Javadoc)
1515 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#getFilePermissions(java.lang.Long, java.lang.Long)
1516 14ad7326 pastith
         */
1517 14ad7326 pastith
        @Override
1518 14ad7326 pastith
        public Set<PermissionDTO> getFilePermissions(Long userId, Long fileId) throws ObjectNotFoundException, InsufficientPermissionsException {
1519 14ad7326 pastith
                if (userId == null)
1520 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1521 14ad7326 pastith
                if (fileId == null)
1522 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
1523 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
1524 14ad7326 pastith
                FileHeader folder = dao.getEntityById(FileHeader.class, fileId);
1525 14ad7326 pastith
                if(!folder.hasReadPermission(user))
1526 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
1527 14ad7326 pastith
                Set<Permission> perms = folder.getPermissions();
1528 14ad7326 pastith
                Set<PermissionDTO> result = new LinkedHashSet<PermissionDTO>();
1529 14ad7326 pastith
                for (Permission perm : perms)
1530 14ad7326 pastith
                        if (perm.getUser() != null && perm.getUser().getId().equals(folder.getOwner().getId()))
1531 14ad7326 pastith
                                result.add(perm.getDTO());
1532 14ad7326 pastith
                for (Permission perm : perms)
1533 14ad7326 pastith
                        if (perm.getUser() != null && perm.getUser().getId().equals(folder.getOwner().getId())) {
1534 14ad7326 pastith
                        } else
1535 14ad7326 pastith
                                result.add(perm.getDTO());
1536 14ad7326 pastith
                return result;
1537 14ad7326 pastith
        }
1538 14ad7326 pastith
1539 14ad7326 pastith
        @Override
1540 14ad7326 pastith
        public void setFilePermissions(Long userId, Long fileId, Boolean readForAll, Set<PermissionDTO> permissions) throws ObjectNotFoundException, InsufficientPermissionsException {
1541 14ad7326 pastith
                if (userId == null)
1542 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1543 14ad7326 pastith
                if (fileId == null)
1544 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
1545 14ad7326 pastith
1546 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
1547 14ad7326 pastith
                FileHeader file = dao.getEntityById(FileHeader.class, fileId);
1548 14ad7326 pastith
                if(!file.hasModifyACLPermission(user))
1549 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
1550 14ad7326 pastith
1551 14ad7326 pastith
                if (readForAll != null)
1552 02d7b4b7 pastith
                        if (user.equals(file.getOwner()))
1553 02d7b4b7 pastith
                                file.setReadForAll(readForAll);
1554 02d7b4b7 pastith
                        else
1555 02d7b4b7 pastith
                                throw new InsufficientPermissionsException("Only the owner can change the read-for-all flag");
1556 14ad7326 pastith
1557 66c7511a Dimitris Routsis
                // Update the file if there was a change.
1558 66c7511a Dimitris Routsis
                if (readForAll != null || permissions != null && !permissions.isEmpty()) {
1559 66c7511a Dimitris Routsis
                        if (permissions != null && !permissions.isEmpty()) {
1560 66c7511a Dimitris Routsis
                                // Delete previous entries
1561 66c7511a Dimitris Routsis
                                for (Permission perm: file.getPermissions())
1562 66c7511a Dimitris Routsis
                                        dao.delete(perm);
1563 66c7511a Dimitris Routsis
                                file.getPermissions().clear();
1564 66c7511a Dimitris Routsis
                                for (PermissionDTO dto : permissions) {
1565 66c7511a Dimitris Routsis
                                        if (dto.getUser()!=null && dto.getUser().getId().equals(file.getOwner().getId()) && (!dto.hasRead() || !dto.hasWrite() || !dto.hasModifyACL()))
1566 66c7511a Dimitris Routsis
                                                throw new InsufficientPermissionsException("Can't remove permissions from owner");
1567 66c7511a Dimitris Routsis
                                        // Don't include 'empty' permission
1568 66c7511a Dimitris Routsis
                                        if (!dto.getRead() && !dto.getWrite() && !dto.getModifyACL()) continue;
1569 66c7511a Dimitris Routsis
                                        file.addPermission(getPermission(dto));
1570 66c7511a Dimitris Routsis
                                }
1571 3da65b2c droutsis
                        }
1572 14ad7326 pastith
1573 14ad7326 pastith
                        dao.update(file);
1574 66c7511a Dimitris Routsis
                }
1575 14ad7326 pastith
        }
1576 14ad7326 pastith
1577 14ad7326 pastith
        @Override
1578 14ad7326 pastith
        public List<FileHeaderDTO> getSharedFilesNotInSharedFolders(Long userId) throws ObjectNotFoundException {
1579 14ad7326 pastith
                if (userId == null)
1580 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1581 14ad7326 pastith
                List<FileHeader> files = dao.getSharedFilesNotInSharedFolders(userId);
1582 14ad7326 pastith
                List<FileHeaderDTO> result = new ArrayList<FileHeaderDTO>();
1583 14ad7326 pastith
                for (FileHeader f : files)
1584 14ad7326 pastith
                        result.add(f.getDTO());
1585 14ad7326 pastith
                return result;
1586 14ad7326 pastith
        }
1587 14ad7326 pastith
1588 14ad7326 pastith
        @Override
1589 14ad7326 pastith
        public List<FileHeaderDTO> getSharedFiles(Long userId) throws ObjectNotFoundException {
1590 14ad7326 pastith
                if (userId == null)
1591 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1592 14ad7326 pastith
                List<FileHeader> files = dao.getSharedFiles(userId);
1593 14ad7326 pastith
                List<FileHeaderDTO> result = new ArrayList<FileHeaderDTO>();
1594 14ad7326 pastith
                for (FileHeader f : files)
1595 14ad7326 pastith
                        result.add(f.getDTO());
1596 14ad7326 pastith
                return result;
1597 14ad7326 pastith
        }
1598 14ad7326 pastith
1599 14ad7326 pastith
        @Override
1600 14ad7326 pastith
        public List<FolderDTO> getSharedFolders(Long userId) throws ObjectNotFoundException {
1601 14ad7326 pastith
                if (userId == null)
1602 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1603 14ad7326 pastith
                List<Folder> folders = dao.getSharedFolders(userId);
1604 14ad7326 pastith
                List<FolderDTO> result = new ArrayList<FolderDTO>();
1605 14ad7326 pastith
                for (Folder f : folders)
1606 14ad7326 pastith
                        result.add(f.getDTO());
1607 14ad7326 pastith
                return result;
1608 14ad7326 pastith
        }
1609 14ad7326 pastith
1610 14ad7326 pastith
        /* (non-Javadoc)
1611 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#getSharedFiles(java.lang.Long, java.lang.Long)
1612 14ad7326 pastith
         */
1613 14ad7326 pastith
        @Override
1614 14ad7326 pastith
        public List<FileHeaderDTO> getSharedFiles(Long ownerId, Long callingUserId) throws ObjectNotFoundException {
1615 14ad7326 pastith
                if (ownerId == null)
1616 14ad7326 pastith
                        throw new ObjectNotFoundException("No owner specified");
1617 14ad7326 pastith
                if (callingUserId == null)
1618 14ad7326 pastith
                        throw new ObjectNotFoundException("No calling user specified");
1619 14ad7326 pastith
                List<FileHeader> folders = dao.getSharedFiles(ownerId, callingUserId);
1620 14ad7326 pastith
                List<FileHeaderDTO> result = new ArrayList<FileHeaderDTO>();
1621 14ad7326 pastith
                for (FileHeader f : folders)
1622 14ad7326 pastith
                        result.add(f.getDTO());
1623 14ad7326 pastith
                return result;
1624 14ad7326 pastith
        }
1625 14ad7326 pastith
1626 14ad7326 pastith
        @Override
1627 14ad7326 pastith
        public List<FolderDTO> getSharedRootFolders(Long ownerId, Long callingUserId) throws ObjectNotFoundException {
1628 14ad7326 pastith
                if (ownerId == null)
1629 14ad7326 pastith
                        throw new ObjectNotFoundException("No owner specified");
1630 14ad7326 pastith
                if (callingUserId == null)
1631 14ad7326 pastith
                        throw new ObjectNotFoundException("No calling user specified");
1632 14ad7326 pastith
                List<Folder> folders = dao.getSharedRootFolders(ownerId, callingUserId);
1633 14ad7326 pastith
                List<FolderDTO> result = new ArrayList<FolderDTO>();
1634 68410d59 pastith
                for (Folder f : folders) {
1635 68410d59 pastith
                        FolderDTO dto = f.getDTO();
1636 68410d59 pastith
                        dto.setSubfolders(getSharedSubfolders(ownerId, callingUserId, f.getId()));
1637 68410d59 pastith
                        result.add(dto);
1638 68410d59 pastith
                }
1639 14ad7326 pastith
                return result;
1640 14ad7326 pastith
1641 14ad7326 pastith
        }
1642 14ad7326 pastith
1643 14ad7326 pastith
        @Override
1644 14ad7326 pastith
        public List<FolderDTO> getSharedSubfolders(Long userId, Long folderId) throws ObjectNotFoundException {
1645 14ad7326 pastith
                if (userId == null)
1646 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1647 14ad7326 pastith
                if (folderId == null)
1648 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
1649 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
1650 14ad7326 pastith
                Folder folder = dao.getEntityById(Folder.class, folderId);
1651 14ad7326 pastith
                List<FolderDTO> result = new ArrayList<FolderDTO>();
1652 14ad7326 pastith
                if (folder.isShared(user))
1653 14ad7326 pastith
                        for (Folder f : folder.getSubfolders())
1654 14ad7326 pastith
                                if (f.isShared(user) && !f.isDeleted())
1655 14ad7326 pastith
                                        result.add(f.getDTO());
1656 14ad7326 pastith
                return result;
1657 14ad7326 pastith
        }
1658 14ad7326 pastith
1659 14ad7326 pastith
        @Override
1660 14ad7326 pastith
        public List<FolderDTO> getSharedSubfolders(Long userId, Long callingUserId, Long folderId) throws ObjectNotFoundException {
1661 14ad7326 pastith
                if (userId == null)
1662 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1663 14ad7326 pastith
                if (callingUserId == null)
1664 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1665 14ad7326 pastith
                if (folderId == null)
1666 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
1667 14ad7326 pastith
                User user = dao.getEntityById(User.class, callingUserId);
1668 14ad7326 pastith
                Folder folder = dao.getEntityById(Folder.class, folderId);
1669 14ad7326 pastith
                List<FolderDTO> result = new ArrayList<FolderDTO>();
1670 14ad7326 pastith
                if (folder.isSharedForOtherUser(user))
1671 14ad7326 pastith
                        for (Folder f : folder.getSubfolders())
1672 14ad7326 pastith
                                if (f.isSharedForOtherUser(user) && !f.isDeleted()){
1673 14ad7326 pastith
                                        FolderDTO dto = f.getDTO();
1674 14ad7326 pastith
                                        dto.setSubfolders(getSharedSubfolders(userId, callingUserId, dto.getId()));
1675 14ad7326 pastith
                                        result.add(dto);
1676 14ad7326 pastith
                                }
1677 14ad7326 pastith
                return result;
1678 14ad7326 pastith
1679 14ad7326 pastith
        }
1680 14ad7326 pastith
1681 14ad7326 pastith
        /* (non-Javadoc)
1682 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#searchFiles(java.lang.Long, java.lang.String)
1683 14ad7326 pastith
         */
1684 14ad7326 pastith
        @Override
1685 14ad7326 pastith
        public List<FileHeaderDTO> searchFiles(Long userId, String query) throws ObjectNotFoundException {
1686 14ad7326 pastith
                if (userId == null)
1687 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1688 14ad7326 pastith
                User user = getUser(userId);
1689 14ad7326 pastith
                if (query == null)
1690 14ad7326 pastith
                        throw new ObjectNotFoundException("No query specified");
1691 14ad7326 pastith
                List<FileHeader> files = search(user.getId(), query);
1692 14ad7326 pastith
                List<FileHeaderDTO> res = new ArrayList<FileHeaderDTO>();
1693 14ad7326 pastith
                for(FileHeader f : files)
1694 14ad7326 pastith
                        res.add(f.getDTO());
1695 14ad7326 pastith
                return res;
1696 14ad7326 pastith
        }
1697 14ad7326 pastith
1698 14ad7326 pastith
        /**
1699 14ad7326 pastith
         * Performs the actuals search on the solr server and returns the results
1700 14ad7326 pastith
         *
1701 14ad7326 pastith
         * We have to use the dismax query type (instead of the
1702 14ad7326 pastith
         * standard) because it allows for search time field boosting. This is because we can't use indexing
1703 14ad7326 pastith
         * time field boosting due to the patched rich indexing API that does not allow it
1704 14ad7326 pastith
         *
1705 14ad7326 pastith
         * @param userId
1706 14ad7326 pastith
         * @param query
1707 14ad7326 pastith
         * @return a List of FileHeader objects
1708 14ad7326 pastith
         */
1709 14ad7326 pastith
        private List<FileHeader> search(Long userId, String query) {
1710 14ad7326 pastith
                try {
1711 14ad7326 pastith
                        HttpClient httpClient = new HttpClient();
1712 14ad7326 pastith
1713 bde4eafb pastith
                        GetMethod method = new GetMethod(getConfiguration().getString("solrSelectUrl"));
1714 14ad7326 pastith
                        NameValuePair[] params = {new NameValuePair("qt", "dismax"),
1715 14ad7326 pastith
                                                                                new NameValuePair("q", query),
1716 14ad7326 pastith
                                                                                new NameValuePair("sort", "score desc"),
1717 14ad7326 pastith
                                                                                new NameValuePair("indent", "on")};
1718 14ad7326 pastith
                        method.setQueryString(params);
1719 14ad7326 pastith
                        int retryCount = 0;
1720 14ad7326 pastith
                        int statusCode = 0;
1721 14ad7326 pastith
                        String response = null;
1722 14ad7326 pastith
                        do {
1723 14ad7326 pastith
                                statusCode = httpClient.executeMethod(method);
1724 14ad7326 pastith
                                logger.debug("HTTP status: " + statusCode);
1725 14ad7326 pastith
                                response = method.getResponseBodyAsString();
1726 14ad7326 pastith
                                logger.debug(response);
1727 14ad7326 pastith
                                retryCount++;
1728 14ad7326 pastith
                                if (statusCode != 200 && retryCount < 3)
1729 14ad7326 pastith
                                        try {
1730 14ad7326 pastith
                                                Thread.sleep(3000); //Give Solr a little time to be available
1731 14ad7326 pastith
                                        } catch (InterruptedException e) {
1732 14ad7326 pastith
                                        }
1733 14ad7326 pastith
                        } while (statusCode != 200 && retryCount < 3);
1734 14ad7326 pastith
                        if (statusCode != 200)
1735 14ad7326 pastith
                                throw new EJBException("Search query return error:\n" + response);
1736 14ad7326 pastith
1737 14ad7326 pastith
                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
1738 14ad7326 pastith
                        DocumentBuilder db = dbf.newDocumentBuilder();
1739 14ad7326 pastith
                        Document doc = db.parse(method.getResponseBodyAsStream());
1740 14ad7326 pastith
                        method.releaseConnection();
1741 14ad7326 pastith
1742 14ad7326 pastith
                        Node root = doc.getElementsByTagName("response").item(0);
1743 14ad7326 pastith
                        Node lst = root.getFirstChild().getNextSibling();
1744 14ad7326 pastith
                        Node status = lst.getFirstChild().getNextSibling();
1745 14ad7326 pastith
                        if (status.getAttributes().getNamedItem("name").getNodeValue().equals("status") &&
1746 14ad7326 pastith
                                status.getTextContent().equals("0")) {
1747 14ad7326 pastith
                                List<FileHeader> fileResult = new ArrayList<FileHeader>();
1748 14ad7326 pastith
                                Node result = lst.getNextSibling().getNextSibling();
1749 14ad7326 pastith
                                NodeList docs = result.getChildNodes();
1750 14ad7326 pastith
                                User user = getUser(userId);
1751 14ad7326 pastith
                                for (int i=1; i<docs.getLength(); i=i+2) {
1752 14ad7326 pastith
                                        Node d = docs.item(i);
1753 14ad7326 pastith
                                        NodeList docData = d.getChildNodes();
1754 14ad7326 pastith
                                        for (int j=1; j<docData.getLength(); j=j+2) {
1755 14ad7326 pastith
                                                Node dd = docData.item(j);
1756 14ad7326 pastith
                                                if (dd.getAttributes().item(0).getNodeName().equals("name") &&
1757 14ad7326 pastith
                                                        dd.getAttributes().item(0).getNodeValue().equals("id")) {
1758 14ad7326 pastith
                                                        Long fileId = Long.valueOf(dd.getTextContent());
1759 14ad7326 pastith
                                                        try {
1760 14ad7326 pastith
                                                                FileHeader file = dao.getEntityById(FileHeader.class, fileId);
1761 14ad7326 pastith
                                                                if (file.hasReadPermission(user)) {
1762 14ad7326 pastith
                                                                        fileResult.add(file);
1763 14ad7326 pastith
                                                                        logger.debug("File added " + fileId);
1764 14ad7326 pastith
                                                                }
1765 14ad7326 pastith
                                                        } catch (ObjectNotFoundException e) {
1766 14ad7326 pastith
                                                                logger.warn("Search result not found", e);
1767 14ad7326 pastith
                                                        }
1768 14ad7326 pastith
                                                }
1769 14ad7326 pastith
                                        }
1770 14ad7326 pastith
                                }
1771 14ad7326 pastith
                                return fileResult;
1772 14ad7326 pastith
                        }
1773 14ad7326 pastith
                        throw new EJBException();
1774 14ad7326 pastith
                } catch (HttpException e) {
1775 14ad7326 pastith
                        throw new EJBException(e);
1776 14ad7326 pastith
                } catch (IOException e) {
1777 14ad7326 pastith
                        throw new EJBException(e);
1778 14ad7326 pastith
                } catch (SAXException e) {
1779 14ad7326 pastith
                        throw new EJBException(e);
1780 14ad7326 pastith
                } catch (ParserConfigurationException e) {
1781 14ad7326 pastith
                        throw new EJBException(e);
1782 14ad7326 pastith
                } catch (ObjectNotFoundException e) {
1783 14ad7326 pastith
                        throw new EJBException(e);
1784 14ad7326 pastith
                }
1785 14ad7326 pastith
        }
1786 14ad7326 pastith
1787 14ad7326 pastith
        /* (non-Javadoc)
1788 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#copyFiles(java.lang.Long, java.util.List, java.lang.Long)
1789 14ad7326 pastith
         */
1790 14ad7326 pastith
        @Override
1791 14ad7326 pastith
        public void copyFiles(Long userId, List<Long> fileIds, Long destId) throws ObjectNotFoundException, DuplicateNameException, GSSIOException, InsufficientPermissionsException, QuotaExceededException {
1792 14ad7326 pastith
                for(Long l : fileIds){
1793 14ad7326 pastith
                        FileHeader file = dao.getEntityById(FileHeader.class, l);
1794 14ad7326 pastith
                        copyFile(userId, l, destId, file.getName());
1795 14ad7326 pastith
                }
1796 14ad7326 pastith
1797 14ad7326 pastith
1798 14ad7326 pastith
        }
1799 14ad7326 pastith
1800 14ad7326 pastith
        /* (non-Javadoc)
1801 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#moveFiles(java.lang.Long, java.util.List, java.lang.Long)
1802 14ad7326 pastith
         */
1803 14ad7326 pastith
        @Override
1804 4684df80 Fotis Stamatelopoulos
        public void moveFiles(Long userId, List<Long> fileIds, Long destId) throws InsufficientPermissionsException, ObjectNotFoundException, QuotaExceededException {
1805 14ad7326 pastith
                for(Long l : fileIds){
1806 14ad7326 pastith
                        FileHeader file = dao.getEntityById(FileHeader.class, l);
1807 14ad7326 pastith
                        moveFile(userId, l, destId, file.getName());
1808 14ad7326 pastith
                }
1809 14ad7326 pastith
1810 14ad7326 pastith
        }
1811 14ad7326 pastith
1812 14ad7326 pastith
        /* (non-Javadoc)
1813 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#deleteFiles(java.lang.Long, java.util.List)
1814 14ad7326 pastith
         */
1815 14ad7326 pastith
        @Override
1816 14ad7326 pastith
        public void deleteFiles(Long userId, List<Long> fileIds) throws ObjectNotFoundException, InsufficientPermissionsException {
1817 14ad7326 pastith
                if (userId == null)
1818 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1819 14ad7326 pastith
                final User user = dao.getEntityById(User.class, userId);
1820 4d737770 Fotis Stamatelopoulos
                List<String> filesToRemove = new ArrayList<String>();
1821 14ad7326 pastith
                //first delete database objects
1822 14ad7326 pastith
                for(Long fileId : fileIds){
1823 14ad7326 pastith
                        if (fileId == null)
1824 14ad7326 pastith
                                throw new ObjectNotFoundException("No file specified");
1825 14ad7326 pastith
                        final FileHeader file = dao.getEntityById(FileHeader.class, fileId);
1826 14ad7326 pastith
                        final Folder parent = file.getFolder();
1827 14ad7326 pastith
                        if (parent == null)
1828 14ad7326 pastith
                                throw new ObjectNotFoundException("The specified file has no parent folder");
1829 14ad7326 pastith
                        if (!file.hasDeletePermission(user))
1830 14ad7326 pastith
                                throw new InsufficientPermissionsException("User " + user.getId() + " cannot delete file " + file.getName() + "(" + file.getId() + ")");
1831 14ad7326 pastith
1832 14ad7326 pastith
                        parent.removeFile(file);
1833 4d737770 Fotis Stamatelopoulos
                        for (final FileBody body : file.getBodies())
1834 4d737770 Fotis Stamatelopoulos
                                filesToRemove.add(body.getStoredFilePath());
1835 14ad7326 pastith
                        dao.delete(file);
1836 14ad7326 pastith
                }
1837 14ad7326 pastith
                //then remove physical files if everything is ok
1838 4d737770 Fotis Stamatelopoulos
                for(String physicalFileName : filesToRemove)
1839 4d737770 Fotis Stamatelopoulos
                        deleteActualFile(physicalFileName);
1840 14ad7326 pastith
                //then unindex deleted files
1841 14ad7326 pastith
                for(Long fileId : fileIds)
1842 14ad7326 pastith
                        indexFile(fileId, true);
1843 14ad7326 pastith
1844 14ad7326 pastith
        }
1845 14ad7326 pastith
1846 14ad7326 pastith
        /* (non-Javadoc)
1847 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#moveFilesToTrash(java.lang.Long, java.util.List)
1848 14ad7326 pastith
         */
1849 14ad7326 pastith
        @Override
1850 14ad7326 pastith
        public void moveFilesToTrash(Long userId, List<Long> fileIds) throws ObjectNotFoundException, InsufficientPermissionsException {
1851 14ad7326 pastith
                for(Long l : fileIds)
1852 14ad7326 pastith
                        moveFileToTrash(userId, l);
1853 14ad7326 pastith
1854 14ad7326 pastith
        }
1855 14ad7326 pastith
1856 14ad7326 pastith
        @Override
1857 14ad7326 pastith
        public void removeFilesFromTrash(Long userId, List<Long> fileIds) throws ObjectNotFoundException, InsufficientPermissionsException {
1858 14ad7326 pastith
                for(Long l : fileIds)
1859 14ad7326 pastith
                        removeFileFromTrash(userId, l);
1860 14ad7326 pastith
1861 14ad7326 pastith
        }
1862 14ad7326 pastith
1863 14ad7326 pastith
        @Override
1864 14ad7326 pastith
        public Nonce createNonce(Long userId) throws ObjectNotFoundException {
1865 14ad7326 pastith
                if (userId == null)
1866 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1867 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
1868 14ad7326 pastith
                Nonce nonce = Nonce.createNonce(user.getId());
1869 14ad7326 pastith
                dao.create(nonce);
1870 14ad7326 pastith
                return nonce;
1871 14ad7326 pastith
        }
1872 14ad7326 pastith
1873 14ad7326 pastith
        @Override
1874 14ad7326 pastith
        public Nonce getNonce(String nonce, Long userId) throws ObjectNotFoundException {
1875 14ad7326 pastith
                if (userId == null)
1876 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1877 14ad7326 pastith
                if (nonce == null)
1878 14ad7326 pastith
                        throw new ObjectNotFoundException("No nonce specified");
1879 14ad7326 pastith
                return dao.getNonce(nonce, userId);
1880 14ad7326 pastith
        }
1881 14ad7326 pastith
1882 14ad7326 pastith
        @Override
1883 14ad7326 pastith
        public void removeNonce(Long id) throws ObjectNotFoundException {
1884 14ad7326 pastith
                if (id == null)
1885 14ad7326 pastith
                        throw new ObjectNotFoundException("No nonce specified");
1886 14ad7326 pastith
                Nonce nonce = dao.getEntityById(Nonce.class, id);
1887 14ad7326 pastith
                dao.delete(nonce);
1888 14ad7326 pastith
        }
1889 14ad7326 pastith
1890 14ad7326 pastith
        @Override
1891 14ad7326 pastith
        public void activateUserNonce(Long userId, String nonce, Date nonceExpiryDate) throws ObjectNotFoundException {
1892 14ad7326 pastith
                if (userId == null)
1893 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1894 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
1895 14ad7326 pastith
                user.setNonce(nonce);
1896 14ad7326 pastith
                user.setNonceExpiryDate(nonceExpiryDate);
1897 14ad7326 pastith
        }
1898 14ad7326 pastith
1899 14ad7326 pastith
        /* (non-Javadoc)
1900 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#getUserStatistics(java.lang.Long)
1901 14ad7326 pastith
         */
1902 14ad7326 pastith
        @Override
1903 14ad7326 pastith
        public StatsDTO getUserStatistics(Long userId) throws ObjectNotFoundException {
1904 14ad7326 pastith
                if (userId == null)
1905 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1906 14ad7326 pastith
                StatsDTO stats = new StatsDTO();
1907 14ad7326 pastith
                stats.setFileCount(dao.getFileCount(userId));
1908 14ad7326 pastith
                Long fileSize = dao.getFileSize(userId);
1909 14ad7326 pastith
                stats.setFileSize(fileSize);
1910 d3ff9c69 droutsis
                Long quota = getQuota(userId);
1911 14ad7326 pastith
                Long quotaLeft = quota - fileSize;
1912 14ad7326 pastith
                stats.setQuotaLeftSize(quotaLeft);
1913 14ad7326 pastith
                return stats;
1914 14ad7326 pastith
        }
1915 14ad7326 pastith
1916 14ad7326 pastith
        /* (non-Javadoc)
1917 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#getVersions(java.lang.Long, java.lang.Long)
1918 14ad7326 pastith
         */
1919 14ad7326 pastith
        @Override
1920 14ad7326 pastith
        public List<FileBodyDTO> getVersions(Long userId, Long fileId) throws ObjectNotFoundException, InsufficientPermissionsException {
1921 14ad7326 pastith
                if (userId == null)
1922 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1923 14ad7326 pastith
                if (fileId == null)
1924 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
1925 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
1926 14ad7326 pastith
                FileHeader header = dao.getEntityById(FileHeader.class, fileId);
1927 14ad7326 pastith
                if(!header.hasReadPermission(user))
1928 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
1929 14ad7326 pastith
                List<FileBodyDTO> result = new LinkedList<FileBodyDTO>();
1930 14ad7326 pastith
                for(int i = header.getBodies().size()-1 ; i>=0; i--)
1931 14ad7326 pastith
                        result.add(header.getBodies().get(i).getDTO());
1932 14ad7326 pastith
                return result;
1933 14ad7326 pastith
        }
1934 14ad7326 pastith
1935 14ad7326 pastith
        /* (non-Javadoc)
1936 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#removeVersion(java.lang.Long, java.lang.Long, java.lang.Long)
1937 14ad7326 pastith
         */
1938 14ad7326 pastith
        @Override
1939 14ad7326 pastith
        public void removeVersion(Long userId, Long fileId, Long bodyId) throws ObjectNotFoundException, InsufficientPermissionsException {
1940 14ad7326 pastith
                if (userId == null)
1941 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1942 14ad7326 pastith
                if (fileId == null)
1943 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
1944 14ad7326 pastith
                if (bodyId == null)
1945 14ad7326 pastith
                        throw new ObjectNotFoundException("No body specified");
1946 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
1947 14ad7326 pastith
                FileHeader header = dao.getEntityById(FileHeader.class, fileId);
1948 14ad7326 pastith
                if(!header.hasWritePermission(user))
1949 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
1950 14ad7326 pastith
                FileBody body = dao.getEntityById(FileBody.class, bodyId);
1951 14ad7326 pastith
                if(body.equals(header.getCurrentBody())){
1952 14ad7326 pastith
1953 14ad7326 pastith
                        if(header.getBodies().size() == 1)
1954 14ad7326 pastith
                                throw new InsufficientPermissionsException("You cant delete this version, Delete file instead!");
1955 14ad7326 pastith
                        for(FileBody b : header.getBodies())
1956 14ad7326 pastith
                                if(b.getVersion() == body.getVersion()-1)
1957 14ad7326 pastith
                                        header.setCurrentBody(b);
1958 14ad7326 pastith
                }
1959 4d737770 Fotis Stamatelopoulos
                deleteActualFile(body.getStoredFilePath());
1960 14ad7326 pastith
                header.getBodies().remove(body);
1961 14ad7326 pastith
1962 14ad7326 pastith
1963 14ad7326 pastith
        }
1964 14ad7326 pastith
1965 14ad7326 pastith
        @Override
1966 39c34533 pastith
        public void restoreVersion(Long userId, Long fileId, int version) throws ObjectNotFoundException, InsufficientPermissionsException,  GSSIOException, QuotaExceededException {
1967 14ad7326 pastith
                if (userId == null)
1968 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1969 14ad7326 pastith
                if (fileId == null)
1970 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
1971 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
1972 14ad7326 pastith
                FileHeader header = dao.getEntityById(FileHeader.class, fileId);
1973 14ad7326 pastith
                if(!header.hasWritePermission(user))
1974 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
1975 39c34533 pastith
                FileBody body = dao.getFileVersion(fileId, version);
1976 14ad7326 pastith
                final File fileContents = new File(body.getStoredFilePath());
1977 14ad7326 pastith
1978 14ad7326 pastith
                try {
1979 14ad7326 pastith
                        updateFileContents(userId, fileId, body.getMimeType(), new FileInputStream(fileContents) );
1980 14ad7326 pastith
                } catch (FileNotFoundException e) {
1981 14ad7326 pastith
                        throw new GSSIOException(e);
1982 14ad7326 pastith
                }
1983 14ad7326 pastith
1984 14ad7326 pastith
        }
1985 14ad7326 pastith
1986 14ad7326 pastith
        /* (non-Javadoc)
1987 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#removeOldVersions(java.lang.Long, java.lang.Long)
1988 14ad7326 pastith
         */
1989 14ad7326 pastith
        @Override
1990 14ad7326 pastith
        public void removeOldVersions(Long userId, Long fileId) throws ObjectNotFoundException, InsufficientPermissionsException {
1991 14ad7326 pastith
                if (userId == null)
1992 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
1993 14ad7326 pastith
                if (fileId == null)
1994 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
1995 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
1996 14ad7326 pastith
                FileHeader header = dao.getEntityById(FileHeader.class, fileId);
1997 14ad7326 pastith
                if(!header.hasWritePermission(user))
1998 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
1999 14ad7326 pastith
                Iterator<FileBody> it = header.getBodies().iterator();
2000 14ad7326 pastith
                while(it.hasNext()){
2001 14ad7326 pastith
                        FileBody body = it.next();
2002 14ad7326 pastith
                        if(!body.equals(header.getCurrentBody())){
2003 4d737770 Fotis Stamatelopoulos
                                deleteActualFile(body.getStoredFilePath());
2004 14ad7326 pastith
                                it.remove();
2005 14ad7326 pastith
                                dao.delete(body);
2006 14ad7326 pastith
                        }
2007 14ad7326 pastith
                }
2008 14ad7326 pastith
                header.getCurrentBody().setVersion(1);
2009 14ad7326 pastith
2010 14ad7326 pastith
        }
2011 14ad7326 pastith
2012 14ad7326 pastith
        /* (non-Javadoc)
2013 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#toggleFileVersioning(java.lang.Long, java.lang.Long, boolean)
2014 14ad7326 pastith
         */
2015 14ad7326 pastith
        @Override
2016 14ad7326 pastith
        public void toggleFileVersioning(Long userId, Long fileId, boolean versioned) throws ObjectNotFoundException, InsufficientPermissionsException {
2017 14ad7326 pastith
                if (userId == null)
2018 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
2019 14ad7326 pastith
                if (fileId == null)
2020 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
2021 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
2022 14ad7326 pastith
                FileHeader header = dao.getEntityById(FileHeader.class, fileId);
2023 14ad7326 pastith
                if(!header.hasWritePermission(user))
2024 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
2025 14ad7326 pastith
                if(!header.isVersioned() == versioned){
2026 14ad7326 pastith
                        if(header.isVersioned())
2027 14ad7326 pastith
                                removeOldVersions(userId, fileId);
2028 14ad7326 pastith
                        header.setVersioned(versioned);
2029 14ad7326 pastith
2030 14ad7326 pastith
                }
2031 14ad7326 pastith
        }
2032 14ad7326 pastith
2033 14ad7326 pastith
        /**
2034 14ad7326 pastith
         * Gets the quota left for specified userId
2035 14ad7326 pastith
         * @param userId
2036 14ad7326 pastith
         * @return
2037 14ad7326 pastith
         */
2038 14ad7326 pastith
        private Long getQuotaLeft(Long userId){
2039 14ad7326 pastith
                Long fileSize = dao.getFileSize(userId);
2040 d3ff9c69 droutsis
                Long quota = getQuota(userId);
2041 14ad7326 pastith
                return quota - fileSize;
2042 14ad7326 pastith
        }
2043 14ad7326 pastith
2044 d3ff9c69 droutsis
        /**
2045 d3ff9c69 droutsis
         * Gets the quota for specified userId
2046 78214787 Panagiotis Astithas
         * @param userId
2047 78214787 Panagiotis Astithas
         * @return
2048 78214787 Panagiotis Astithas
         */
2049 78214787 Panagiotis Astithas
        private Long getQuota(@SuppressWarnings("unused") Long userId){
2050 78214787 Panagiotis Astithas
                Long quota = getConfiguration().getLong("quota", new Long(52428800L));
2051 78214787 Panagiotis Astithas
                return quota;
2052 78214787 Panagiotis Astithas
        }
2053 d3ff9c69 droutsis
2054 14ad7326 pastith
        public void rebuildSolrIndex() {
2055 14ad7326 pastith
                MessageProducer sender = null;
2056 14ad7326 pastith
                Session session = null;
2057 14ad7326 pastith
                Connection qConn = null;
2058 14ad7326 pastith
                try {
2059 14ad7326 pastith
                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
2060 14ad7326 pastith
                        DocumentBuilder db = dbf.newDocumentBuilder();
2061 14ad7326 pastith
                        Document doc = db.newDocument();
2062 14ad7326 pastith
                        Node root = doc.createElement("delete");
2063 14ad7326 pastith
                        doc.appendChild(root);
2064 14ad7326 pastith
                        Node queryNode = doc.createElement("query");
2065 14ad7326 pastith
                        root.appendChild(queryNode);
2066 14ad7326 pastith
                        queryNode.appendChild(doc.createTextNode("*:*"));
2067 14ad7326 pastith
2068 14ad7326 pastith
                        TransformerFactory fact = TransformerFactory.newInstance();
2069 14ad7326 pastith
                        Transformer trans = fact.newTransformer();
2070 14ad7326 pastith
                        trans.setOutputProperty(OutputKeys.INDENT, "yes");
2071 14ad7326 pastith
                        StringWriter sw = new StringWriter();
2072 14ad7326 pastith
                        StreamResult sr = new StreamResult(sw);
2073 14ad7326 pastith
                        DOMSource source = new DOMSource(doc);
2074 14ad7326 pastith
                        trans.transform(source, sr);
2075 14ad7326 pastith
                        logger.debug(sw.toString());
2076 14ad7326 pastith
2077 14ad7326 pastith
                        HttpClient httpClient = new HttpClient();
2078 bde4eafb pastith
                        PostMethod method = new PostMethod(getConfiguration().getString("solrUpdateUrl"));
2079 14ad7326 pastith
                        method.setRequestEntity(new StringRequestEntity(sw.toString()));
2080 14ad7326 pastith
                        int retryCount = 0;
2081 14ad7326 pastith
                        int statusCode = 0;
2082 14ad7326 pastith
                        String response = null;
2083 14ad7326 pastith
                        do {
2084 14ad7326 pastith
                                statusCode = httpClient.executeMethod(method);
2085 14ad7326 pastith
                                logger.debug("HTTP status: " + statusCode);
2086 14ad7326 pastith
                                response = method.getResponseBodyAsString();
2087 14ad7326 pastith
                                logger.debug(response);
2088 14ad7326 pastith
                                retryCount++;
2089 14ad7326 pastith
                                if (statusCode != 200 && retryCount < 3)
2090 14ad7326 pastith
                                        try {
2091 14ad7326 pastith
                                                Thread.sleep(10000); //Give Solr a little time to be available
2092 14ad7326 pastith
                                        } catch (InterruptedException e) {
2093 14ad7326 pastith
                                        }
2094 14ad7326 pastith
                        } while (statusCode != 200 && retryCount < 3);
2095 14ad7326 pastith
                        method.releaseConnection();
2096 14ad7326 pastith
                        if (statusCode != 200)
2097 14ad7326 pastith
                                throw new EJBException("Cannot clear Solr index. Solr response is:\n" + response);
2098 14ad7326 pastith
                        List<Long> fileIds = dao.getAllFileIds();
2099 14ad7326 pastith
2100 14ad7326 pastith
                        Context jndiCtx = new InitialContext();
2101 14ad7326 pastith
                        ConnectionFactory factory = (QueueConnectionFactory) jndiCtx.lookup("java:/JmsXA");
2102 14ad7326 pastith
                        Queue queue = (Queue) jndiCtx.lookup("queue/gss-indexingQueue");
2103 14ad7326 pastith
                        qConn = factory.createConnection();
2104 14ad7326 pastith
                        session = qConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
2105 14ad7326 pastith
                        sender = session.createProducer(queue);
2106 14ad7326 pastith
2107 14ad7326 pastith
                        for (Long id : fileIds) {
2108 14ad7326 pastith
                                MapMessage map = session.createMapMessage();
2109 14ad7326 pastith
                                map.setObject("id", id);
2110 14ad7326 pastith
                                map.setBoolean("delete", false);
2111 14ad7326 pastith
                                sender.send(map);
2112 14ad7326 pastith
                        }
2113 14ad7326 pastith
                        sendOptimize(httpClient, 0);
2114 14ad7326 pastith
                } catch (DOMException e) {
2115 14ad7326 pastith
                        throw new EJBException(e);
2116 14ad7326 pastith
                } catch (TransformerConfigurationException e) {
2117 14ad7326 pastith
                        throw new EJBException(e);
2118 14ad7326 pastith
                } catch (IllegalArgumentException e) {
2119 14ad7326 pastith
                        throw new EJBException(e);
2120 14ad7326 pastith
                } catch (HttpException e) {
2121 14ad7326 pastith
                        throw new EJBException(e);
2122 14ad7326 pastith
                } catch (UnsupportedEncodingException e) {
2123 14ad7326 pastith
                        throw new EJBException(e);
2124 14ad7326 pastith
                } catch (ParserConfigurationException e) {
2125 14ad7326 pastith
                        throw new EJBException(e);
2126 14ad7326 pastith
                } catch (TransformerException e) {
2127 14ad7326 pastith
                        throw new EJBException(e);
2128 14ad7326 pastith
                } catch (IOException e) {
2129 14ad7326 pastith
                        throw new EJBException(e);
2130 14ad7326 pastith
                } catch (NamingException e) {
2131 14ad7326 pastith
                        throw new EJBException(e);
2132 14ad7326 pastith
                } catch (JMSException e) {
2133 14ad7326 pastith
                        throw new EJBException(e);
2134 14ad7326 pastith
                }
2135 14ad7326 pastith
                finally {
2136 14ad7326 pastith
                        try {
2137 14ad7326 pastith
                                if (sender != null)
2138 14ad7326 pastith
                                        sender.close();
2139 14ad7326 pastith
                                if (session != null)
2140 14ad7326 pastith
                                        session.close();
2141 14ad7326 pastith
                                if (qConn != null)
2142 14ad7326 pastith
                                        qConn.close();
2143 14ad7326 pastith
                        }
2144 14ad7326 pastith
                        catch (JMSException e) {
2145 14ad7326 pastith
                                logger.warn(e);
2146 14ad7326 pastith
                        }
2147 14ad7326 pastith
                }
2148 14ad7326 pastith
        }
2149 14ad7326 pastith
2150 14ad7326 pastith
        /**
2151 14ad7326 pastith
         * Sends a optimize message to the solr server
2152 14ad7326 pastith
         *
2153 14ad7326 pastith
         * @param httpClient
2154 14ad7326 pastith
         * @param retryCount If the commit fails, it is retried three times. This parameter is passed in the recursive
2155 14ad7326 pastith
         *                                         calls to stop the recursion
2156 14ad7326 pastith
         * @throws UnsupportedEncodingException
2157 14ad7326 pastith
         * @throws IOException
2158 14ad7326 pastith
         * @throws HttpException
2159 14ad7326 pastith
         */
2160 14ad7326 pastith
        private void sendOptimize(HttpClient httpClient, int retryCount) throws UnsupportedEncodingException, IOException, HttpException {
2161 14ad7326 pastith
                PostMethod method = null;
2162 14ad7326 pastith
                try {
2163 14ad7326 pastith
                        logger.debug("Optimize retry: " + retryCount);
2164 bde4eafb pastith
                        method = new PostMethod(getConfiguration().getString("solrUpdateUrl"));
2165 14ad7326 pastith
                        method.setRequestEntity(new StringRequestEntity("<optimize/>", "text/xml", "iso8859-1"));
2166 14ad7326 pastith
                        int statusCode = httpClient.executeMethod(method);
2167 14ad7326 pastith
                        logger.debug("HTTP status: " + statusCode);
2168 14ad7326 pastith
                        String response = method.getResponseBodyAsString();
2169 14ad7326 pastith
                        logger.debug(response);
2170 14ad7326 pastith
                        if (statusCode != 200 && retryCount < 2) {
2171 14ad7326 pastith
                                try {
2172 14ad7326 pastith
                                        Thread.sleep(10000); //Give Solr a little time to be available
2173 14ad7326 pastith
                                } catch (InterruptedException e) {
2174 14ad7326 pastith
                                }
2175 14ad7326 pastith
                                sendOptimize(httpClient, retryCount + 1);
2176 14ad7326 pastith
                        }
2177 14ad7326 pastith
                }
2178 14ad7326 pastith
                finally {
2179 14ad7326 pastith
                        if (method != null)
2180 14ad7326 pastith
                                method.releaseConnection();
2181 14ad7326 pastith
                }
2182 14ad7326 pastith
        }
2183 14ad7326 pastith
2184 4d737770 Fotis Stamatelopoulos
        public FileHeaderDTO createFile(Long userId, Long folderId, String name, String mimeType, long fileSize, String filePath)
2185 14ad7326 pastith
                        throws DuplicateNameException, ObjectNotFoundException, GSSIOException,
2186 14ad7326 pastith
                        InsufficientPermissionsException, QuotaExceededException {
2187 14ad7326 pastith
                // Validate.
2188 14ad7326 pastith
                if (userId == null)
2189 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
2190 14ad7326 pastith
                if (folderId == null)
2191 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
2192 14ad7326 pastith
                String contentType = mimeType;
2193 14ad7326 pastith
                if (StringUtils.isEmpty(mimeType))
2194 14ad7326 pastith
                        contentType = DEFAULT_MIME_TYPE;
2195 14ad7326 pastith
                if (StringUtils.isEmpty(name))
2196 14ad7326 pastith
                        throw new ObjectNotFoundException("No file name specified");
2197 14ad7326 pastith
                if (dao.existsFolderOrFile(folderId, name))
2198 14ad7326 pastith
                        throw new DuplicateNameException("A folder or file with the name '" + name +
2199 14ad7326 pastith
                                                "' already exists at this level");
2200 14ad7326 pastith
2201 14ad7326 pastith
                // Do the actual work.
2202 14ad7326 pastith
                Folder parent = null;
2203 14ad7326 pastith
                try {
2204 14ad7326 pastith
                        parent = dao.getEntityById(Folder.class, folderId);
2205 14ad7326 pastith
                } catch (final ObjectNotFoundException onfe) {
2206 14ad7326 pastith
                        // Supply a more accurate problem description.
2207 14ad7326 pastith
                        throw new ObjectNotFoundException("Parent folder not found");
2208 14ad7326 pastith
                }
2209 14ad7326 pastith
                final User owner = dao.getEntityById(User.class, userId);
2210 14ad7326 pastith
                if (!parent.hasWritePermission(owner))
2211 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the permissions to write to this folder");
2212 14ad7326 pastith
                final FileHeader file = new FileHeader();
2213 14ad7326 pastith
                file.setName(name);
2214 14ad7326 pastith
                parent.addFile(file);
2215 14ad7326 pastith
                // set file owner to folder owner
2216 14ad7326 pastith
                file.setOwner(parent.getOwner());
2217 14ad7326 pastith
2218 14ad7326 pastith
                final Date now = new Date();
2219 14ad7326 pastith
                final AuditInfo auditInfo = new AuditInfo();
2220 14ad7326 pastith
                auditInfo.setCreatedBy(owner);
2221 14ad7326 pastith
                auditInfo.setCreationDate(now);
2222 14ad7326 pastith
                auditInfo.setModifiedBy(owner);
2223 14ad7326 pastith
                auditInfo.setModificationDate(now);
2224 14ad7326 pastith
                file.setAuditInfo(auditInfo);
2225 14ad7326 pastith
                // TODO set the proper versioning flag on creation
2226 14ad7326 pastith
                file.setVersioned(false);
2227 14ad7326 pastith
2228 14ad7326 pastith
                for (final Permission p : parent.getPermissions()) {
2229 14ad7326 pastith
                        final Permission permission = new Permission();
2230 14ad7326 pastith
                        permission.setGroup(p.getGroup());
2231 14ad7326 pastith
                        permission.setUser(p.getUser());
2232 14ad7326 pastith
                        permission.setRead(p.getRead());
2233 14ad7326 pastith
                        permission.setWrite(p.getWrite());
2234 14ad7326 pastith
                        permission.setModifyACL(p.getModifyACL());
2235 14ad7326 pastith
                        file.addPermission(permission);
2236 14ad7326 pastith
                }
2237 14ad7326 pastith
2238 14ad7326 pastith
                // Create the file body.
2239 14ad7326 pastith
                try {
2240 4d737770 Fotis Stamatelopoulos
                        createFileBody(name, contentType, fileSize, filePath, file, auditInfo);
2241 14ad7326 pastith
                } catch (FileNotFoundException e) {
2242 14ad7326 pastith
                        throw new GSSIOException(e);
2243 14ad7326 pastith
                }
2244 14ad7326 pastith
                dao.flush();
2245 14ad7326 pastith
                indexFile(file.getId(), false);
2246 8f128261 droutsis
2247 8f128261 droutsis
                return file.getDTO();
2248 14ad7326 pastith
        }
2249 14ad7326 pastith
2250 14ad7326 pastith
        /* (non-Javadoc)
2251 14ad7326 pastith
         * @see gr.ebs.gss.server.ejb.ExternalAPI#updateFileContents(java.lang.Long, java.lang.Long, java.lang.String, java.io.InputStream)
2252 14ad7326 pastith
         */
2253 4d737770 Fotis Stamatelopoulos
        public FileHeaderDTO updateFileContents(Long userId, Long fileId, String mimeType, long fileSize, String filePath) throws ObjectNotFoundException, GSSIOException, InsufficientPermissionsException, QuotaExceededException {
2254 14ad7326 pastith
                if (userId == null)
2255 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
2256 14ad7326 pastith
                if (fileId == null)
2257 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
2258 14ad7326 pastith
                String contentType = mimeType;
2259 14ad7326 pastith
2260 14ad7326 pastith
                FileHeader file = dao.getEntityById(FileHeader.class, fileId);
2261 5ca9c0d6 fstamatelopoulos
2262 5ca9c0d6 fstamatelopoulos
                // if no mime type or the generic mime type is defined by the client, then try to identify it from the filename extension
2263 f92730cd droutsis
                if (StringUtils.isEmpty(mimeType) || "application/octet-stream".equals(mimeType)
2264 f92730cd droutsis
                                        || "application/download".equals(mimeType) || "application/force-download".equals(mimeType)
2265 f92730cd droutsis
                                        || "octet/stream".equals(mimeType) || "application/unknown".equals(mimeType))
2266 5ca9c0d6 fstamatelopoulos
                        contentType = identifyMimeType(file.getName());
2267 5ca9c0d6 fstamatelopoulos
2268 14ad7326 pastith
                final User owner = dao.getEntityById(User.class, userId);
2269 14ad7326 pastith
                if (!file.hasWritePermission(owner))
2270 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
2271 14ad7326 pastith
                final Date now = new Date();
2272 14ad7326 pastith
                final AuditInfo auditInfo = new AuditInfo();
2273 14ad7326 pastith
                auditInfo.setCreatedBy(owner);
2274 14ad7326 pastith
                auditInfo.setCreationDate(now);
2275 14ad7326 pastith
                auditInfo.setModifiedBy(owner);
2276 14ad7326 pastith
                auditInfo.setModificationDate(now);
2277 14ad7326 pastith
                try {
2278 4d737770 Fotis Stamatelopoulos
                        createFileBody(file.getName(), contentType, fileSize, filePath, file, auditInfo);
2279 14ad7326 pastith
                } catch (FileNotFoundException e) {
2280 14ad7326 pastith
                        throw new GSSIOException(e);
2281 14ad7326 pastith
                }
2282 14ad7326 pastith
2283 14ad7326 pastith
                indexFile(fileId, false);
2284 8f128261 droutsis
                return file.getDTO();
2285 14ad7326 pastith
        }
2286 14ad7326 pastith
2287 14ad7326 pastith
        /**
2288 5ca9c0d6 fstamatelopoulos
         * Helper method for identifying mime type by examining the filename extension
2289 5ca9c0d6 fstamatelopoulos
         *
2290 5ca9c0d6 fstamatelopoulos
         * @param filename
2291 5ca9c0d6 fstamatelopoulos
         * @return the mime type
2292 5ca9c0d6 fstamatelopoulos
         */
2293 5ca9c0d6 fstamatelopoulos
        private String identifyMimeType(String filename) {
2294 09051786 droutsis
                if (filename.indexOf('.') != -1) {
2295 f3f7bdf3 Fotis Stamatelopoulos
                        String extension = filename.substring(filename.lastIndexOf('.')).toLowerCase(Locale.ENGLISH);
2296 5ca9c0d6 fstamatelopoulos
                        if (".doc".equals(extension))
2297 5ca9c0d6 fstamatelopoulos
                                return "application/msword";
2298 5ca9c0d6 fstamatelopoulos
                        else if (".xls".equals(extension))
2299 5ca9c0d6 fstamatelopoulos
                                return "application/vnd.ms-excel";
2300 5ca9c0d6 fstamatelopoulos
                        else if (".ppt".equals(extension))
2301 5ca9c0d6 fstamatelopoulos
                                return "application/vnd.ms-powerpoint";
2302 5ca9c0d6 fstamatelopoulos
                        else if (".pdf".equals(extension))
2303 5ca9c0d6 fstamatelopoulos
                                return "application/pdf";
2304 4684df80 Fotis Stamatelopoulos
                        else if (".gif".equals(extension))
2305 4684df80 Fotis Stamatelopoulos
                                return "image/gif";
2306 4684df80 Fotis Stamatelopoulos
                        else if (".jpg".equals(extension) || ".jpeg".equals(extension) || ".jpe".equals(extension))
2307 4684df80 Fotis Stamatelopoulos
                                return "image/jpeg";
2308 4684df80 Fotis Stamatelopoulos
                        else if (".tiff".equals(extension) || ".tif".equals(extension))
2309 4684df80 Fotis Stamatelopoulos
                                return "image/tiff";
2310 4684df80 Fotis Stamatelopoulos
                        else if (".png".equals(extension))
2311 4684df80 Fotis Stamatelopoulos
                                return "image/png";
2312 4684df80 Fotis Stamatelopoulos
                        else if (".bmp".equals(extension))
2313 4684df80 Fotis Stamatelopoulos
                                return "image/bmp";
2314 5ca9c0d6 fstamatelopoulos
                }
2315 5ca9c0d6 fstamatelopoulos
                // when all else fails assign the default mime type
2316 5ca9c0d6 fstamatelopoulos
                return DEFAULT_MIME_TYPE;
2317 5ca9c0d6 fstamatelopoulos
        }
2318 5ca9c0d6 fstamatelopoulos
2319 5ca9c0d6 fstamatelopoulos
        /**
2320 14ad7326 pastith
         * Helper method to create a new file body and attach it as the current body
2321 14ad7326 pastith
         * of the provided file header.
2322 14ad7326 pastith
         *
2323 14ad7326 pastith
         * @param name the original file name
2324 14ad7326 pastith
         * @param mimeType the content type
2325 4d737770 Fotis Stamatelopoulos
         * @param fileSize the uploaded file size
2326 4d737770 Fotis Stamatelopoulos
         * @param filePath the uploaded file full path
2327 14ad7326 pastith
         * @param header the file header that will be associated with the new body
2328 14ad7326 pastith
         * @param auditInfo the audit info
2329 14ad7326 pastith
         * @param owner the owner of the file
2330 14ad7326 pastith
         * @throws FileNotFoundException
2331 14ad7326 pastith
         * @throws QuotaExceededException
2332 14ad7326 pastith
         */
2333 4d737770 Fotis Stamatelopoulos
        private void createFileBody(String name, String mimeType, long fileSize, String filePath,
2334 4d737770 Fotis Stamatelopoulos
                                FileHeader header, AuditInfo auditInfo)
2335 14ad7326 pastith
                        throws FileNotFoundException, QuotaExceededException {
2336 6dddaedf Dimitris Routsis
2337 6dddaedf Dimitris Routsis
                long currentTotalSize = 0;
2338 6dddaedf Dimitris Routsis
                if (!header.isVersioned() && header.getCurrentBody() != null && header.getBodies() != null)
2339 6dddaedf Dimitris Routsis
                        currentTotalSize = header.getTotalSize();
2340 b6510556 Dimitris Routsis
                Long quotaLeft = getQuotaLeft(header.getOwner().getId());
2341 4d737770 Fotis Stamatelopoulos
                if(quotaLeft < fileSize-currentTotalSize) {
2342 4d737770 Fotis Stamatelopoulos
                        // quota exceeded -> delete the file
2343 4d737770 Fotis Stamatelopoulos
                        deleteActualFile(filePath);
2344 6dddaedf Dimitris Routsis
                        throw new QuotaExceededException("Not enough free space available");
2345 6dddaedf Dimitris Routsis
                }
2346 6dddaedf Dimitris Routsis
2347 14ad7326 pastith
                FileBody body = new FileBody();
2348 5ca9c0d6 fstamatelopoulos
2349 5ca9c0d6 fstamatelopoulos
                // if no mime type or the generic mime type is defined by the client, then try to identify it from the filename extension
2350 f92730cd droutsis
                if (StringUtils.isEmpty(mimeType) || "application/octet-stream".equals(mimeType)
2351 f92730cd droutsis
                                        || "application/download".equals(mimeType) || "application/force-download".equals(mimeType)
2352 f92730cd droutsis
                                        || "octet/stream".equals(mimeType) || "application/unknown".equals(mimeType))
2353 5ca9c0d6 fstamatelopoulos
                        body.setMimeType(identifyMimeType(name));
2354 5ca9c0d6 fstamatelopoulos
                else
2355 78214787 Panagiotis Astithas
                        body.setMimeType(mimeType);
2356 14ad7326 pastith
                body.setAuditInfo(auditInfo);
2357 4d737770 Fotis Stamatelopoulos
                body.setFileSize(fileSize);
2358 14ad7326 pastith
                body.setOriginalFilename(name);
2359 4d737770 Fotis Stamatelopoulos
                body.setStoredFilePath(filePath);
2360 14ad7326 pastith
                //CLEAR OLD VERSION IF FILE IS NOT VERSIONED AND GETS UPDATED
2361 14ad7326 pastith
                if(!header.isVersioned() && header.getCurrentBody() != null){
2362 14ad7326 pastith
                        header.setCurrentBody(null);
2363 a7401f95 pastith
                        if (header.getBodies() != null) {
2364 a7401f95 pastith
                                Iterator<FileBody> it = header.getBodies().iterator();
2365 a7401f95 pastith
                                while(it.hasNext()){
2366 a7401f95 pastith
                                        FileBody bo = it.next();
2367 4d737770 Fotis Stamatelopoulos
                                        deleteActualFile(bo.getStoredFilePath());
2368 a7401f95 pastith
                                        it.remove();
2369 a7401f95 pastith
                                        dao.delete(bo);
2370 a7401f95 pastith
                                }
2371 14ad7326 pastith
                        }
2372 14ad7326 pastith
                }
2373 14ad7326 pastith
2374 14ad7326 pastith
                dao.flush();
2375 14ad7326 pastith
                header.addBody(body);
2376 14ad7326 pastith
2377 14ad7326 pastith
                dao.create(body);
2378 14ad7326 pastith
        }
2379 14ad7326 pastith
2380 14ad7326 pastith
2381 14ad7326 pastith
        @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
2382 a0788710 pastith
        public File uploadFile(InputStream stream, Long userId) throws IOException, ObjectNotFoundException {
2383 14ad7326 pastith
                if (userId == null)
2384 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
2385 14ad7326 pastith
                User owner = dao.getEntityById(User.class, userId);
2386 14ad7326 pastith
                if(owner == null)
2387 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
2388 14ad7326 pastith
                long start = 0, end = 0;
2389 14ad7326 pastith
                if (logger.isDebugEnabled())
2390 14ad7326 pastith
                        start = System.currentTimeMillis();
2391 14ad7326 pastith
                File result = new File(generateRepositoryFilePath());
2392 a0788710 pastith
                try {
2393 a0788710 pastith
                        final FileOutputStream output = new FileOutputStream(result);
2394 a0788710 pastith
                        final byte[] buffer = new byte[UPLOAD_BUFFER_SIZE];
2395 a0788710 pastith
                        int n = 0;
2396 a0788710 pastith
2397 a0788710 pastith
                        while (-1 != (n = stream.read(buffer)))
2398 a0788710 pastith
                                output.write(buffer, 0, n);
2399 a0788710 pastith
                        output.close();
2400 a0788710 pastith
                        stream.close();
2401 a0788710 pastith
                } catch (IOException e) {
2402 a0788710 pastith
                        if (!result.delete())
2403 a0788710 pastith
                                logger.warn("Could not delete " + result.getPath());
2404 a0788710 pastith
                        throw e;
2405 a0788710 pastith
                }
2406 14ad7326 pastith
                if (logger.isDebugEnabled()) {
2407 14ad7326 pastith
                        end = System.currentTimeMillis();
2408 a0788710 pastith
                        logger.debug("Time to upload: " + (end - start) + " (msec)");
2409 14ad7326 pastith
                }
2410 14ad7326 pastith
                return result;
2411 14ad7326 pastith
        }
2412 14ad7326 pastith
2413 14ad7326 pastith
2414 14ad7326 pastith
        public void createFileUploadProgress(Long userId, String filename, Long bytesTransfered, Long fileSize) throws ObjectNotFoundException{
2415 14ad7326 pastith
2416 14ad7326 pastith
                if (userId == null)
2417 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
2418 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
2419 14ad7326 pastith
                FileUploadStatus status = dao.getFileUploadStatus(userId, filename);
2420 14ad7326 pastith
                if(status == null){
2421 14ad7326 pastith
                        status = new FileUploadStatus();
2422 14ad7326 pastith
                        status.setOwner(user);
2423 14ad7326 pastith
                        status.setFilename(filename);
2424 14ad7326 pastith
                        status.setBytesUploaded(bytesTransfered);
2425 14ad7326 pastith
                        status.setFileSize(fileSize);
2426 14ad7326 pastith
                        dao.create(status);
2427 14ad7326 pastith
                }
2428 14ad7326 pastith
                else{
2429 14ad7326 pastith
                        status.setBytesUploaded(bytesTransfered);
2430 14ad7326 pastith
                        status.setFileSize(fileSize);
2431 14ad7326 pastith
                        dao.update(status);
2432 14ad7326 pastith
                }
2433 14ad7326 pastith
2434 14ad7326 pastith
        }
2435 14ad7326 pastith
2436 14ad7326 pastith
        public void removeFileUploadProgress(Long userId, String filename) throws ObjectNotFoundException{
2437 14ad7326 pastith
                if (userId == null)
2438 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
2439 14ad7326 pastith
                FileUploadStatus status = dao.getFileUploadStatus(userId, filename);
2440 14ad7326 pastith
                if(status != null)
2441 14ad7326 pastith
                        dao.delete(status);
2442 14ad7326 pastith
        }
2443 14ad7326 pastith
2444 14ad7326 pastith
        @Override
2445 14ad7326 pastith
        public FileUploadStatus getFileUploadStatus(Long userId, String fileName) {
2446 14ad7326 pastith
                return dao.getFileUploadStatus(userId, fileName);
2447 14ad7326 pastith
        }
2448 14ad7326 pastith
2449 14ad7326 pastith
        @Override
2450 14ad7326 pastith
        public FolderDTO getFolderWithSubfolders(Long userId, Long folderId) throws ObjectNotFoundException, InsufficientPermissionsException {
2451 14ad7326 pastith
                if (userId == null)
2452 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
2453 14ad7326 pastith
                if (folderId == null)
2454 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
2455 14ad7326 pastith
                final User user = dao.getEntityById(User.class, userId);
2456 14ad7326 pastith
                final Folder folder = dao.getEntityById(Folder.class, folderId);
2457 14ad7326 pastith
                // Check permissions
2458 14ad7326 pastith
                if (!folder.hasReadPermission(user))
2459 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the permissions to read this folder");
2460 14ad7326 pastith
                List<FolderDTO> subfolders = new ArrayList<FolderDTO>();
2461 14ad7326 pastith
                if (folder.hasReadPermission(user))
2462 14ad7326 pastith
                        for (Folder f : folder.getSubfolders())
2463 14ad7326 pastith
                                if (f.hasReadPermission(user) && !f.isDeleted())
2464 14ad7326 pastith
                                        subfolders.add(f.getDTO());
2465 14ad7326 pastith
                FolderDTO result = folder.getDTO();
2466 14ad7326 pastith
                result.setSubfolders(subfolders);
2467 14ad7326 pastith
                return folder.getDTO();
2468 14ad7326 pastith
        }
2469 14ad7326 pastith
2470 14ad7326 pastith
        @Override
2471 14ad7326 pastith
        public FolderDTO getFolderWithSubfolders(Long userId, Long callingUserId, Long folderId) throws ObjectNotFoundException, InsufficientPermissionsException {
2472 14ad7326 pastith
                if (userId == null)
2473 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
2474 14ad7326 pastith
                if (folderId == null)
2475 14ad7326 pastith
                        throw new ObjectNotFoundException("No folder specified");
2476 68410d59 pastith
                User user = dao.getEntityById(User.class, callingUserId);
2477 68410d59 pastith
                Folder folder = dao.getEntityById(Folder.class, folderId);
2478 14ad7326 pastith
                // Check permissions
2479 14ad7326 pastith
                if (!folder.hasReadPermission(user))
2480 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the permissions to read this folder");
2481 14ad7326 pastith
2482 14ad7326 pastith
                FolderDTO result = folder.getDTO();
2483 14ad7326 pastith
                result.setSubfolders(getSharedSubfolders(userId, callingUserId, folder.getId()));
2484 14ad7326 pastith
                return result;
2485 14ad7326 pastith
        }
2486 14ad7326 pastith
2487 14ad7326 pastith
        @Override
2488 14ad7326 pastith
        public FileBodyDTO getFileVersion(Long userId, Long fileId, int version)
2489 14ad7326 pastith
                        throws ObjectNotFoundException, InsufficientPermissionsException {
2490 14ad7326 pastith
                if (userId == null)
2491 14ad7326 pastith
                        throw new ObjectNotFoundException("No user specified");
2492 14ad7326 pastith
                if (fileId == null)
2493 14ad7326 pastith
                        throw new ObjectNotFoundException("No file specified");
2494 14ad7326 pastith
                if (version < 1)
2495 14ad7326 pastith
                        throw new ObjectNotFoundException("No valid version specified");
2496 14ad7326 pastith
                User user = dao.getEntityById(User.class, userId);
2497 14ad7326 pastith
                FileHeader file = dao.getEntityById(FileHeader.class, fileId);
2498 14ad7326 pastith
                if (!file.hasReadPermission(user) && !file.getFolder().hasReadPermission(user))
2499 14ad7326 pastith
                        throw new InsufficientPermissionsException("You don't have the necessary permissions");
2500 14ad7326 pastith
                FileBody body = dao.getFileVersion(fileId, version);
2501 14ad7326 pastith
                return body.getDTO();
2502 14ad7326 pastith
        }
2503 14ad7326 pastith
2504 0a4b8f82 pastith
        @Override
2505 0a4b8f82 pastith
        public User updateUserPolicyAcceptance(Long userId, boolean isAccepted) throws ObjectNotFoundException {
2506 0a4b8f82 pastith
                if (userId == null)
2507 0a4b8f82 pastith
                        throw new ObjectNotFoundException("No user specified");
2508 0a4b8f82 pastith
                User user = dao.getEntityById(User.class, userId);
2509 0a4b8f82 pastith
                user.setAcceptedPolicy(isAccepted);
2510 0a4b8f82 pastith
                return user;
2511 0a4b8f82 pastith
        }
2512 0a4b8f82 pastith
2513 8f128261 droutsis
        @Override
2514 8f128261 droutsis
        public void updateAccounting(User user, Date date, long bandwidthDiff) {
2515 8f128261 droutsis
                dao.updateAccounting(user, date, bandwidthDiff);
2516 8f128261 droutsis
        }
2517 8f128261 droutsis
2518 77f75ac4 pastith
        @Override
2519 77f75ac4 pastith
        public boolean canReadFolder(Long userId, Long folderId) throws ObjectNotFoundException {
2520 77f75ac4 pastith
                if (userId == null)
2521 77f75ac4 pastith
                        throw new ObjectNotFoundException("No user specified");
2522 77f75ac4 pastith
                if (folderId == null)
2523 77f75ac4 pastith
                        throw new ObjectNotFoundException("No folder specified");
2524 77f75ac4 pastith
                User user = dao.getEntityById(User.class, userId);
2525 77f75ac4 pastith
                Folder folder = dao.getEntityById(Folder.class, folderId);
2526 77f75ac4 pastith
                // Check permissions
2527 77f75ac4 pastith
                if (!folder.hasReadPermission(user))
2528 77f75ac4 pastith
                        return false;
2529 77f75ac4 pastith
                return true;
2530 77f75ac4 pastith
        }
2531 77f75ac4 pastith
2532 3ef7b691 Dimitris Routsis
        /**
2533 3ef7b691 Dimitris Routsis
         * Reset WebDAV password for given user.
2534 3ef7b691 Dimitris Routsis
         *
2535 3ef7b691 Dimitris Routsis
         * @param userId
2536 3ef7b691 Dimitris Routsis
         * @return the new password
2537 3ef7b691 Dimitris Routsis
         * @throws ObjectNotFoundException
2538 3ef7b691 Dimitris Routsis
         */
2539 3ef7b691 Dimitris Routsis
        @Override
2540 3ef7b691 Dimitris Routsis
        public String resetWebDAVPassword(Long userId) throws ObjectNotFoundException {
2541 3ef7b691 Dimitris Routsis
                if (userId == null)
2542 3ef7b691 Dimitris Routsis
                        throw new ObjectNotFoundException("No user specified");
2543 3ef7b691 Dimitris Routsis
                User user = dao.getEntityById(User.class, userId);
2544 3ef7b691 Dimitris Routsis
                user.generateWebDAVPassword();
2545 3ef7b691 Dimitris Routsis
                return user.getWebDAVPassword();
2546 3ef7b691 Dimitris Routsis
        }
2547 3ef7b691 Dimitris Routsis
2548 14ad7326 pastith
}