001/* 002 * Copyright 2014 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 018/** 019 * Represents a {@link Query} corresponding to the logical negation of another {@link Query}. 020 */ 021public class NotQuery implements Query 022{ 023 /** The prefix for making a query negative. */ 024 public static final String NEGATION_QUERY_PREFIX = "*:* -"; 025 026 /** The negated query. */ 027 protected Query _query; 028 029 /** 030 * Build a NotQuery object. 031 * @param query the negated query. 032 */ 033 public NotQuery(Query query) 034 { 035 _query = query; 036 } 037 038 /** 039 * Get the negated query. 040 * @return the negated query. 041 */ 042 public Query getQuery() 043 { 044 return _query; 045 } 046 047 /** 048 * Appends a negation to the query being built. 049 * <br>This method just does <code>sb.append({@value #NEGATION_QUERY_PREFIX});</code> 050 * @param query The query builder 051 * @return The given query builder 052 */ 053 public static StringBuilder appendNegation(StringBuilder query) 054 { 055 query.append(NEGATION_QUERY_PREFIX); 056 return query; 057 } 058 059 @Override 060 public String build() throws QuerySyntaxException 061 { 062 String queryString = _query.build(); 063 if (queryString.isEmpty()) 064 { 065 return ""; 066 } 067 else 068 { 069 return "(" + NEGATION_QUERY_PREFIX + "(" + _query.build() + "))"; 070 } 071 } 072 073 @Override 074 public int hashCode() 075 { 076 final int prime = 31; 077 int result = 1; 078 result = prime * result + ((_query == null) ? 0 : _query.hashCode()); 079 return result; 080 } 081 082 @Override 083 public boolean equals(Object obj) 084 { 085 if (this == obj) 086 { 087 return true; 088 } 089 if (obj == null) 090 { 091 return false; 092 } 093 if (getClass() != obj.getClass()) 094 { 095 return false; 096 } 097 NotQuery other = (NotQuery) obj; 098 if (_query == null) 099 { 100 if (other._query != null) 101 { 102 return false; 103 } 104 } 105 else if (!_query.equals(other._query)) 106 { 107 return false; 108 } 109 return true; 110 } 111}