Add support to output date types with JsonBuilder

This commit is contained in:
kimchy 2010-02-12 16:12:16 +02:00
parent 9e8b5e5060
commit 8f1023cbbe
13 changed files with 69 additions and 20 deletions

View File

@ -26,7 +26,7 @@ import org.elasticsearch.util.json.JsonBuilder;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import static org.elasticsearch.util.json.JsonBuilder.Cached.*; import static org.elasticsearch.util.json.JsonBuilder.*;
/** /**
* @author kimchy (Shay Banon) * @author kimchy (Shay Banon)
@ -59,7 +59,7 @@ public class JsonThrowableHttpResponse extends JsonHttpResponse {
Holder holder = cache.get(); Holder holder = cache.get();
holder.writer.reset(); holder.writer.reset();
t.printStackTrace(holder.printWriter); t.printStackTrace(holder.printWriter);
JsonBuilder builder = cached().prettyPrint() JsonBuilder builder = jsonBuilder().prettyPrint()
.startObject().field("error", ExceptionsHelper.detailedMessage(t, false, 0)); .startObject().field("error", ExceptionsHelper.detailedMessage(t, false, 0));
builder.startObject("debug"); builder.startObject("debug");
boolean first = true; boolean first = true;

View File

@ -85,7 +85,7 @@ public class HttpCreateIndexAction extends BaseHttpServerHandler {
try { try {
Throwable t = unwrapCause(e); Throwable t = unwrapCause(e);
if (t instanceof IndexAlreadyExistsException || t instanceof InvalidIndexNameException) { if (t instanceof IndexAlreadyExistsException || t instanceof InvalidIndexNameException) {
channel.sendResponse(new JsonHttpResponse(request, BAD_REQUEST, JsonBuilder.cached().startObject().field("error", t.getMessage()).endObject())); channel.sendResponse(new JsonHttpResponse(request, BAD_REQUEST, JsonBuilder.jsonBuilder().startObject().field("error", t.getMessage()).endObject()));
} else { } else {
channel.sendResponse(new JsonThrowableHttpResponse(request, e)); channel.sendResponse(new JsonThrowableHttpResponse(request, e));
} }

View File

@ -36,7 +36,7 @@ import java.io.IOException;
import static org.elasticsearch.http.HttpResponse.Status.*; import static org.elasticsearch.http.HttpResponse.Status.*;
import static org.elasticsearch.util.TimeValue.*; import static org.elasticsearch.util.TimeValue.*;
import static org.elasticsearch.util.json.JsonBuilder.Cached.*; import static org.elasticsearch.util.json.JsonBuilder.*;
/** /**
* @author kimchy (Shay Banon) * @author kimchy (Shay Banon)
@ -54,7 +54,7 @@ public class HttpDeleteIndexAction extends BaseHttpServerHandler {
client.admin().indices().execDelete(deleteIndexRequest, new ActionListener<DeleteIndexResponse>() { client.admin().indices().execDelete(deleteIndexRequest, new ActionListener<DeleteIndexResponse>() {
@Override public void onResponse(DeleteIndexResponse result) { @Override public void onResponse(DeleteIndexResponse result) {
try { try {
channel.sendResponse(new JsonHttpResponse(request, OK, cached().startObject().field("ok", true).endObject())); channel.sendResponse(new JsonHttpResponse(request, OK, jsonBuilder().startObject().field("ok", true).endObject()));
} catch (IOException e) { } catch (IOException e) {
onFailure(e); onFailure(e);
} }

View File

@ -69,7 +69,7 @@ public class HttpCreateMappingAction extends BaseHttpServerHandler {
try { try {
Throwable t = unwrapCause(e); Throwable t = unwrapCause(e);
if (t instanceof IndexMissingException || t instanceof InvalidTypeNameException) { if (t instanceof IndexMissingException || t instanceof InvalidTypeNameException) {
channel.sendResponse(new JsonHttpResponse(request, BAD_REQUEST, JsonBuilder.cached().startObject().field("error", t.getMessage()).endObject())); channel.sendResponse(new JsonHttpResponse(request, BAD_REQUEST, JsonBuilder.jsonBuilder().startObject().field("error", t.getMessage()).endObject()));
} else { } else {
channel.sendResponse(new JsonThrowableHttpResponse(request, e)); channel.sendResponse(new JsonThrowableHttpResponse(request, e));
} }

View File

@ -71,7 +71,7 @@ public class HttpCountAction extends BaseHttpServerHandler {
} }
} catch (Exception e) { } catch (Exception e) {
try { try {
channel.sendResponse(new JsonHttpResponse(request, BAD_REQUEST, JsonBuilder.cached().startObject().field("error", e.getMessage()).endObject())); channel.sendResponse(new JsonHttpResponse(request, BAD_REQUEST, JsonBuilder.jsonBuilder().startObject().field("error", e.getMessage()).endObject()));
} catch (IOException e1) { } catch (IOException e1) {
logger.error("Failed to send failure response", e1); logger.error("Failed to send failure response", e1);
} }

View File

@ -63,7 +63,7 @@ public class HttpDeleteByQueryAction extends BaseHttpServerHandler {
deleteByQueryRequest.timeout(TimeValue.parseTimeValue(request.param("timeout"), ShardDeleteByQueryRequest.DEFAULT_TIMEOUT)); deleteByQueryRequest.timeout(TimeValue.parseTimeValue(request.param("timeout"), ShardDeleteByQueryRequest.DEFAULT_TIMEOUT));
} catch (Exception e) { } catch (Exception e) {
try { try {
channel.sendResponse(new JsonHttpResponse(request, PRECONDITION_FAILED, JsonBuilder.cached().startObject().field("error", e.getMessage()).endObject())); channel.sendResponse(new JsonHttpResponse(request, PRECONDITION_FAILED, JsonBuilder.jsonBuilder().startObject().field("error", e.getMessage()).endObject()));
} catch (IOException e1) { } catch (IOException e1) {
logger.error("Failed to send failure response", e1); logger.error("Failed to send failure response", e1);
} }

View File

@ -56,7 +56,7 @@ public class HttpIndexAction extends BaseHttpServerHandler {
indexRequest.opType(IndexRequest.OpType.CREATE); indexRequest.opType(IndexRequest.OpType.CREATE);
} else { } else {
try { try {
channel.sendResponse(new JsonHttpResponse(request, BAD_REQUEST, JsonBuilder.cached().startObject().field("error", "opType [" + sOpType + "] not allowed, either [index] or [create] are allowed").endObject())); channel.sendResponse(new JsonHttpResponse(request, BAD_REQUEST, JsonBuilder.jsonBuilder().startObject().field("error", "opType [" + sOpType + "] not allowed, either [index] or [create] are allowed").endObject()));
} catch (IOException e1) { } catch (IOException e1) {
logger.warn("Failed to send response", e1); logger.warn("Failed to send response", e1);
return; return;

View File

@ -77,7 +77,7 @@ public class HttpSearchAction extends BaseHttpServerHandler {
searchRequest.operationThreading(operationThreading); searchRequest.operationThreading(operationThreading);
} catch (Exception e) { } catch (Exception e) {
try { try {
channel.sendResponse(new JsonHttpResponse(request, BAD_REQUEST, JsonBuilder.cached().startObject().field("error", e.getMessage()).endObject())); channel.sendResponse(new JsonHttpResponse(request, BAD_REQUEST, JsonBuilder.jsonBuilder().startObject().field("error", e.getMessage()).endObject()));
} catch (IOException e1) { } catch (IOException e1) {
logger.error("Failed to send failure response", e1); logger.error("Failed to send failure response", e1);
} }

View File

@ -30,7 +30,7 @@ import java.io.IOException;
public class HttpJsonBuilder { public class HttpJsonBuilder {
public static JsonBuilder cached(HttpRequest request) throws IOException { public static JsonBuilder cached(HttpRequest request) throws IOException {
JsonBuilder builder = JsonBuilder.cached(); JsonBuilder builder = JsonBuilder.jsonBuilder();
String prettyPrint = request.param("pretty"); String prettyPrint = request.param("pretty");
if (prettyPrint != null && "true".equals(prettyPrint)) { if (prettyPrint != null && "true".equals(prettyPrint)) {
builder.prettyPrint(); builder.prettyPrint();

View File

@ -31,7 +31,7 @@ public abstract class BaseJsonQueryBuilder implements JsonQueryBuilder {
@Override public String build() throws QueryBuilderException { @Override public String build() throws QueryBuilderException {
try { try {
JsonBuilder builder = JsonBuilder.cached(); JsonBuilder builder = JsonBuilder.jsonBuilder();
toJson(builder); toJson(builder);
return builder.string(); return builder.string();
} catch (Exception e) { } catch (Exception e) {

View File

@ -124,7 +124,7 @@ public class SearchSourceBuilder {
public String build() { public String build() {
try { try {
JsonBuilder builder = JsonBuilder.cached(); JsonBuilder builder = JsonBuilder.jsonBuilder();
builder.startObject(); builder.startObject();
if (from != -1) { if (from != -1) {

View File

@ -24,8 +24,13 @@ import org.codehaus.jackson.JsonFactory;
import org.elasticsearch.ElasticSearchException; import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.util.concurrent.NotThreadSafe; import org.elasticsearch.util.concurrent.NotThreadSafe;
import org.elasticsearch.util.io.FastCharArrayWriter; import org.elasticsearch.util.io.FastCharArrayWriter;
import org.joda.time.DateTimeZone;
import org.joda.time.ReadableInstant;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import java.io.IOException; import java.io.IOException;
import java.util.Date;
/** /**
* @author kimchy (Shay Banon) * @author kimchy (Shay Banon)
@ -33,6 +38,8 @@ import java.io.IOException;
@NotThreadSafe @NotThreadSafe
public class JsonBuilder { public class JsonBuilder {
private final static DateTimeFormatter defaultDatePrinter = ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC);
/** /**
* A thread local based cache of {@link JsonBuilder}. * A thread local based cache of {@link JsonBuilder}.
*/ */
@ -57,19 +64,14 @@ public class JsonBuilder {
/** /**
* Returns the cached thread local generator, with its internal {@link StringBuilder} cleared. * Returns the cached thread local generator, with its internal {@link StringBuilder} cleared.
*/ */
public static JsonBuilder cached() throws IOException { static JsonBuilder cached() throws IOException {
Cached cached = cache.get(); Cached cached = cache.get();
cached.generator.reset(); cached.generator.reset();
return cached.generator; return cached.generator;
} }
public static JsonBuilder cachedNoReset() {
Cached cached = cache.get();
return cached.generator;
}
} }
public static JsonBuilder cached() throws IOException { public static JsonBuilder jsonBuilder() throws IOException {
return Cached.cached(); return Cached.cached();
} }
@ -226,6 +228,26 @@ public class JsonBuilder {
return this; return this;
} }
public JsonBuilder field(String name, ReadableInstant date) throws IOException {
generator.writeFieldName(name);
return date(date);
}
public JsonBuilder field(String name, ReadableInstant date, DateTimeFormatter formatter) throws IOException {
generator.writeFieldName(name);
return date(date, formatter);
}
public JsonBuilder field(String name, Date date) throws IOException {
generator.writeFieldName(name);
return date(date);
}
public JsonBuilder field(String name, Date date, DateTimeFormatter formatter) throws IOException {
generator.writeFieldName(name);
return date(date, formatter);
}
public JsonBuilder nullField(String name) throws IOException { public JsonBuilder nullField(String name) throws IOException {
generator.writeNullField(name); generator.writeNullField(name);
return this; return this;
@ -286,6 +308,24 @@ public class JsonBuilder {
return this; return this;
} }
public JsonBuilder date(ReadableInstant date) throws IOException {
return date(date, defaultDatePrinter);
}
public JsonBuilder date(ReadableInstant date, DateTimeFormatter dateTimeFormatter) throws IOException {
string(dateTimeFormatter.print(date));
return this;
}
public JsonBuilder date(Date date) throws IOException {
return date(date, defaultDatePrinter);
}
public JsonBuilder date(Date date, DateTimeFormatter dateTimeFormatter) throws IOException {
string(dateTimeFormatter.print(date.getTime()));
return this;
}
public JsonBuilder value(Object value) throws IOException { public JsonBuilder value(Object value) throws IOException {
Class type = value.getClass(); Class type = value.getClass();
if (type == String.class) { if (type == String.class) {

View File

@ -24,6 +24,8 @@ import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat; import org.joda.time.format.ISODateTimeFormat;
import org.testng.annotations.Test; import org.testng.annotations.Test;
import java.util.Date;
import static org.hamcrest.MatcherAssert.*; import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
@ -54,4 +56,11 @@ public class SimpleJodaTests {
millis = formatter.parseMillis("1970-01-01"); millis = formatter.parseMillis("1970-01-01");
assertThat(millis, equalTo(0l)); assertThat(millis, equalTo(0l));
} }
@Test public void testWriteAndParse() {
DateTimeFormatter dateTimeWriter = ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC);
DateTimeFormatter formatter = ISODateTimeFormat.dateOptionalTimeParser().withZone(DateTimeZone.UTC);
Date date = new Date();
assertThat(formatter.parseMillis(dateTimeWriter.print(date.getTime())), equalTo(date.getTime()));
}
} }