001/*
002 * (C) Copyright 2011 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 *     Thierry Delprat
018 */
019package org.nuxeo.ecm.automation.core.operations.services;
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.OperationContext;
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.Paginable;
037import org.nuxeo.ecm.automation.core.util.Properties;
038import org.nuxeo.ecm.automation.core.util.StringList;
039import org.nuxeo.ecm.core.api.CoreSession;
040import org.nuxeo.ecm.core.api.DocumentModel;
041import org.nuxeo.ecm.core.api.SortInfo;
042import org.nuxeo.ecm.core.query.sql.NXQL;
043import org.nuxeo.ecm.platform.audit.api.AuditPageProvider;
044import org.nuxeo.ecm.platform.audit.api.LogEntry;
045import org.nuxeo.ecm.platform.audit.api.LogEntryList;
046import org.nuxeo.ecm.platform.query.api.PageProvider;
047import org.nuxeo.ecm.platform.query.api.PageProviderService;
048import org.nuxeo.ecm.platform.query.core.GenericPageProviderDescriptor;
049import org.nuxeo.ecm.platform.query.nxql.CoreQueryDocumentPageProvider;
050
051/**
052 * Operation to execute a query or a named provider against Audit with support for Pagination
053 *
054 * @author Tiry (tdelprat@nuxeo.com)
055 * @since 5.8
056 */
057@Operation(id = AuditPageProviderOperation.ID, category = Constants.CAT_FETCH, label = "Audit Query With Page Provider", description = "Perform "
058        + "a query or a named provider query against Audit logs. Result is "
059        + "paginated. The query result will become the input for the next "
060        + "operation. If no query or provider name is given, a query based on default Audit page provider will be executed.", addToStudio = false, aliases = { "Audit.PageProvider" })
061public class AuditPageProviderOperation {
062
063    public static final String ID = "Audit.QueryWithPageProvider";
064
065    public static final String CURRENT_USERID_PATTERN = "$currentUser";
066
067    public static final String CURRENT_REPO_PATTERN = "$currentRepository";
068
069    private static final String SORT_PARAMETER_SEPARATOR = " ";
070
071    public static final String DESC = "DESC";
072
073    public static final String ASC = "ASC";
074
075    @Context
076    protected OperationContext context;
077
078    @Context
079    protected CoreSession session;
080
081    @Context
082    protected PageProviderService ppService;
083
084    @Param(name = "providerName", required = false)
085    protected String providerName;
086
087    @Param(name = "query", required = false)
088    protected String query;
089
090    @Param(name = "language", required = false, widget = Constants.W_OPTION, values = { NXQL.NXQL })
091    protected String lang = NXQL.NXQL;
092
093    @Param(name = "page", required = false)
094    @Deprecated
095    protected Integer page;
096
097    @Param(name = "currentPageIndex", required = false)
098    protected Integer currentPageIndex;
099
100    @Param(name = "pageSize", required = false)
101    protected Integer pageSize;
102
103    /**
104     * @deprecated since 6.0 use instead {@link #sortBy and @link #sortOrder}.
105     */
106    @Deprecated
107    @Param(name = "sortInfo", required = false)
108    protected StringList sortInfoAsStringList;
109
110    @Param(name = "queryParams", required = false)
111    protected StringList strParameters;
112
113    @Param(name = "namedQueryParams", required = false)
114    protected Properties namedQueryParams;
115
116    /**
117     * @deprecated since 6.0, not used in operation.
118     */
119    @Deprecated
120    @Param(name = "maxResults", required = false)
121    protected Integer maxResults = 100;
122
123    /**
124     * @since 6.0
125     */
126    @Param(name = "sortBy", required = false, description = "Sort by " + "properties (separated by comma)")
127    protected String sortBy;
128
129    /**
130     * @since 6.0
131     */
132    @Param(name = "sortOrder", required = false, description = "Sort order, " + "ASC or DESC", widget = Constants.W_OPTION, values = {
133            ASC, DESC })
134    protected String sortOrder;
135
136    @SuppressWarnings("unchecked")
137    @OperationMethod
138    public Paginable<LogEntry> run() throws IOException {
139
140        List<SortInfo> sortInfos = null;
141        if (sortInfoAsStringList != null) {
142            sortInfos = new ArrayList<SortInfo>();
143            for (String sortInfoDesc : sortInfoAsStringList) {
144                SortInfo sortInfo;
145                if (sortInfoDesc.contains(SORT_PARAMETER_SEPARATOR)) {
146                    String[] parts = sortInfoDesc.split(SORT_PARAMETER_SEPARATOR);
147                    sortInfo = new SortInfo(parts[0], Boolean.parseBoolean(parts[1]));
148                } else {
149                    sortInfo = new SortInfo(sortInfoDesc, true);
150                }
151                sortInfos.add(sortInfo);
152            }
153        } else {
154            // Sort Info Management
155            if (!StringUtils.isBlank(sortBy)) {
156                sortInfos = new ArrayList<>();
157                String[] sorts = sortBy.split(",");
158                String[] orders = null;
159                if (!StringUtils.isBlank(sortOrder)) {
160                    orders = sortOrder.split(",");
161                }
162                for (int i = 0; i < sorts.length; i++) {
163                    String sort = sorts[i];
164                    boolean sortAscending = (orders != null && orders.length > i && "asc".equals(orders[i].toLowerCase()));
165                    sortInfos.add(new SortInfo(sort, sortAscending));
166                }
167            }
168        }
169
170        Object[] parameters = null;
171
172        if (strParameters != null && !strParameters.isEmpty()) {
173            parameters = strParameters.toArray(new String[strParameters.size()]);
174            // expand specific parameters
175            for (int idx = 0; idx < parameters.length; idx++) {
176                String value = (String) parameters[idx];
177                if (value.equals(CURRENT_USERID_PATTERN)) {
178                    parameters[idx] = session.getPrincipal().getName();
179                } else if (value.equals(CURRENT_REPO_PATTERN)) {
180                    parameters[idx] = session.getRepositoryName();
181                }
182            }
183        }
184        if (parameters == null) {
185            parameters = new Object[0];
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 && (providerName == null || providerName.length() == 0)) {
192            // provide a defaut provider
193            providerName = "AUDIT_BROWSER";
194        }
195
196        Long targetPage = null;
197        if (page != null) {
198            targetPage = page.longValue();
199        }
200        if (currentPageIndex != null) {
201            targetPage = currentPageIndex.longValue();
202        }
203        Long targetPageSize = null;
204        if (pageSize != null) {
205            targetPageSize = pageSize.longValue();
206        }
207
208        if (query != null) {
209
210            AuditPageProvider app = new AuditPageProvider();
211            app.setProperties(props);
212            GenericPageProviderDescriptor desc = new GenericPageProviderDescriptor();
213            desc.setPattern(query);
214            app.setParameters(parameters);
215            app.setDefinition(desc);
216            app.setSortInfos(sortInfos);
217            app.setPageSize(targetPageSize);
218            app.setCurrentPage(targetPage);
219            return new LogEntryList(app);
220        } else {
221
222            DocumentModel searchDoc = null;
223            if (namedQueryParams != null && namedQueryParams.size() > 0) {
224                String docType = ppService.getPageProviderDefinition(providerName).getWhereClause().getDocType();
225                searchDoc = session.createDocumentModel(docType);
226                DocumentHelper.setProperties(session, searchDoc, namedQueryParams);
227            }
228
229            PageProvider<LogEntry> pp = (PageProvider<LogEntry>) ppService.getPageProvider(providerName, searchDoc,
230                    sortInfos, targetPageSize, targetPage, props, parameters);
231            // return new PaginablePageProvider<LogEntry>(pp);
232            return new LogEntryList(pp);
233        }
234
235    }
236}