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 java.io.ByteArrayOutputStream;
19  import java.io.IOException;
20  import java.io.OutputStream;
21  
22  import org.elasticsearch.common.xcontent.ToXContent;
23  import org.elasticsearch.common.xcontent.XContentBuilder;
24  import org.elasticsearch.common.xcontent.XContentFactory;
25  import org.elasticsearch.common.xcontent.XContentType;
26  import org.slf4j.Logger;
27  import org.slf4j.LoggerFactory;
28  
29  public final class EsUtil {
30  
31      private static final Logger logger = LoggerFactory.getLogger(EsUtil.class);
32  
33      private EsUtil() {
34      }
35  
36      public static OutputStream getXContentBuilderOutputStream(final XContentBuilderCallback func, final XContentType xContentType) {
37          try (final XContentBuilder builder = func.apply(XContentFactory.contentBuilder(xContentType), ToXContent.EMPTY_PARAMS)) {
38              builder.flush();
39              return builder.getOutputStream();
40          } catch (final IOException e) {
41              if (logger.isDebugEnabled()) {
42                  logger.debug("Failed to print the output.", e);
43              }
44              return new ByteArrayOutputStream();
45          }
46      }
47  
48      public static OutputStream getXContentOutputStream(final ToXContent xContent, final XContentType xContentType) {
49          return getXContentBuilderOutputStream((builder, params) -> xContent.toXContent(builder, params), xContentType);
50      }
51  
52      public interface XContentBuilderCallback {
53          XContentBuilder apply(XContentBuilder builder, ToXContent.Params params) throws IOException;
54      }
55  }