View Javadoc
1   /*
2    * Copyright 2012-2021 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 java.io.ByteArrayOutputStream;
19  import java.io.IOException;
20  import java.io.OutputStream;
21  import java.util.function.Function;
22  
23  import org.apache.logging.log4j.LogManager;
24  import org.apache.logging.log4j.Logger;
25  import org.codelibs.fesen.common.xcontent.ToXContent;
26  import org.codelibs.fesen.common.xcontent.XContentBuilder;
27  import org.codelibs.fesen.common.xcontent.XContentFactory;
28  import org.codelibs.fesen.common.xcontent.XContentType;
29  import org.codelibs.fesen.search.SearchHit;
30  import org.codelibs.fess.es.client.SearchEngineClient;
31  
32  public final class SearchEngineUtil {
33  
34      private static final Logger logger = LogManager.getLogger(SearchEngineUtil.class);
35  
36      private SearchEngineUtil() {
37      }
38  
39      public static OutputStream getXContentBuilderOutputStream(final XContentBuilderCallback func, final XContentType xContentType) {
40          try (final XContentBuilder builder = func.apply(XContentFactory.contentBuilder(xContentType), ToXContent.EMPTY_PARAMS)) {
41              builder.flush();
42              return builder.getOutputStream();
43          } catch (final IOException e) {
44              if (logger.isDebugEnabled()) {
45                  logger.debug("Failed to print the output.", e);
46              }
47              return new ByteArrayOutputStream();
48          }
49      }
50  
51      public static OutputStream getXContentOutputStream(final ToXContent xContent, final XContentType xContentType) {
52          return getXContentBuilderOutputStream((builder, params) -> xContent.toXContent(builder, params), xContentType);
53      }
54  
55      public static long scroll(final String index, final Function<SearchHit, Boolean> callback) {
56          final SearchEngineClient client = ComponentUtil.getSearchEngineClient();
57          return client.<SearchHit> scrollSearch(index, searchRequestBuilder -> true, (searchResponse, hit) -> hit,
58                  hit -> callback.apply(hit));
59      }
60  
61      public interface XContentBuilderCallback {
62          XContentBuilder apply(XContentBuilder builder, ToXContent.Params params) throws IOException;
63      }
64  
65  }