Statistics
| Branch: | Tag: | Revision:

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

History | View | Annotate | Download (101.4 kB)

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