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