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