001/*
002 * (C) Copyright 2006-2014 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 *      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.lang.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 " + "operation.", since = "6.0", addToStudio = true, aliases = { "Document.Query" })
056public class DocumentPaginatedQuery {
057
058    public static final String ID = "Repository.Query";
059
060    public static final String CURRENT_USERID_PATTERN = "$currentUser";
061
062    public static final String CURRENT_REPO_PATTERN = "$currentRepository";
063
064    public static final String DESC = "DESC";
065
066    public static final String ASC = "ASC";
067
068    @Context
069    protected CoreSession session;
070
071    @Context
072    protected PageProviderService pageProviderService;
073
074    @Param(name = "query", required = true, description = "The query to " + "perform.")
075    protected String query;
076
077    @Param(name = "language", required = false, description = "The query " + "language.", widget = Constants.W_OPTION, values = { NXQL.NXQL })
078    protected String lang = NXQL.NXQL;
079
080    @Param(name = "currentPageIndex", required = false, description = "Target listing page.")
081    protected Integer currentPageIndex;
082
083    @Param(name = "pageSize", required = false, description = "Entries number" + " per page.")
084    protected Integer pageSize;
085
086    @Param(name = "queryParams", required = false, description = "Ordered " + "query parameters.")
087    protected StringList strParameters;
088
089    @Param(name = "sortBy", required = false, description = "Sort by " + "properties (separated by comma)")
090    protected String sortBy;
091
092    @Param(name = "sortOrder", required = false, description = "Sort order, " + "ASC or DESC", widget = Constants.W_OPTION, values = {
093            ASC, DESC })
094    protected String sortOrder;
095
096    @Param(name = PageProviderService.NAMED_PARAMETERS, required = false, description = "Named parameters to pass to the page provider to "
097            + "fill in query variables.")
098    protected Properties namedParameters;
099
100    @SuppressWarnings("unchecked")
101    @OperationMethod
102    public DocumentModelList run() throws OperationException {
103        // Ordered parameters
104        Object[] orderedParameters = null;
105        if (strParameters != null && !strParameters.isEmpty()) {
106            orderedParameters = strParameters.toArray(new String[strParameters.size()]);
107            // expand specific parameters
108            for (int idx = 0; idx < orderedParameters.length; idx++) {
109                String value = (String) orderedParameters[idx];
110                if (value.equals(CURRENT_USERID_PATTERN)) {
111                    orderedParameters[idx] = session.getPrincipal().getName();
112                } else if (value.equals(CURRENT_REPO_PATTERN)) {
113                    orderedParameters[idx] = session.getRepositoryName();
114                }
115            }
116        }
117        // Target query page
118        Long targetPage = null;
119        if (currentPageIndex != null) {
120            targetPage = currentPageIndex.longValue();
121        }
122        // Target page size
123        Long targetPageSize = null;
124        if (pageSize != null) {
125            targetPageSize = pageSize.longValue();
126        }
127
128        // Sort Info Management
129        List<SortInfo> sortInfoList = new ArrayList<>();
130        if (!StringUtils.isBlank(sortBy)) {
131            String[] sorts = sortBy.split(",");
132            String[] orders = null;
133            if (!StringUtils.isBlank(sortOrder)) {
134                orders = sortOrder.split(",");
135            }
136            for (int i = 0; i < sorts.length; i++) {
137                String sort = sorts[i];
138                boolean sortAscending = (orders != null && orders.length > i && "asc".equals(orders[i].toLowerCase()));
139                sortInfoList.add(new SortInfo(sort, sortAscending));
140            }
141        }
142
143        Map<String, Serializable> props = new HashMap<String, Serializable>();
144        props.put(CoreQueryDocumentPageProvider.CORE_SESSION_PROPERTY, (Serializable) session);
145        DocumentModel searchDocumentModel = getSearchDocumentModel(session, namedParameters);
146        CoreQueryPageProviderDescriptor desc = new CoreQueryPageProviderDescriptor();
147        desc.setPattern(query);
148        PaginableDocumentModelListImpl res = new PaginableDocumentModelListImpl(
149                (PageProvider<DocumentModel>) pageProviderService.getPageProvider(StringUtils.EMPTY, desc,
150                        searchDocumentModel, sortInfoList, targetPageSize, targetPage, props, orderedParameters), null);
151        if (res.hasError()) {
152            throw new OperationException(res.getErrorMessage());
153        }
154        return res;
155
156    }
157
158    /**
159     * @since 8.2
160     */
161    public static DocumentModel getSearchDocumentModel(CoreSession session, Properties namedParameters) {
162        SimpleDocumentModel searchDocumentModel = new SimpleDocumentModel();
163        if (namedParameters != null && !namedParameters.isEmpty()) {
164            for (Map.Entry<String, String> entry : namedParameters.entrySet()) {
165                String key = entry.getKey();
166                String value = entry.getValue();
167                try {
168                    DocumentHelper.setProperty(session, searchDocumentModel, key, value, true);
169                } catch (PropertyNotFoundException | IOException e) {
170                    // assume this is a "pure" named parameter, not part of the search doc schema
171                    continue;
172                }
173            }
174            searchDocumentModel.putContextData(PageProviderService.NAMED_PARAMETERS, namedParameters);
175        }
176        return searchDocumentModel;
177    }
178}