]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
ec66b28a20be926dde0ce0803c1bac641f4afdc2
[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                         (MultivaluedMap<String, String>)null, /*queryParams*/\r
163                         this.getCommonPartClass());\r
164         return ctx;\r
165     }    \r
166     \r
167     /**\r
168      * Creates the service context.\r
169      * \r
170      * @param serviceName the service name\r
171      * \r
172      * @return the service context< i t, o t>\r
173      * \r
174      * @throws Exception the exception\r
175      */\r
176     protected ServiceContext<IT, OT> createServiceContext(String serviceName) throws Exception {        \r
177         ServiceContext<IT, OT> ctx = createServiceContext(\r
178                         serviceName,\r
179                         (IT)null, /*input*/\r
180                         (MultivaluedMap<String, String>)null, /*queryParams*/\r
181                         (Class<?>)null  /*input type's Class*/);\r
182         return ctx;\r
183     }\r
184     \r
185     /**\r
186      * Creates the service context.\r
187      * \r
188      * @param serviceName the service name\r
189      * @param input the input\r
190      * \r
191      * @return the service context< i t, o t>\r
192      * \r
193      * @throws Exception the exception\r
194      */\r
195     protected ServiceContext<IT, OT> createServiceContext(String serviceName,\r
196                 IT input) throws Exception {            \r
197         ServiceContext<IT, OT> ctx = createServiceContext(serviceName, input,\r
198                         (MultivaluedMap<String, String>)null, /*queryParams*/\r
199                         (Class<?>)null  /*input type's Class*/);\r
200         return ctx;\r
201     }\r
202     \r
203     /**\r
204      * Creates the service context.\r
205      * \r
206      * @param serviceName the service name\r
207      * @return the service context< i t, o t>\r
208      * @throws Exception the exception\r
209      */\r
210     protected ServiceContext<IT, OT> createServiceContext(String serviceName,\r
211                 MultivaluedMap<String, String> queryParams) throws Exception {          \r
212         ServiceContext<IT, OT> ctx = createServiceContext(serviceName,\r
213                         (IT)null,\r
214                         queryParams,\r
215                         (Class<?>)null  /*input type's Class*/);\r
216         return ctx;\r
217     }    \r
218 \r
219     /**\r
220      * Creates the service context.\r
221      * \r
222      * @param queryParams the query params\r
223      * \r
224      * @return the service context< i t, o t>\r
225      * \r
226      * @throws Exception the exception\r
227      */\r
228     protected ServiceContext<IT, OT> createServiceContext(MultivaluedMap<String, String> queryParams) throws Exception {\r
229         ServiceContext<IT, OT> ctx = createServiceContext(\r
230                         (IT)null, /*input*/\r
231                         queryParams,\r
232                         (Class<?>)null  /*input type's Class*/);\r
233         return ctx;\r
234     }\r
235 \r
236     protected ServiceContext<IT, OT> createServiceContext(UriInfo ui) throws Exception {\r
237         MultivaluedMap<String, String> queryParams = ui.getQueryParameters();\r
238         ServiceContext<IT, OT> ctx = createServiceContext(\r
239                         (IT)null, /*input*/\r
240                         queryParams,\r
241                         (Class<?>)null  /*input type's Class*/);\r
242         return ctx;\r
243     }\r
244 \r
245 \r
246 \r
247         \r
248     /**\r
249      * Creates the service context.\r
250      * \r
251      * @param input the input\r
252      * \r
253      * @return the service context< i t, o t>\r
254      * \r
255      * @throws Exception the exception\r
256      */\r
257     protected ServiceContext<IT, OT> createServiceContext(IT input) throws Exception {          \r
258         ServiceContext<IT, OT> ctx = createServiceContext(\r
259                         input,\r
260                         (Class<?>)null /*input type's Class*/);\r
261         return ctx;\r
262     }\r
263     \r
264     /**\r
265      * Creates the service context.\r
266      * \r
267      * @param input the input\r
268      * @param theClass the the class\r
269      * \r
270      * @return the service context\r
271      * \r
272      * @throws Exception the exception\r
273      */\r
274     protected ServiceContext<IT, OT> createServiceContext(IT input, Class<?> theClass) throws Exception {       \r
275         ServiceContext<IT, OT> ctx = createServiceContext(\r
276                         input,\r
277                         (MultivaluedMap<String, String>)null, //queryParams,\r
278                         theClass);\r
279         return ctx;\r
280     }\r
281     \r
282     protected ServiceContext<IT, OT> createServiceContext(\r
283                 IT input,\r
284                 MultivaluedMap<String, String> queryParams) throws Exception {\r
285         return createServiceContext(this.getServiceName(),\r
286                         input,\r
287                         queryParams,\r
288                         null /* the class of the input type */);\r
289     }\r
290     \r
291     /**\r
292      * Creates the service context.\r
293      * \r
294      * @param input the input\r
295      * @param queryParams the query params\r
296      * @param theClass the the class\r
297      * \r
298      * @return the service context< i t, o t>\r
299      * \r
300      * @throws Exception the exception\r
301      */\r
302     protected ServiceContext<IT, OT> createServiceContext(\r
303                 IT input,\r
304                 MultivaluedMap<String, String> queryParams,\r
305                 Class<?> theClass) throws Exception {\r
306         return createServiceContext(this.getServiceName(),\r
307                         input,\r
308                         queryParams,\r
309                         theClass);\r
310     }\r
311 \r
312     /**\r
313      * Creates the service context.\r
314      * \r
315      * @param serviceName the service name\r
316      * @param input the input\r
317      * @param queryParams the query params\r
318      * @param theClass the the class\r
319      * \r
320      * @return the service context< i t, o t>\r
321      * \r
322      * @throws Exception the exception\r
323      */\r
324     private ServiceContext<IT, OT> createServiceContext(\r
325                 String serviceName,\r
326                 IT input,\r
327                 MultivaluedMap<String, String> queryParams,\r
328                 Class<?> theClass) throws Exception {\r
329         ServiceContext<IT, OT> ctx = getServiceContextFactory().createServiceContext(\r
330                         serviceName,\r
331                         input,\r
332                         queryParams,\r
333                         theClass != null ? theClass.getPackage().getName() : null,\r
334                         theClass != null ? theClass.getName() : null);\r
335         if(theClass != null) {\r
336             ctx.setProperty(ServiceContextProperties.ENTITY_CLASS, theClass);\r
337         }\r
338         return ctx;\r
339     }\r
340         \r
341     /**\r
342      * Gets the version string.\r
343      * \r
344      * @return the version string\r
345      */\r
346     abstract protected String getVersionString();\r
347     \r
348     /**\r
349      * Gets the version.\r
350      * \r
351      * @return the version\r
352      */\r
353     @GET\r
354     @Path("/version")    \r
355     @Produces("application/xml")\r
356     public Version getVersion() {\r
357         Version result = new Version();\r
358         \r
359         result.setVersionString(getVersionString());\r
360         \r
361         return result;\r
362     }\r
363 \r
364     public void checkResult(Object resultToCheck, String csid, String serviceMessage) throws WebApplicationException {\r
365         if (resultToCheck == null) {\r
366             Response response = Response.status(Response.Status.NOT_FOUND).entity(\r
367                     serviceMessage + "csid=" + csid\r
368                     + ": was not found.").type(\r
369                     "text/plain").build();\r
370             throw new WebApplicationException(response);\r
371         }\r
372     }\r
373 \r
374     protected void ensureCSID(String csid, String crudType) throws WebApplicationException {\r
375         ensureCSID(csid, crudType, "csid");\r
376     }\r
377 \r
378     protected void ensureCSID(String csid, String crudType, String whichCsid) throws WebApplicationException {\r
379            if (logger.isDebugEnabled()) {\r
380                logger.debug(crudType + " for " + getClass().getName() + " with csid=" + csid);\r
381            }\r
382            if (csid == null || "".equals(csid)) {\r
383                logger.error(crudType + " for " + getClass().getName() + " missing csid!");\r
384                Response response = Response.status(Response.Status.BAD_REQUEST).entity(crudType + " failed on " + getClass().getName() + ' '+whichCsid+'=' + csid).type("text/plain").build();\r
385                throw new WebApplicationException(response);\r
386            }\r
387        }\r
388 \r
389     protected WebApplicationException bigReThrow(Exception e, String serviceMsg) throws WebApplicationException {\r
390         return bigReThrow(e, serviceMsg, "");\r
391     }\r
392 \r
393     protected WebApplicationException bigReThrow(Exception e, String serviceMsg, String csid) throws WebApplicationException {\r
394         boolean logException = true;\r
395         WebApplicationException result = null;\r
396         Response response;\r
397         \r
398         String detail = Tools.errorToString(e, true);\r
399         String detailNoTrace = Tools.errorToString(e, true, 3);\r
400         if (e instanceof UnauthorizedException) {\r
401             response = Response.status(Response.Status.UNAUTHORIZED).entity(serviceMsg + e.getMessage()).type("text/plain").build();\r
402             result = new WebApplicationException(response);\r
403 \r
404         } else if (e instanceof DocumentNotFoundException) {\r
405                 //\r
406                 // Don't log this error unless we're in 'trace' mode\r
407                 //\r
408                 logException = false;\r
409             response = Response.status(Response.Status.NOT_FOUND).entity(serviceMsg + " on " + getClass().getName() + " csid=" + csid).type("text/plain").build();\r
410             result = new WebApplicationException(response);\r
411 \r
412         } else if (e instanceof BadRequestException) {\r
413             int code = ((BadRequestException) e).getErrorCode();\r
414             if (code == 0) {\r
415                 code = Response.Status.BAD_REQUEST.getStatusCode();\r
416             }\r
417             // CSPACE-1110\r
418             response = Response.status(code).entity(serviceMsg + e.getMessage()).type("text/plain").build();\r
419             // return new WebApplicationException(e, code);\r
420             result = new WebApplicationException(response);\r
421 \r
422         } else if (e instanceof DocumentException) {\r
423             int code = ((DocumentException) e).getErrorCode();\r
424             if (code == 0){\r
425                code = Response.Status.BAD_REQUEST.getStatusCode();\r
426             }\r
427             // CSPACE-1110\r
428             response = Response.status(code).entity(serviceMsg + e.getMessage()).type("text/plain").build();\r
429             // return new WebApplicationException(e, code);\r
430             result = new WebApplicationException(response);\r
431            \r
432         } else if (e instanceof WebApplicationException) {\r
433             // subresource may have already thrown this exception\r
434             // so just pass it on\r
435             result = (WebApplicationException) e;\r
436 \r
437         } else { // e is now instanceof Exception\r
438             response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(serviceMsg + " detail: " + detailNoTrace).type("text/plain").build();\r
439             result = new WebApplicationException(response);\r
440         }\r
441         //\r
442         // Some exceptions like DocumentNotFoundException won't be logged unless we're in 'trace' mode\r
443         //\r
444         boolean traceEnabled = logger.isTraceEnabled();\r
445         if (logException == true || traceEnabled == true) {\r
446                 if (traceEnabled == true) {\r
447                         logger.error(getClass().getName() + " detail: " + detail, e);\r
448                 } else {\r
449                         logger.error(getClass().getName() + " detail: " + detailNoTrace);\r
450                 }\r
451         }\r
452         \r
453         return result;\r
454     }\r
455 }\r