001/*
002 *  Copyright 2017 Anyware Services
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 */
016package org.ametys.plugins.extraction.component;
017
018import java.util.ArrayList;
019import java.util.Arrays;
020import java.util.Collection;
021import java.util.Collections;
022import java.util.HashSet;
023import java.util.LinkedHashSet;
024import java.util.List;
025import java.util.Locale;
026import java.util.Map;
027import java.util.Optional;
028import java.util.Set;
029import java.util.regex.Matcher;
030import java.util.regex.Pattern;
031import java.util.stream.Collectors;
032
033import org.apache.avalon.framework.configuration.Configuration;
034import org.apache.avalon.framework.configuration.ConfigurationException;
035import org.apache.avalon.framework.service.ServiceException;
036import org.apache.avalon.framework.service.ServiceManager;
037import org.apache.commons.lang3.StringUtils;
038import org.apache.solr.client.solrj.util.ClientUtils;
039import org.xml.sax.ContentHandler;
040
041import org.ametys.cms.content.ContentHelper;
042import org.ametys.cms.contenttype.ContentType;
043import org.ametys.cms.data.ContentValue;
044import org.ametys.cms.data.type.ModelItemTypeConstants;
045import org.ametys.cms.data.type.ModelItemTypeExtensionPoint;
046import org.ametys.cms.repository.Content;
047import org.ametys.cms.search.GetQueryFromJSONHelper;
048import org.ametys.cms.search.QueryBuilder;
049import org.ametys.cms.search.content.ContentSearcherFactory;
050import org.ametys.cms.search.content.ContentSearcherFactory.SimpleContentSearcher;
051import org.ametys.cms.search.model.SystemProperty;
052import org.ametys.cms.search.model.SystemPropertyExtensionPoint;
053import org.ametys.cms.search.query.QuerySyntaxException;
054import org.ametys.cms.search.solr.SolrContentQueryHelper;
055import org.ametys.cms.search.ui.model.SearchUIModel;
056import org.ametys.core.util.JSONUtils;
057import org.ametys.core.util.LambdaUtils;
058import org.ametys.plugins.extraction.execution.ExtractionExecutionContext;
059import org.ametys.plugins.extraction.execution.ExtractionExecutionContextHierarchyElement;
060import org.ametys.plugins.queriesdirectory.Query;
061import org.ametys.plugins.repository.AmetysObjectIterable;
062import org.ametys.plugins.repository.AmetysObjectResolver;
063import org.ametys.plugins.repository.EmptyIterable;
064import org.ametys.plugins.thesaurus.ThesaurusDAO;
065import org.ametys.runtime.model.ModelHelper;
066import org.ametys.runtime.model.ModelItem;
067import org.ametys.runtime.model.type.ElementType;
068import org.ametys.runtime.model.type.ModelItemType;
069
070/**
071 * This class represents an extraction component with a solr query
072 */
073public abstract class AbstractSolrExtractionComponent extends AbstractExtractionComponent
074{
075    /** Regex used to extract variables from an expression. A variable is inside a ${} */
076    private static final String __EXTRACT_VARIABLES_REGEX = "\\$\\{([^{}]+)\\}";
077    
078    /**
079     * Regex used to check variables from a join expression: \.\.(?:\/\.\.)*(?:\/[^\/}]+)?
080     * variable starts with .. (to get the direct parent),
081     * has several /.. (to get parent of parent of (...))
082     * and can have a /metadataName (to specify the metadata to join on)
083     */
084    private static final String __CHECK_JOIN_VARIABLES_REGEX = "\\.\\.(?:\\/\\.\\.)*(?:\\/[^\\/}]+)?";
085    
086    /** Content types concerned by the solr search */
087    protected Set<String> _contentTypes = new HashSet<>();
088    
089    /** Reference id of a recorded query */
090    protected String _queryReferenceId;
091    
092    /** The list of clauses */
093    protected List<ExtractionClause> _clauses = new ArrayList<>();
094    
095    /** Helper to resolve referenced query infos */
096    protected GetQueryFromJSONHelper _getQueryFromJSONHelper;
097    
098    /** Util class to manipulate JSON String */
099    protected JSONUtils _jsonUtils;
100    
101    private AmetysObjectResolver _resolver;
102    private SystemPropertyExtensionPoint _systemPropertyExtensionPoint;
103    private ContentHelper _contentHelper;
104    private ContentSearcherFactory _contentSearcherFactory;
105    private QueryBuilder _queryBuilder;
106    private ModelItemTypeExtensionPoint _contentAttributeTypeExtensionPoint;
107    
108    @Override
109    public void service(ServiceManager serviceManager) throws ServiceException
110    {
111        super.service(serviceManager);
112        _jsonUtils = (JSONUtils) serviceManager.lookup(JSONUtils.ROLE);
113        _getQueryFromJSONHelper = (GetQueryFromJSONHelper) serviceManager.lookup(GetQueryFromJSONHelper.ROLE);
114        _resolver = (AmetysObjectResolver) serviceManager.lookup(AmetysObjectResolver.ROLE);
115        _systemPropertyExtensionPoint = (SystemPropertyExtensionPoint) serviceManager.lookup(SystemPropertyExtensionPoint.ROLE);
116        _contentHelper = (ContentHelper) serviceManager.lookup(ContentHelper.ROLE);
117        _contentSearcherFactory = (ContentSearcherFactory) serviceManager.lookup(ContentSearcherFactory.ROLE);
118        _queryBuilder = (QueryBuilder) serviceManager.lookup(QueryBuilder.ROLE);
119        _contentAttributeTypeExtensionPoint = (ModelItemTypeExtensionPoint) serviceManager.lookup(ModelItemTypeExtensionPoint.ROLE_CONTENT_ATTRIBUTE);
120    }
121    
122    @Override
123    public void configure(Configuration configuration) throws ConfigurationException
124    {
125        super.configure(configuration);
126        
127        Configuration clauses = configuration.getChild("clauses");
128        for (Configuration clause : clauses.getChildren("clause"))
129        {
130            addClauses(clause.getValue());
131        }
132
133        _contentTypes = new HashSet<>();
134        if (Arrays.asList(configuration.getAttributeNames()).contains("ref"))
135        {
136            if (Arrays.asList(configuration.getAttributeNames()).contains("contentTypes"))
137            {
138                throw new IllegalArgumentException(getLogsPrefix() + "a component with a query reference should not specify a content type");
139            }
140            
141            _queryReferenceId = configuration.getAttribute("ref");
142        }
143        else
144        {
145            String contentTypesString = configuration.getAttribute("contentTypes");
146            _contentTypes.addAll(org.ametys.core.util.StringUtils.stringToCollection(contentTypesString));
147        }
148    }
149    
150    @Override
151    public void prepareComponentExecution(ExtractionExecutionContext context) throws Exception
152    {
153        super.prepareComponentExecution(context);
154        
155        if (_queryReferenceId != null && !_queryReferenceId.isEmpty())
156        {
157            Query referencedQuery = _resolver.resolveById(_queryReferenceId);
158            computeReferencedQueryInfos(referencedQuery.getContent());
159        }
160        
161        _computeClausesInfos(context);
162    }
163
164    /**
165     * Manages the stored query referenced by the component
166     * @param refQueryContent referenced query content
167     * @throws QuerySyntaxException if there is a syntax error in the referenced query
168     */
169    @SuppressWarnings("unchecked")
170    protected void computeReferencedQueryInfos(String refQueryContent) throws QuerySyntaxException
171    {
172        Map<String, Object> contentMap = _jsonUtils.convertJsonToMap(refQueryContent);
173        Map<String, Object> exportParams = (Map<String, Object>) contentMap.get("exportParams");
174        String modelId = (String) exportParams.get("model");
175        
176        String q;
177        if (modelId.contains("solr"))
178        {
179            Map<String, Object> values = (Map<String, Object>) exportParams.get("values");
180            String baseQuery = (String) values.get("query");
181            
182            _contentTypes = new HashSet<>((List<String>) values.get("contentTypes"));
183            
184            q = SolrContentQueryHelper.buildQuery(_queryBuilder, baseQuery, _contentTypes, Collections.emptySet());
185        }
186        else
187        {
188            SearchUIModel model = _getQueryFromJSONHelper.getSearchUIModel(exportParams);
189            List<String> contentTypesToFill = new ArrayList<>();
190            org.ametys.cms.search.query.Query query = _getQueryFromJSONHelper.getQueryFromModel(model, exportParams, contentTypesToFill);
191            
192            q = query.build();
193            _contentTypes = new HashSet<>(contentTypesToFill);
194        }
195        
196        ExtractionClause clause = new ExtractionClause();
197        clause.setExpression(q);
198        _clauses.add(0, clause);
199    }
200
201    private void _computeClausesInfos(ExtractionExecutionContext context)
202    {
203        for (ExtractionClause clause : _clauses)
204        {
205            String clauseExpression = clause.getExpression();
206            clause.setExpression(clauseExpression);
207            
208            List<ExtractionClauseGroup> groups = _extractGroupExpressionsFromClause(clauseExpression);
209            if (!groups.isEmpty())
210            {
211                Collection<String> groupExpressions = groups.stream()
212                        .map(ExtractionClauseGroup::getCompleteExpression)
213                        .collect(Collectors.toList());
214                if (_hasVariablesOutsideGroups(clauseExpression, groupExpressions, context.getClauseVariables().keySet()))
215                {
216                    throw new IllegalArgumentException(getLogsPrefix() + "if there's at least one group, every variable should be in a group.");
217                }
218            }
219            else
220            {
221                // The only group is the entire expression
222                // The complete expression is the same as the classic one (there is no characters used to identify the group)
223                ExtractionClauseGroup group = new ExtractionClauseGroup();
224                group.setCompleteExpression(clauseExpression);
225                group.setExpression(clauseExpression);
226                groups.add(group);
227            }
228            
229            for (ExtractionClauseGroup group : groups)
230            {
231                Set<String> variables = new HashSet<>(_extractVariableFromClauseExpression(group.getExpression(), context.getClauseVariables().keySet()));
232                if (!variables.isEmpty())
233                {
234                    if (variables.size() > 1)
235                    {
236                        throw new IllegalArgumentException(getLogsPrefix() + "only variables with same name are allowed within a single group");
237                    }
238                    
239                    for (String variable : variables)
240                    {
241                        String[] pathSegments = variable.split(JOIN_HIERARCHY_SEPARATOR);
242                        String fieldPath = pathSegments[pathSegments.length - 1];
243    
244                        group.setVariable(variable);
245                        group.setFieldPath(fieldPath);
246                    }
247                }
248                
249                clause.addGroup(group);
250            }
251        }
252    }
253    
254    private boolean _hasVariablesOutsideGroups(String clauseExpression, Collection<String> groupExpressions, Collection<String> clauseVariableNames)
255    {
256        List<String> variablesInClause = _extractVariableFromClauseExpression(clauseExpression, clauseVariableNames);
257        List<String> variablesInGroups = new ArrayList<>();
258        for (String groupExpression : groupExpressions)
259        {
260            variablesInGroups.addAll(_extractVariableFromClauseExpression(groupExpression, clauseVariableNames));
261        }
262        return variablesInClause.size() > variablesInGroups.size();
263    }
264
265    List<ExtractionClauseGroup> _extractGroupExpressionsFromClause(String expression)
266    {
267        List<ExtractionClauseGroup> groupExpressions = new ArrayList<>();
268        int indexOfGroup = expression.indexOf("#{");
269        while (indexOfGroup != -1)
270        {
271            StringBuilder currentGroupSb = new StringBuilder();
272            int endIndex = indexOfGroup;
273            int braceLevel = 0;
274            for (int i = indexOfGroup + 2; i < expression.length(); i++)
275            {
276                endIndex = i;
277                char currentChar = expression.charAt(i);
278                if ('{' == currentChar)
279                {
280                    braceLevel++;
281                }
282                else if ('}' == currentChar)
283                {
284                    if (0  == braceLevel)
285                    {
286                        ExtractionClauseGroup group = new ExtractionClauseGroup();
287                        String currentGroup = currentGroupSb.toString();
288                        group.setCompleteExpression("#{" + currentGroup + "}");
289                        group.setExpression(currentGroup);
290                        groupExpressions.add(group);
291                        break;
292                    }
293                    braceLevel--;
294                }
295                currentGroupSb.append(currentChar);
296            }
297            
298            indexOfGroup = expression.indexOf("#{", endIndex);
299        }
300        return groupExpressions;
301    }
302
303    List<String> _extractVariableFromClauseExpression(String expression, Collection<String> clauseVariableNames)
304    {
305        List<String> variables = new ArrayList<>();
306        
307        Pattern variablePattern = Pattern.compile(__EXTRACT_VARIABLES_REGEX);
308        Matcher variableMatcher = variablePattern.matcher(expression);
309        
310        while (variableMatcher.find())
311        {
312            String variable = variableMatcher.group(1);
313            Pattern joinPattern = Pattern.compile(__CHECK_JOIN_VARIABLES_REGEX);
314            Matcher joinMatcher = joinPattern.matcher(variable);
315            if (clauseVariableNames.contains(variable) || joinMatcher.matches())
316            {
317                variables.add(variable);
318            }
319        }
320        
321        return variables;
322    }
323
324    @Override
325    public void executeComponent(ContentHandler contentHandler, ExtractionExecutionContext context) throws Exception
326    {
327        Iterable<Content> contents = getContents(context);
328        processContents(contents, contentHandler, context);
329    }
330    
331    List<String> _getClauseQueries(ExtractionExecutionContext context)
332    {
333        List<String> clauseQueries = new ArrayList<>();
334        
335        for (ExtractionClause clause : _clauses)
336        {
337            String expression = clause.getExpression();
338            
339            // Resolve all groups
340            for (ExtractionClauseGroup group : clause.getGroups())
341            {
342                String variable = group.getVariable();
343                
344                if (StringUtils.isNotEmpty(variable))
345                {
346                    String fieldPath = group.getFieldPath();
347                    String attributeTypeId;
348                    Collection<Object> values;
349                    if (context.getClauseVariables().containsKey(variable))
350                    {
351                        attributeTypeId = ModelItemTypeConstants.CONTENT_ELEMENT_TYPE_ID;
352                        values = context.getClauseVariables()
353                                        .get(variable)
354                                        .stream()
355                                        .map(Object.class::cast)
356                                        .collect(Collectors.toList());
357                    }
358                    else
359                    {
360                        ExtractionExecutionContextHierarchyElement currentContextHierarchyElement = _getCurrentContextElementFromVariable(variable, context.getHierarchyElements());
361                        
362                        ExtractionComponent contextComponent = currentContextHierarchyElement.getComponent();
363                        attributeTypeId = _getAttributeTypeId(fieldPath, contextComponent.getContentTypes());
364                        values = _getValuesFromVariable(fieldPath, attributeTypeId, currentContextHierarchyElement, context.getDefaultLocale());
365                    }
366                    
367                    if (values.isEmpty())
368                    {
369                        getLogger().warn(getLogsPrefix() + "no value found for field '" + fieldPath + "'. The query of this component can't be achieved");
370                        return null;
371                    }
372                    
373                    Collection<String> groupExpressions = new ArrayList<>();
374                    for (Object value : values)
375                    {
376                        String valueAsString = _getValueAsString(value, attributeTypeId, fieldPath);
377                        groupExpressions.add("(" + group.getExpression().replace("${" + variable + "}", valueAsString) + ")");
378                    }
379                    
380                    String groupReplacement =  StringUtils.join(groupExpressions, " OR ");
381                    expression = expression.replace(group.getCompleteExpression(), "(" + groupReplacement + ")");
382                }
383            }
384            
385            clauseQueries.add(expression);
386        }
387        
388        return clauseQueries;
389    }
390
391    private ExtractionExecutionContextHierarchyElement _getCurrentContextElementFromVariable(String variable, List<ExtractionExecutionContextHierarchyElement> context)
392    {
393        int lastIndexOfSlash = variable.lastIndexOf(JOIN_HIERARCHY_SEPARATOR);
394        int indexOfCurrentContext = -1;
395        if (lastIndexOfSlash == -1)
396        {
397            indexOfCurrentContext = context.size() - 1;
398        }
399        else
400        {
401            int hierarchicalLevel = (lastIndexOfSlash + 1) / 3;
402            indexOfCurrentContext = context.size() - hierarchicalLevel;
403            if (variable.endsWith(JOIN_HIERARCHY_ELEMENT))
404            {
405                indexOfCurrentContext--;
406            }
407        }
408        if (indexOfCurrentContext < 0 || indexOfCurrentContext >= context.size())
409        {
410            throw new IllegalArgumentException(getLogsPrefix() + "join on '" + variable + "' does not refer to an existing parent");
411        }
412        return context.get(indexOfCurrentContext);
413    }
414    
415    /**
416     * Retrieves the field path's attribute type identifier from content types
417     * @param fieldPath the field path
418     * @param contentTypeIds the content types identifiers
419     * @return the attribute type identifier
420     */
421    protected String _getAttributeTypeId(String fieldPath, Collection<String> contentTypeIds)
422    {
423        // Manage direct content references
424        if (JOIN_HIERARCHY_ELEMENT.equals(fieldPath))
425        {
426            return ModelItemTypeConstants.CONTENT_ELEMENT_TYPE_ID;
427        }
428        
429        // Manage System Properties
430        String[] pathSegments = fieldPath.split(EXTRACTION_ITEM_PATH_SEPARATOR);
431        String propertyName = pathSegments[pathSegments.length - 1];
432        if (_systemPropertyExtensionPoint.hasExtension(propertyName))
433        {
434            SystemProperty systemProperty = _systemPropertyExtensionPoint.getExtension(propertyName);
435            return systemProperty.getType().getId();
436        }
437        
438        String fieldPathWthClassicSeparator = fieldPath.replaceAll(EXTRACTION_ITEM_PATH_SEPARATOR, ModelItem.ITEM_PATH_SEPARATOR);
439        Collection<ContentType> contentTypes = contentTypeIds.stream()
440                .map(_contentTypeExtensionPoint::getExtension)
441                .collect(Collectors.toList());
442        
443        if (ModelHelper.hasModelItem(fieldPathWthClassicSeparator, contentTypes))
444        {
445            ModelItem modelItem = ModelHelper.getModelItem(fieldPathWthClassicSeparator, contentTypes);
446            return modelItem.getType().getId();
447        }
448        
449        throw new IllegalArgumentException(getLogsPrefix() + "join on '" + fieldPath + "'. This attribute is not available");
450    }
451
452    private Collection<Object> _getValuesFromVariable(String fieldPath, String attributeTypeId, ExtractionExecutionContextHierarchyElement contextHierarchyElement, Locale defaultLocale)
453    {
454        Collection<Object> values = new LinkedHashSet<>();
455        
456        Iterable<Content> contents = contextHierarchyElement.getContents();
457        for (Content content: contents)
458        {
459            boolean isAutoposting = contextHierarchyElement.isAutoposting();
460            Collection<Object> contentValues = _getContentValuesFromVariable(content, fieldPath, attributeTypeId, isAutoposting, defaultLocale);
461            values.addAll(contentValues);
462        }
463        
464        return values;
465    }
466    
467    private Collection<Object> _getContentValuesFromVariable(Content content, String fieldPath, String attributeTypeId, boolean isAutoposting, Locale defaultLocale)
468    {
469        Collection<Object> values = new LinkedHashSet<>();
470        
471        Object value = _getContentValue(content, fieldPath);
472        if (value == null)
473        {
474            return Collections.emptyList();
475        }
476        
477        if (value instanceof Collection<?>)
478        {
479            values.addAll((Collection<?>) value);
480        }
481        else
482        {
483            values.add(value);
484        }
485        
486        Collection<Object> result = new LinkedHashSet<>(values);
487        
488        if (isAutoposting && ModelItemTypeConstants.CONTENT_ELEMENT_TYPE_ID.equals(attributeTypeId))
489        {
490            for (Object object : values)
491            {
492                Optional<? extends Content> parent = object instanceof ContentValue ? ((ContentValue) object).getContentIfExists() : Optional.of((Content) object);
493                ContentType contentType = parent.map(_contentTypesHelper::getFirstContentType)
494                                                .orElse(null);
495                
496                // Manage autoposting only if the current value is a thesaurus term
497                if (contentType != null && Arrays.asList(_contentTypesHelper.getSupertypeIds(contentType.getId()).getLeft()).contains(ThesaurusDAO.MICROTHESAURUS_ABSTRACT_CONTENT_TYPE))
498                {
499                    AmetysObjectIterable<Content> chidren = _thesaurusDAO.getChildTerms(contentType.getId(), parent.get().getId());
500                    for (Content child : chidren)
501                    {
502                        Collection<Object> childValues = _getContentValuesFromVariable(child, JOIN_HIERARCHY_ELEMENT, attributeTypeId, isAutoposting, defaultLocale);
503                        result.addAll(childValues);
504                    }
505                }
506            }
507        }
508
509        return result;
510    }
511    
512    private Object _getContentValue(Content content, String fieldPath)
513    {
514        if (JOIN_HIERARCHY_ELEMENT.equals(fieldPath))
515        {
516            return content;
517        }
518        else 
519        {
520            String fieldPathWthClassicSeparator = fieldPath.replaceAll(EXTRACTION_ITEM_PATH_SEPARATOR, ModelItem.ITEM_PATH_SEPARATOR);
521            return _contentHelper.getValue(content, fieldPathWthClassicSeparator);
522        }
523    }
524    
525    private <T> String _getValueAsString(Object value, String attributeTypeId, String fieldPath)
526    {
527        ModelItemType modelItemType = _contentAttributeTypeExtensionPoint.getExtension(attributeTypeId);
528        if (modelItemType instanceof ElementType)
529        {
530            @SuppressWarnings("unchecked")
531            ElementType<T> elementType = (ElementType<T>) modelItemType;
532            T typedValue = elementType.castValue(value);
533            String valueAsString = elementType.toString(typedValue);
534            return ClientUtils.escapeQueryChars(valueAsString);
535        }
536        else
537        {
538            throw new IllegalArgumentException(getLogsPrefix() + "join on '" + fieldPath + "'. Attribute type '" + attributeTypeId + "' is not supported by extraction module");
539        }
540    }
541    
542    /**
543     * Retrieves the content searcher to use for solr search
544     * @return the content searcher
545     */
546    protected SimpleContentSearcher getContentSearcher()
547    {
548        return _contentSearcherFactory.create(_contentTypes);
549    }
550    
551    /**
552     * Gets the content results from Solr
553     * @param context component execution context
554     * @return the content results from Solr
555     * @throws Exception if an error occurs
556     */
557    protected Iterable<Content> getContents(ExtractionExecutionContext context) throws Exception
558    {
559        List<String> clauseQueries = _getClauseQueries(context);
560        if (clauseQueries == null)
561        {
562            return new EmptyIterable<>();
563        }
564        else
565        {
566            List<String> filterQueryStrings = clauseQueries
567                    .stream()
568                    .map(LambdaUtils.wrap(clauseQuery -> SolrContentQueryHelper.buildQuery(_queryBuilder, clauseQuery, Collections.emptySet(), Collections.emptySet())))
569                    .collect(Collectors.toList());
570            return getContentSearcher()
571                    .withFilterQueryStrings(filterQueryStrings)
572                    .setCheckRights(false)
573                    .search("*:*");
574        }
575    }
576
577    /**
578     * Process result contents to format the result document
579     * @param contents search results
580     * @param contentHandler result document
581     * @param context component execution context
582     * @throws Exception if an error occurs
583     */
584    protected abstract void processContents(Iterable<Content> contents, ContentHandler contentHandler, ExtractionExecutionContext context) throws Exception;
585
586    @Override
587    public Map<String, Object> getComponentDetailsForTree()
588    {
589        Map<String, Object> details = super.getComponentDetailsForTree();
590        
591        @SuppressWarnings("unchecked")
592        Map<String, Object> data = (Map<String, Object>) details.get("data");
593        
594        List<String> clauses = new ArrayList<>();
595        for (ExtractionClause clause : this.getClauses())
596        {
597            clauses.add(clause.getExpression());
598        }
599        data.put("clauses", clauses);
600        
601        data.put("useQueryRef", StringUtils.isNotEmpty(_queryReferenceId));
602        data.put("contentTypes", this.getContentTypes());
603        data.put("queryReferenceId", this.getQueryReferenceId());
604        
605        return details;
606    }
607    
608    public Set<String> getContentTypes()
609    {
610        return _contentTypes;
611    }
612
613    /**
614     * Add content types to component
615     * @param contentTypes Array of content types to add
616     */
617    public void addContentTypes(String... contentTypes)
618    {
619        _contentTypes.addAll(Arrays.asList(contentTypes));
620    }
621
622    /**
623     * Retrieves the id of the referenced query
624     * @return the id of the referenced query
625     */
626    public String getQueryReferenceId()
627    {
628        return _queryReferenceId;
629    }
630    
631    /**
632     * Sets the id of the referenced query
633     * @param queryReferenceId The id of the referenced query to set
634     */
635    public void setQueryReferenceId(String queryReferenceId)
636    {
637        _queryReferenceId = queryReferenceId;
638    }
639
640    /**
641     * Retrieves the component clauses
642     * @return the component clauses
643     */
644    public List<ExtractionClause> getClauses()
645    {
646        return _clauses;
647    }
648
649    /**
650     * Add clauses to the component. Do not manage clauses' groups
651     * @param expressions Array clauses expressions to add
652     */
653    public void addClauses(String... expressions)
654    {
655        for (String expression : expressions)
656        {
657            ExtractionClause clause = new ExtractionClause();
658            clause.setExpression(expression);
659            _clauses.add(clause);
660        }
661    }
662}