001/* 002 * Copyright 2015 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.web.search.query; 017 018import org.ametys.cms.search.query.NotQuery; 019import org.ametys.cms.search.query.Query; 020import org.ametys.cms.search.query.QueryHelper; 021import org.ametys.cms.search.query.QuerySyntaxException; 022import org.ametys.web.indexing.solr.SolrWebFieldNames; 023 024/** 025 * Represents a {@link Query} testing the shared status of a content. 026 */ 027public class SharedQuery implements Query 028{ 029 030 private boolean _shared; 031 private Operator _operator; 032 033 034 /** 035 * Create a SharedQuery. 036 */ 037 public SharedQuery() 038 { 039 this._operator = Operator.EXISTS; 040 } 041 042 /** 043 * Create a SharedQuery. 044 * @param shared <code>true</code> to get only shared contents, 045 * <code>false</code> to get only non-shared contents. 046 */ 047 public SharedQuery(boolean shared) 048 { 049 this._shared = shared; 050 } 051 052 /** 053 * Create a SharedQuery. 054 * @param shared <code>true</code> to get only shared contents, 055 * <code>false</code> to get only non-shared contents. 056 * @param operator the operator. 057 */ 058 public SharedQuery(boolean shared, Operator operator) 059 { 060 this._shared = shared; 061 this._operator = Operator.EQ; 062 } 063 064 @Override 065 public String build() throws QuerySyntaxException 066 { 067 StringBuilder query = new StringBuilder(); 068 069 boolean appendNegation = _operator == Operator.NE && _shared || _operator == Operator.EQ && !_shared; 070 if (appendNegation) 071 { 072 query.append('('); 073 NotQuery.appendNegation(query); 074 } 075 076 query.append(SolrWebFieldNames.SHARED).append(":") 077 .append(_operator == Operator.EXISTS ? QueryHelper.EXISTS_VALUE : "true"); 078 079 if (appendNegation) 080 { 081 query.append(')'); 082 } 083 084 return query.toString(); 085 } 086 087 @Override 088 public int hashCode() 089 { 090 final int prime = 31; 091 int result = 1; 092 result = prime * result + (_shared ? 1231 : 1237); 093 return result; 094 } 095 096 @Override 097 public boolean equals(Object obj) 098 { 099 if (this == obj) 100 { 101 return true; 102 } 103 if (obj == null) 104 { 105 return false; 106 } 107 if (getClass() != obj.getClass()) 108 { 109 return false; 110 } 111 SharedQuery other = (SharedQuery) obj; 112 if (_shared != other._shared) 113 { 114 return false; 115 } 116 return true; 117 } 118}