1
2
3
4
5
6
7
8
9
10
11
12
13
14
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 }