001/* 002 * (C) Copyright 2006-2011 Nuxeo SA (http://nuxeo.com/) and others. 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 * 016 * Contributors: 017 * Thierry Delprat 018 * Marwane Kalam-Alami 019 */ 020package org.nuxeo.ecm.automation.core.operations.services; 021 022import java.io.IOException; 023import java.io.Serializable; 024import java.util.ArrayList; 025import java.util.HashMap; 026import java.util.List; 027import java.util.Map; 028 029import javax.el.ELContext; 030import javax.el.ValueExpression; 031 032import org.apache.commons.lang.StringUtils; 033import org.apache.commons.logging.Log; 034import org.apache.commons.logging.LogFactory; 035import org.nuxeo.ecm.automation.OperationContext; 036import org.nuxeo.ecm.automation.OperationException; 037import org.nuxeo.ecm.automation.core.Constants; 038import org.nuxeo.ecm.automation.core.annotations.Context; 039import org.nuxeo.ecm.automation.core.annotations.Operation; 040import org.nuxeo.ecm.automation.core.annotations.OperationMethod; 041import org.nuxeo.ecm.automation.core.annotations.Param; 042import org.nuxeo.ecm.automation.core.util.DocumentHelper; 043import org.nuxeo.ecm.automation.core.util.Properties; 044import org.nuxeo.ecm.automation.core.util.StringList; 045import org.nuxeo.ecm.automation.jaxrs.io.documents.PaginableDocumentModelListImpl; 046import org.nuxeo.ecm.core.api.CoreSession; 047import org.nuxeo.ecm.core.api.DocumentModel; 048import org.nuxeo.ecm.core.api.SortInfo; 049import org.nuxeo.ecm.core.api.impl.SimpleDocumentModel; 050import org.nuxeo.ecm.core.api.model.PropertyNotFoundException; 051import org.nuxeo.ecm.core.query.sql.NXQL; 052import org.nuxeo.ecm.platform.actions.ActionContext; 053import org.nuxeo.ecm.platform.actions.ELActionContext; 054import org.nuxeo.ecm.platform.el.ELService; 055import org.nuxeo.ecm.platform.query.api.PageProvider; 056import org.nuxeo.ecm.platform.query.api.PageProviderDefinition; 057import org.nuxeo.ecm.platform.query.api.PageProviderService; 058import org.nuxeo.ecm.platform.query.core.CoreQueryPageProviderDescriptor; 059import org.nuxeo.ecm.platform.query.nxql.CoreQueryDocumentPageProvider; 060import org.nuxeo.runtime.api.Framework; 061 062/** 063 * Operation to execute a query or a named provider with support for Pagination. 064 * 065 * @author Tiry (tdelprat@nuxeo.com) 066 * @since 5.4.2 067 */ 068@Operation(id = DocumentPageProviderOperation.ID, category = Constants.CAT_FETCH, label = "PageProvider", description = "Perform " 069 + "a query or a named provider query on the repository. Result is " 070 + "paginated. The query result will become the input for the next " 071 + "operation. If no query or provider name is given, a query returning " 072 + "all the documents that the user has access to will be executed.", aliases = { "Document.PageProvider" }) 073public class DocumentPageProviderOperation { 074 075 public static final String ID = "Repository.PageProvider"; 076 077 public static final String CURRENT_USERID_PATTERN = "$currentUser"; 078 079 public static final String CURRENT_REPO_PATTERN = "$currentRepository"; 080 081 private static final String SORT_PARAMETER_SEPARATOR = " "; 082 083 public static final String ASC = "ASC"; 084 085 public static final String DESC = "DESC"; 086 087 private static final Log log = LogFactory.getLog(DocumentPageProviderOperation.class); 088 089 @Context 090 protected OperationContext context; 091 092 @Context 093 protected CoreSession session; 094 095 @Context 096 protected PageProviderService ppService; 097 098 @Param(name = "providerName", required = false) 099 protected String providerName; 100 101 /** 102 * @deprecated since 6.0 use instead {@link org.nuxeo.ecm.automation .core.operations.services.query.DocumentQuery}. 103 */ 104 @Deprecated 105 @Param(name = "query", required = false) 106 protected String query; 107 108 @Param(name = "language", required = false, widget = Constants.W_OPTION, values = { NXQL.NXQL }) 109 protected String lang = NXQL.NXQL; 110 111 @Param(name = "page", required = false) 112 @Deprecated 113 protected Integer page; 114 115 @Param(name = "currentPageIndex", required = false) 116 protected Integer currentPageIndex; 117 118 @Param(name = "pageSize", required = false) 119 protected Integer pageSize; 120 121 /** 122 * @deprecated since 6.0 use instead {@link #sortBy and @link #sortOrder}. 123 */ 124 @Deprecated 125 @Param(name = "sortInfo", required = false) 126 protected StringList sortInfoAsStringList; 127 128 @Param(name = "queryParams", alias = "searchTerm", required = false) 129 protected StringList strParameters; 130 131 @Param(name = "documentLinkBuilder", required = false) 132 protected String documentLinkBuilder; 133 134 /** 135 * @since 5.7 136 */ 137 @Param(name = "maxResults", required = false) 138 protected String maxResults = "100"; 139 140 /** 141 * @since 6.0 142 */ 143 @Param(name = PageProviderService.NAMED_PARAMETERS, required = false, description = "Named parameters to pass to the page provider to " 144 + "fill in query variables.") 145 protected Properties namedParameters; 146 147 /** 148 * @since 6.0 149 */ 150 @Param(name = "sortBy", required = false, description = "Sort by " + "properties (separated by comma)") 151 protected String sortBy; 152 153 /** 154 * @since 7.10 155 */ 156 @Param(name = "quotePatternParameters", required = false, description = "Quote query parameters if the query is specified") 157 protected boolean quotePatternParameters = true; 158 159 /** 160 * @since 7.10 161 */ 162 @Param(name = "escapePatternParameters", required = false, description = "Escape query parameters if the query is specified") 163 protected boolean escapePatternParameters = true; 164 165 /** 166 * @since 6.0 167 */ 168 @Param(name = "sortOrder", required = false, description = "Sort order, " + "ASC or DESC", widget = Constants.W_OPTION, values = { 169 ASC, DESC }) 170 protected String sortOrder; 171 172 @SuppressWarnings("unchecked") 173 @OperationMethod 174 public PaginableDocumentModelListImpl run() throws OperationException { 175 List<SortInfo> sortInfos = null; 176 if (sortInfoAsStringList != null) { 177 // BBB 178 sortInfos = new ArrayList<SortInfo>(); 179 for (String sortInfoDesc : sortInfoAsStringList) { 180 SortInfo sortInfo; 181 if (sortInfoDesc.contains(SORT_PARAMETER_SEPARATOR)) { 182 String[] parts = sortInfoDesc.split(SORT_PARAMETER_SEPARATOR); 183 sortInfo = new SortInfo(parts[0], Boolean.parseBoolean(parts[1])); 184 } else { 185 sortInfo = new SortInfo(sortInfoDesc, true); 186 } 187 sortInfos.add(sortInfo); 188 } 189 } else { 190 // Sort Info Management 191 if (!StringUtils.isBlank(sortBy)) { 192 sortInfos = new ArrayList<>(); 193 String[] sorts = sortBy.split(","); 194 String[] orders = null; 195 if (!StringUtils.isBlank(sortOrder)) { 196 orders = sortOrder.split(","); 197 } 198 for (int i = 0; i < sorts.length; i++) { 199 String sort = sorts[i]; 200 boolean sortAscending = (orders != null && orders.length > i && "asc".equals(orders[i].toLowerCase())); 201 sortInfos.add(new SortInfo(sort, sortAscending)); 202 } 203 } 204 } 205 206 Object[] parameters = null; 207 208 if (strParameters != null && !strParameters.isEmpty()) { 209 parameters = strParameters.toArray(new String[strParameters.size()]); 210 // expand specific parameters 211 for (int idx = 0; idx < parameters.length; idx++) { 212 String value = (String) parameters[idx]; 213 if (value.equals(CURRENT_USERID_PATTERN)) { 214 parameters[idx] = session.getPrincipal().getName(); 215 } else if (value.equals(CURRENT_REPO_PATTERN)) { 216 parameters[idx] = session.getRepositoryName(); 217 } 218 } 219 } 220 221 Map<String, Serializable> props = new HashMap<String, Serializable>(); 222 props.put(CoreQueryDocumentPageProvider.CORE_SESSION_PROPERTY, (Serializable) session); 223 224 if (query == null && StringUtils.isBlank(providerName)) { 225 // provide a defaut query 226 query = "SELECT * from Document"; 227 } 228 229 Long targetPage = null; 230 if (page != null) { 231 targetPage = page.longValue(); 232 } 233 if (currentPageIndex != null) { 234 targetPage = currentPageIndex.longValue(); 235 } 236 Long targetPageSize = null; 237 if (pageSize != null) { 238 targetPageSize = pageSize.longValue(); 239 } 240 241 DocumentModel searchDocumentModel = getSearchDocumentModel(session, ppService, providerName, namedParameters); 242 243 PaginableDocumentModelListImpl res; 244 if (query != null) { 245 CoreQueryPageProviderDescriptor desc = new CoreQueryPageProviderDescriptor(); 246 desc.setPattern(query); 247 desc.setQuotePatternParameters(quotePatternParameters); 248 desc.setEscapePatternParameters(escapePatternParameters); 249 if (maxResults != null && !maxResults.isEmpty() && !maxResults.equals("-1")) { 250 // set the maxResults to avoid slowing down queries 251 desc.getProperties().put("maxResults", maxResults); 252 } 253 PageProvider<DocumentModel> pp = (PageProvider<DocumentModel>) ppService.getPageProvider("", desc, 254 searchDocumentModel, sortInfos, targetPageSize, targetPage, props, parameters); 255 res = new PaginableDocumentModelListImpl(pp, documentLinkBuilder); 256 } else { 257 parameters = resolveParameters(parameters); 258 PageProvider<DocumentModel> pp = (PageProvider<DocumentModel>) ppService.getPageProvider(providerName, 259 searchDocumentModel, sortInfos, targetPageSize, targetPage, props, parameters); 260 res = new PaginableDocumentModelListImpl(pp, documentLinkBuilder); 261 } 262 if (res.hasError()) { 263 throw new OperationException(res.getErrorMessage()); 264 } 265 return res; 266 } 267 268 /** 269 * Resolves additional parameters that could have been defined in the contribution. 270 * 271 * @param parameters parameters from the operation 272 * @since 5.8 273 */ 274 private Object[] resolveParameters(Object[] parameters) { 275 ActionContext actionContext = (ActionContext) context.get(GetActions.SEAM_ACTION_CONTEXT); 276 if (actionContext == null) { 277 // if no Seam Context has been initialized, don't do evaluation 278 return parameters; 279 } 280 281 // resolve additional parameters 282 PageProviderDefinition ppDef = ppService.getPageProviderDefinition(providerName); 283 String[] params = ppDef.getQueryParameters(); 284 if (params == null) { 285 params = new String[0]; 286 } 287 288 Object[] resolvedParams = new Object[params.length + (parameters != null ? parameters.length : 0)]; 289 290 ELContext elContext = Framework.getService(ELService.class).createELContext(); 291 292 int i = 0; 293 if (parameters != null) { 294 i = parameters.length; 295 System.arraycopy(parameters, 0, resolvedParams, 0, i); 296 } 297 for (int j = 0; j < params.length; j++) { 298 ValueExpression ve = ELActionContext.EXPRESSION_FACTORY.createValueExpression(elContext, params[j], 299 Object.class); 300 resolvedParams[i + j] = ve.getValue(elContext); 301 } 302 return resolvedParams; 303 } 304 305 /** 306 * @since 7.1 307 */ 308 public static DocumentModel getSearchDocumentModel(CoreSession session, PageProviderService pps, 309 String providerName, Properties namedParameters) { 310 // generate search document model if type specified on the definition 311 DocumentModel searchDocumentModel = null; 312 if (!StringUtils.isBlank(providerName)) { 313 PageProviderDefinition pageProviderDefinition = pps.getPageProviderDefinition(providerName); 314 if (pageProviderDefinition != null) { 315 String searchDocType = pageProviderDefinition.getSearchDocumentType(); 316 if (searchDocType != null) { 317 searchDocumentModel = session.createDocumentModel(searchDocType); 318 } else if (pageProviderDefinition.getWhereClause() != null) { 319 // avoid later error on null search doc, in case where clause is only referring to named parameters 320 // (and no namedParameters are given) 321 searchDocumentModel = new SimpleDocumentModel(); 322 } 323 } else { 324 log.error("No page provider definition found for " + providerName); 325 } 326 } 327 328 if (namedParameters != null && !namedParameters.isEmpty()) { 329 // fall back on simple document if no type defined on page provider 330 if (searchDocumentModel == null) { 331 searchDocumentModel = new SimpleDocumentModel(); 332 } 333 for (Map.Entry<String, String> entry : namedParameters.entrySet()) { 334 String key = entry.getKey(); 335 String value = entry.getValue(); 336 try { 337 DocumentHelper.setProperty(session, searchDocumentModel, key, value, true); 338 } catch (PropertyNotFoundException | IOException e) { 339 // assume this is a "pure" named parameter, not part of the search doc schema 340 continue; 341 } 342 } 343 searchDocumentModel.putContextData(PageProviderService.NAMED_PARAMETERS, namedParameters); 344 } 345 return searchDocumentModel; 346 } 347 348}