001package org.xbib.elasticsearch.rest; 002 003import org.elasticsearch.common.io.stream.BytesStreamOutput; 004import org.elasticsearch.common.xcontent.XContentBuilder; 005import org.elasticsearch.common.xcontent.XContentFactory; 006import org.elasticsearch.common.xcontent.XContentType; 007import org.elasticsearch.rest.RestRequest; 008 009import java.io.IOException; 010 011public class RestXContentBuilder { 012 013 public static XContentBuilder restContentBuilder(RestRequest request) throws IOException { 014 XContentType contentType = XContentType.fromRestContentType(request.param("format", request.header("Content-Type"))); 015 if (contentType == null) { 016 // default to JSON 017 contentType = XContentType.JSON; 018 } 019 XContentBuilder builder = new XContentBuilder(XContentFactory.xContent(contentType), 020 new BytesStreamOutput()); 021 if (request.paramAsBoolean("pretty", false)) { 022 builder.prettyPrint().lfAtEnd(); 023 } 024 String casing = request.param("case"); 025 if (casing != null && "camelCase".equals(casing)) { 026 builder.fieldCaseConversion(XContentBuilder.FieldCaseConversion.CAMELCASE); 027 } else { 028 // we expect all REST interfaces to write results in underscore casing, so 029 // no need for double casing 030 builder.fieldCaseConversion(XContentBuilder.FieldCaseConversion.NONE); 031 } 032 return builder; 033 } 034 035 public static XContentBuilder emptyBuilder(RestRequest request) throws IOException { 036 return restContentBuilder(request).startObject().endObject(); 037 } 038 039}