1 /* 2 * Copyright (C) 2021 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.queryable.queries; 18 19 import com.android.queryable.Queryable; 20 21 import java.io.Serializable; 22 import java.util.ArrayList; 23 import java.util.HashSet; 24 import java.util.List; 25 import java.util.Set; 26 27 /** Implementation of {@link StringQuery}. */ 28 public final class StringQueryHelper<E extends Queryable> 29 implements StringQuery<E>, Serializable{ 30 31 private static final long serialVersionUID = 1; 32 33 private final transient E mQuery; 34 private String mEqualsValue; 35 private Set<String> mNotEqualsValues = new HashSet<>(); 36 StringQueryHelper()37 StringQueryHelper() { 38 mQuery = (E) this; 39 } 40 StringQueryHelper(E query)41 public StringQueryHelper(E query) { 42 mQuery = query; 43 } 44 45 @Override isEqualTo(String string)46 public E isEqualTo(String string) { 47 mEqualsValue = string; 48 return mQuery; 49 } 50 51 @Override isNotEqualTo(String string)52 public E isNotEqualTo(String string) { 53 mNotEqualsValues.add(string); 54 return mQuery; 55 } 56 57 @Override matches(String value)58 public boolean matches(String value) { 59 if (mEqualsValue != null && !mEqualsValue.equals(value)) { 60 return false; 61 } 62 if (mNotEqualsValues.contains(value)) { 63 return false; 64 } 65 66 return true; 67 } 68 matches(StringQueryHelper<?> stringQueryHelper, String value)69 public static boolean matches(StringQueryHelper<?> stringQueryHelper, String value) { 70 return stringQueryHelper.matches(value); 71 } 72 73 /** 74 * True if this query has not been configured. 75 */ isEmpty()76 public boolean isEmpty() { 77 return mEqualsValue == null && mNotEqualsValues.isEmpty(); 78 } 79 80 /** 81 * True if this query is for an exact string match. 82 */ isQueryingForExactMatch()83 public boolean isQueryingForExactMatch() { 84 return mEqualsValue != null; 85 } 86 87 @Override describeQuery(String fieldName)88 public String describeQuery(String fieldName) { 89 List<String> queryStrings = new ArrayList<>(); 90 if (mEqualsValue != null) { 91 queryStrings.add(fieldName + "=\"" + mEqualsValue + "\""); 92 } 93 94 for (String notEquals : mNotEqualsValues) { 95 queryStrings.add(fieldName + "!=\"" + notEquals + "\""); 96 } 97 98 return Queryable.joinQueryStrings(queryStrings); 99 } 100 } 101