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