Statistics
| Branch: | Tag: | Revision:

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

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