]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
d84be81faae78ffe07fb027c2dd2bf52586c0e54
[tmp/jakarta-migration.git] /
1 /**
2  *  This document is a part of the source code and related artifacts
3  *  for CollectionSpace, an open source collections management system
4  *  for museums and related institutions:
5
6  *  http://www.collectionspace.org
7  *  http://wiki.collectionspace.org
8
9  *  Copyright 2009 University of California at Berkeley
10
11  *  Licensed under the Educational Community License (ECL), Version 2.0.
12  *  You may not use this file except in compliance with this License.
13
14  *  You may obtain a copy of the ECL 2.0 License at
15
16  *  https://source.collectionspace.org/collection-space/LICENSE.txt
17
18  *  Unless required by applicable law or agreed to in writing, software
19  *  distributed under the License is distributed on an "AS IS" BASIS,
20  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21  *  See the License for the specific language governing permissions and
22  *  limitations under the License.
23  */
24 package org.collectionspace.services.common;
25
26 import java.lang.reflect.Method;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30
31 import javax.ws.rs.GET;
32 import javax.ws.rs.Path;
33 import javax.ws.rs.Produces;
34 import javax.ws.rs.core.MultivaluedMap;
35 import javax.ws.rs.core.Response;
36 import javax.ws.rs.core.UriInfo;
37
38 import org.collectionspace.services.common.CSWebApplicationException;
39 import org.collectionspace.services.common.api.Tools;
40 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
41 import org.collectionspace.services.common.context.ServiceContext;
42 import org.collectionspace.services.common.context.ServiceContextProperties;
43 import org.collectionspace.services.common.document.BadRequestException;
44 import org.collectionspace.services.common.document.DocumentException;
45 import org.collectionspace.services.common.document.DocumentHandler;
46 import org.collectionspace.services.common.document.DocumentNotFoundException;
47 import org.collectionspace.services.common.document.TransactionException;
48 import org.collectionspace.services.common.repository.RepositoryClient;
49 import org.collectionspace.services.common.repository.RepositoryClientFactory;
50 import org.collectionspace.services.common.security.UnauthorizedException;
51 import org.collectionspace.services.common.storage.StorageClient;
52 import org.collectionspace.services.common.storage.jpa.JpaStorageClientImpl;
53 import org.collectionspace.services.config.service.ServiceBindingType;
54 import org.jboss.resteasy.core.ResourceMethodInvoker;
55 //import org.jboss.resteasy.core.ResourceMethod;
56 import org.jboss.resteasy.spi.HttpRequest;
57 import org.jboss.resteasy.spi.metadata.ResourceMethod;
58 import org.slf4j.Logger;
59 import org.slf4j.LoggerFactory;
60
61 /**
62  * The Class AbstractCollectionSpaceResourceImpl.
63  *
64  * @param <IT> the generic type
65  * @param <OT> the generic type
66  */
67 public abstract class AbstractCollectionSpaceResourceImpl<IT, OT>
68         implements CollectionSpaceResource<IT, OT> {
69
70     protected final Logger logger = LoggerFactory.getLogger(this.getClass());
71
72     protected final ServiceContext<IT, OT> NULL_CONTEXT = null;
73     // Fields for default client factory and client
74     /** The repository client factory. */
75     private RepositoryClientFactory<IT, OT> repositoryClientFactory;
76     
77     /** The repository client. */
78     private RepositoryClient<IT, OT> repositoryClient;
79     
80     /** The storage client. */
81     private StorageClient storageClient;
82     
83     /**
84      * Extract id.
85      *
86      * @param res the res
87      * @return the string
88      */
89     protected static String extractId(Response res) {
90         MultivaluedMap<String, Object> mvm = res.getMetadata();
91         String uri = (String) ((List<Object>) mvm.get("Location")).get(0);
92         String[] segments = uri.split("/");
93         String id = segments[segments.length - 1];
94         return id;
95     }
96             
97     /**
98      * Instantiates a new abstract collection space resource.
99      */
100     public AbstractCollectionSpaceResourceImpl() {
101         repositoryClientFactory = (RepositoryClientFactory<IT, OT>) RepositoryClientFactory.getInstance();
102     }
103
104     /* (non-Javadoc)
105      * @see org.collectionspace.services.common.CollectionSpaceResource#getServiceName()
106      */
107     @Override
108     abstract public String getServiceName();
109
110
111     /* (non-Javadoc)
112      * @see org.collectionspace.services.common.CollectionSpaceResource#getRepositoryClient(org.collectionspace.services.common.context.ServiceContext)
113      */
114     @Override
115     synchronized public RepositoryClient<IT, OT> getRepositoryClient(ServiceContext<IT, OT> ctx) {
116         if(repositoryClient != null){
117             return repositoryClient;
118         }
119         repositoryClient = repositoryClientFactory.getClient(ctx.getRepositoryClientName());
120         return repositoryClient;
121     }
122
123     /* (non-Javadoc)
124      * @see org.collectionspace.services.common.CollectionSpaceResource#getStorageClient(org.collectionspace.services.common.context.ServiceContext)
125      */
126     @Override
127     synchronized public StorageClient getStorageClient(ServiceContext<IT, OT> ctx) {
128         if(storageClient != null) {
129             return storageClient;
130         }
131         storageClient = new JpaStorageClientImpl();
132         return storageClient;
133     }
134     
135     /* (non-Javadoc)
136      * @see org.collectionspace.services.common.CollectionSpaceResource#createDocumentHandler(org.collectionspace.services.common.context.ServiceContext)
137      */
138     @Override
139     public DocumentHandler createDocumentHandler(ServiceContext<IT, OT> ctx) throws Exception {
140         DocumentHandler docHandler = createDocumentHandler(ctx, ctx.getInput());
141         return docHandler;
142     }
143     
144     /**
145      * Creates the document handler.
146      * 
147      * @param ctx the ctx
148      * @param commonPart the common part
149      * 
150      * @return the document handler
151      * 
152      * @throws Exception the exception
153      */
154     public DocumentHandler createDocumentHandler(ServiceContext<IT, OT> ctx,
155                 Object commonPart) throws Exception {
156         DocumentHandler docHandler = ctx.getDocumentHandler();
157         docHandler.setCommonPart(commonPart);
158         return docHandler;
159     }    
160     
161     /**
162      * Creates the service context.
163      * 
164      * @return the service context< i t, o t>
165      * 
166      * @throws Exception the exception
167      */
168     protected ServiceContext<IT, OT> createServiceContext() throws Exception {          
169         ServiceContext<IT, OT> ctx = createServiceContext(this.getServiceName(),
170                         (IT)null, //inputType
171                         null, // The resource map
172                         (UriInfo)null, // The query params
173                         this.getCommonPartClass());
174         return ctx;
175     }    
176     
177     /**
178      * Creates the service context.
179      * 
180      * @param serviceName the service name
181      * 
182      * @return the service context< i t, o t>
183      * 
184      * @throws Exception the exception
185      */
186     protected ServiceContext<IT, OT> createServiceContext(String serviceName) throws Exception {        
187         ServiceContext<IT, OT> ctx = createServiceContext(
188                         serviceName,
189                         (IT)null, // The input part
190                         null, // The resource map
191                         (UriInfo)null, // The queryParams
192                         (Class<?>)null  /*input type's Class*/);
193         return ctx;
194     }
195     
196     protected ServiceContext<IT, OT> createServiceContext(String serviceName, UriInfo ui) throws Exception {            
197         ServiceContext<IT, OT> ctx = createServiceContext(
198                         serviceName,
199                         (IT)null, // The input part
200                         null, // The resource map
201                         (UriInfo)null, // The queryParams
202                         (Class<?>)null  /*input type's Class*/);
203         ctx.setUriInfo(ui);
204         return ctx;
205     }    
206     
207     /**
208      * Creates the service context.
209      * 
210      * @param serviceName the service name
211      * @param input the input
212      * 
213      * @return the service context< i t, o t>
214      * 
215      * @throws Exception the exception
216      */
217     protected ServiceContext<IT, OT> createServiceContext(String serviceName,
218                 IT input) throws Exception {            
219         ServiceContext<IT, OT> ctx = createServiceContext(serviceName,
220                         input,
221                         null, // The resource map
222                         (UriInfo)null, /*queryParams*/
223                         (Class<?>)null  /*input type's Class*/);
224         return ctx;
225     }
226     
227     protected ServiceContext<IT, OT> createServiceContext(String serviceName,
228                 IT input,
229                 UriInfo uriInfo) throws Exception {     
230         ServiceContext<IT, OT> ctx = createServiceContext(serviceName,
231                         input,
232                         null, // The resource map
233                         uriInfo, /*queryParams*/
234                         (Class<?>)null  /*input type's Class*/);
235         return ctx;
236     }
237     
238     protected ServiceContext<IT, OT> createServiceContext(UriInfo uriInfo) throws Exception {
239         ServiceContext<IT, OT> ctx = createServiceContext(
240                         (IT)null, /*input*/
241                         uriInfo,
242                         (Class<?>)null  /*input type's Class*/);
243         return ctx;
244     }
245
246     /**
247      * Creates the service context.
248      * 
249      * @param input the input
250      * 
251      * @return the service context< i t, o t>
252      * 
253      * @throws Exception the exception
254      */
255     protected ServiceContext<IT, OT> createServiceContext(IT input) throws Exception {          
256         ServiceContext<IT, OT> ctx = createServiceContext(
257                         input,
258                         (Class<?>)null /*input type's Class*/);
259         return ctx;
260     }
261     
262     protected ServiceContext<IT, OT> createServiceContext(IT input, UriInfo uriInfo) throws Exception {         
263         ServiceContext<IT, OT> ctx = createServiceContext(
264                         input,
265                         uriInfo,
266                         null ); // The class param/argument
267         return ctx;
268     }    
269     
270     /**
271      * Creates the service context.
272      * 
273      * @param input the input
274      * @param theClass the the class
275      * 
276      * @return the service context
277      * 
278      * @throws Exception the exception
279      */
280     protected ServiceContext<IT, OT> createServiceContext(IT input, Class<?> theClass) throws Exception {       
281         ServiceContext<IT, OT> ctx = createServiceContext(
282                         input,
283                         (UriInfo)null, //queryParams,
284                         theClass);
285         return ctx;
286     }
287     
288     protected ServiceContext<IT, OT> createServiceContext(IT input, Class<?> theClass, UriInfo uriInfo) throws Exception {      
289         ServiceContext<IT, OT> ctx = createServiceContext(
290                         input,
291                         uriInfo,
292                         theClass);
293         return ctx;
294     }
295     
296     protected ServiceContext<IT, OT> createServiceContext(
297                 String serviceName,
298                 ResourceMap resourceMap,
299                 UriInfo uriInfo) throws Exception {
300         ServiceContext<IT, OT> ctx = createServiceContext(
301                         serviceName,
302                         null, // The input object
303                         resourceMap,
304                         uriInfo,
305                         null /* the class of the input type */);
306         return ctx;
307     }
308         
309     protected ServiceContext<IT, OT> createServiceContext(
310                 IT input,
311                 ResourceMap resourceMap,
312                 UriInfo uriInfo) throws Exception {
313         ServiceContext<IT, OT> ctx = createServiceContext(
314                         this.getServiceName(),
315                         input,
316                         resourceMap,
317                         uriInfo,
318                         null /* the class of the input type */);
319         return ctx;
320     }
321     
322     protected ServiceContext<IT, OT> createServiceContext(
323                 String serviceName,
324                 IT input,
325                 ResourceMap resourceMap,
326                 UriInfo uriInfo) throws Exception {
327         ServiceContext<IT, OT> ctx = createServiceContext(
328                         serviceName,
329                         input,
330                         resourceMap,
331                         uriInfo,
332                         null /* the class of the input type */);
333         return ctx;
334     }
335         
336     /**
337      * Creates the service context.
338      * 
339      * @param input the input
340      * @param queryParams the query params
341      * @param theClass the the class
342      * 
343      * @return the service context< i t, o t>
344      * 
345      * @throws Exception the exception
346      */
347     private ServiceContext<IT, OT> createServiceContext(
348                 IT input,
349                 UriInfo uriInfo,
350                 Class<?> theClass) throws Exception {
351         return createServiceContext(this.getServiceName(),
352                         input,
353                         null, // The resource map
354                         uriInfo,
355                         theClass);
356     }
357
358     /**
359      * Creates the service context.
360      * 
361      * @param serviceName the service name
362      * @param input the input
363      * @param queryParams the query params
364      * @param theClass the the class
365      * 
366      * @return the service context< i t, o t>
367      * 
368      * @throws Exception the exception
369      */
370     private ServiceContext<IT, OT> createServiceContext(
371                 String serviceName,
372                 IT input,
373                 ResourceMap resourceMap,
374                 UriInfo uriInfo,
375                 Class<?> theClass) throws Exception {
376         ServiceContext<IT, OT> ctx = getServiceContextFactory().createServiceContext(
377                         serviceName,
378                         input,
379                         resourceMap,
380                         uriInfo,
381                         theClass != null ? theClass.getPackage().getName() : null,
382                         theClass != null ? theClass.getName() : null);
383         if (theClass != null) {
384             ctx.setProperty(ServiceContextProperties.ENTITY_CLASS, theClass);
385         }
386         
387         return ctx;
388     }
389         
390     /**
391      * Gets the version string.
392      * 
393      * @return the version string
394      */
395     abstract protected String getVersionString();
396     
397     /**
398      * Gets the version.
399      * 
400      * @return the version
401      */
402     @GET
403     @Path("/version")    
404     @Produces("application/xml")
405     public Version getVersion() {
406         Version result = new Version();
407         
408         result.setVersionString(getVersionString());
409         
410         return result;
411     }
412
413     public void checkResult(Object resultToCheck, String csid, String serviceMessage) throws CSWebApplicationException {
414         if (resultToCheck == null) {
415             Response response = Response.status(Response.Status.NOT_FOUND).entity(
416                     serviceMessage + "csid=" + csid
417                     + ": was not found.").type(
418                     "text/plain").build();
419             throw new CSWebApplicationException(response);
420         }
421     }
422
423     protected void ensureCSID(String csid, String crudType) throws CSWebApplicationException {
424         ensureCSID(csid, crudType, "csid");
425     }
426
427     protected void ensureCSID(String csid, String crudType, String whichCsid) throws CSWebApplicationException {
428            if (logger.isDebugEnabled()) {
429                logger.debug(crudType + " for " + getClass().getName() + " with csid=" + csid);
430            }
431            if (csid == null || "".equals(csid)) {
432                logger.error(crudType + " for " + getClass().getName() + " missing csid!");
433                Response response = Response.status(Response.Status.BAD_REQUEST).entity(crudType + " failed on " + getClass().getName() + ' '+whichCsid+'=' + csid).type("text/plain").build();
434                throw new CSWebApplicationException(response);
435            }
436        }
437
438     protected CSWebApplicationException bigReThrow(Exception e, String serviceMsg) throws CSWebApplicationException {
439         return bigReThrow(e, serviceMsg, "");
440     }
441
442     protected CSWebApplicationException bigReThrow(Exception e, String serviceMsg, String csid) throws CSWebApplicationException {
443         boolean logException = true;
444         CSWebApplicationException result = null;
445         Response response;
446         String detail = Tools.errorToString(e, true);
447         String detailNoTrace = Tools.errorToString(e, true, 3);
448         
449         if (e instanceof UnauthorizedException) {
450             response = Response.status(Response.Status.UNAUTHORIZED).entity(serviceMsg + e.getMessage()).type("text/plain").build();
451             result = new CSWebApplicationException(e, response);
452
453         } else if (e instanceof DocumentNotFoundException) {
454                 //
455                 // Don't log this error unless we're in 'trace' mode
456                 //
457                 logException = false;
458             response = Response.status(Response.Status.NOT_FOUND).entity(serviceMsg + " on " + getClass().getName() + " csid=" + csid).type("text/plain").build();
459             result = new CSWebApplicationException(e, response);
460             
461         } else if (e instanceof TransactionException) {
462             int code = ((TransactionException) e).getErrorCode();
463             response = Response.status(code).entity(e.getMessage()).type("text/plain").build();
464             result = new CSWebApplicationException(e, response);
465
466         } else if (e instanceof BadRequestException) {
467             int code = ((BadRequestException) e).getErrorCode();
468             if (code == 0) {
469                 code = Response.Status.BAD_REQUEST.getStatusCode();
470             }
471             // CSPACE-1110
472             response = Response.status(code).entity(serviceMsg + e.getMessage()).type("text/plain").build();
473             // return new WebApplicationException(e, code);
474             result = new CSWebApplicationException(e, response);
475
476         } else if (e instanceof DocumentException) {
477             int code = ((DocumentException) e).getErrorCode();
478             if (code == 0){
479                code = Response.Status.BAD_REQUEST.getStatusCode();
480             }
481             // CSPACE-1110
482             response = Response.status(code).entity(serviceMsg + e.getMessage()).type("text/plain").build();
483             // return new WebApplicationException(e, code);
484             result = new CSWebApplicationException(e, response);
485            
486         } else if (e instanceof CSWebApplicationException) {
487             // subresource may have already thrown this exception
488             // so just pass it on
489             result = (CSWebApplicationException) e;
490
491         } else { // e is now instanceof Exception
492             response = Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(serviceMsg + " detail: " + detailNoTrace).type("text/plain").build();
493             result = new CSWebApplicationException(e, response);
494         }
495         //
496         // Some exceptions like DocumentNotFoundException won't be logged unless we're in 'trace' mode
497         //
498         boolean traceEnabled = logger.isTraceEnabled();
499         if (logException == true || traceEnabled == true) {
500                 if (traceEnabled == true) {
501                         logger.error(getClass().getName() + " detail: " + detail, e);
502                 } else {
503                         logger.error(getClass().getName() + " detail: " + detailNoTrace);
504                 }
505         }
506         
507         return result;
508     }
509     
510         @Override
511         public boolean allowAnonymousAccess(HttpRequest request,
512                         Class<?> resourceClass) {
513                 return false;
514         }
515         
516     /**
517      * Returns a UriRegistry entry: a map of tenant-qualified URI templates
518      * for the current resource, for all tenants
519      * 
520      * @return a map of URI templates for the current resource, for all tenants
521      */
522     public Map<UriTemplateRegistryKey,StoredValuesUriTemplate> getUriRegistryEntries() {
523         Map<UriTemplateRegistryKey,StoredValuesUriTemplate> uriRegistryEntriesMap =
524                 new HashMap<UriTemplateRegistryKey,StoredValuesUriTemplate>();
525         List<String> tenantIds = getTenantBindingsReader().getTenantIds();
526         for (String tenantId : tenantIds) {
527                 uriRegistryEntriesMap.putAll(getUriRegistryEntries(tenantId, getDocType(tenantId), UriTemplateFactory.RESOURCE));
528         }
529         return uriRegistryEntriesMap;
530     }
531     
532     /**
533      * Returns a resource's document type.
534      * 
535      * @param tenantId
536      * @return
537      */
538     @Override
539     public String getDocType(String tenantId) {
540         return getDocType(tenantId, getServiceName());
541     }
542
543     /**
544      * Returns the document type associated with a specified service, within a specified tenant.
545      * 
546      * @param tenantId a tenant ID
547      * @param serviceName a service name
548      * @return the Nuxeo document type associated with that service and tenant.
549      */
550     // FIXME: This method may properly belong in a different services package or class.
551     // Also, we need to check for any existing methods that may duplicate this one.
552     protected String getDocType(String tenantId, String serviceName) {
553         String docType = "";
554         if (Tools.isBlank(tenantId)) {
555             return docType;
556         }
557         ServiceBindingType sb = getTenantBindingsReader().getServiceBinding(tenantId, serviceName);
558         if (sb == null) {
559             return docType;
560         }
561         docType = sb.getObject().getName(); // Reads the Document Type from tenant bindings configuration
562         return docType;
563     }
564
565         /**
566      * Returns a UriRegistry entry: a map of tenant-qualified URI templates
567      * for the current resource, for a specified tenants
568      * 
569      * @return a map of URI templates for the current resource, for a specified tenant
570      */
571     @Override
572     public Map<UriTemplateRegistryKey,StoredValuesUriTemplate> getUriRegistryEntries(String tenantId,
573             String docType, UriTemplateFactory.UriTemplateType type) {
574         Map<UriTemplateRegistryKey,StoredValuesUriTemplate> uriRegistryEntriesMap =
575                 new HashMap<UriTemplateRegistryKey,StoredValuesUriTemplate>();
576         UriTemplateRegistryKey key;
577         if (Tools.isBlank(tenantId) || Tools.isBlank(docType)) {
578             return uriRegistryEntriesMap;
579         }
580         key = new UriTemplateRegistryKey();
581         key.setTenantId(tenantId);
582         key.setDocType(docType); 
583         uriRegistryEntriesMap.put(key, getUriTemplate(type));
584         return uriRegistryEntriesMap;
585     }
586     
587     /**
588      * Returns a URI template of the appropriate type, populated with the
589      * current service name as one of its stored values.
590      *      * 
591      * @param type a URI template type
592      * @return a URI template of the appropriate type.
593      */
594     @Override
595     public StoredValuesUriTemplate getUriTemplate(UriTemplateFactory.UriTemplateType type) {
596         Map<String,String> storedValuesMap = new HashMap<String,String>();
597         storedValuesMap.put(UriTemplateFactory.SERVICENAME_VAR, getServiceName());
598         StoredValuesUriTemplate template =
599                 UriTemplateFactory.getURITemplate(type, storedValuesMap);
600         return template;
601     }
602
603     /**
604      * Returns a reader for reading values from tenant bindings configuration
605      * 
606      * @return a tenant bindings configuration reader
607      */
608     @Override
609     public TenantBindingConfigReaderImpl getTenantBindingsReader() {
610         return ServiceMain.getInstance().getTenantBindingConfigReader();
611     }
612         
613 }