]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
229a198c00e2578193128dd83df9e18298ab1d80
[tmp/jakarta-migration.git] /
1 /**\r
2  *  This document is a part of the source code and related artifacts\r
3  *  for CollectionSpace, an open source collections management system\r
4  *  for museums and related institutions:\r
5 \r
6  *  http://www.collectionspace.org\r
7  *  http://wiki.collectionspace.org\r
8 \r
9  *  Copyright 2009 University of California at Berkeley\r
10 \r
11  *  Licensed under the Educational Community License (ECL), Version 2.0.\r
12  *  You may not use this file except in compliance with this License.\r
13 \r
14  *  You may obtain a copy of the ECL 2.0 License at\r
15 \r
16  *  https://source.collectionspace.org/collection-space/LICENSE.txt\r
17 \r
18  *  Unless required by applicable law or agreed to in writing, software\r
19  *  distributed under the License is distributed on an "AS IS" BASIS,\r
20  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
21  *  See the License for the specific language governing permissions and\r
22  *  limitations under the License.\r
23  */\r
24 package org.collectionspace.services.common;\r
25 \r
26 import java.util.List;\r
27 \r
28 import javax.ws.rs.GET;\r
29 import javax.ws.rs.Path;\r
30 import javax.ws.rs.Produces;\r
31 import javax.ws.rs.WebApplicationException;\r
32 import javax.ws.rs.core.MultivaluedMap;\r
33 import javax.ws.rs.core.Response;\r
34 import javax.ws.rs.core.UriInfo;\r
35 \r
36 import org.collectionspace.services.common.api.Tools;\r
37 import org.collectionspace.services.common.context.ServiceContext;\r
38 import org.collectionspace.services.common.context.ServiceContextProperties;\r
39 import org.collectionspace.services.common.document.BadRequestException;\r
40 import org.collectionspace.services.common.document.DocumentException;\r
41 import org.collectionspace.services.common.document.DocumentHandler;\r
42 import org.collectionspace.services.common.document.DocumentNotFoundException;\r
43 import org.collectionspace.services.common.repository.RepositoryClient;\r
44 import org.collectionspace.services.common.repository.RepositoryClientFactory;\r
45 import org.collectionspace.services.common.security.UnauthorizedException;\r
46 import org.collectionspace.services.common.storage.StorageClient;\r
47 import org.collectionspace.services.common.storage.jpa.JpaStorageClientImpl;\r
48 import org.jboss.resteasy.client.ClientResponse;\r
49 import org.slf4j.Logger;\r
50 import org.slf4j.LoggerFactory;\r
51 \r
52 /**\r
53  * The Class AbstractCollectionSpaceResourceImpl.\r
54  *\r
55  * @param <IT> the generic type\r
56  * @param <OT> the generic type\r
57  */\r
58 public abstract class AbstractCollectionSpaceResourceImpl<IT, OT>\r
59         implements CollectionSpaceResource<IT, OT> {\r
60 \r
61     protected final Logger logger = LoggerFactory.getLogger(this.getClass());\r
62 \r
63 \r
64     // Fields for default client factory and client\r
65     /** The repository client factory. */\r
66     private RepositoryClientFactory repositoryClientFactory;\r
67     \r
68     /** The repository client. */\r
69     private RepositoryClient repositoryClient;\r
70     \r
71     /** The storage client. */\r
72     private StorageClient storageClient;\r
73 \r
74     /**\r
75      * Extract id.\r
76      *\r
77      * @param res the res\r
78      * @return the string\r
79      */\r
80     protected static String extractId(Response res) {\r
81         MultivaluedMap<String, Object> mvm = res.getMetadata();\r
82         String uri = (String) ((List<Object>) mvm.get("Location")).get(0);\r
83         String[] segments = uri.split("/");\r
84         String id = segments[segments.length - 1];\r
85         return id;\r
86     }    \r
87     \r
88     /**\r
89      * Instantiates a new abstract collection space resource.\r
90      */\r
91     public AbstractCollectionSpaceResourceImpl() {\r
92         repositoryClientFactory = RepositoryClientFactory.getInstance();\r
93     }\r
94 \r
95     /* (non-Javadoc)\r
96      * @see org.collectionspace.services.common.CollectionSpaceResource#getServiceName()\r
97      */\r
98     @Override\r
99     abstract public String getServiceName();\r
100 \r
101 \r
102     /* (non-Javadoc)\r
103      * @see org.collectionspace.services.common.CollectionSpaceResource#getRepositoryClient(org.collectionspace.services.common.context.ServiceContext)\r
104      */\r
105     @Override\r
106     synchronized public RepositoryClient getRepositoryClient(ServiceContext<IT, OT> ctx) {\r
107         if(repositoryClient != null){\r
108             return repositoryClient;\r
109         }\r
110         repositoryClient = repositoryClientFactory.getClient(ctx.getRepositoryClientName());\r
111         return repositoryClient;\r
112     }\r
113 \r
114     /* (non-Javadoc)\r
115      * @see org.collectionspace.services.common.CollectionSpaceResource#getStorageClient(org.collectionspace.services.common.context.ServiceContext)\r
116      */\r
117     @Override\r
118     synchronized public StorageClient getStorageClient(ServiceContext<IT, OT> ctx) {\r
119         if(storageClient != null) {\r
120             return storageClient;\r
121         }\r
122         storageClient = new JpaStorageClientImpl();\r
123         return storageClient;\r
124     }\r
125     \r
126     /* (non-Javadoc)\r
127      * @see org.collectionspace.services.common.CollectionSpaceResource#createDocumentHandler(org.collectionspace.services.common.context.ServiceContext)\r
128      */\r
129     @Override\r
130     public DocumentHandler createDocumentHandler(ServiceContext<IT, OT> ctx) throws Exception {\r
131         DocumentHandler docHandler = createDocumentHandler(ctx, ctx.getInput());\r
132         return docHandler;\r
133     }\r
134     \r
135     /**\r
136      * Creates the document handler.\r
137      * \r
138      * @param ctx the ctx\r
139      * @param commonPart the common part\r
140      * \r
141      * @return the document handler\r
142      * \r
143      * @throws Exception the exception\r
144      */\r
145     public DocumentHandler createDocumentHandler(ServiceContext<IT, OT> ctx,\r
146                 Object commonPart) throws Exception {\r
147         DocumentHandler docHandler = ctx.getDocumentHandler();\r
148         docHandler.setCommonPart(commonPart);\r
149         return docHandler;\r
150     }    \r
151     \r
152     /**\r
153      * Creates the service context.\r
154      * \r
155      * @return the service context< i t, o t>\r
156      * \r
157      * @throws Exception the exception\r
158      */\r
159     protected ServiceContext<IT, OT> createServiceContext() throws Exception {          \r
160         ServiceContext<IT, OT> ctx = createServiceContext(this.getServiceName(),\r
161                         (IT)null, //inputType\r
162                         null, // The resource map\r
163                         (MultivaluedMap<String, String>)null, // The query params\r
164                         this.getCommonPartClass());\r
165         return ctx;\r
166     }    \r
167     \r
168     /**\r
169      * Creates the service context.\r
170      * \r
171      * @param serviceName the service name\r
172      * \r
173      * @return the service context< i t, o t>\r
174      * \r
175      * @throws Exception the exception\r
176      */\r
177     protected ServiceContext<IT, OT> createServiceContext(String serviceName) throws Exception {        \r
178         ServiceContext<IT, OT> ctx = createServiceContext(\r
179                         serviceName,\r
180                         (IT)null, // The input part\r
181                         null, // The resource map\r
182                         (MultivaluedMap<String, String>)null, // The queryParams\r
183                         (Class<?>)null  /*input type's Class*/);\r
184         return ctx;\r
185     }\r
186     \r
187     /**\r
188      * Creates the service context.\r
189      * \r
190      * @param serviceName the service name\r
191      * @param input the input\r
192      * \r
193      * @return the service context< i t, o t>\r
194      * \r
195      * @throws Exception the exception\r
196      */\r
197     protected ServiceContext<IT, OT> createServiceContext(String serviceName,\r
198                 IT input) throws Exception {            \r
199         ServiceContext<IT, OT> ctx = createServiceContext(serviceName,\r
200                         input,\r
201                         null, // The resource map\r
202                         (MultivaluedMap<String, String>)null, /*queryParams*/\r
203                         (Class<?>)null  /*input type's Class*/);\r
204         return ctx;\r
205     }\r
206     \r
207     /**\r
208      * Creates the service context.\r
209      * \r
210      * @param serviceName the service name\r
211      * @return the service context< i t, o t>\r
212      * @throws Exception the exception\r
213      */\r
214     protected ServiceContext<IT, OT> createServiceContext(String serviceName,\r
215                 MultivaluedMap<String, String> queryParams) throws Exception {          \r
216         ServiceContext<IT, OT> ctx = createServiceContext(serviceName,\r
217                         (IT)null,\r
218                         null, // The resource map\r
219                         queryParams,\r
220                         (Class<?>)null  /*input type's Class*/);\r
221         return ctx;\r
222     }    \r
223 \r
224     /**\r
225      * Creates the service context.\r
226      * \r
227      * @param queryParams the query params\r
228      * \r
229      * @return the service context< i t, o t>\r
230      * \r
231      * @throws Exception the exception\r
232      */\r
233     protected ServiceContext<IT, OT> createServiceContext(MultivaluedMap<String, String> queryParams) throws Exception {\r
234         ServiceContext<IT, OT> ctx = createServiceContext(\r
235                         (IT)null, /*input*/\r
236                         queryParams,\r
237                         (Class<?>)null  /*input type's Class*/);\r
238         return ctx;\r
239     }\r
240 \r
241     protected ServiceContext<IT, OT> createServiceContext(UriInfo ui) throws Exception {\r
242         MultivaluedMap<String, String> queryParams = ui.getQueryParameters();\r
243         ServiceContext<IT, OT> ctx = createServiceContext(\r
244                         (IT)null, /*input*/\r
245                         queryParams,\r
246                         (Class<?>)null  /*input type's Class*/);\r
247         return ctx;\r
248     }\r
249 \r
250 \r
251 \r
252         \r
253     /**\r
254      * Creates the service context.\r
255      * \r
256      * @param input the input\r
257      * \r
258      * @return the service context< i t, o t>\r
259      * \r
260      * @throws Exception the exception\r
261      */\r
262     protected ServiceContext<IT, OT> createServiceContext(IT input) throws Exception {          \r
263         ServiceContext<IT, OT> ctx = createServiceContext(\r
264                         input,\r
265                         (Class<?>)null /*input type's Class*/);\r
266         return ctx;\r
267     }\r
268     \r
269     /**\r
270      * Creates the service context.\r
271      * \r
272      * @param input the input\r
273      * @param theClass the the class\r
274      * \r
275      * @return the service context\r
276      * \r
277      * @throws Exception the exception\r
278      */\r
279     protected ServiceContext<IT, OT> createServiceContext(IT input, Class<?> theClass) throws Exception {       \r
280         ServiceContext<IT, OT> ctx = createServiceContext(\r
281                         input,\r
282                         (MultivaluedMap<String, String>)null, //queryParams,\r
283                         theClass);\r
284         return ctx;\r
285     }\r
286     \r
287     protected ServiceContext<IT, OT> createServiceContext(\r
288                 String serviceName,\r
289                 ResourceMap resourceMap,\r
290                 UriInfo ui) throws Exception {\r
291         ServiceContext<IT, OT> ctx = createServiceContext(\r
292                         serviceName,\r
293                         null, // The input object\r
294                         resourceMap,\r
295                         ui.getQueryParameters(),\r
296                         null /* the class of the input type */);\r
297         ctx.setUriInfo(ui);\r
298         return ctx;\r
299     }\r
300     \r
301     protected ServiceContext<IT, OT> createServiceContext(\r
302                 IT input,\r
303                 ResourceMap resourceMap,\r
304                 UriInfo ui) throws Exception {\r
305         ServiceContext<IT, OT> ctx = createServiceContext(\r
306                         this.getServiceName(),\r
307                         input,\r
308                         resourceMap,\r
309                         ui.getQueryParameters(),\r
310                         null /* the class of the input type */);\r
311         ctx.setUriInfo(ui);\r
312         return ctx;\r
313     }\r
314 \r
315     protected ServiceContext<IT, OT> createServiceContext(\r
316                 IT input,\r
317                 MultivaluedMap<String, String> queryParams) throws Exception {\r
318         return createServiceContext(this.getServiceName(),\r
319                         input,\r
320                         null, // The resource map\r
321                         queryParams,\r
322                         null); // The class of the input type.\r
323     }\r
324     \r
325     /**\r
326      * Creates the service context.\r
327      * \r
328      * @param input the input\r
329      * @param queryParams the query params\r
330      * @param theClass the the class\r
331      * \r
332      * @return the service context< i t, o t>\r
333      * \r
334      * @throws Exception the exception\r
335      */\r
336     protected ServiceContext<IT, OT> createServiceContext(\r
337                 IT input,\r
338                 MultivaluedMap<String, String> queryParams,\r
339                 Class<?> theClass) throws Exception {\r
340         return createServiceContext(this.getServiceName(),\r
341                         input,\r
342                         null, // The resource map\r
343                         queryParams,\r
344                         theClass);\r
345     }\r
346 \r
347     /**\r
348      * Creates the service context.\r
349      * \r
350      * @param serviceName the service name\r
351      * @param input the input\r
352      * @param queryParams the query params\r
353      * @param theClass the the class\r
354      * \r
355      * @return the service context< i t, o t>\r
356      * \r
357      * @throws Exception the exception\r
358      */\r
359     private ServiceContext<IT, OT> createServiceContext(\r
360                 String serviceName,\r
361                 IT input,\r
362                 ResourceMap resourceMap,\r
363                 MultivaluedMap<String, String> queryParams,\r
364                 Class<?> theClass) throws Exception {\r
365         ServiceContext<IT, OT> ctx = getServiceContextFactory().createServiceContext(\r
366                         serviceName,\r
367                         input,\r
368                         resourceMap,\r
369                         queryParams,\r
370                         theClass != null ? theClass.getPackage().getName() : null,\r
371                         theClass != null ? theClass.getName() : null);\r
372         if (theClass != null) {\r
373             ctx.setProperty(ServiceContextProperties.ENTITY_CLASS, theClass);\r
374         }\r
375         \r
376         return ctx;\r
377     }\r
378         \r
379     /**\r
380      * Gets the version string.\r
381      * \r
382      * @return the version string\r
383      */\r
384     abstract protected String getVersionString();\r
385     \r
386     /**\r
387      * Gets the version.\r
388      * \r
389      * @return the version\r
390      */\r
391     @GET\r
392     @Path("/version")    \r
393     @Produces("application/xml")\r
394     public Version getVersion() {\r
395         Version result = new Version();\r
396         \r
397         result.setVersionString(getVersionString());\r
398         \r
399         return result;\r
400     }\r
401 \r
402     public void checkResult(Object resultToCheck, String csid, String serviceMessage) throws WebApplicationException {\r
403         if (resultToCheck == null) {\r
404             Response response = Response.status(Response.Status.NOT_FOUND).entity(\r
405                     serviceMessage + "csid=" + csid\r
406                     + ": was not found.").type(\r
407                     "text/plain").build();\r
408             throw new WebApplicationException(response);\r
409         }\r
410     }\r
411 \r
412     protected void ensureCSID(String csid, String crudType) throws WebApplicationException {\r
413         ensureCSID(csid, crudType, "csid");\r
414     }\r
415 \r
416     protected void ensureCSID(String csid, String crudType, String whichCsid) throws WebApplicationException {\r
417            if (logger.isDebugEnabled()) {\r
418                logger.debug(crudType + " for " + getClass().getName() + " with csid=" + csid);\r
419            }\r
420            if (csid == null || "".equals(csid)) {\r
421                logger.error(crudType + " for " + getClass().getName() + " missing csid!");\r
422                Response response = Response.status(Response.Status.BAD_REQUEST).entity(crudType + " failed on " + getClass().getName() + ' '+whichCsid+'=' + csid).type("text/plain").build();\r
423                throw new WebApplicationException(response);\r
424            }\r
425        }\r
426 \r
427     protected WebApplicationException bigReThrow(Exception e, String serviceMsg) throws WebApplicationException {\r
428         return bigReThrow(e, serviceMsg, "");\r
429     }\r
430 \r
431     protected WebApplicationException bigReThrow(Exception e, String serviceMsg, String csid) throws WebApplicationException {\r
432         boolean logException = true;\r
433         WebApplicationException result = null;\r
434         Response response;\r
435         \r
436         String detail = Tools.errorToString(e, true);\r
437         String detailNoTrace = Tools.errorToString(e, true, 3);\r
438         if (e instanceof UnauthorizedException) {\r
439             response = Response.status(Response.Status.UNAUTHORIZED).entity(serviceMsg + e.getMessage()).type("text/plain").build();\r
440             result = new WebApplicationException(response);\r
441 \r
442         } else if (e instanceof DocumentNotFoundException) {\r
443                 //\r
444                 // Don't log this error unless we're in 'trace' mode\r
445                 //\r
446                 logException = false;\r
447             response = Response.status(Response.Status.NOT_FOUND).entity(serviceMsg + " on " + getClass().getName() + " csid=" + csid).type("text/plain").build();\r
448             result = new WebApplicationException(response);\r
449 \r
450         } else if (e instanceof BadRequestException) {\r
451             int code = ((BadRequestException) e).getErrorCode();\r
452             if (code == 0) {\r
453                 code = Response.Status.BAD_REQUEST.getStatusCode();\r
454             }\r
455             // CSPACE-1110\r
456             response = Response.status(code).entity(serviceMsg + e.getMessage()).type("text/plain").build();\r
457             // return new WebApplicationException(e, code);\r
458             result = new WebApplicationException(response);\r
459 \r
460         } else if (e instanceof DocumentException) {\r
461             int code = ((DocumentException) e).getErrorCode();\r
462             if (code == 0){\r
463                code = Response.Status.BAD_REQUEST.getStatusCode();\r
464             }\r
465             // CSPACE-1110\r
466             response = Response.status(code).entity(serviceMsg + e.getMessage()).type("text/plain").build();\r
467             // return new WebApplicationException(e, code);\r
468             result = new WebApplicationException(response);\r
469            \r
470         } else if (e instanceof WebApplicationException) {\r
471             // subresource may have already thrown this exception\r
472             // so just pass it on\r
473             result = (WebApplicationException) e;\r
474 \r
475         } else { // e is now instanceof Exception\r
476             response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(serviceMsg + " detail: " + detailNoTrace).type("text/plain").build();\r
477             result = new WebApplicationException(response);\r
478         }\r
479         //\r
480         // Some exceptions like DocumentNotFoundException won't be logged unless we're in 'trace' mode\r
481         //\r
482         boolean traceEnabled = logger.isTraceEnabled();\r
483         if (logException == true || traceEnabled == true) {\r
484                 if (traceEnabled == true) {\r
485                         logger.error(getClass().getName() + " detail: " + detail, e);\r
486                 } else {\r
487                         logger.error(getClass().getName() + " detail: " + detailNoTrace);\r
488                 }\r
489         }\r
490         \r
491         return result;\r
492     }\r
493 }\r