001/*
002 *  Copyright 2016 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.cms.search.query;
017
018import java.util.Arrays;
019import java.util.Collection;
020import java.util.HashSet;
021
022import org.apache.solr.client.solrj.util.ClientUtils;
023
024import org.ametys.core.user.UserIdentity;
025
026/**
027 * {@link Query} testing users.
028 */
029public abstract class AbstractUsersQuery implements Query
030{
031    
032    private Collection<UserIdentity> _users;
033    private Operator _operator;
034    
035    /**
036     * Build a user query.
037     * @param users The users to test.
038     */
039    public AbstractUsersQuery(UserIdentity... users)
040    {
041        this(Arrays.asList(users));
042    }
043    
044    /**
045     * Build a user query.
046     * @param users The users to test.
047     */
048    public AbstractUsersQuery(Collection<UserIdentity> users)
049    {
050        this(users, Operator.EQ);
051    }
052    
053    /**
054     * Build a user query.
055     * @param users The users to test.
056     * @param operator The query operator (can be EQ or NE).
057     */
058    public AbstractUsersQuery(Collection<UserIdentity> users, Operator operator)
059    {
060        this._users = new HashSet<>(users);
061        this._operator = operator;
062    }
063    
064    @Override
065    public String build() throws QuerySyntaxException
066    {
067        if (_users.isEmpty())
068        {
069            return "";
070        }
071        
072        StringBuilder query = new StringBuilder();
073        
074        if (_operator == Operator.NE)
075        {
076            query.append('-');
077        }
078        
079        query.append(getField()).append(":(");
080        
081        boolean first = true;
082        for (UserIdentity user : _users)
083        {
084            if (!first)
085            {
086                query.append(" OR ");
087            }
088            query.append(ClientUtils.escapeQueryChars(UserIdentity.userIdentityToString(user)));
089            first = false;
090        }
091        
092        query.append(')');
093        
094        return query.toString();
095    }
096    
097    /**
098     * The query field.
099     * @return The query field.
100     */
101    protected abstract String getField();
102    
103}