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.group.GroupIdentity; 025 026/** 027 * {@link Query} testing groups. 028 */ 029public abstract class AbstractGroupsQuery implements Query 030{ 031 032 private Collection<GroupIdentity> _groups; 033 private Operator _operator; 034 035 /** 036 * Build a group query. 037 * @param groups The groups to test. 038 */ 039 public AbstractGroupsQuery(GroupIdentity... groups) 040 { 041 this(Arrays.asList(groups)); 042 } 043 044 /** 045 * Build a group query. 046 * @param groups The groups to test. 047 */ 048 public AbstractGroupsQuery(Collection<GroupIdentity> groups) 049 { 050 this(Operator.EQ, groups); 051 } 052 053 /** 054 * Build a group query. 055 * @param operator The query operator (can be EQ or NE). 056 * @param groups The groups to test. 057 */ 058 public AbstractGroupsQuery(Operator operator, GroupIdentity... groups) 059 { 060 this(operator, Arrays.asList(groups)); 061 } 062 063 /** 064 * Build a group query. 065 * @param operator The query operator (can be EQ or NE). 066 * @param groups The groups to test. 067 */ 068 public AbstractGroupsQuery(Operator operator, Collection<GroupIdentity> groups) 069 { 070 this._groups = new HashSet<>(groups); 071 this._operator = operator; 072 } 073 074 @Override 075 public String build() throws QuerySyntaxException 076 { 077 if (_groups.isEmpty()) 078 { 079 return ""; 080 } 081 082 StringBuilder query = new StringBuilder(); 083 084 if (_operator == Operator.NE) 085 { 086 query.append('-'); 087 } 088 089 query.append(getField()).append(":("); 090 091 boolean first = true; 092 for (GroupIdentity group : _groups) 093 { 094 if (!first) 095 { 096 query.append(" OR "); 097 } 098 query.append(ClientUtils.escapeQueryChars(GroupIdentity.groupIdentityToString(group))); 099 first = false; 100 } 101 102 query.append(')'); 103 104 return query.toString(); 105 } 106 107 /** 108 * The query field. 109 * @return The query field. 110 */ 111 protected abstract String getField(); 112 113}