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

Last change on this file since 229 was 229, checked in by oschonef, 14 years ago

HEADS UP: database layout changed

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