001/*
002 * (C) Copyright 2013 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 *     <a href="mailto:grenard@nuxeo.com">Guillaume</a>
018 */
019package org.nuxeo.ecm.platform.ui.select2.common;
020
021import java.io.IOException;
022import java.util.ArrayList;
023import java.util.Arrays;
024import java.util.LinkedHashMap;
025import java.util.List;
026import java.util.Map;
027
028import org.apache.commons.logging.Log;
029import org.apache.commons.logging.LogFactory;
030import org.nuxeo.ecm.automation.features.SuggestConstants;
031import org.nuxeo.ecm.core.api.CoreSession;
032import org.nuxeo.ecm.core.api.DocumentModel;
033import org.nuxeo.ecm.core.api.DocumentModelList;
034import org.nuxeo.ecm.core.api.DocumentRef;
035import org.nuxeo.ecm.core.api.IdRef;
036import org.nuxeo.ecm.core.api.NuxeoException;
037import org.nuxeo.ecm.core.api.PathRef;
038import org.nuxeo.ecm.core.query.sql.NXQL;
039
040import com.fasterxml.jackson.databind.ObjectMapper;
041
042/**
043 * Group fields and methods used at initialization and runtime for select2 feature.
044 *
045 * @since 5.7.3
046 */
047public class Select2Common extends SuggestConstants {
048
049    private static final Log log = LogFactory.getLog(Select2Common.class);
050
051    protected static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
052
053    // no instantiation
054    private Select2Common() {
055    }
056
057    public static final String LOCKED = "locked";
058
059    public static final String PLACEHOLDER = "placeholder";
060
061    public static final List<String> SELECT2_USER_WIDGET_TYPE_LIST = new ArrayList<String>(
062            Arrays.asList("singleUserSuggestion", "multipleUsersSuggestion"));
063
064    public static final List<String> SELECT2_DOC_WIDGET_TYPE_LIST = new ArrayList<String>(
065            Arrays.asList("singleDocumentSuggestion", "multipleDocumentsSuggestion"));
066
067    public static final String SUGGESTION_FORMATTER = "suggestionFormatter";
068
069    public static final String SELECTION_FORMATTER = "selectionFormatter";
070
071    public static final String USER_DEFAULT_SUGGESTION_FORMATTER = "userEntryDefaultFormatter";
072
073    public static final String DOC_DEFAULT_SUGGESTION_FORMATTER = "docEntryDefaultFormatter";
074
075    public static final List<String> SELECT2_DIR_WIDGET_TYPE_LIST = new ArrayList<String>(
076            Arrays.asList("suggestOneDirectory", "suggestManyDirectory"));
077
078    public static final List<String> SELECT2_DEFAULT_DOCUMENT_SCHEMAS = new ArrayList<String>(
079            Arrays.asList("dublincore", "common"));
080
081    public static final String DIR_DEFAULT_SUGGESTION_FORMATTER = "dirEntryDefaultFormatter";
082
083    public static final String READ_ONLY_PARAM = "readonly";
084
085    public static final String RERENDER_JS_FUNCTION_NAME = "reRenderFunctionName";
086
087    public static final String AJAX_RERENDER = "ajaxReRender";
088
089    public static final String USER_DEFAULT_SELECTION_FORMATTER = "userSelectionDefaultFormatter";
090
091    public static final String DOC_DEFAULT_SELECTION_FORMATTER = "docSelectionDefaultFormatter";
092
093    public static final String DIR_DEFAULT_SELECTION_FORMATTER = "dirSelectionDefaultFormatter";
094
095    public static final String WIDTH = "width";
096
097    public static final String DEFAULT_WIDTH = "300";
098
099    public static final String MIN_CHARS = "minChars";
100
101    public static final int DEFAULT_MIN_CHARS = 3;
102
103    public static final String TITLE = "title";
104
105    public static final String OPERATION_ID = "operationId";
106
107    /**
108     * @since 5.9.3
109     */
110    public static String[] getDefaultSchemas() {
111        return getSchemas(null);
112    }
113
114    /**
115     * Returns an array containing the given schema names plus the default ones if not included
116     *
117     * @param schemaNames
118     * @since 5.8
119     */
120    public static String[] getSchemas(final String schemaNames) {
121        List<String> result = new ArrayList<String>();
122        result.addAll(Select2Common.SELECT2_DEFAULT_DOCUMENT_SCHEMAS);
123        String[] temp = null;
124        if (schemaNames != null && !schemaNames.isEmpty()) {
125            temp = schemaNames.split(",");
126        }
127        if (temp != null) {
128            for (String s : temp) {
129                result.add(s);
130            }
131        }
132        return result.toArray(new String[result.size()]);
133    }
134
135    /**
136     * @since 6.0
137     */
138    public static String resolveDefaultEntries(final List<String> list) {
139        if (list == null || list.isEmpty()) {
140            return "[]";
141        } else {
142            try {
143                List<Map<String, Object>> result = new ArrayList<>();
144                for (String l : list) {
145                    Map<String, Object> obj = new LinkedHashMap<>();
146                    obj.put(Select2Common.ID, l);
147                    obj.put(Select2Common.LABEL, l);
148                    result.add(obj);
149                }
150               return OBJECT_MAPPER.writeValueAsString(result);
151            } catch (IOException e) {
152                throw new NuxeoException("Unable to serialize json", e);
153            }
154        }
155    }
156
157    /**
158     * Finds a document by the given property and value. If the property is null or empty the value is considered as a
159     * {@link DocumentRef}.
160     *
161     * @since 9.2
162     */
163    public static DocumentModel resolveReference(String property, String value, CoreSession session) {
164        if (property != null && !property.isEmpty()) {
165            String query = "select * from Document where " + property + "=" + NXQL.escapeString(value);
166            DocumentModelList docs = session.query(query);
167            if (docs.size() > 0) {
168                return docs.get(0);
169            }
170            log.warn("Unable to resolve doc using property " + property + " and value " + value);
171            return null;
172        }
173        DocumentRef ref = null;
174        if (value.startsWith("/")) {
175            ref = new PathRef(value);
176        } else {
177            ref = new IdRef(value);
178        }
179        if (session.exists(ref)) {
180            return session.getDocument(ref);
181        }
182        log.warn("Unable to resolve reference on " + ref);
183        return null;
184    }
185
186}