]> git.aero2k.de Git - tmp/jakarta-migration.git/blob
58febc704fe3d4b3ee128bbcfbe6234cac72714b
[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.servicegroup.nuxeo;
25
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.Iterator;
29 import java.util.List;
30 import java.util.Map;
31
32 import javax.ws.rs.core.Response;
33
34 import org.collectionspace.services.nuxeo.client.java.CommonList;
35 import org.collectionspace.services.nuxeo.client.java.NuxeoDocumentModelHandler;
36 import org.collectionspace.services.nuxeo.client.java.CoreSessionInterface;
37 import org.collectionspace.services.nuxeo.client.java.RepositoryClientImpl;
38 import org.collectionspace.services.nuxeo.util.NuxeoUtils;
39 import org.collectionspace.services.jaxb.AbstractCommonList;
40 import org.collectionspace.services.client.IQueryManager;
41 import org.collectionspace.services.client.PoxPayloadIn;
42 import org.collectionspace.services.client.PoxPayloadOut;
43
44 import org.collectionspace.services.common.NuxeoBasedResource;
45 import org.collectionspace.services.common.CSWebApplicationException;
46 import org.collectionspace.services.common.ServiceMain;
47 import org.collectionspace.services.common.ServiceMessages;
48 import org.collectionspace.services.common.StoredValuesUriTemplate;
49 import org.collectionspace.services.common.UriTemplateFactory;
50 import org.collectionspace.services.common.UriTemplateRegistry;
51 import org.collectionspace.services.common.UriTemplateRegistryKey;
52 import org.collectionspace.services.common.config.TenantBindingConfigReaderImpl;
53 import org.collectionspace.services.common.context.ServiceBindingUtils;
54 import org.collectionspace.services.common.context.ServiceContext;
55 import org.collectionspace.services.common.document.DocumentException;
56 import org.collectionspace.services.common.document.DocumentFilter;
57 import org.collectionspace.services.common.document.DocumentWrapper;
58 import org.collectionspace.services.common.security.SecurityUtils;
59 import org.collectionspace.services.common.query.nuxeo.QueryManagerNuxeoImpl;
60
61 import org.collectionspace.services.config.service.ServiceBindingType;
62 import org.collectionspace.services.config.service.ServiceObjectType;
63 import org.collectionspace.services.servicegroup.ServicegroupsCommon;
64
65 import org.nuxeo.ecm.core.api.DocumentModel;
66 import org.nuxeo.ecm.core.api.DocumentModelList;
67
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70
71 public class ServiceGroupDocumentModelHandler 
72         extends NuxeoDocumentModelHandler<ServicegroupsCommon> {
73         
74     protected final Logger logger = LoggerFactory.getLogger(this.getClass());
75     
76     protected static final int NUM_META_FIELDS = 3;
77     protected static final String DOC_TYPE_FIELD = "docType";
78     protected static final String DOC_NUMBER_FIELD = "docNumber";
79     protected static final String DOC_NAME_FIELD = "docName";
80
81     public PoxPayloadOut getItemForCsid(ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
82                 List<String> serviceGroupNames,
83                 String csid) throws DocumentException {
84         PoxPayloadOut result = null;
85         CoreSessionInterface repoSession = null;
86         boolean releaseRepoSession = false;
87         
88         try { 
89                 RepositoryClientImpl repoClient = (RepositoryClientImpl)this.getRepositoryClient(ctx);
90                 repoSession = this.getRepositorySession();
91                 if (repoSession == null) {
92                         repoSession = repoClient.getRepositorySession(ctx);
93                         releaseRepoSession = true;
94                 }
95                 try {
96                 Map<String, ServiceBindingType> queriedServiceBindings = new HashMap<String, ServiceBindingType>();
97                 DocumentModelList docList = this.getDocListForGroup(ctx, serviceGroupNames, queriedServiceBindings,
98                                 repoSession, repoClient);
99                 if (docList == null) { // found no authRef fields - nothing to process
100                     //return list;
101                 }
102                 DocumentModel docModel = docList.get(0);
103                 TenantBindingConfigReaderImpl bindingReader = ServiceMain.getInstance().getTenantBindingConfigReader();
104                 String serviceName = ServiceBindingUtils.getServiceNameFromObjectName(bindingReader, ctx.getTenantId(),
105                                 docModel.getDocumentType().getName());
106                 NuxeoBasedResource resource = (NuxeoBasedResource) ctx.getResourceMap().get(serviceName);
107                 resource.hashCode();
108
109                 } catch (DocumentException de) {
110                         throw de;
111                 } catch (Exception e) {
112                         if (logger.isDebugEnabled()) {
113                                 logger.debug("Caught exception ", e);
114                         }
115                         throw new DocumentException(e);
116                 } finally {
117                         if (releaseRepoSession && repoSession != null) {
118                                 repoClient.releaseRepositorySession(ctx, repoSession);
119                         }
120                 }
121         } catch (Exception e) {
122                 if (logger.isDebugEnabled()) {
123                         logger.debug("Caught exception ", e);
124                 }
125                 throw new DocumentException(e);
126         }
127         
128         return result;
129     }
130     
131     private DocumentModelList getDocListForGroup(
132                 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
133                 List<String> serviceGroupNames,
134                 Map<String, ServiceBindingType> queriedServiceBindings,
135                 CoreSessionInterface repoSession,
136                 RepositoryClientImpl repoClient) throws Exception {
137         
138         RepositoryClientImpl nuxeoRepoClient = (RepositoryClientImpl)repoClient;
139         // Get the service bindings for this tenant
140         TenantBindingConfigReaderImpl tReader = ServiceMain.getInstance().getTenantBindingConfigReader();
141         // We need to get all the procedures, authorities, and objects.
142         List<ServiceBindingType> servicebindings = 
143                         tReader.getServiceBindingsByType(ctx.getTenantId(), serviceGroupNames);
144         if (servicebindings == null || servicebindings.isEmpty()) {
145             Response response = Response.status(Response.Status.NOT_FOUND).entity(
146                     ServiceMessages.READ_FAILED + 
147                     ServiceMessages.resourceNotFoundMsg(implode(serviceGroupNames, ","))).type("text/plain").build();
148             throw new CSWebApplicationException(response);
149         }
150         
151         servicebindings = SecurityUtils.getReadableServiceBindingsForCurrentUser(servicebindings);
152         // Build the list of docTypes for allowed serviceBindings
153         ArrayList<String> docTypes = new ArrayList<String>();
154         for(ServiceBindingType binding:servicebindings) {
155                 ServiceObjectType serviceObj = binding.getObject();
156                 if(serviceObj!=null) {
157                 String docType = serviceObj.getName();
158                         docTypes.add(docType);
159                 queriedServiceBindings.put(docType, binding);
160                 }
161         }
162         
163         // This should be type "Document" but CMIS is gagging on that right now.
164         ctx.getQueryParams().add(IQueryManager.SELECT_DOC_TYPE_FIELD, QueryManagerNuxeoImpl.COLLECTIONSPACE_DOCUMENT_TYPE);
165         
166         // Now we have to issue the search
167         // The findDocs() method will build a QueryContext, which wants to see a docType for our context
168         ctx.setDocumentType(QueryManagerNuxeoImpl.NUXEO_DOCUMENT_TYPE);
169         DocumentWrapper<DocumentModelList> docListWrapper = 
170                         nuxeoRepoClient.findDocs(ctx, this, repoSession, docTypes );
171         // Now we gather the info for each document into the list and return
172         DocumentModelList docList = docListWrapper.getWrappedObject();
173         
174         return docList;
175     }
176     
177     public AbstractCommonList getItemListForGroup(
178                 ServiceContext<PoxPayloadIn, PoxPayloadOut> ctx,
179                 List<String> serviceGroupNames) throws Exception {
180         CommonList commonList = new CommonList();
181         AbstractCommonList list = (AbstractCommonList)commonList;
182         CoreSessionInterface repoSession = null;
183         boolean releaseRepoSession = false;
184         
185         try { 
186             DocumentFilter myFilter = getDocumentFilter();
187                 int pageSize = myFilter.getPageSize();
188                 int pageNum = myFilter.getStartPage();
189                 list.setPageNum(pageNum);
190                 list.setPageSize(pageSize);
191
192                 RepositoryClientImpl repoClient = (RepositoryClientImpl)this.getRepositoryClient(ctx);
193                 repoSession = this.getRepositorySession();
194                 if (repoSession == null) {
195                         repoSession = repoClient.getRepositorySession(ctx);
196                         releaseRepoSession = true;
197                 }
198                 try {
199                 Map<String, ServiceBindingType> queriedServiceBindings = new HashMap<String, ServiceBindingType>();
200                 DocumentModelList docList = this.getDocListForGroup(ctx, serviceGroupNames, queriedServiceBindings,
201                                 repoSession, repoClient);
202                 if (docList == null) { // found no authRef fields - nothing to process
203                     return list;
204                 }
205                 processDocList(ctx.getTenantId(), docList, queriedServiceBindings, commonList);
206                 list.setItemsInPage(docList.size());
207                 list.setTotalItems(docList.totalSize());
208                 } catch (DocumentException de) {
209                         throw de;
210                 } catch (Exception e) {
211                         if (logger.isDebugEnabled()) {
212                                 logger.debug("Caught exception ", e);
213                         }
214                         throw new DocumentException(e);
215                 } finally {
216                         if (releaseRepoSession && repoSession != null) {
217                                 repoClient.releaseRepositorySession(ctx, repoSession);
218                         }
219                 }
220         } catch (Exception e) {
221                 if (logger.isDebugEnabled()) {
222                         logger.debug("Caught exception ", e);
223                 }
224                 throw new DocumentException(e);
225         }
226         
227         return list;
228     }
229     
230     // Move this to a Utils class!
231     public static String implode(List<String> stringList, String sep) {
232         StringBuilder sb = new StringBuilder();
233         
234         boolean fFirst = false;
235         for (String name:stringList) {
236                 if(fFirst) {
237                         fFirst = false;
238                 } else {
239                         sb.append(sep);
240                 }
241                 sb.append(name);
242         }
243         
244         return sb.toString();
245     }
246     
247     private String getUriFromServiceBinding(ServiceBindingType sb, String csid) {
248         return "/" + sb.getName().toLowerCase() + "/" + csid;
249     }
250     
251     private void processDocList(String tenantId,
252                         DocumentModelList docList,
253                         Map<String, ServiceBindingType> queriedServiceBindings,
254                         CommonList list) {
255         String fields[] = new String[NUM_META_FIELDS + NUM_STANDARD_LIST_RESULT_FIELDS];
256         fields[0] = STANDARD_LIST_CSID_FIELD;
257         fields[1] = STANDARD_LIST_URI_FIELD;
258         fields[2] = STANDARD_LIST_UPDATED_AT_FIELD;
259         fields[3] = STANDARD_LIST_WORKFLOW_FIELD;
260         fields[4] = STANDARD_LIST_REFNAME_FIELD;
261         fields[5] = DOC_NAME_FIELD;
262         fields[6] = DOC_NUMBER_FIELD;
263         fields[7] = DOC_TYPE_FIELD;
264         list.setFieldsReturned(fields);
265         
266         Iterator<DocumentModel> iter = docList.iterator();
267                 HashMap<String, Object> item = new HashMap<String, Object>();
268         while (iter.hasNext()) {
269             DocumentModel docModel = iter.next();
270             String docType = docModel.getDocumentType().getName();
271             docType = ServiceBindingUtils.getUnqualifiedTenantDocType(docType);
272             ServiceBindingType sb = queriedServiceBindings.get(docType);
273             if (sb == null) {
274                 throw new RuntimeException(
275                         "processDocList: No Service Binding for docType: " + docType);
276             }
277             
278             String csid = NuxeoUtils.getCsid(docModel);
279             item.put(STANDARD_LIST_CSID_FIELD, csid);
280                         
281             UriTemplateRegistry uriTemplateRegistry = ServiceMain.getInstance().getUriTemplateRegistry();            
282             StoredValuesUriTemplate storedValuesResourceTemplate = uriTemplateRegistry.get(new UriTemplateRegistryKey(tenantId, docType));
283                     Map<String, String> additionalValues = new HashMap<String, String>();
284                     if (storedValuesResourceTemplate.getUriTemplateType() == UriTemplateFactory.ITEM) {
285                 try {
286                     String inAuthorityCsid = (String) NuxeoUtils.getProperyValue(docModel, "inAuthority"); //docModel.getPropertyValue("inAuthority"); // AuthorityItemJAXBSchema.IN_AUTHORITY
287                     additionalValues.put(UriTemplateFactory.IDENTIFIER_VAR, inAuthorityCsid);
288                     additionalValues.put(UriTemplateFactory.ITEM_IDENTIFIER_VAR, csid);
289                 } catch (Exception e) {
290                         String msg = String.format("Could not extract inAuthority property from authority item with CSID = ", docModel.getName());
291                     logger.warn(msg, e);
292                 }
293                     } else {
294                 additionalValues.put(UriTemplateFactory.IDENTIFIER_VAR, csid);
295             }
296                     
297             String uriStr = storedValuesResourceTemplate.buildUri(additionalValues);
298             item.put(STANDARD_LIST_URI_FIELD, uriStr);
299             try {
300                 item.put(STANDARD_LIST_UPDATED_AT_FIELD, getUpdatedAtAsString(docModel));
301                 item.put(STANDARD_LIST_WORKFLOW_FIELD, docModel.getCurrentLifeCycleState());
302                 item.put(STANDARD_LIST_REFNAME_FIELD, getRefname(docModel));
303             } catch(Exception e) {
304                 logger.error("Error getting core values for doc ["+csid+"]: "+e.getLocalizedMessage());
305             }
306
307             String value = ServiceBindingUtils.getMappedFieldInDoc(sb, ServiceBindingUtils.OBJ_NUMBER_PROP, docModel);
308             if (value != null) {
309                 item.put(DOC_NUMBER_FIELD, value);
310             }
311             
312             value = ServiceBindingUtils.getMappedFieldInDoc(sb, ServiceBindingUtils.OBJ_NAME_PROP, docModel);
313             if (value != null) {
314                 item.put(DOC_NAME_FIELD, value);
315             }
316             
317             item.put(DOC_TYPE_FIELD, docType);
318             // add the item to the list
319             list.addItem(item);
320             item.clear();
321         }
322     }
323 }
324