001/**
002 * Copyright 2015 Tampere University of Technology, Pori Department
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 core.tut.pori.dao.filter;
017
018import org.apache.commons.lang3.StringUtils;
019import org.apache.solr.client.solrj.util.ClientUtils;
020
021import core.tut.pori.dao.SolrQueryBuilder;
022
023/**
024 * Filter that supports range operations (field:[* TO *]) for Solr queries
025 * 
026 */
027public class RangeQueryFilter implements AbstractQueryFilter {
028  private String _fieldName = null;
029  private Object _from = null;
030  private Object _to = null;
031  private QueryType _type = null;
032  
033  /**
034   * Both from and to can be of any object type, which can be converted to string using java.lang.String.valueOf()
035   * 
036   * @param fieldName solr field to target the search on
037   * @param from start range (inclusive), if null all values <= end will be returned
038   * @param to end range clause (inclusive), if null all values >= start will be returned
039   * @throws IllegalArgumentException on bad field name, or if both from and to are null
040   */
041  public RangeQueryFilter(String fieldName, Object from, Object to) throws IllegalArgumentException{
042    if(StringUtils.isBlank(fieldName)){
043      throw new IllegalArgumentException("Invalid field name : "+fieldName);
044    }
045    if(from == null && to == null){
046      throw new IllegalArgumentException("From and to cannot both be null.");
047    }
048    _fieldName = fieldName;
049    _from = from;
050    _to = to;
051  }
052
053  @Override
054  public void toFilterString(StringBuilder fq) {
055    fq.append('(');
056    fq.append(_fieldName);
057    fq.append(SolrQueryBuilder.SEPARATOR_SOLR_FIELD_VALUE);
058    fq.append('[');
059    if(_from != null){
060      fq.append(ClientUtils.escapeQueryChars(String.valueOf(_from)));
061      fq.append(" TO ");
062    }else{ // everything < _to
063      fq.append("* TO ");
064    }
065    if(_to != null){
066      fq.append(ClientUtils.escapeQueryChars(String.valueOf(_to)));
067      fq.append("]");
068    }else{ // everything > _from
069      fq.append("*]");
070    } // else
071    
072    fq.append(')');
073  }
074
075  @Override
076  public QueryType getQueryType() {
077    return _type;
078  }
079}