source: DASISH/t5.6/backend/annotator-backend/trunk/annotator-backend/src/main/java/eu/dasish/annotation/backend/dao/impl/DBIntegrityServiceImlp.java @ 4603

Last change on this file since 4603 was 4603, checked in by olhsha, 10 years ago

test commit after disaster

File size: 37.2 KB
Line 
1/*
2 * Copyright (C) 2013 DASISH
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17 */
18package eu.dasish.annotation.backend.dao.impl;
19
20import eu.dasish.annotation.backend.Resource;
21import eu.dasish.annotation.backend.Helpers;
22import eu.dasish.annotation.backend.dao.AnnotationDao;
23import eu.dasish.annotation.backend.dao.CachedRepresentationDao;
24import eu.dasish.annotation.backend.dao.DBIntegrityService;
25import eu.dasish.annotation.backend.dao.NotebookDao;
26import eu.dasish.annotation.backend.dao.ResourceDao;
27import eu.dasish.annotation.backend.dao.TargetDao;
28import eu.dasish.annotation.backend.dao.UserDao;
29import eu.dasish.annotation.backend.rest.AnnotationResource;
30import eu.dasish.annotation.schema.Action;
31import eu.dasish.annotation.schema.ActionList;
32import eu.dasish.annotation.schema.Annotation;
33import eu.dasish.annotation.schema.AnnotationActionName;
34import eu.dasish.annotation.schema.AnnotationBody;
35import eu.dasish.annotation.schema.AnnotationInfo;
36import eu.dasish.annotation.schema.AnnotationInfoList;
37import eu.dasish.annotation.schema.CachedRepresentationFragment;
38import eu.dasish.annotation.schema.CachedRepresentationFragmentList;
39import eu.dasish.annotation.schema.CachedRepresentationInfo;
40import eu.dasish.annotation.schema.Notebook;
41import eu.dasish.annotation.schema.NotebookInfo;
42import eu.dasish.annotation.schema.NotebookInfoList;
43import eu.dasish.annotation.schema.TargetInfoList;
44import eu.dasish.annotation.schema.Permission;
45import eu.dasish.annotation.schema.PermissionActionName;
46import eu.dasish.annotation.schema.UserWithPermissionList;
47import eu.dasish.annotation.schema.ReferenceList;
48import eu.dasish.annotation.schema.ResponseBody;
49import eu.dasish.annotation.schema.Target;
50import eu.dasish.annotation.schema.TargetInfo;
51import eu.dasish.annotation.schema.User;
52import eu.dasish.annotation.schema.UserWithPermission;
53import java.io.InputStream;
54import java.lang.Number;
55import java.util.ArrayList;
56import java.util.HashMap;
57import java.util.List;
58import java.util.Map;
59import java.util.UUID;
60import java.lang.reflect.Field;
61import org.springframework.beans.factory.annotation.Autowired;
62import org.slf4j.Logger;
63import org.slf4j.LoggerFactory;
64
65/**
66 *
67 * @author olhsha
68 */
69public class DBIntegrityServiceImlp implements DBIntegrityService {
70
71    @Autowired
72    UserDao userDao;
73    @Autowired
74    CachedRepresentationDao cachedRepresentationDao;
75    @Autowired
76    TargetDao targetDao;
77    @Autowired
78    AnnotationDao annotationDao;
79    @Autowired
80    NotebookDao notebookDao;
81    private String remoteUser=null;
82   
83   
84    final static protected String admin = "admin";
85    private static final Logger logger = LoggerFactory.getLogger(DBIntegrityServiceImlp.class);
86
87    //////////////////////////////////
88    private ResourceDao getDao(Resource resource) {
89        switch (resource) {
90            case PRINCIPAL:
91                return userDao;
92            case ANNOTATION:
93                return annotationDao;
94            case TARGET:
95                return targetDao;
96            case CACHED_REPRESENTATION:
97                return cachedRepresentationDao;
98            case NOTEBOOK:
99                return notebookDao;
100            default:
101                return null;
102        }
103    }
104   
105    public String getRemoteUser(){
106        return remoteUser;
107    }
108   
109    public void setRemoteUser(String currentUser){
110        remoteUser = currentUser;
111    }
112   
113
114    @Override
115    public void setServiceURI(String serviceURI) {
116        userDao.setServiceURI(serviceURI + "users/");
117        cachedRepresentationDao.setServiceURI(serviceURI + "cached/");
118        targetDao.setServiceURI(serviceURI + "targets/");
119        annotationDao.setServiceURI(serviceURI + "annotations/");
120        notebookDao.setServiceURI(serviceURI + "notebooks/");
121    }
122
123    ///////////// GETTERS //////////////////////////
124    @Override
125    public Number getResourceInternalIdentifier(UUID externalID, Resource resource) {
126        return this.getDao(resource).getInternalID(externalID);
127    }
128
129    @Override
130    public Number getResourceInternalIdentifierFromURI(String uri, Resource resource) {
131        return this.getDao(resource).getInternalIDFromURI(uri);
132    }
133
134    @Override
135    public UUID getResourceExternalIdentifier(Number resourceID, Resource resource) {
136        return this.getDao(resource).getExternalID(resourceID);
137    }
138
139    @Override
140    public String getResourceURI(Number resourceID, Resource resource) {
141        return this.getDao(resource).getURIFromInternalID(resourceID);
142    }
143
144    @Override
145    public Annotation getAnnotation(Number annotationID) {
146        if (annotationID != null) {
147            Annotation result = annotationDao.getAnnotationWithoutTargetsAndPermissions(annotationID);
148            result.setOwnerRef(userDao.getURIFromInternalID(annotationDao.getOwner(annotationID)));
149            List<Number> targetIDs = targetDao.retrieveTargetIDs(annotationID);
150            TargetInfoList sis = new TargetInfoList();
151            for (Number targetID : targetIDs) {
152                TargetInfo targetInfo = getTargetInfoFromTarget(targetDao.getTarget(targetID));
153                sis.getTargetInfo().add(targetInfo);
154            }
155            result.setTargets(sis);
156
157            result.setPermissions(this.getPermissions(annotationID, Resource.ANNOTATION));
158            return result;
159        } else {
160            return null;
161        }
162    }
163
164    @Override
165    public Number getAnnotationOwnerID(Number annotationID) {
166        return annotationDao.getOwner(annotationID);
167    }
168   
169    @Override
170    public User getAnnotationOwner(Number annotationID) {
171       return userDao.getUser(annotationDao.getOwner(annotationID)); 
172    }
173
174    ///////////////////////////////////////////////////
175    // TODO UNIT tests
176    @Override
177    public UserWithPermissionList getPermissions(Number resourceID, Resource resource) {
178        if (resourceID != null) {
179            List<Map<Number, String>> principalsPermissions = this.getDao(resource).getPermissions(resourceID);
180            UserWithPermissionList result = new UserWithPermissionList();
181            List<UserWithPermission> list = result.getUserWithPermission();
182            for (Map<Number, String> principalPermission : principalsPermissions) {
183                Number[] principal = new Number[1];
184                principalPermission.keySet().toArray(principal);
185                UserWithPermission userWithPermission = new UserWithPermission();
186                userWithPermission.setRef(userDao.getURIFromInternalID(principal[0]));
187                userWithPermission.setPermission(Permission.fromValue(principalPermission.get(principal[0])));
188                list.add(userWithPermission);
189            }
190            return result;
191
192        }
193        return null;
194    }
195
196////////////////////////////////////////////////////////////////////////
197    @Override
198    public List<Number> getFilteredAnnotationIDs(UUID ownerId, String link, String text, Number inloggedUserID, String access, String namespace, String after, String before) {
199
200        Number ownerID = (ownerId != null) ? userDao.getInternalID(ownerId) : null;
201        if (ownerID != null) {
202            if ("owner".equals(access) && !inloggedUserID.equals(ownerID)) {
203                logger.info("The inlogged user cannot be the owner of the annotations owned by " + ownerId.toString());
204                return null;
205            }
206        }
207
208        //filtering on tables "target" and "annotations_targets"
209        List<Number> annotationIDsForTargets = null;
210        if (link != null) {
211            List<Number> targetIDs = targetDao.getTargetsReferringTo(link);
212            annotationIDsForTargets = annotationDao.getAnnotationIDsForTargets(targetIDs);
213            if (annotationIDsForTargets == null) {
214                logger.info("There are no annotations for the targets referring to " + link + ".");
215                return null;
216            }
217        }
218
219        // filtering in the table "annotation"
220        if (ownerID == null && "owner".equals(access)) {
221            ownerID = inloggedUserID;
222        }
223        List<Number> annotationIDs = annotationDao.getFilteredAnnotationIDs(ownerID, text, namespace, after, before);
224        if (annotationIDs != null) {
225            if (annotationIDsForTargets != null) {
226                annotationIDs.retainAll(annotationIDsForTargets);
227            } else {
228                // nothing to filter on link == null
229            }
230        } else {
231            logger.info("There are no annotations for the given filters on the annotation table.");
232            return null;
233        }
234
235        // filtering on table "annotations_principals_permissions"
236        if ("reader".equals(access) || "writer".equals(access)) {
237            // owner != inloggedUser
238            List<Number> annotationIDsPermission = annotationDao.getAnnotationIDsForUserWithPermission(inloggedUserID, access);
239            if (annotationIDsPermission != null) {
240                annotationIDs.retainAll(annotationIDsPermission);
241            } else {
242                logger.info("There are no annotations for which the inlogged user has access " + access);
243                return null;
244            }
245        } else {
246            // inloggedUser == owner
247        }
248        return annotationIDs;
249    }
250
251    @Override
252    public ReferenceList getAnnotationTargets(Number annotationID) {
253        ReferenceList result = new ReferenceList();
254        List<Number> targetIDs = targetDao.retrieveTargetIDs(annotationID);
255        for (Number targetID : targetIDs) {
256            result.getRef().add(targetDao.getURIFromInternalID(targetID));
257        }
258        return result;
259    }
260
261    @Override
262    public List<String> getTargetsWithNoCachedRepresentation(Number annotationID) {
263        if (annotationID == null) {
264            return null;
265        }
266        List<String> result = new ArrayList<String>();
267        List<Number> targetIDs = targetDao.retrieveTargetIDs(annotationID);
268        for (Number targetID : targetIDs) {
269            List<Number> versions = cachedRepresentationDao.getCachedRepresentationsForTarget(targetID);
270            if (versions == null) {
271                result.add(targetDao.getURIFromInternalID(targetID));
272            } else {
273                if (versions.isEmpty()) {
274                    result.add(targetDao.getURIFromInternalID(targetID));
275                }
276
277            }
278        }
279        return result;
280    }
281
282    @Override
283    public List<String> getUsersWithNoInfo(Number annotationID) {
284        if (annotationID == null) {
285            return null;
286        }
287        List<String> result = new ArrayList<String>();
288        List<Map<Number, String>> usersWithPermissions = annotationDao.getPermissions(annotationID);
289        for (Map<Number, String> userWithPermission : usersWithPermissions) {
290            Number[] userID = new Number[1];
291            userWithPermission.keySet().toArray(userID);
292            User user = userDao.getUser(userID[0]);
293
294            if (user.getDisplayName() == null || user.getDisplayName().trim().isEmpty() || user.getEMail() == null || user.getEMail().trim().isEmpty()) {
295                result.add(userDao.getURIFromInternalID(userID[0]));
296
297            }
298        }
299        return result;
300    }
301
302    @Override
303    public AnnotationInfoList getFilteredAnnotationInfos(UUID ownerId, String word, String text, Number inloggedUserID, String access, String namespace, String after, String before) {
304        List<Number> annotationIDs = this.getFilteredAnnotationIDs(ownerId, word, text, inloggedUserID, access, namespace, after, before);
305        if (annotationIDs != null) {
306            AnnotationInfoList result = new AnnotationInfoList();
307            for (Number annotationID : annotationIDs) {
308                AnnotationInfo annotationInfo = annotationDao.getAnnotationInfoWithoutTargets(annotationID);
309                annotationInfo.setTargets(this.getAnnotationTargets(annotationID));
310                annotationInfo.setOwnerRef(userDao.getURIFromInternalID(annotationDao.getOwner(annotationID)));
311                result.getAnnotationInfo().add(annotationInfo);
312            }
313
314            return result;
315        } else {
316            return null;
317        }
318    }
319
320    @Override
321    public AnnotationInfoList getAllAnnotationInfos() {
322        List<Number> annotationIDs = annotationDao.getAllAnnotationIDs();
323        if (annotationIDs != null) {
324            AnnotationInfoList result = new AnnotationInfoList();
325            for (Number annotationID : annotationIDs) {
326                Number ownerID = annotationDao.getOwner(annotationID);
327                ReferenceList targets = getAnnotationTargets(annotationID);
328                AnnotationInfo annotationInfo = annotationDao.getAnnotationInfoWithoutTargets(annotationID);
329                annotationInfo.setTargets(targets);
330                if (ownerID != null) {
331                    annotationInfo.setOwnerRef(userDao.getURIFromInternalID(ownerID));
332                } else {
333                    annotationInfo.setOwnerRef("ACHTUNG: This annotation does not have an owner in the DB!!!!");
334                }
335                result.getAnnotationInfo().add(annotationInfo);
336            }
337
338            return result;
339        } else {
340            return null;
341        }
342    }
343
344    // TODO unit test
345    @Override
346    public Target getTarget(Number internalID) {
347        Target result = targetDao.getTarget(internalID);
348        result.setSiblingTargets(getTargetsForTheSameLinkAs(internalID));
349        Map<Number, String> cachedIDsFragments = targetDao.getCachedRepresentationFragmentPairs(internalID);
350        CachedRepresentationFragmentList cachedRepresentationFragmentList = new CachedRepresentationFragmentList();
351        for (Number key : cachedIDsFragments.keySet()) {
352            CachedRepresentationFragment cachedRepresentationFragment = new CachedRepresentationFragment();
353            cachedRepresentationFragment.setRef(cachedRepresentationDao.getURIFromInternalID(key));
354            cachedRepresentationFragment.setFragmentString(cachedIDsFragments.get(key));
355            cachedRepresentationFragmentList.getCached().add(cachedRepresentationFragment);
356        }
357        result.setCachedRepresentatinons(cachedRepresentationFragmentList);
358        return result;
359    }
360
361    // TODO unit test
362    @Override
363    public CachedRepresentationInfo getCachedRepresentationInfo(Number internalID) {
364        return cachedRepresentationDao.getCachedRepresentationInfo(internalID);
365    }
366
367    //TODO unit test
368    @Override
369    public InputStream getCachedRepresentationBlob(Number cachedID) {
370        return cachedRepresentationDao.getCachedRepresentationBlob(cachedID);
371    }
372
373    @Override
374    public ReferenceList getTargetsForTheSameLinkAs(Number targetID) {
375        List<Number> targetIDs = targetDao.getTargetsForLink(targetDao.getLink(targetID));
376        ReferenceList referenceList = new ReferenceList();
377        for (Number siblingID : targetIDs) {
378            referenceList.getRef().add(targetDao.externalIDtoURI(targetDao.getExternalID(siblingID).toString()));
379        }
380        return referenceList;
381    }
382
383    @Override
384    public User getUser(Number userID) {
385        return userDao.getUser(userID);
386    }
387
388    @Override
389    public User getUserByInfo(String eMail) {
390        return userDao.getUserByInfo(eMail);
391    }
392
393    @Override
394    public String getUserRemoteID(Number internalID) {
395        return userDao.getRemoteID(internalID);
396    }
397
398    @Override
399    public Permission getPermission(Number annotationID, Number userID) {
400        return annotationDao.getPermission(annotationID, userID);
401    }
402
403    @Override
404    public Number getUserInternalIDFromRemoteID(String remoteID) {
405        return userDao.getUserInternalIDFromRemoteID(remoteID);
406    }
407
408    @Override
409    public String getTypeOfUserAccount(Number userID) {
410        return userDao.getTypeOfUserAccount(userID);
411    }
412   
413    @Override
414    public User getDataBaseAdmin(){
415        return userDao.getUser(userDao.getDBAdminID());
416    }
417   
418
419    @Override
420    public boolean canRead(Number userID, Number annotationID) {
421        if (userID.equals(annotationDao.getOwner(annotationID)) || userDao.getTypeOfUserAccount(userID).equals(admin)) {
422            return true;
423        }
424
425        final Permission permission = annotationDao.getPermission(annotationID, userID);
426        if (permission != null) {
427            return (permission.value().equals(Permission.WRITER.value()) || permission.value().equals(Permission.READER.value()));
428        } else {
429            return false;
430        }
431    }
432
433    @Override
434    public boolean canWrite(Number userID, Number annotationID) {
435        if (userID.equals(annotationDao.getOwner(annotationID)) || userDao.getTypeOfUserAccount(userID).equals(admin)) {
436            return true;
437        }
438        final Permission permission = annotationDao.getPermission(annotationID, userID);
439        if (permission != null) {
440            return (permission.value().equals(Permission.WRITER.value()));
441        } else {
442            return false;
443        }
444    }
445   
446    ////// noetbooks ///////
447
448    @Override
449    public NotebookInfoList getNotebooks(Number principalID, String permission) {
450        NotebookInfoList result = new NotebookInfoList();
451        if (permission.equalsIgnoreCase("reader") || permission.equalsIgnoreCase("writer")) {
452            List<Number> notebookIDs = notebookDao.getNotebookIDs(principalID, Permission.fromValue(permission));
453            for (Number notebookID : notebookIDs) {
454                NotebookInfo notebookInfo = notebookDao.getNotebookInfoWithoutOwner(notebookID);
455                Number ownerID = notebookDao.getOwner(notebookID);
456                notebookInfo.setOwnerRef(userDao.getURIFromInternalID(ownerID));
457                result.getNotebookInfo().add(notebookInfo);
458            }
459        } else {
460            if (permission.equalsIgnoreCase("owner")) {
461                List<Number> notebookIDs = notebookDao.getNotebookIDsOwnedBy(principalID);
462                String ownerRef = userDao.getURIFromInternalID(principalID);
463                for (Number notebookID : notebookIDs) {
464                    NotebookInfo notebookInfo = notebookDao.getNotebookInfoWithoutOwner(notebookID);
465                    notebookInfo.setOwnerRef(ownerRef);
466                    result.getNotebookInfo().add(notebookInfo);
467                }
468            } else {
469                return null;
470            }
471        }
472        return result;
473    }
474
475    @Override
476    public boolean hasAccess(Number notebookID, Number principalID, Permission permission) {
477        List<Number> notebookIDs = notebookDao.getNotebookIDs(principalID, permission);
478        if (notebookIDs == null) {
479            return false;
480        }
481        return notebookIDs.contains(notebookID);
482    }
483
484    @Override
485    public ReferenceList getNotebooksOwnedBy(Number principalID) {
486        ReferenceList result = new ReferenceList();
487        List<Number> notebookIDs = notebookDao.getNotebookIDsOwnedBy(principalID);
488        for (Number notebookID : notebookIDs) {
489            String reference = notebookDao.getURIFromInternalID(notebookID);
490            result.getRef().add(reference);
491        }
492        return result;
493    }
494
495    @Override
496    public ReferenceList getPrincipals(Number notebookID, String permission) {
497        ReferenceList result = new ReferenceList();
498        List<Number> principalIDs = userDao.getPrincipalIDsWithPermissionForNotebook(notebookID, Permission.fromValue(permission));
499        for (Number principalID : principalIDs) {
500            String reference = userDao.getURIFromInternalID(principalID);
501            result.getRef().add(reference);
502        }
503        return result;
504    }
505
506    @Override
507    public Notebook getNotebook(Number notebookID) {
508        Notebook result = notebookDao.getNotebookWithoutAnnotationsAndPermissionsAndOwner(notebookID);
509
510        result.setOwnerRef(userDao.getURIFromInternalID(notebookDao.getOwner(notebookID)));
511
512        ReferenceList annotations = new ReferenceList();
513        List<Number> annotationIDs = annotationDao.getAnnotations(notebookID);
514        for (Number annotationID : annotationIDs) {
515            annotations.getRef().add(annotationDao.getURIFromInternalID(annotationID));
516        }
517        result.setAnnotations(annotations);
518
519        UserWithPermissionList ups = new UserWithPermissionList();
520        List<Permission> permissions = new ArrayList<Permission>();
521        permissions.add(Permission.READER);
522        permissions.add(Permission.WRITER);
523        for (Permission permission : permissions) {
524            List<Number> users = userDao.getPrincipalIDsWithPermissionForNotebook(notebookID, permission);
525            if (users != null) {
526                for (Number user : users) {
527                    UserWithPermission up = new UserWithPermission();
528                    up.setRef(userDao.getURIFromInternalID(user));
529                    up.setPermission(permission);
530                    ups.getUserWithPermission().add(up);
531                }
532            }
533        }
534        result.setPermissions(ups);
535        return result;
536    }
537
538    @Override
539    public Number getNotebookOwner(Number notebookID) {
540        return notebookDao.getOwner(notebookID);
541    }
542
543    /////////////////////////////////////////////////////////////
544    @Override
545    public ReferenceList getAnnotationsForNotebook(Number notebookID, int startAnnotation, int maximumAnnotations, String orderedBy, boolean desc) {
546        List<Number> annotationIDs = annotationDao.getAnnotations(notebookID);
547
548        if (startAnnotation < -1) {
549            logger.info("Variable's startAnnotation value " + startAnnotation + " is invalid. I will return null.");
550            return null;
551        }
552
553        if (maximumAnnotations < -1) {
554            logger.info("Variable's maximumAnnotations value " + maximumAnnotations + " is invalid. I will return null.");
555            return null;
556        }
557
558        int offset = (startAnnotation > 0) ? startAnnotation - 1 : 0;
559        String direction = desc ? "DESC" : "ASC";
560        List<Number> selectedAnnotIDs = annotationDao.sublistOrderedAnnotationIDs(annotationIDs, offset, maximumAnnotations, orderedBy, direction);
561        ReferenceList references = new ReferenceList();
562        for (Number annotationID : selectedAnnotIDs) {
563            references.getRef().add(annotationDao.getURIFromInternalID(annotationID));
564        }
565        return references;
566    }
567
568    ///// UPDATERS /////////////////
569    @Override
570    public boolean updateAccount(UUID userExternalID, String account) {
571        return userDao.updateAccount(userExternalID, account);
572    }
573
574    @Override
575    public int updateAnnotationPrincipalPermission(Number annotationID, Number userID, Permission permission) {
576        if (permission != null) {
577            return annotationDao.updateAnnotationPrincipalPermission(annotationID, userID, permission);
578        } else {
579            return annotationDao.deleteAnnotationPrincipalPermission(annotationID, userID);
580        }
581    }
582
583    @Override
584    public int updatePermissions(Number annotationID, UserWithPermissionList permissionList) {
585
586        List<UserWithPermission> usersWithPermissions = permissionList.getUserWithPermission();
587        int result = 0;
588        for (UserWithPermission userWithPermission : usersWithPermissions) {
589            Number userID = userDao.getInternalID(UUID.fromString(userDao.stringURItoExternalID(userWithPermission.getRef())));
590            if (userID != null) {
591                Permission permission = userWithPermission.getPermission();
592                Permission currentPermission = annotationDao.getPermission(annotationID, userID);
593                if (currentPermission != null) {
594                    if (!permission.value().equals(currentPermission.value())) {
595                        result = result + annotationDao.updateAnnotationPrincipalPermission(annotationID, userID, permission);
596                    }
597                } else {
598                    result = result + annotationDao.addAnnotationPrincipalPermission(annotationID, userID, permission);
599                }
600            }
601        }
602
603        return result;
604    }
605
606    // TODO: optimize (not chnaged targets should not be deleted)
607    // TODO: unit test
608    @Override
609    public int updateAnnotation(Annotation annotation) {
610        int updatedAnnotations = annotationDao.updateAnnotation(annotation, userDao.getInternalIDFromURI(annotation.getOwnerRef()));
611        Number annotationID = annotationDao.getInternalIDFromURI(annotation.getURI());
612        int deletedTargets = annotationDao.deleteAllAnnotationTarget(annotationID);
613        int deletedPrinsipalsPermissions = annotationDao.deleteAnnotationPrincipalPermissions(annotationID);
614        int addedTargets = addTargets(annotation, annotationID);
615        int addedPrincipalsPermissions = addPrincipalsPermissions(annotation.getPermissions().getUserWithPermission(), annotationID);
616        return updatedAnnotations;
617    }
618
619    // TODO: unit test
620    @Override
621    public int updateAnnotationBody(Number internalID, AnnotationBody annotationBody) {
622        String[] body = annotationDao.retrieveBodyComponents(annotationBody);
623        return annotationDao.updateAnnotationBody(internalID, body[0], body[1], annotationBody.getXmlBody() != null);
624    }
625
626    @Override
627    public Number updateUser(User user) {
628        return userDao.updateUser(user);
629    }
630    /// notebooks ///
631
632    @Override
633    public boolean updateNotebookMetadata(Number notebookID, NotebookInfo upToDateNotebookInfo) {
634        Number ownerID = userDao.getInternalIDFromURI(upToDateNotebookInfo.getOwnerRef());
635        return notebookDao.updateNotebookMetadata(notebookID, upToDateNotebookInfo.getTitle(), ownerID);
636    }
637
638    @Override
639    public boolean addAnnotationToNotebook(Number notebookID, Number annotationID) {
640        return notebookDao.addAnnotationToNotebook(notebookID, annotationID);
641    }
642
643    /////////////// ADDERS  /////////////////////////////////
644    @Override
645    public Number[] addCachedForTarget(Number targetID, String fragmentDescriptor, CachedRepresentationInfo cachedInfo, InputStream cachedBlob) {
646        Number[] result = new Number[2];
647        result[1] = cachedRepresentationDao.getInternalIDFromURI(cachedInfo.getURI());
648        if (result[1] == null) {
649            result[1] = cachedRepresentationDao.addCachedRepresentation(cachedInfo, cachedBlob);
650        }
651        result[0] = targetDao.addTargetCachedRepresentation(targetID, result[1], fragmentDescriptor);
652        return result;
653
654    }
655
656    // TODo: mapping uri to external ID
657    @Override
658    public Map<String, String> addTargetsForAnnotation(Number annotationID, List<TargetInfo> targets) {
659        Map<String, String> result = new HashMap<String, String>();
660        Number targetIDRunner;
661        for (TargetInfo targetInfo : targets) {
662            targetIDRunner = targetDao.getInternalIDFromURI(targetInfo.getRef());
663            if (targetIDRunner != null) {
664                int affectedRows = annotationDao.addAnnotationTarget(annotationID, targetIDRunner);
665            } else {
666                Target newTarget = createFreshTarget(targetInfo);
667                Number targetID = targetDao.addTarget(newTarget);
668                String targetTemporaryID = targetDao.stringURItoExternalID(targetInfo.getRef());
669                result.put(targetTemporaryID, targetDao.getExternalID(targetID).toString());
670                int affectedRows = annotationDao.addAnnotationTarget(annotationID, targetID);
671            }
672        }
673        return result;
674    }
675
676    @Override
677    public Number addUsersAnnotation(Number ownerID, Annotation annotation) {
678        Number annotationID = annotationDao.addAnnotation(annotation, ownerID);
679        int affectedAnnotRows = addTargets(annotation, annotationID);
680        if (annotation.getPermissions() != null) {
681            if (annotation.getPermissions().getUserWithPermission() != null) {
682                int addedPrincipalsPermissions = this.addPrincipalsPermissions(annotation.getPermissions().getUserWithPermission(), annotationID);
683            }
684        }
685        return annotationID;
686    }
687
688    @Override
689    public Number addUser(User user, String remoteID) {
690        if (userDao.userExists(user)) {
691            return null;
692        } else {
693            return userDao.addUser(user, remoteID);
694        }
695    }
696
697    @Override
698    public int addAnnotationPrincipalPermission(Number annotationID, Number userID, Permission permission) {
699        return annotationDao.addAnnotationPrincipalPermission(annotationID, userID, permission);
700    }
701
702    //////////// notebooks //////
703    @Override
704    public Number createNotebook(Notebook notebook, Number ownerID) {
705        Number notebookID = notebookDao.createNotebookWithoutPermissionsAndAnnotations(notebook, ownerID);
706        boolean updateOwner = notebookDao.setOwner(notebookID, ownerID);
707        List<UserWithPermission> permissions = notebook.getPermissions().getUserWithPermission();
708        for (UserWithPermission principalPermission : permissions) {
709            Number principalID = userDao.getInternalIDFromURI(principalPermission.getRef());
710            Permission permission = principalPermission.getPermission();
711            boolean updatePermissions = notebookDao.addPermissionToNotebook(notebookID, principalID, permission);
712        }
713        return notebookID;
714    }
715
716    @Override
717    public boolean createAnnotationInNotebook(Number notebookID, Annotation annotation, Number ownerID) {
718        Number newAnnotationID = this.addUsersAnnotation(ownerID, annotation);
719        return notebookDao.addAnnotationToNotebook(notebookID, newAnnotationID);
720    }
721
722    ////////////// DELETERS //////////////////
723   
724   
725   
726   
727    @Override
728    public int deleteUser(Number userID) {
729        return userDao.deleteUser(userID);
730    }
731
732   
733    @Override
734    public int deleteUserSafe(Number userID) {
735        return userDao.deleteUserSafe(userID);
736    }
737
738    @Override
739    public int deleteCachedRepresentation(Number internalID) {
740       
741        if (internalID == null) {
742            logger.debug("Cached's internalID is null");
743            return 0;
744        }
745       
746        if (targetDao.cachedIsInUse(internalID)) {
747            logger.debug("Cached Repr. is in use, and cannot be deleted.");
748            return 0;
749        }
750
751        return cachedRepresentationDao.deleteCachedRepresentation(internalID);
752    };
753   
754   
755    @Override
756    public int[] deleteCachedRepresentationOfTarget(Number versionID, Number cachedID) {
757        int[] result = new int[2];
758        result[0] = targetDao.deleteTargetCachedRepresentation(versionID, cachedID);
759        if (result[0] > 0) {
760            result[1] = cachedRepresentationDao.deleteCachedRepresentation(cachedID);
761        } else {
762            result[1] = 0;
763
764        }
765        return result;
766    }
767
768    @Override
769    public int[] deleteAllCachedRepresentationsOfTarget(Number targetID) {
770        int[] result = new int[2];
771        result[0] = 0;
772        result[1] = 0;
773        List<Number> cachedIDs = cachedRepresentationDao.getCachedRepresentationsForTarget(targetID);
774        for (Number cachedID : cachedIDs) {
775            int[] currentResult = this.deleteCachedRepresentationOfTarget(targetID, cachedID);
776            result[0] = result[0] + currentResult[0];
777            result[1] = result[1] + currentResult[1];
778        }
779        return result;
780    }
781
782    @Override
783    public int[] deleteAnnotation(Number annotationID) {
784        int[] result = new int[5];
785        result[1] = annotationDao.deleteAnnotationPrincipalPermissions(annotationID);
786        List<Number> targetIDs = targetDao.retrieveTargetIDs(annotationID);
787        result[2] = annotationDao.deleteAllAnnotationTarget(annotationID);
788        result[3] = 0;
789        if (targetIDs != null) {
790            for (Number targetID : targetIDs) {
791                this.deleteAllCachedRepresentationsOfTarget(targetID);
792                result[3] = result[3] + this.deleteTarget(targetID);
793
794            }
795        }
796       
797        result[4] = annotationDao.deleteAnnotationFromAllNotebooks(annotationID);
798       
799        result[0] = annotationDao.deleteAnnotation(annotationID);
800        return result;
801    }
802   
803    ////////////////////// DELETERS ////////////////////////
804    @Override
805    public int deleteTarget(Number internalID) {
806        if (internalID == null) {
807            logger.debug("internalID of the target is null.");
808            return 0;
809        }
810       
811        if (annotationDao.targetIsInUse(internalID)) {
812            logger.debug("The target is in use, and cannot be deleted.");
813            return 0;
814        }
815       
816        return targetDao.deleteTarget(internalID);
817
818    }
819
820    @Override
821    public boolean deleteNotebook(Number notebookID) {
822        if (notebookDao.deleteAllPermissionsForNotebook(notebookID) || notebookDao.deleteAllAnnotationsFromNotebook(notebookID)) {
823            return notebookDao.deleteNotebook(notebookID);
824        } else {
825            return false;
826        }
827    }
828
829////////////// HELPERS ////////////////////
830    ////////////////////////////////////////
831    @Override
832    public ResponseBody makeAnnotationResponseEnvelope(Number annotationID) {
833        ResponseBody result = new ResponseBody();
834        Annotation annotation = this.getAnnotation(annotationID);
835        result.setAnnotation(annotation);
836        List<String> targetsNoCached = this.getTargetsWithNoCachedRepresentation(annotationID);
837        ActionList actionList = new ActionList();
838        result.setActionList(actionList);
839        actionList.getAction().addAll(makeActionList(targetsNoCached, AnnotationActionName.CREATE_CACHED_REPRESENTATION.value()));
840        return result;
841    }
842
843    @Override
844    public ResponseBody makeNotebookResponseEnvelope(Number notebookID) {
845        ResponseBody result = new ResponseBody();
846        result.setPermissions(null);
847        Notebook notebook = this.getNotebook(notebookID);
848        result.setNotebook(notebook);
849        return result;
850    }
851
852    @Override
853    public ResponseBody makePermissionResponseEnvelope(Number resourceID, Resource resource) {
854        ResponseBody result = new ResponseBody();
855        UserWithPermissionList permissions = this.getPermissions(resourceID, resource);
856        result.setPermissions(permissions);
857        List<String> usersWithNoInfo = this.getUsersWithNoInfo(resourceID);
858        ActionList actionList = new ActionList();
859        result.setActionList(actionList);
860        actionList.getAction().addAll(makeActionList(usersWithNoInfo, PermissionActionName.PROVIDE_USER_INFO.value()));
861        return result;
862    }
863
864    private List<Action> makeActionList(List<String> resourceURIs, String message) {
865        if (resourceURIs != null) {
866            if (resourceURIs.isEmpty()) {
867                return (new ArrayList<Action>());
868            } else {
869                List<Action> result = new ArrayList<Action>();
870                for (String resourceURI : resourceURIs) {
871                    Action action = new Action();
872                    result.add(action);
873                    action.setMessage(message);
874                    action.setObject(resourceURI);
875                }
876                return result;
877            }
878        } else {
879            return null;
880        }
881    }
882
883    //// priveee ///
884    private Target createFreshTarget(TargetInfo targetInfo) {
885        Target target = new Target();
886        target.setLink(targetInfo.getLink());
887        target.setVersion(targetInfo.getVersion());
888        return target;
889    }
890
891    private int addTargets(Annotation annotation, Number annotationID) {
892        List<TargetInfo> targets = annotation.getTargets().getTargetInfo();
893        Map<String, String> targetIdPairs = addTargetsForAnnotation(annotationID, targets);
894        AnnotationBody annotationBody = annotation.getBody();
895        String bodyText;
896        String newBodyText;
897        String mimeType;
898        if (annotationBody.getXmlBody() != null) {
899            bodyText = Helpers.elementToString(annotation.getBody().getXmlBody().getAny());
900            mimeType = annotationBody.getXmlBody().getMimeType();
901        } else {
902            if (annotation.getBody().getTextBody() != null) {
903                bodyText = annotation.getBody().getTextBody().getBody();
904                mimeType = annotationBody.getTextBody().getMimeType();
905            } else {
906                logger.error("The client has sent ill-formed annotation body.");
907                return -1;
908            }
909        }
910        newBodyText = Helpers.replace(bodyText, targetIdPairs);
911        return annotationDao.updateAnnotationBody(annotationID, newBodyText, mimeType, annotationBody.getXmlBody() != null);
912    }
913
914    private int addPrincipalsPermissions(List<UserWithPermission> permissions, Number annotationID) {
915        int addedPermissions = 0;
916        for (UserWithPermission permission : permissions) {
917            addedPermissions = addedPermissions + annotationDao.addAnnotationPrincipalPermission(annotationID, userDao.getInternalIDFromURI(permission.getRef()), permission.getPermission());
918
919        }
920        return addedPermissions;
921    }
922
923    private TargetInfo getTargetInfoFromTarget(Target target) {
924        TargetInfo targetInfo = new TargetInfo();
925        targetInfo.setRef(target.getURI());
926        targetInfo.setLink(target.getLink());
927        targetInfo.setVersion(target.getVersion());
928        return targetInfo;
929    }
930}
Note: See TracBrowser for help on using the repository browser.