source: ComponentRegistry/trunk/ComponentRegistry/src/main/java/clarin/cmdi/componentregistry/persistence/impl/ComponentDaoImpl.java @ 4098

Last change on this file since 4098 was 4098, checked in by George.Georgovassilis@mpi.nl, 10 years ago

#360, #431, #432: JPA and unified component entities

File size: 12.3 KB
Line 
1package clarin.cmdi.componentregistry.persistence.impl;
2
3import java.util.ArrayList;
4import java.util.HashMap;
5import java.util.List;
6import java.util.Map;
7
8import org.slf4j.Logger;
9import org.slf4j.LoggerFactory;
10import org.springframework.beans.factory.annotation.Autowired;
11import org.springframework.dao.DataAccessException;
12import org.springframework.stereotype.Repository;
13
14import clarin.cmdi.componentregistry.impl.ComponentUtils;
15import clarin.cmdi.componentregistry.model.BaseDescription;
16import clarin.cmdi.componentregistry.model.ComponentDescription;
17import clarin.cmdi.componentregistry.model.ProfileDescription;
18import clarin.cmdi.componentregistry.model.RegistryUser;
19import clarin.cmdi.componentregistry.persistence.ComponentDao;
20import clarin.cmdi.componentregistry.persistence.jpa.CommentsDao;
21import clarin.cmdi.componentregistry.persistence.jpa.JpaComponentDao;
22import clarin.cmdi.componentregistry.persistence.jpa.UserDao;
23
24/**
25 * Base DAO which can be extended to serve {@link ComponentDescription}s and
26 * {@link ProfileDescription}s
27 *
28 * @author Twan Goosen <twan.goosen@mpi.nl>
29 * @author George.Georgovassilis@mpi.nl
30 */
31
32@Repository
33public class ComponentDaoImpl implements ComponentDao {
34
35    @Autowired
36    private JpaComponentDao jpaComponentDao;
37
38    @Autowired
39    private CommentsDao commentsDao;
40
41    @Autowired
42    private UserDao userDao;
43
44    private final static Logger LOG = LoggerFactory
45            .getLogger(ComponentDaoImpl.class);
46
47    /**
48     * Copy a set of properties which are allowed to change from "from" to "to"
49     * thus making sure that only those properties are updated and not other
50     * ones.
51     *
52     * @param from
53     * @param to
54     */
55    protected void copyPersistentProperties(BaseDescription from, BaseDescription to) {
56        to.setName(from.getName());
57        to.setDescription(from.getDescription());
58        to.setRegistrationDate(from.getRegistrationDate());
59        to.setCreatorName(from.getCreatorName());
60        to.setDomainName(from.getDomainName());
61        to.setGroupName(from.getGroupName());
62        to.setHref(from.getHref());
63    }
64
65    protected String getTableName() {
66        return "persistentcomponents";
67    };
68
69    private boolean compare(String s, Number n) {
70        return ("" + s).equals("" + n);
71    }
72
73    private String toString(Number n) {
74        if (n == null)
75            return null;
76        return n.toString();
77    }
78
79    private BaseDescription castDown(BaseDescription c) {
80        // JPA will save only BaseComponent instances, not derived classes
81        if (c instanceof ComponentDescription
82                || c instanceof ProfileDescription) {
83            BaseDescription copy = new BaseDescription();
84            ComponentUtils.copyPropertiesFrom(c, copy);
85            return copy;
86        }
87        return c;
88    }
89
90    /**
91     * Update {@link BaseDescription#getCommentsCount()} (which is a transient
92     * property) with the number of comments for that component and load
93     * {@link BaseDescription#getContent()}
94     *
95     * @param baseDescription
96     */
97    private void augment(BaseDescription baseDescription) {
98        if (baseDescription == null)
99            return;
100        int count = (int) commentsDao.findCommentCountForComponent(baseDescription
101                .getId());
102        baseDescription.setCommentsCount(count);
103        baseDescription.setContent(jpaComponentDao.findContentByComponentId(baseDescription
104                .getId()));
105    }
106
107/**
108     * Update {@link BaseDescription#getCommentsCount()
109     * @param baseDescription
110     */
111    private List<BaseDescription> augment(List<BaseDescription> baseDescription) {
112        if (baseDescription.isEmpty())
113            return baseDescription;
114        Map<String, BaseDescription> map = new HashMap<String, BaseDescription>();
115        List<String> idlist = new ArrayList<String>();
116        for (BaseDescription c:baseDescription) {
117            idlist.add(c.getId());
118            map.put(c.getId(), c);
119        }
120        List<Object[]> tuples = commentsDao
121                .findCommentCountForComponents(idlist);
122        for (Object[] tuple : tuples) {
123            String id = tuple[0].toString();
124            int count = Integer.parseInt(tuple[1].toString());
125            map.get(id).setCommentsCount(count);
126        }
127        return baseDescription;
128    }
129
130    /**
131     *
132     * @param cmdId
133     *            CMD id
134     * @return Whether the specified item is in the public space
135     */
136    @Override
137    public boolean isPublic(String cmdId) {
138        BaseDescription baseDescription = jpaComponentDao.findByComponentId(cmdId);
139        return baseDescription != null && baseDescription.isPublic();
140    }
141
142    /**
143     *
144     * @param cmdId
145     *            CMD id
146     * @param userId
147     *            User db id of workspace owner
148     * @return Whether the specified item is in the specified user's workspace
149     */
150    @Override
151    public boolean isInUserSpace(String cmdId, Number userId) {
152        BaseDescription baseDescription = jpaComponentDao.findByComponentId(cmdId);
153        boolean b = baseDescription != null && !baseDescription.isPublic()
154                && compare(baseDescription.getUserId(), userId);
155        return b;
156    }
157
158    /**
159     *
160     * @param cmdId
161     *            CMD id
162     * @param userId
163     *            User db id of workspace owner, null for public registry
164     * @return Whether the specified item is in the specified workspace (user or
165     *         public)
166     */
167    @Override
168    public boolean isInRegistry(String cmdId, Number userId) {
169        if (userId == null) {
170            return isPublic(cmdId);
171        } else {
172            return isInUserSpace(cmdId, userId);
173        }
174    }
175
176    /**
177     *
178     * @param cmdId
179     *            Profile or component Id (not primary key)
180     * @return String value of XML content for profile or component
181     */
182    @Override
183    public String getContent(boolean isDeleted, String cmdId) {
184        return jpaComponentDao.findContentByComponentId(cmdId, isDeleted);
185    }
186
187    /**
188     * @param description
189     *            Description to insert
190     * @param content
191     *            Content to insert and refer to from description
192     * @return Id of newly inserted description
193     */
194    @Override
195    public Number insertDescription(BaseDescription description, String content,
196            boolean isPublic, Number userId) {
197
198        if (description.getId() != null
199                && jpaComponentDao.findByComponentId(description.getId()) != null) {
200            throw new IllegalArgumentException("Component "
201                    + description.getId() + " already in DB");
202        }
203        if (content == null)
204            content = "";
205        BaseDescription copy = castDown(description);
206        copy.setContent(content);
207        copy.setPublic(isPublic);
208        copy.setUserId(toString(userId));
209        copy = jpaComponentDao.saveAndFlush(copy);
210        jpaComponentDao.updateContent(copy.getId(), content);
211        return copy.getDbId();
212    }
213
214    /**
215     * Updates a description by database id
216     *
217     * @param id
218     *            Id (key) of description record
219     * @param description
220     *            New values for description (leave null to not change)
221     * @param content
222     *            New content for description (leave null to not change)
223     */
224    @Override
225    public void updateDescription(Number id, BaseDescription description,
226            String content) {
227        if (content == null)
228            content = "";
229        if (description != null) {
230            // Update description
231            BaseDescription copy = jpaComponentDao.findByComponentId(description
232                    .getId());
233            copyPersistentProperties(description, copy);
234            jpaComponentDao.saveAndFlush(copy);
235            jpaComponentDao.updateContent(copy.getId(), content);
236        }
237
238        if (content != null) {
239            BaseDescription copy = jpaComponentDao.findOne(id.longValue());
240            copy.setContent(content);
241            jpaComponentDao.saveAndFlush(copy);
242            jpaComponentDao.updateContent(copy.getId(), content);
243        }
244    }
245
246    /**
247     * Retrieves description by it's primary key Id
248     *
249     * @param id
250     *            Description key
251     * @return The description, if it exists; null otherwise
252     */
253    @Override
254    public BaseDescription getById(Number id) {
255        BaseDescription baseDescription = jpaComponentDao.findOne(id.longValue());
256        if (baseDescription != null && !baseDescription.isDeleted()) {
257            augment(baseDescription);
258            return baseDescription;
259        }
260        return null;
261    }
262
263    /**
264     * Get by ComponentId / ProfileId, whether in userspace or public
265     *
266     * @param id
267     *            Full component id
268     * @return The description, if it exists; null otherwise
269     */
270    @Override
271    public BaseDescription getByCmdId(String id) {
272        BaseDescription baseDescription = jpaComponentDao.findByComponentId(id);
273        if (baseDescription != null && !baseDescription.isDeleted()) {
274            augment(baseDescription);
275            return baseDescription;
276        }
277        return null;
278    }
279
280    /**
281     * Get by ComponentId / ProfileId
282     *
283     * @param id
284     *            Full component id
285     * @param userId
286     *            Db id of user for workspace; null for public space
287     * @return The description, if it exists; null otherwise
288     */
289    @Override
290    public BaseDescription getByCmdId(String id, Number userId) {
291        BaseDescription baseDescription = getByCmdId(id);
292        if (baseDescription != null) {
293            augment(baseDescription);
294            if (userId == null) {
295                if (!baseDescription.isPublic())
296                    baseDescription = null;
297            } else {
298                if (baseDescription.isPublic()
299                        || !compare(baseDescription.getUserId(), userId))
300                    baseDescription = null;
301            }
302        }
303        return baseDescription;
304    }
305
306    /**
307     *
308     * @param cmdId
309     *            CMD Id of description
310     * @return Database id for description record
311     */
312    @Override
313    public Number getDbId(String cmdId) {
314        Number id = null;
315        BaseDescription c = jpaComponentDao.findByComponentId(cmdId);
316        if (c != null)
317            id = c.getDbId();
318        return id;
319    }
320
321    /**
322     *
323     * @return All descriptions in the public space. Won't include xml content
324     *         and comments count.
325     */
326    @Override
327    public List<BaseDescription> getPublicDescriptions() {
328        return augment(jpaComponentDao.findPublicItems());
329    }
330
331    /**
332     * @return List of deleted descriptions in user space or in public when
333     *         userId=null. Won't include xml content and comments count.
334     * @param userId
335     */
336    @Override
337    public List<BaseDescription> getDeletedDescriptions(Number userId) {
338        List<BaseDescription> list = null;
339        if (userId != null) {
340            list = jpaComponentDao.findDeletedItemsForUser(userId.longValue());
341        } else {
342            list = jpaComponentDao.findPublicDeletedItems();
343        }
344        list = augment(list);
345        return list;
346    }
347
348    /**
349     *
350     * @return All the user's descriptions not in the public space .Won't
351     *         include xml content and comments count.
352     */
353    @Override
354    public List<BaseDescription> getUserspaceComponents(Number userId) {
355        return augment(jpaComponentDao
356                .findItemsForUserThatAreNotInGroups(userId.longValue(),
357                        ComponentDescription.COMPONENT_PREFIX + "%"));
358    }
359
360    @Override
361    public List<BaseDescription> getUserspaceProfiles(Number userId) {
362        return augment(jpaComponentDao.findItemsForUserThatAreNotInGroups(
363                userId.longValue(), ProfileDescription.PROFILE_PREFIX + "%"));
364    }
365
366    @Override
367    public void setDeleted(BaseDescription desc, boolean isDeleted) {
368        BaseDescription copy = jpaComponentDao.findByComponentId(desc.getId());
369        copy.setDeleted(isDeleted);
370        jpaComponentDao.saveAndFlush(copy);
371    }
372
373    @Override
374    public void setPublished(Number id, boolean published) {
375        BaseDescription copy = jpaComponentDao.findOne(id.longValue());
376        copy.setPublic(published);
377        jpaComponentDao.saveAndFlush(copy);
378    }
379
380    /**
381     *
382     * @param id
383     *            Id of description record
384     * @return Principal name of description's owner, if any. Otherwise, null.
385     */
386    @Override
387    public String getOwnerPrincipalName(Number id) {
388        BaseDescription baseDescription = getById(id);
389        if (baseDescription == null)
390            return null;
391
392        long userId = baseDescription.getDbUserId();
393        RegistryUser user = userDao.findOne(userId);
394        if (user == null)
395            return null;
396
397        return user.getPrincipalName();
398    }
399
400    @Override
401    public List<BaseDescription> getPublicComponentDescriptions() {
402        return augment(jpaComponentDao
403                .findPublicItems(ComponentDescription.COMPONENT_PREFIX + "%"));
404    }
405
406    @Override
407    public List<BaseDescription> getPublicProfileDescriptions() {
408        return augment(jpaComponentDao
409                .findPublicItems(ProfileDescription.PROFILE_PREFIX + "%"));
410    }
411
412    @Override
413    public List<String> getAllNonDeletedProfileIds() {
414        return jpaComponentDao.findNonDeletedItemIds(ProfileDescription.PROFILE_PREFIX+"%");
415    }
416
417    @Override
418    public List<String> getAllNonDeletedComponentIds() {
419        return jpaComponentDao.findNonDeletedItemIds(ComponentDescription.COMPONENT_PREFIX+"%");
420    }
421
422}
Note: See TracBrowser for help on using the repository browser.