Statistics
| Branch: | Tag: | Revision:

root / src / gr / ebs / gss / server / ejb / AdminAPIBean.java @ 023f6f1e

History | View | Annotate | Download (16.1 kB)

1
/*
2
 * Copyright 2010 Electronic Business Systems Ltd.
3
 *
4
 * This file is part of GSS.
5
 *
6
 * GSS is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * GSS is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with GSS.  If not, see <http://www.gnu.org/licenses/>.
18
 */
19
package gr.ebs.gss.server.ejb;
20

    
21
import gr.ebs.gss.client.exceptions.InsufficientPermissionsException;
22
import gr.ebs.gss.client.exceptions.ObjectNotFoundException;
23
import gr.ebs.gss.server.domain.AccountingInfo;
24
import gr.ebs.gss.server.domain.AuditInfo;
25
import gr.ebs.gss.server.domain.FileBody;
26
import gr.ebs.gss.server.domain.FileHeader;
27
import gr.ebs.gss.server.domain.Folder;
28
import gr.ebs.gss.server.domain.Group;
29
import gr.ebs.gss.server.domain.Permission;
30
import gr.ebs.gss.server.domain.User;
31
import gr.ebs.gss.server.domain.UserClass;
32
import gr.ebs.gss.server.domain.dto.FileBodyDTO;
33
import gr.ebs.gss.server.domain.dto.FileHeaderDTO;
34
import gr.ebs.gss.server.domain.dto.FolderDTO;
35
import gr.ebs.gss.server.domain.dto.GroupDTO;
36
import gr.ebs.gss.server.domain.dto.PermissionDTO;
37
import gr.ebs.gss.server.domain.dto.StatsDTO;
38
import gr.ebs.gss.server.domain.dto.SystemStatsDTO;
39
import gr.ebs.gss.server.domain.dto.UserClassDTO;
40
import gr.ebs.gss.server.domain.dto.UserDTO;
41

    
42
import java.util.ArrayList;
43
import java.util.Calendar;
44
import java.util.Date;
45
import java.util.Iterator;
46
import java.util.LinkedHashSet;
47
import java.util.List;
48
import java.util.Set;
49
import java.util.StringTokenizer;
50

    
51
import javax.ejb.EJB;
52
import javax.ejb.Stateless;
53
import javax.jms.Connection;
54
import javax.jms.ConnectionFactory;
55
import javax.jms.JMSException;
56
import javax.jms.MapMessage;
57
import javax.jms.MessageProducer;
58
import javax.jms.Queue;
59
import javax.jms.QueueConnectionFactory;
60
import javax.jms.Session;
61
import javax.naming.Context;
62
import javax.naming.InitialContext;
63
import javax.naming.NamingException;
64

    
65
import org.apache.commons.lang.StringUtils;
66
import org.apache.commons.logging.Log;
67
import org.apache.commons.logging.LogFactory;
68

    
69
/**
70
 * @author kman
71
 */
72
@Stateless
73
public class AdminAPIBean implements AdminAPI {
74
        /**
75
         * Injected reference to the ExternalAPI service.
76
         */
77
        @EJB
78
        private ExternalAPI api;
79

    
80
        /**
81
         * The logger.
82
         */
83
        private static Log logger = LogFactory.getLog(AdminAPIBean.class);
84
        /**
85
         * Injected reference to the GSSDAO data access facade.
86
         */
87
        @EJB
88
        private GSSDAO dao;
89

    
90
        @Override
91
        public FileHeaderDTO getFile(String uri) throws ObjectNotFoundException {
92
                if (uri == null)
93
                        throw new ObjectNotFoundException("No uri specified");
94

    
95
                List<String> pathElements = new ArrayList<String>();
96
                StringTokenizer st = new StringTokenizer(uri, "/");
97
                String username = st.nextToken();
98
                st.nextToken();
99
                while (st.hasMoreTokens())
100
                        pathElements.add(st.nextToken());
101
                if (pathElements.size() < 1)
102
                        throw new ObjectNotFoundException("No file found");
103
                User owner = dao.getUser(username);
104
                // Store the last element, since it requires special handling.
105
                String lastElement = pathElements.remove(pathElements.size() - 1);
106
                FolderDTO cursor = api.getRootFolder(owner.getId());
107
                // Traverse and verify the specified folder path.
108
                for (String pathElement : pathElements) {
109
                        cursor = getFolder(cursor.getId(), pathElement);
110
                        if (cursor.isDeleted())
111
                                throw new ObjectNotFoundException("Folder " + cursor.getPath() + " not found");
112
                }
113
                FileHeaderDTO file = getFile(cursor.getId(), lastElement);
114
                return file;
115
        }
116

    
117
        @Override
118
        public List<FileHeaderDTO> getFiles(String uri) throws ObjectNotFoundException, InsufficientPermissionsException {
119
                if (uri == null)
120
                        throw new ObjectNotFoundException("No uri specified");
121
                List<FileHeaderDTO> res = new ArrayList<FileHeaderDTO>();
122
                List<String> pathElements = new ArrayList<String>();
123
                StringTokenizer st = new StringTokenizer(uri, "/");
124
                if(st.countTokens()<2)
125
                        return res;
126
                String username = st.nextToken();
127
                st.nextToken();
128
                User owner = dao.getUser(username);
129
                while (st.hasMoreTokens())
130
                        pathElements.add(st.nextToken());
131
                if (pathElements.size() < 1){
132

    
133
                                FolderDTO folder = api.getRootFolder(owner.getId());
134
                                res.addAll(api.getFiles(folder.getOwner().getId(), folder.getId(), false));
135
                                return res;
136
                }
137

    
138
                // Store the last element, since it requires special handling.
139
                String lastElement = pathElements.remove(pathElements.size() - 1);
140
                FolderDTO cursor = api.getRootFolder(owner.getId());
141
                // Traverse and verify the specified folder path.
142
                for (String pathElement : pathElements) {
143
                        cursor = getFolder(cursor.getId(), pathElement);
144
                        if (cursor.isDeleted())
145
                                throw new ObjectNotFoundException("Folder " + cursor.getPath() + " not found");
146
                }
147
                try {
148
                        FileHeaderDTO file = getFile(cursor.getId(), lastElement);
149
                        res.add(file);
150
                } catch (ObjectNotFoundException e) {
151
                        // Perhaps the requested resource is not a file, so
152
                        // check for folders as well.
153
                        FolderDTO folder = getFolder(cursor.getId(), lastElement);
154
                        res.addAll(api.getFiles(folder.getOwner().getId(), folder.getId(), false));
155

    
156
                }
157

    
158
                return res;
159
        }
160

    
161
        private FolderDTO getFolder(Long parentId, String name) throws ObjectNotFoundException {
162
                if (parentId == null)
163
                        throw new ObjectNotFoundException("No parent folder specified");
164
                if (StringUtils.isEmpty(name))
165
                        throw new ObjectNotFoundException("No folder specified");
166

    
167
                Folder folder = dao.getFolder(parentId, name);
168
                return folder.getDTO();
169
        }
170

    
171
        private FileHeaderDTO getFile(Long folderId, String name) throws ObjectNotFoundException {
172
                if (folderId == null)
173
                        throw new ObjectNotFoundException("No parent folder specified");
174
                if (StringUtils.isEmpty(name))
175
                        throw new ObjectNotFoundException("No file specified");
176

    
177
                FileHeader file = dao.getFile(folderId, name);
178
                FileHeaderDTO dto = file.getDTO();
179
                Set<Permission> perms = file.getPermissions();
180
                Set<PermissionDTO> result = new LinkedHashSet<PermissionDTO>();
181
                for (Permission perm : perms)
182
                        if (perm.getUser() != null && perm.getUser().getId().equals(file.getOwner().getId()))
183
                                result.add(perm.getDTO());
184
                for (Permission perm : perms)
185
                        if (perm.getUser() != null && perm.getUser().getId().equals(file.getOwner().getId())) {
186
                        } else
187
                                result.add(perm.getDTO());
188
                dto.setPermissions(result);
189
                return dto;
190
        }
191
        @Override
192
        public FileHeaderDTO getFile(Long fileId) throws ObjectNotFoundException {
193
                FileHeader file = dao.getEntityById(FileHeader.class, fileId);
194
                FileHeaderDTO dto = file.getDTO();
195
                Set<Permission> perms = file.getPermissions();
196
                Set<PermissionDTO> result = new LinkedHashSet<PermissionDTO>();
197
                for (Permission perm : perms)
198
                        if (perm.getUser() != null && perm.getUser().getId().equals(file.getOwner().getId()))
199
                                result.add(perm.getDTO());
200
                for (Permission perm : perms)
201
                        if (perm.getUser() != null && perm.getUser().getId().equals(file.getOwner().getId())) {
202
                        } else
203
                                result.add(perm.getDTO());
204
                dto.setPermissions(result);
205
                return dto;
206
        }
207

    
208
        @Override
209
        public UserDTO getUser(Long userId) throws ObjectNotFoundException {
210
                return api.getUserDTO(userId);
211
        }
212

    
213
        @Override
214
        public StatsDTO getUserStatistics(Long userId) throws ObjectNotFoundException {
215
                StatsDTO stats = api.getUserStatistics(userId);
216
                User user = dao.getEntityById(User.class, userId);
217
                AccountingInfo info = dao.getAccountingInfo(user, new Date());
218
                stats.setBandwithQuotaUsed(info.getBandwidthUsed());
219
                return stats;
220
        }
221

    
222
        @Override
223
        public List<UserDTO> searchUsers(String query) {
224
                List<User> users = dao.getUsersByUserNameOrEmailLike(query);
225
                List<UserDTO> result = new ArrayList<UserDTO>();
226
                for (User u : users)
227
                        result.add(u.getDTO());
228
                return result;
229
        }
230

    
231
        @Override
232
        public UserDTO getUser(String username) throws ObjectNotFoundException{
233
                User u = dao.getUser(username);
234
                if(u!=null)
235
                        return u.getDTO();
236
                return null;
237
        }
238
        @Override
239
        public void toggleActiveUser(Long userId) throws ObjectNotFoundException {
240
                User user = dao.getEntityById(User.class, userId);
241
                user.setActive(!user.isActive());
242
                dao.update(user);
243
        }
244

    
245
        @Override
246
        public void setFilePermissions(String uri, Set<PermissionDTO> permissions)
247
                        throws ObjectNotFoundException {
248
                FileHeaderDTO filedto = getFile(uri);
249
                FileHeader file = dao.getEntityById(FileHeader.class, filedto.getId());
250
                if (permissions != null && !permissions.isEmpty()) {
251
                        // Send e-mails to the users that are granted new permissions on the file
252
                        // Delete previous entries.
253
                        for (Permission perm: file.getPermissions())
254
                                dao.delete(perm);
255
                        file.getPermissions().clear();
256
                        for (PermissionDTO dto : permissions) {
257
                                //if (dto.getUser()!=null && dto.getUser().getId().equals(file.getOwner().getId()) && (!dto.hasRead() || !dto.hasWrite() || !dto.hasModifyACL()))
258
                                        //throw new InsufficientPermissionsException("Can't remove permissions from owner");
259
                                // Don't include 'empty' permission.
260
                                if (!dto.getRead() && !dto.getWrite() && !dto.getModifyACL()) continue;
261
                                file.addPermission(getPermission(dto));
262
                        }
263
                        dao.flush();
264
                }
265
        }
266

    
267
        private Permission getPermission(PermissionDTO dto) throws ObjectNotFoundException {
268
                Permission res = new Permission();
269
                if (dto.getGroup() != null)
270
                        res.setGroup(dao.getEntityById(Group.class, dto.getGroup().getId()));
271
                else if (dto.getUser() != null)
272
                        if (dto.getUser().getId() == null)
273
                                res.setUser(dao.getUser(dto.getUser().getUsername()));
274
                        else
275
                                res.setUser(dao.getEntityById(User.class, dto.getUser().getId()));
276
                res.setRead(dto.hasRead());
277
                res.setWrite(dto.hasWrite());
278
                res.setModifyACL(dto.hasModifyACL());
279
                return res;
280
        }
281

    
282
        @Override
283
        public SystemStatsDTO getSystemStatistics() {
284
                SystemStatsDTO statistics = new SystemStatsDTO();
285
                List<UserClass> uclasses = dao.getUserClasses();
286
                for (UserClass u : uclasses){
287
                        UserClassDTO dto = u.getDTOWithoutUsers();
288
                        SystemStatsDTO stats = new SystemStatsDTO();
289
                        stats.setFileCount(dao.getFileCount(u));
290
                        stats.setFileSize(dao.getFileSize(u));
291
                        stats.setUserCount(dao.getUserCount(u));
292
                        stats.setBandwithUsed(dao.getBandwithUsed(u, new Date()));
293
                        dto.setStatistics(stats);
294
                        statistics.getUserClasses().add(dto);
295

    
296
                }
297
                Calendar now = Calendar.getInstance();
298
                now.add(Calendar.DAY_OF_MONTH, -7);
299
                Date week = now.getTime();
300
                now=Calendar.getInstance();
301
                now.add(Calendar.MONTH, -1);
302
                Date month = now.getTime();
303
                statistics.setLastMonthUsers(dao.getCountUsersByLastLogin(month));
304
                statistics.setLastWeekUsers(dao.getCountUsersByLastLogin(week));
305
                statistics.setFileCount(dao.getFileCount((UserClass)null));
306
                statistics.setFileSize(dao.getFileSize((UserClass)null));
307
                statistics.setUserCount(dao.getUserCount((UserClass)null));
308
                statistics.setBandwithUsed(dao.getBandwithUsed(null, new Date()));
309
                return statistics;
310
        }
311

    
312
        @Override
313
        public List<UserDTO> getLastLoggedInUsers(Date lastLoginDate) {
314
                List<User> users = dao.getUsersByLastLogin(lastLoginDate);
315
                List<UserDTO> result = new ArrayList<UserDTO>();
316
                for (User u : users)
317
                        result.add(u.getDTO());
318
                return result;
319
        }
320

    
321
        @Override
322
        public List<FileBodyDTO> getVersions(Long userId, Long fileId) throws ObjectNotFoundException, InsufficientPermissionsException {
323
                return api.getVersions(userId, fileId);
324
        }
325
        @Override
326
        public List<UserDTO> getUsersWaitingActivation(){
327
                List<User> users = dao.getInactiveUsers();
328
                List<UserDTO> result = new ArrayList<UserDTO>();
329
                for(User u :users)
330
                        result.add(u.getDTO());
331
                return result;
332
        }
333

    
334
        @Override
335
        public void changeUserClass(Long userId, Long userClassId) throws ObjectNotFoundException{
336
                User user = dao.getEntityById(User.class, userId);
337
                UserClass userClass = dao.getEntityById(UserClass.class, userClassId);
338
                user.setUserClass(userClass);
339
                dao.update(user);
340
        }
341

    
342
        @Override
343
        public List<UserClassDTO> getUserClasses(){
344
                List<UserClassDTO> result = new ArrayList<UserClassDTO>();
345
                for(UserClass c : dao.getUserClasses())
346
                        result.add(c.getDTOWithoutUsers());
347
                return result;
348
        }
349

    
350
        @Override
351
        public void saveOrUpdateUserClass(UserClassDTO dto) throws ObjectNotFoundException{
352
                UserClass uclass;
353
                if(dto.getId()!=null)
354
                        uclass = dao.getEntityById(UserClass.class, dto.getId());
355
                else
356
                        uclass = new UserClass();
357
                uclass.setName(dto.getName());
358
                uclass.setQuota(dto.getQuota());
359
                if(dto.getId()!=null)
360
                        dao.update(uclass);
361
                else
362
                        dao.create(uclass);
363
                dao.flush();
364

    
365
        }
366

    
367
        @Override
368
        public void removeUserClass(UserClassDTO dto) throws ObjectNotFoundException{
369
                UserClass uclass = dao.getEntityById(UserClass.class, dto.getId());
370
                if(uclass==null)
371
                        throw new ObjectNotFoundException("User Class not found");
372
                dao.delete(uclass);
373
        }
374

    
375
        @Override
376
        public List<FileHeaderDTO> searchFileByFilename(String fileName){
377
                List<FileHeader> files = dao.searchFileByFilename(fileName);
378
                List<FileHeaderDTO> result = new ArrayList<FileHeaderDTO>();
379
                for(FileHeader h : files)
380
                        result.add(h.getDTO());
381
                return result;
382
        }
383

    
384
        @Override
385
        public void removeUser(Long userId) throws ObjectNotFoundException, InsufficientPermissionsException{
386
                User user = api.getUser(userId);
387
                try{
388
                        FolderDTO folder = api.getRootFolder(userId);
389
                        deleteFolder(userId, folder.getId());
390
                        List<GroupDTO> groups = api.getGroups(userId);
391
                        for(GroupDTO group : groups)
392
                                api.deleteGroup(userId, group.getId());
393
                }
394
                catch(ObjectNotFoundException e){}
395
                List<AccountingInfo> infos = dao.getAccountingInfo(user);
396
                Iterator<AccountingInfo> it = infos.iterator();
397
                while(it.hasNext()){
398
                        AccountingInfo a = it.next();
399
                        dao.delete(a);
400
                }
401
                dao.flush();
402
                dao.delete(user);
403
        }
404

    
405
        /**
406
         * Deletes the given folder and all its subfolders and files
407
         * Only the permissions for top folder are checked
408
         *
409
         * @see gr.ebs.gss.server.ejb.ExternalAPI#deleteFolder(java.lang.Long,
410
         *      java.lang.Long)
411
         */
412
        public void deleteFolder(final Long userId, final Long folderId) throws ObjectNotFoundException {
413
                // Validate.
414
                if (userId == null)
415
                        throw new ObjectNotFoundException("No user specified");
416
                if (folderId == null)
417
                        throw new ObjectNotFoundException("No folder specified");
418

    
419
                // Do the actual work.
420
                final Folder folder = dao.getEntityById(Folder.class, folderId);
421
                final Folder parent = folder.getParent();
422
                final User user = dao.getEntityById(User.class, userId);
423

    
424
                removeSubfolderFiles(folder);
425
                if(parent!=null)
426
                        parent.removeSubfolder(folder);
427
                dao.delete(folder);
428
                if(parent!=null)
429
                        touchParentFolders(parent, user, new Date());
430
        }
431

    
432
        private void removeSubfolderFiles(Folder folder) {
433
                //remove files for all subfolders
434
                for (Folder subfolder:folder.getSubfolders())
435
                        removeSubfolderFiles(subfolder);
436
                //remove this folder's file bodies (actual files)
437
                for (FileHeader file:folder.getFiles()) {
438
                        for (FileBody body:file.getBodies())
439
                                api.deleteActualFile(body.getStoredFilePath());
440
                        indexFile(file.getId(), true);
441
                }
442
        }
443

    
444
        private void touchParentFolders(Folder folder, User modifiedBy, Date modificationDate) {
445
                Folder f = folder;
446
                while (f!=null) {
447
                        AuditInfo ai = f.getAuditInfo();
448
                        ai.setModifiedBy(modifiedBy);
449
                        ai.setModificationDate(modificationDate);
450
                        f.setAuditInfo(ai);
451
                        f = f.getParent();
452
                }
453
        }
454

    
455
        public void indexFile(Long fileId, boolean delete) {
456
                Connection qConn = null;
457
                Session session = null;
458
                MessageProducer sender = null;
459
                try {
460
                        Context jndiCtx = new InitialContext();
461
                        ConnectionFactory factory = (QueueConnectionFactory) jndiCtx.lookup("java:/JmsXA");
462
                        Queue queue = (Queue) jndiCtx.lookup("queue/gss-indexingQueue");
463
                        qConn = factory.createConnection();
464
                        session = qConn.createSession(false, Session.AUTO_ACKNOWLEDGE);
465
                        sender = session.createProducer(queue);
466

    
467
                        MapMessage map = session.createMapMessage();
468
                        map.setObject("id", fileId);
469
                        map.setBoolean("delete", delete);
470
                        sender.send(map);
471
                }
472
                catch (NamingException e) {
473
                        logger.error("Index was not updated: ", e);
474
                }
475
                catch (JMSException e) {
476
                        logger.error("Index was not updated: ", e);
477
                }
478
                finally {
479
                        try {
480
                                if (sender != null)
481
                                        sender.close();
482
                                if (session != null)
483
                                        session.close();
484
                                if (qConn != null)
485
                                        qConn.close();
486
                        }
487
                        catch (JMSException e) {
488
                                logger.warn(e);
489
                        }
490
                }
491
        }
492
}