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