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.Serializable;
022import java.util.ArrayList;
023import java.util.HashMap;
024import java.util.List;
025import java.util.Map;
026
027import org.apache.commons.lang.StringUtils;
028import org.nuxeo.ecm.automation.OperationException;
029import org.nuxeo.ecm.automation.core.Constants;
030import org.nuxeo.ecm.automation.core.annotations.Context;
031import org.nuxeo.ecm.automation.core.annotations.Operation;
032import org.nuxeo.ecm.automation.core.annotations.OperationMethod;
033import org.nuxeo.ecm.automation.core.annotations.Param;
034import org.nuxeo.ecm.automation.core.operations.services.PaginableRecordSetImpl;
035import org.nuxeo.ecm.automation.core.util.Properties;
036import org.nuxeo.ecm.automation.core.util.RecordSet;
037import org.nuxeo.ecm.automation.core.util.StringList;
038import org.nuxeo.ecm.core.api.CoreSession;
039import org.nuxeo.ecm.core.api.DocumentModel;
040import org.nuxeo.ecm.core.api.SortInfo;
041import org.nuxeo.ecm.core.query.sql.NXQL;
042import org.nuxeo.ecm.platform.query.api.PageProvider;
043import org.nuxeo.ecm.platform.query.api.PageProviderService;
044import org.nuxeo.ecm.platform.query.core.GenericPageProviderDescriptor;
045import org.nuxeo.ecm.platform.query.nxql.CoreQueryAndFetchPageProvider;
046import org.nuxeo.ecm.platform.query.nxql.CoreQueryDocumentPageProvider;
047
048/**
049 * @since 6.0 Result set query operation to perform queries on the repository.
050 */
051@Operation(id = ResultSetPaginatedQuery.ID, category = Constants.CAT_FETCH, label = "ResultSet Query", description = "Perform a query on the "
052        + "repository. The result set returned will become the input for the " + "next operation.", since = "6.0", addToStudio = true, aliases = { "ResultSet.PaginatedQuery" })
053public class ResultSetPaginatedQuery {
054
055    public static final String ID = "Repository.ResultSetQuery";
056
057    public static final String CURRENT_USERID_PATTERN = "$currentUser";
058
059    public static final String CURRENT_REPO_PATTERN = "$currentRepository";
060
061    public static final String ASC = "ASC";
062
063    public static final String DESC = "DESC";
064
065    public static final String CMIS = "CMIS";
066
067    @Context
068    protected CoreSession session;
069
070    @Context
071    protected PageProviderService pageProviderService;
072
073    @Param(name = "query", required = true, description = "The query to " + "perform.")
074    protected String query;
075
076    @Param(name = "language", required = false, description = "The query " + "language.", widget = Constants.W_OPTION, values = {
077            NXQL.NXQL, CMIS })
078    protected String lang = NXQL.NXQL;
079
080    @Param(name = PageProviderService.NAMED_PARAMETERS, required = false, description = "Named parameters to pass to the page provider to "
081            + "fill in query variables.")
082    protected Properties namedParameters;
083
084    @Param(name = "currentPageIndex", required = false, description = "Target listing page.")
085    protected Integer currentPageIndex;
086
087    @Param(name = "pageSize", required = false, description = "Entries number" + " per page.")
088    protected Integer pageSize;
089
090    @Param(name = "queryParams", required = false, description = "Ordered " + "query parameters.")
091    protected StringList strParameters;
092
093    @Param(name = "sortBy", required = false, description = "Sort by " + "properties (separated by comma)")
094    protected String sortBy;
095
096    @Param(name = "sortOrder", required = false, description = "Sort order, " + "ASC or DESC", widget = Constants.W_OPTION, values = {
097            ASC, DESC })
098    protected String sortOrder;
099
100    @SuppressWarnings("unchecked")
101    @OperationMethod
102    public RecordSet 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
118        // Target query page
119        Long targetPage = null;
120        if (currentPageIndex != null) {
121            targetPage = currentPageIndex.longValue();
122        }
123        // Target page size
124        Long targetPageSize = null;
125        if (pageSize != null) {
126            targetPageSize = pageSize.longValue();
127        }
128
129        // Sort Info Management
130        List<SortInfo> sortInfoList = new ArrayList<>();
131        if (!StringUtils.isBlank(sortBy)) {
132            String[] sorts = sortBy.split(",");
133            String[] orders = null;
134            if (!StringUtils.isBlank(sortOrder)) {
135                orders = sortOrder.split(",");
136            }
137            for (int i = 0; i < sorts.length; i++) {
138                String sort = sorts[i];
139                boolean sortAscending = (orders != null && orders.length > i && "asc".equals(orders[i].toLowerCase()));
140                sortInfoList.add(new SortInfo(sort, sortAscending));
141            }
142        }
143
144        Map<String, Serializable> props = new HashMap<String, Serializable>();
145        props.put(CoreQueryDocumentPageProvider.CORE_SESSION_PROPERTY, (Serializable) session);
146        DocumentModel searchDocumentModel = DocumentPaginatedQuery.getSearchDocumentModel(session, namedParameters);
147        QueryAndFetchProviderDescriptor desc = new QueryAndFetchProviderDescriptor();
148        desc.setPattern(query);
149        PageProvider<Map<String, Serializable>> pp = (PageProvider<Map<String, Serializable>>) pageProviderService.getPageProvider(
150                StringUtils.EMPTY, desc, searchDocumentModel, sortInfoList, targetPageSize, targetPage, props,
151                orderedParameters);
152        PaginableRecordSetImpl res = new PaginableRecordSetImpl(pp);
153        if (res.hasError()) {
154            throw new OperationException(res.getErrorMessage());
155        }
156        return res;
157    }
158
159    @SuppressWarnings("unchecked")
160    final class QueryAndFetchProviderDescriptor extends GenericPageProviderDescriptor {
161        private static final long serialVersionUID = 1L;
162
163        public QueryAndFetchProviderDescriptor() {
164            super();
165            try {
166                klass = (Class<PageProvider<?>>) Class.forName(CoreQueryAndFetchPageProvider.class.getName());
167            } catch (ClassNotFoundException e) {
168
169            }
170        }
171    }
172
173}