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