source: VirtualCollectionRegistry/trunk/VirtualCollectionRegistry/src/main/java/eu/clarin/cmdi/virtualcollectionregistry/VirtualCollectionRegistry.java @ 276

Last change on this file since 276 was 276, checked in by oschonef, 14 years ago
  • further work an GWDG handle integration
  • Property svn:eol-style set to native
File size: 12.5 KB
Line 
1package eu.clarin.cmdi.virtualcollectionregistry;
2
3import java.security.Principal;
4import java.util.Collections;
5import java.util.List;
6import java.util.Map;
7import java.util.concurrent.atomic.AtomicBoolean;
8
9import javax.persistence.EntityManager;
10import javax.persistence.NoResultException;
11import javax.persistence.TypedQuery;
12
13import org.slf4j.Logger;
14import org.slf4j.LoggerFactory;
15
16import eu.clarin.cmdi.virtualcollectionregistry.model.PersistentIdentifier;
17import eu.clarin.cmdi.virtualcollectionregistry.model.PersistentIdentifierProvider;
18import eu.clarin.cmdi.virtualcollectionregistry.model.User;
19import eu.clarin.cmdi.virtualcollectionregistry.model.VirtualCollection;
20import eu.clarin.cmdi.virtualcollectionregistry.model.VirtualCollectionList;
21import eu.clarin.cmdi.virtualcollectionregistry.model.VirtualCollectionValidator;
22import eu.clarin.cmdi.virtualcollectionregistry.query.ParsedQuery;
23import eu.clarin.cmdi.virtualcollectionregistry.query.QueryException;
24
25public class VirtualCollectionRegistry {
26        private static final Logger logger =
27                LoggerFactory.getLogger(VirtualCollectionRegistry.class);
28        private static final VirtualCollectionRegistry s_instance =
29                new VirtualCollectionRegistry();
30        private AtomicBoolean intialized = new AtomicBoolean(false);
31        private DataStore datastore = null;
32        private PersistentIdentifierProvider pid_provider = null;
33        private VirtualCollectionRegistryMarshaller marshaller = null;
34
35        private VirtualCollectionRegistry() {
36                super();
37        }
38
39        public static void initalize(Map<String, String> config)
40                        throws VirtualCollectionRegistryException {
41                s_instance.doInitalize(config);
42        }
43
44        private void doInitalize(Map<String, String> config)
45                        throws VirtualCollectionRegistryException {
46                if (intialized.get()) {
47                        throw new VirtualCollectionRegistryException("already initialized");
48                }
49                logger.debug("initializing virtual collection registry ...");
50                if (config != null) {
51                        config = Collections.unmodifiableMap(config);
52                } else {
53                        config = Collections.emptyMap();
54                }
55                // XXX: the whole config / setup stuff is not very beautiful
56                this.datastore    = new DataStore(config);
57                this.pid_provider = PersistentIdentifierProvider.createProvider(config);
58                this.marshaller   = new VirtualCollectionRegistryMarshaller();
59                this.intialized.set(true);
60                logger.info("virtual collection registry successfully intialized");
61        }
62
63        public void destroy() throws VirtualCollectionRegistryException {
64                if (datastore != null) {
65                        datastore.destroy();
66                }
67        }
68
69        public static VirtualCollectionRegistry instance() {
70                if (!s_instance.intialized.get()) {
71                        throw new InternalError("virtual collection registry failed " +
72                                        "to initialize correctly");
73                }
74                return s_instance;
75        }
76
77        public DataStore getDataStore() {
78                return datastore;
79        }
80
81        public VirtualCollectionRegistryMarshaller getMarshaller() {
82                return marshaller;
83        }
84
85        public long createVirtualCollection(Principal principal,
86                        VirtualCollection vc) throws VirtualCollectionRegistryException {
87                if (principal == null) {
88                        throw new NullPointerException("principal == null");
89                }
90                if (vc == null) {
91                        throw new NullPointerException("vc == null");
92                }
93
94                logger.debug("creating virtual collection");
95
96                VirtualCollectionValidator validator =
97                        new VirtualCollectionValidator();
98                validator.validate(vc);
99
100                try {
101                        EntityManager em = datastore.getEntityManager();
102                        em.getTransaction().begin();
103
104                        // fetch user, if user does not exist create new
105                        User user = fetchUser(em, principal);
106                        if (user == null) {
107                                user = new User(principal.getName());
108                                em.persist(user);
109                        }
110
111                        // store virtual collection
112                        vc.setOwner(user);
113                        vc.createUUID();
114                        em.persist(vc);
115                        em.getTransaction().commit();
116
117                        PersistentIdentifier pid = pid_provider.createIdentifier(vc);
118                        em.getTransaction().begin();
119                        em.persist(pid);
120                        em.getTransaction().commit();
121                        logger.debug("created virtual collection (id={}, pid={})",
122                                             vc.getId(), pid.getIdentifier());
123                        return vc.getId();
124                } catch (VirtualCollectionRegistryException e) {
125                        logger.debug("failed creating virtual collecion: {}",
126                                             e.getMessage());
127                        throw e;
128                } catch (Exception e) {
129                        logger.error("error while creating virtual collection", e);
130                        throw new VirtualCollectionRegistryException(
131                                        "error while creating virtual collection", e);
132                }
133        }
134
135        public long updateVirtualCollection(Principal principal, long id,
136                        VirtualCollection vc) throws VirtualCollectionRegistryException {
137                if (principal == null) {
138                        throw new NullPointerException("principal == null");
139                }
140                if (id <= 0) {
141                        throw new IllegalArgumentException("id <= 0");
142                }
143                if (vc == null) {
144                        throw new NullPointerException("vc == null");
145                }
146
147                logger.debug("updating virtual collection (id={})", id);
148
149                VirtualCollectionValidator validator =
150                        new VirtualCollectionValidator();
151                validator.validate(vc);
152
153                try {
154                        EntityManager em = datastore.getEntityManager();
155                        em.getTransaction().begin();
156                        VirtualCollection c = em.find(VirtualCollection.class, new Long(id));
157                        if (c == null) {
158                                throw new VirtualCollectionNotFoundException(id);
159                        }
160                        if (!c.getOwner().equalsPrincipal(principal)) {
161                                throw new VirtualCollectionRegistryPermissionException(
162                                                "permission denied for user \"" +
163                                                principal.getName() + "\"");
164                        }
165                        c.updateFrom(vc);
166                        validator.validate(c);
167                        em.getTransaction().commit();
168                        logger.debug("updated virtual collection (id={})", vc.getId());
169                        return vc.getId();
170                } catch (VirtualCollectionRegistryException e) {
171                        logger.debug("failed updating virtual collecion (id={}): {}",
172                                                 id, e.getMessage());
173                        throw e;
174                } catch (Exception e) {
175                        logger.error("error while updating virtual collection", e);
176                        throw new VirtualCollectionRegistryException(
177                                        "error while updating virtual collection", e);
178                }
179        }
180
181        public long deleteVirtualCollection(Principal principal, long id)
182                        throws VirtualCollectionRegistryException {
183                if (principal == null) {
184                        throw new NullPointerException("principal == null");
185                }
186                if (id <= 0) {
187                        throw new IllegalArgumentException("id <= 0");
188                }
189
190                logger.debug("deleting virtual collection (id={})", id);
191
192                try {
193                        EntityManager em = datastore.getEntityManager();
194                        em.getTransaction().begin();
195                        VirtualCollection vc = em.find(VirtualCollection.class, new Long(id));
196                        if (vc == null) {
197                                logger.debug("virtual collection (id={}) not found", id);
198                                throw new VirtualCollectionNotFoundException(id);
199                        }
200                        if (!vc.getOwner().equalsPrincipal(principal)) {
201                                throw new VirtualCollectionRegistryPermissionException(
202                                                "permission denied for user \"" +
203                                                principal.getName() + "\"");
204                        }
205                        em.remove(vc);
206                        em.getTransaction().commit();
207                        return vc.getId();
208                } catch (VirtualCollectionRegistryException e) {
209                        logger.debug("failed deleting virtual collecion (id={}): {}",
210                                         id, e.getMessage());
211                        throw e;
212                } catch (Exception e) {
213                        logger.error("error while deleting virtual collection", e);
214                        throw new VirtualCollectionRegistryException(
215                                        "error while deleting virtual collection", e);
216                }
217        }
218
219        public VirtualCollection retrieveVirtualCollection(long id)
220                        throws VirtualCollectionRegistryException {
221                if (id <= 0) {
222                        throw new IllegalArgumentException("id <= 0");
223                }
224
225                logger.debug("retrieve virtual collection (id={})", id);
226
227                try {
228                        EntityManager em = datastore.getEntityManager();
229                        em.getTransaction().begin();
230                        VirtualCollection vc = em.find(VirtualCollection.class,
231                                        new Long(id));
232                        em.getTransaction().commit();
233                        if (vc == null) {
234                                logger.debug("virtual collection (id={}) not found", id);
235                                throw new VirtualCollectionNotFoundException(id);
236                        }
237                        return vc;
238                } catch (VirtualCollectionRegistryException e) {
239                        throw e;
240                } catch (Exception e) {
241                        logger.error("error while retrieving virtual collection", e);
242                        throw new VirtualCollectionRegistryException(
243                                        "error while retrieving virtual collection", e);
244                }
245        }
246
247        public VirtualCollection retrieveVirtualCollection(String uuid)
248                        throws VirtualCollectionRegistryException {
249                if (uuid == null) {
250                        throw new NullPointerException("uuid == null");
251                }
252                uuid = uuid.trim();
253                if (uuid.isEmpty()) {
254                        throw new IllegalArgumentException("uuid is empty");
255                }
256
257                logger.debug("retrieve virtual collection (uuid={})", uuid);
258
259                try {
260                        EntityManager em = datastore.getEntityManager();
261                        em.getTransaction().begin();
262                        TypedQuery<VirtualCollection> q =
263                                em.createNamedQuery("VirtualCollection.byUUID",
264                                                                        VirtualCollection.class);
265                        q.setParameter("uuid", uuid);
266                        VirtualCollection vc = q.getSingleResult();
267                        em.getTransaction().commit();
268                        return vc;
269                } catch (NoResultException e) {
270                        logger.debug("virtual collection (uuid={}) not found", uuid);
271                        throw new VirtualCollectionNotFoundException(uuid);
272                } catch (Exception e) {
273                        logger.error("error while retrieving virtual collection", e);
274                        throw new VirtualCollectionRegistryException(
275                                        "error while retrieving virtual collection", e);
276                }
277        }
278
279        public VirtualCollectionList getVirtualCollections(String query,
280                        int offset, int count) throws VirtualCollectionRegistryException {
281                EntityManager em = datastore.getEntityManager();
282                try {
283                        em.getTransaction().begin();
284
285                        // setup queries
286                        TypedQuery<Long>              cq = null;
287                        TypedQuery<VirtualCollection>  q = null;
288                        if (query != null) {
289                                ParsedQuery parsedQuery = ParsedQuery.parseQuery(em, query);
290                                cq = parsedQuery.getCountQuery(null);
291                                q = parsedQuery.getQuery(null);
292                        } else {
293                                cq = em.createNamedQuery("VirtualCollection.countAll",
294                                                Long.class);
295                                q = em.createNamedQuery("VirtualCollection.findAll",
296                                                VirtualCollection.class);
297                        }
298
299                        // commence query ...
300                        List<VirtualCollection> results = null;
301                        long totalCount = cq.getSingleResult();
302
303                        // optimization; don't query, if we won't get any results
304                        if ( totalCount > 0) {
305                                if (offset > 0) {
306                                        q.setFirstResult(offset);
307                                }
308                                if (count > 0) {
309                                        q.setMaxResults(count);
310                                }
311                                results = q.getResultList();
312                        }
313                        return new VirtualCollectionList(results, offset, (int) totalCount);
314                } catch (QueryException e) {
315                        throw new VirtualCollectionRegistryUsageException(
316                                "query invalid", e);
317                } catch (Exception e) {
318                        logger.error("error while enumerating virtual collections", e);
319                        throw new VirtualCollectionRegistryException(
320                                        "error while enumerating virtual collections", e);
321                } finally {
322                        em.getTransaction().commit();
323                }
324        }
325
326        public VirtualCollectionList getVirtualCollections(Principal principal,
327                        String query, int offset, int count)
328                        throws VirtualCollectionRegistryException {
329                if (principal == null) {
330                        throw new NullPointerException("principal == null");
331                }
332                EntityManager em = datastore.getEntityManager();
333                try {
334                        em.getTransaction().begin();
335
336                        // fetch user
337                        User user = fetchUser(em, principal);
338                        if (user == null) {
339                                throw new VirtualCollectionRegistryPermissionException("user " +
340                                                principal.getName() + " does not exist");
341                        }
342
343                        // setup queries
344                        TypedQuery<Long>              cq = null;
345                        TypedQuery<VirtualCollection>  q = null;
346                        if (query != null) {
347                                ParsedQuery parsedQuery = ParsedQuery.parseQuery(em, query);
348                                cq = parsedQuery.getCountQuery(user);
349                                q = parsedQuery.getQuery(user);
350                        } else {
351                                cq = em.createNamedQuery("VirtualCollection.countByOwner", Long.class);
352                                cq.setParameter("owner", user);
353                                q = em.createNamedQuery("VirtualCollection.findByOwner",
354                                                VirtualCollection.class);
355                                q.setParameter("owner", user);
356                        }
357
358                        // commence query ...
359                        List<VirtualCollection> results = null;
360                        long totalCount = cq.getSingleResult();
361
362                        // optimization; don't query, if we won't get any results
363                        if (totalCount > 0) {
364                                if (offset > 0) {
365                                        q.setFirstResult(offset);
366                                }
367                                if (count > 0) {
368                                        q.setMaxResults(count);
369                                }
370                                results = q.getResultList();
371                        }
372                        return new VirtualCollectionList(results, offset, (int) totalCount);
373                } catch (QueryException e) {
374                        throw new VirtualCollectionRegistryUsageException(
375                                "query invalid", e);
376                } catch (VirtualCollectionRegistryException e) {
377                        throw e;
378                } catch (Exception e) {
379                        logger.error("error while enumerating virtual collections", e);
380                        throw new VirtualCollectionRegistryException(
381                                        "error while enumerating virtual collections", e);
382                } finally {
383                        em.getTransaction().commit();
384                }
385        }
386
387        private static User fetchUser(EntityManager em, Principal principal) {
388                User user = null;
389                try {
390                        TypedQuery<User> q =
391                                em.createNamedQuery("User.findByName", User.class);
392                        q.setParameter("name", principal.getName());
393                        user = q.getSingleResult();
394                } catch (NoResultException e) {
395                        /* IGNORE */
396                }
397                return user;
398        }
399
400} // class VirtualCollectionRegistry
Note: See TracBrowser for help on using the repository browser.