001/*
002 * (C) Copyright 2006-2018 Nuxeo (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 *      Vladimir Pasquier <vpasquier@nuxeo.com>
018 */
019package org.nuxeo.ecm.automation.core.operations.services.query;
020
021import java.io.IOException;
022import java.io.Serializable;
023import java.util.ArrayList;
024import java.util.HashMap;
025import java.util.List;
026import java.util.Map;
027
028import org.apache.commons.lang3.StringUtils;
029import org.nuxeo.ecm.automation.OperationException;
030import org.nuxeo.ecm.automation.core.Constants;
031import org.nuxeo.ecm.automation.core.annotations.Context;
032import org.nuxeo.ecm.automation.core.annotations.Operation;
033import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
034import org.nuxeo.ecm.automation.core.annotations.Param;
035import org.nuxeo.ecm.automation.core.util.DocumentHelper;
036import org.nuxeo.ecm.automation.core.util.Properties;
037import org.nuxeo.ecm.automation.core.util.StringList;
038import org.nuxeo.ecm.automation.jaxrs.io.documents.PaginableDocumentModelListImpl;
039import org.nuxeo.ecm.core.api.CoreSession;
040import org.nuxeo.ecm.core.api.DocumentModel;
041import org.nuxeo.ecm.core.api.DocumentModelList;
042import org.nuxeo.ecm.core.api.SortInfo;
043import org.nuxeo.ecm.core.api.impl.SimpleDocumentModel;
044import org.nuxeo.ecm.core.api.model.PropertyNotFoundException;
045import org.nuxeo.ecm.core.query.sql.NXQL;
046import org.nuxeo.ecm.platform.query.api.PageProvider;
047import org.nuxeo.ecm.platform.query.api.PageProviderService;
048import org.nuxeo.ecm.platform.query.core.CoreQueryPageProviderDescriptor;
049import org.nuxeo.ecm.platform.query.nxql.CoreQueryDocumentPageProvider;
050
051/**
052 * @since 6.0 Document query operation to perform queries on the repository.
053 */
054@Operation(id = DocumentPaginatedQuery.ID, category = Constants.CAT_FETCH, label = "Query", description = "Perform a query on the repository. "
055        + "The document list returned will become the input for the next "
056        + "operation.", since = "6.0", addToStudio = true, aliases = { "Document.Query" })
057public class DocumentPaginatedQuery {
058
059    public static final String ID = "Repository.Query";
060
061    public static final String CURRENT_USERID_PATTERN = "$currentUser";
062
063    public static final String CURRENT_REPO_PATTERN = "$currentRepository";
064
065    public static final String DESC = "DESC";
066
067    public static final String ASC = "ASC";
068
069    @Context
070    protected CoreSession session;
071
072    @Context
073    protected PageProviderService pageProviderService;
074
075    @Param(name = "query", required = true, description = "The query to " + "perform.")
076    protected String query;
077
078    @Param(name = "language", required = false, description = "The query "
079            + "language.", widget = Constants.W_OPTION, values = { NXQL.NXQL })
080    protected String lang = NXQL.NXQL;
081
082    @Param(name = "currentPageIndex", required = false, description = "Target listing page.")
083    protected Integer currentPageIndex;
084
085    @Param(name = "pageSize", required = false, description = "Entries number" + " per page.")
086    protected Integer pageSize;
087
088    @Param(name = "queryParams", required = false, description = "Ordered " + "query parameters.")
089    protected StringList strParameters;
090
091    @Param(name = "sortBy", required = false, description = "Sort by " + "properties (separated by comma)")
092    protected String sortBy;
093
094    @Param(name = "sortOrder", required = false, description = "Sort order, "
095            + "ASC or DESC", widget = Constants.W_OPTION, values = { ASC, DESC })
096    protected String sortOrder;
097
098    @Param(name = PageProviderService.NAMED_PARAMETERS, required = false, description = "Named parameters to pass to the page provider to "
099            + "fill in query variables.")
100    protected Properties namedParameters;
101
102    @SuppressWarnings("unchecked")
103    @OperationMethod
104    public DocumentModelList run() throws OperationException {
105        // Ordered parameters
106        Object[] orderedParameters = null;
107        if (strParameters != null && !strParameters.isEmpty()) {
108            orderedParameters = strParameters.toArray(new String[strParameters.size()]);
109            // expand specific parameters
110            for (int idx = 0; idx < orderedParameters.length; idx++) {
111                String value = (String) orderedParameters[idx];
112                if (value.equals(CURRENT_USERID_PATTERN)) {
113                    orderedParameters[idx] = session.getPrincipal().getName();
114                } else if (value.equals(CURRENT_REPO_PATTERN)) {
115                    orderedParameters[idx] = session.getRepositoryName();
116                }
117            }
118        }
119        // Target query page
120        Long targetPage = null;
121        if (currentPageIndex != null) {
122            targetPage = currentPageIndex.longValue();
123        }
124        // Target page size
125        Long targetPageSize = null;
126        if (pageSize != null) {
127            targetPageSize = pageSize.longValue();
128        }
129
130        // Sort Info Management
131        List<SortInfo> sortInfoList = new ArrayList<>();
132        if (!StringUtils.isBlank(sortBy)) {
133            String[] sorts = sortBy.split(",");
134            String[] orders = null;
135            if (!StringUtils.isBlank(sortOrder)) {
136                orders = sortOrder.split(",");
137            }
138            for (int i = 0; i < sorts.length; i++) {
139                String sort = sorts[i];
140                boolean sortAscending = (orders != null && orders.length > i && "asc".equals(orders[i].toLowerCase()));
141                sortInfoList.add(new SortInfo(sort, sortAscending));
142            }
143        }
144
145        Map<String, Serializable> props = new HashMap<String, Serializable>();
146        props.put(CoreQueryDocumentPageProvider.CORE_SESSION_PROPERTY, (Serializable) session);
147        DocumentModel searchDocumentModel = getSearchDocumentModel(session, namedParameters);
148        CoreQueryPageProviderDescriptor desc = new CoreQueryPageProviderDescriptor();
149        desc.setPattern(query);
150        PaginableDocumentModelListImpl res = new PaginableDocumentModelListImpl(
151                (PageProvider<DocumentModel>) pageProviderService.getPageProvider(StringUtils.EMPTY, desc,
152                        searchDocumentModel, sortInfoList, targetPageSize, targetPage, props, orderedParameters),
153                null);
154        if (res.hasError()) {
155            throw new OperationException(res.getErrorMessage());
156        }
157        return res;
158
159    }
160
161    /**
162     * @since 8.2
163     */
164    public static DocumentModel getSearchDocumentModel(CoreSession session, Properties namedParameters) {
165        SimpleDocumentModel searchDocumentModel = new SimpleDocumentModel();
166        if (namedParameters != null && !namedParameters.isEmpty()) {
167            for (Map.Entry<String, String> entry : namedParameters.entrySet()) {
168                String key = entry.getKey();
169                String value = entry.getValue();
170                try {
171                    DocumentHelper.setProperty(session, searchDocumentModel, key, value, true);
172                } catch (PropertyNotFoundException | IOException e) {
173                    // assume this is a "pure" named parameter, not part of the search doc schema
174                    continue;
175                }
176            }
177            searchDocumentModel.putContextData(PageProviderService.NAMED_PARAMETERS, namedParameters);
178        }
179        return searchDocumentModel;
180    }
181}