Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (99.3 kB)

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