Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (96.1 kB)

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