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

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