View Javadoc
1   /*
2    * Copyright 2012-2019 CodeLibs Project and the Others.
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,
13   * either express or implied. See the License for the specific language
14   * governing permissions and limitations under the License.
15   */
16  package org.codelibs.fess.util;
17  
18  import static org.codelibs.core.stream.StreamUtil.split;
19  import static org.codelibs.core.stream.StreamUtil.stream;
20  
21  import java.util.Map;
22  import java.util.stream.Collectors;
23  
24  import org.codelibs.core.lang.StringUtil;
25  import org.codelibs.fess.entity.SearchRequestParams;
26  import org.codelibs.fess.helper.RelatedQueryHelper;
27  import org.codelibs.fess.mylasta.direction.FessConfig;
28  
29  public class QueryStringBuilder {
30  
31      private static final String OR_ALT = " || ";
32  
33      private static final String OR = " OR ";
34  
35      private static final String SPACE = " ";
36  
37      private SearchRequestParams params;
38  
39      protected String quote(final String value) {
40          if (value.split("\\s").length > 1) {
41              return new StringBuilder().append('"').append(value.replace('"', ' ')).append('"').toString();
42          }
43          return value;
44      }
45  
46      public String build() {
47          final FessConfig fessConfig = ComponentUtil.getFessConfig();
48          final int maxQueryLength = fessConfig.getQueryMaxLengthAsInteger().intValue();
49          final StringBuilder queryBuf = new StringBuilder(255);
50  
51          final String query = buildBaseQuery();
52          if (StringUtil.isNotBlank(query)) {
53              queryBuf.append(query);
54          }
55  
56          stream(params.getExtraQueries()).of(
57                  stream -> stream.filter(q -> StringUtil.isNotBlank(q) && q.length() <= maxQueryLength).forEach(q -> {
58                      appendQuery(queryBuf, q);
59                  }));
60  
61          stream(params.getFields()).of(stream -> stream.forEach(entry -> {
62              final String key = entry.getKey();
63              final String[] values = entry.getValue();
64              if (values == null) {
65                  // nothing
66              } else if (values.length == 1) {
67                  queryBuf.append(' ').append(key).append(":\"").append(values[0]).append('\"');
68              } else if (values.length > 1) {
69                  boolean first = true;
70                  queryBuf.append(" (");
71                  for (final String value : values) {
72                      if (first) {
73                          first = false;
74                      } else {
75                          queryBuf.append(OR);
76                      }
77                      queryBuf.append(key).append(":\"").append(value).append('\"');
78                  }
79                  queryBuf.append(')');
80              }
81          }));
82  
83          return queryBuf.toString().trim();
84      }
85  
86      protected void appendQuery(final StringBuilder queryBuf, final String query) {
87          String q = query;
88          for (final String s : ComponentUtil.getFessConfig().getCrawlerDocumentSpaces()) {
89              q = q.replace(s, SPACE);
90          }
91          final boolean exists = q.indexOf(OR) != -1 || q.indexOf(OR_ALT) != -1;
92          queryBuf.append(' ');
93          if (exists) {
94              queryBuf.append('(');
95          }
96          queryBuf.append(query);
97          if (exists) {
98              queryBuf.append(')');
99          }
100     }
101 
102     protected String buildBaseQuery() {
103         final StringBuilder queryBuf = new StringBuilder(255);
104         if (params.hasConditionQuery()) {
105             appendConditions(queryBuf, params.getConditions());
106         } else {
107             final String query = params.getQuery();
108             if (StringUtil.isNotBlank(query)) {
109                 if (ComponentUtil.hasRelatedQueryHelper()) {
110                     final RelatedQueryHelper relatedQueryHelper = ComponentUtil.getRelatedQueryHelper();
111                     final String[] relatedQueries = relatedQueryHelper.getRelatedQueries(query);
112                     if (relatedQueries.length == 0) {
113                         appendQuery(queryBuf, query);
114                     } else {
115                         queryBuf.append('(');
116                         queryBuf.append(quote(query));
117                         for (final String s : relatedQueries) {
118                             queryBuf.append(OR);
119                             queryBuf.append(quote(s));
120                         }
121                         queryBuf.append(')');
122                     }
123                 } else {
124                     appendQuery(queryBuf, query);
125                 }
126             }
127         }
128         return queryBuf.toString().trim();
129     }
130 
131     protected void appendConditions(final StringBuilder queryBuf, final Map<String, String[]> conditions) {
132         if (conditions == null) {
133             return;
134         }
135         final FessConfig fessConfig = ComponentUtil.getFessConfig();
136         final int maxQueryLength = fessConfig.getQueryMaxLengthAsInteger().intValue();
137 
138         stream(conditions.get(SearchRequestParams.AS_OCCURRENCE)).of(
139                 stream -> stream.filter(q -> isOccurrence(q)).findFirst().ifPresent(q -> queryBuf.insert(0, q + ":")));
140 
141         stream(conditions.get(SearchRequestParams.AS_Q)).of(
142                 stream -> stream.filter(q -> StringUtil.isNotBlank(q) && q.length() <= maxQueryLength).forEach(
143                         q -> queryBuf.append(' ').append(q)));
144         stream(conditions.get(SearchRequestParams.AS_EPQ)).of(
145                 stream -> stream.filter(q -> StringUtil.isNotBlank(q) && q.length() <= maxQueryLength).forEach(
146                         q -> queryBuf.append(" \"").append(escape(q, "\"")).append('"')));
147         stream(conditions.get(SearchRequestParams.AS_OQ)).of(
148                 stream -> stream.filter(q -> StringUtil.isNotBlank(q) && q.length() <= maxQueryLength).forEach(
149                         oq -> split(oq, " ").get(
150                                 s -> s.filter(StringUtil::isNotBlank).reduce((q1, q2) -> escape(q1, "(", ")") + OR + escape(q2, "(", ")")))
151                                 .ifPresent(q -> {
152                                     appendQuery(queryBuf, q);
153                                 })));
154         stream(conditions.get(SearchRequestParams.AS_NQ)).of(
155                 stream -> stream.filter(q -> StringUtil.isNotBlank(q) && q.length() <= maxQueryLength).forEach(
156                         eq -> {
157                             final String nq =
158                                     split(eq, " ").get(
159                                             s -> s.filter(StringUtil::isNotBlank).map(q -> "NOT " + q).collect(Collectors.joining(" ")));
160                             queryBuf.append(' ').append(nq);
161                         }));
162         stream(conditions.get(SearchRequestParams.AS_FILETYPE)).of(
163                 stream -> stream.filter(q -> StringUtil.isNotBlank(q) && q.length() <= maxQueryLength).forEach(
164                         q -> queryBuf.append(" filetype:\"").append(q.trim()).append('"')));
165         stream(conditions.get(SearchRequestParams.AS_SITESEARCH)).of(
166                 stream -> stream.filter(q -> StringUtil.isNotBlank(q) && q.length() <= maxQueryLength).forEach(
167                         q -> queryBuf.append(" site:").append(q.trim())));
168         stream(conditions.get(SearchRequestParams.AS_TIMESTAMP)).of(
169                 stream -> stream.filter(q -> StringUtil.isNotBlank(q) && q.length() <= maxQueryLength).forEach(
170                         q -> queryBuf.append(" timestamp:").append(q.trim())));
171     }
172 
173     protected boolean isOccurrence(final String value) {
174         return "allintitle".equals(value) || "allinurl".equals(value);
175     }
176 
177     protected String escape(final String q, final String... values) {
178         String value = q;
179         for (final String s : values) {
180             value = value.replace(s, "\\" + s);
181         }
182         return value;
183     }
184 
185     public QueryStringBuilder params(final SearchRequestParams params) {
186         this.params = params;
187         return this;
188     }
189 }