001/*
002 * Copyright (c) 2006-2011 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 *
009 * Contributors:
010 *     Thierry Delprat
011 */
012package org.nuxeo.ecm.automation.core.operations.services;
013
014import java.io.Serializable;
015import java.util.ArrayList;
016import java.util.HashMap;
017import java.util.List;
018import java.util.Map;
019
020import org.apache.commons.lang.StringUtils;
021import org.apache.commons.logging.Log;
022import org.apache.commons.logging.LogFactory;
023import org.nuxeo.ecm.automation.OperationContext;
024import org.nuxeo.ecm.automation.OperationException;
025import org.nuxeo.ecm.automation.core.Constants;
026import org.nuxeo.ecm.automation.core.annotations.Context;
027import org.nuxeo.ecm.automation.core.annotations.Operation;
028import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
029import org.nuxeo.ecm.automation.core.annotations.Param;
030import org.nuxeo.ecm.automation.core.util.Properties;
031import org.nuxeo.ecm.automation.core.util.RecordSet;
032import org.nuxeo.ecm.automation.core.util.StringList;
033import org.nuxeo.ecm.core.api.CoreSession;
034import org.nuxeo.ecm.core.api.DocumentModel;
035import org.nuxeo.ecm.core.api.SortInfo;
036import org.nuxeo.ecm.core.query.sql.NXQL;
037import org.nuxeo.ecm.platform.query.api.PageProvider;
038import org.nuxeo.ecm.platform.query.api.PageProviderService;
039import org.nuxeo.ecm.platform.query.core.GenericPageProviderDescriptor;
040import org.nuxeo.ecm.platform.query.nxql.CoreQueryAndFetchPageProvider;
041import org.nuxeo.ecm.platform.query.nxql.CoreQueryDocumentPageProvider;
042
043/**
044 * Operation to execute a query or a named provider with support for Pagination
045 *
046 * @author Tiry (tdelprat@nuxeo.com)
047 * @since 5.7
048 */
049@Operation(id = ResultSetPageProviderOperation.ID, category = Constants.CAT_FETCH, label = "QueryAndFetch", description = "Perform "
050        + "a query or a named provider query on the repository. Result is "
051        + "paginated. The result is returned as a RecordSet (QueryAndFetch) "
052        + "rather than as a List of Document"
053        + "The query result will become the input for the next "
054        + "operation. If no query or provider name is given, a query returning "
055        + "all the documents that the user has access to will be executed.", addToStudio = false, aliases = { "Resultset.PageProvider" })
056public class ResultSetPageProviderOperation {
057
058    private static final Log log = LogFactory.getLog(ResultSetPageProviderOperation.class);
059
060    public static final String ID = "Repository.ResultSetPageProvider";
061
062    public static final String CURRENT_USERID_PATTERN = "$currentUser";
063
064    public static final String CURRENT_REPO_PATTERN = "$currentRepository";
065
066    public static final String DESC = "DESC";
067
068    public static final String ASC = "ASC";
069
070    public static final String CMIS = "CMIS";
071
072    @Context
073    protected OperationContext context;
074
075    @Context
076    protected CoreSession session;
077
078    @Context
079    protected PageProviderService ppService;
080
081    @Param(name = "providerName", required = false)
082    protected String providerName;
083
084    /**
085     * @deprecated since 6.0 use instead {@link org.nuxeo.ecm.automation .core.operations.services.query.ResultSetQuery}
086     */
087    @Deprecated
088    @Param(name = "query", required = false)
089    protected String query;
090
091    @Param(name = "language", required = false, widget = Constants.W_OPTION, values = { NXQL.NXQL, CMIS })
092    protected String lang = NXQL.NXQL;
093
094    @Param(name = "page", required = false)
095    protected Integer page;
096
097    @Param(name = "pageSize", required = false)
098    protected Integer pageSize;
099
100    /**
101     * @deprecated since 6.0 use instead {@link #sortBy and @link #sortOrder}
102     */
103    @Deprecated
104    @Param(name = "sortInfo", required = false)
105    protected StringList sortInfoAsStringList;
106
107    @Param(name = "queryParams", required = false)
108    protected StringList strParameters;
109
110    @Param(name = "documentLinkBuilder", required = false)
111    protected String documentLinkBuilder;
112
113    /**
114     * @since 5.7
115     */
116    @Param(name = "maxResults", required = false)
117    protected String maxResults = "100";
118
119    /**
120     * @since 6.0
121     */
122    @Param(name = PageProviderService.NAMED_PARAMETERS, required = false, description = "Named parameters to pass to the page provider to "
123            + "fill in query variables.")
124    protected Properties namedParameters;
125
126    /**
127     * @since 6.0
128     */
129    @Param(name = "sortBy", required = false, description = "Sort by " + "properties (separated by comma)")
130    protected String sortBy;
131
132    /**
133     * @since 6.0
134     */
135    @Param(name = "sortOrder", required = false, description = "Sort order, " + "ASC or DESC", widget = Constants.W_OPTION, values = {
136            ASC, DESC })
137    protected String sortOrder;
138
139    @SuppressWarnings("unchecked")
140    @OperationMethod
141    public RecordSet run() throws OperationException {
142
143        List<SortInfo> sortInfos = null;
144        if (sortInfoAsStringList != null) {
145            sortInfos = new ArrayList<SortInfo>();
146            for (String sortInfoDesc : sortInfoAsStringList) {
147                SortInfo sortInfo;
148                if (sortInfoDesc.contains("|")) {
149                    String[] parts = sortInfoDesc.split("|");
150                    sortInfo = new SortInfo(parts[0], Boolean.parseBoolean(parts[1]));
151                } else {
152                    sortInfo = new SortInfo(sortInfoDesc, true);
153                }
154                sortInfos.add(sortInfo);
155            }
156        } else {
157            // Sort Info Management
158            if (!StringUtils.isBlank(sortBy)) {
159                sortInfos = new ArrayList<>();
160                String[] sorts = sortBy.split(",");
161                String[] orders = null;
162                if (!StringUtils.isBlank(sortOrder)) {
163                    orders = sortOrder.split(",");
164                }
165                for (int i = 0; i < sorts.length; i++) {
166                    String sort = sorts[i];
167                    boolean sortAscending = (orders != null && orders.length > i && "asc".equals(orders[i].toLowerCase()));
168                    sortInfos.add(new SortInfo(sort, sortAscending));
169                }
170            }
171        }
172
173        Object[] parameters = null;
174
175        if (strParameters != null && !strParameters.isEmpty()) {
176            parameters = strParameters.toArray(new String[strParameters.size()]);
177            // expand specific parameters
178            for (int idx = 0; idx < parameters.length; idx++) {
179                String value = (String) parameters[idx];
180                if (value.equals(CURRENT_USERID_PATTERN)) {
181                    parameters[idx] = session.getPrincipal().getName();
182                } else if (value.equals(CURRENT_REPO_PATTERN)) {
183                    parameters[idx] = session.getRepositoryName();
184                }
185            }
186        }
187
188        Map<String, Serializable> props = new HashMap<String, Serializable>();
189        props.put(CoreQueryDocumentPageProvider.CORE_SESSION_PROPERTY, (Serializable) session);
190
191        if (query == null && StringUtils.isEmpty(providerName)) {
192            // provide a defaut query
193            query = "SELECT * from Document";
194        }
195
196        Long targetPage = null;
197        if (page != null) {
198            targetPage = page.longValue();
199        }
200        Long targetPageSize = null;
201        if (pageSize != null) {
202            targetPageSize = pageSize.longValue();
203        }
204
205        DocumentModel searchDocumentModel = DocumentPageProviderOperation.getSearchDocumentModel(session, ppService,
206                providerName, namedParameters);
207
208        final class QueryAndFetchProviderDescriptor extends GenericPageProviderDescriptor {
209            private static final long serialVersionUID = 1L;
210
211            public QueryAndFetchProviderDescriptor() {
212                super();
213                try {
214                    klass = (Class<PageProvider<?>>) Class.forName(CoreQueryAndFetchPageProvider.class.getName());
215                } catch (ClassNotFoundException e) {
216                    log.error(e, e);
217                }
218            }
219        }
220
221        PageProvider<Map<String, Serializable>> pp = null;
222        if (query != null) {
223            QueryAndFetchProviderDescriptor desc = new QueryAndFetchProviderDescriptor();
224            desc.setPattern(query);
225            if (maxResults != null && !maxResults.isEmpty() && !maxResults.equals("-1")) {
226                // set the maxResults to avoid slowing down queries
227                desc.getProperties().put("maxResults", maxResults);
228            }
229            pp = (CoreQueryAndFetchPageProvider) ppService.getPageProvider("", desc, searchDocumentModel, sortInfos,
230                    targetPageSize, targetPage, props, parameters);
231        } else {
232            pp = (PageProvider<Map<String, Serializable>>) ppService.getPageProvider(providerName, searchDocumentModel,
233                    sortInfos, targetPageSize, targetPage, props, parameters);
234        }
235        PaginableRecordSetImpl res = new PaginableRecordSetImpl(pp);
236        if (res.hasError()) {
237            throw new OperationException(res.getErrorMessage());
238        }
239        return res;
240
241    }
242}