Search in sources :

Example 1 with JSONPObject

use of org.codehaus.jackson.map.util.JSONPObject in project meteo by pierre.

the class StreamResource method buildJsonpResponse.

private Response buildJsonpResponse(final String attribute, final Cache<Object, Object> samples, final String callback) {
    try {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        final JsonGenerator generator = objectMapper.getJsonFactory().createJsonGenerator(out);
        generator.writeStartObject();
        generator.writeFieldName("attribute");
        generator.writeString(attribute);
        generator.writeFieldName("samples");
        generator.writeStartArray();
        if (samples != null) {
            final ConcurrentMap<Object, Object> samplesForType = samples.asMap();
            final List<DateTime> timestamps = new ArrayList<DateTime>();
            for (final Object timestamp : samplesForType.keySet()) {
                timestamps.add((DateTime) timestamp);
            }
            Collections.sort(timestamps);
            for (final DateTime timestamp : timestamps) {
                final Object dataPoint = samplesForType.get(timestamp);
                // Might have been evicted already
                if (dataPoint != null) {
                    generator.writeNumber(unixSeconds(timestamp));
                    generator.writeObject(dataPoint);
                }
            }
        }
        generator.writeEndArray();
        generator.writeEndObject();
        generator.close();
        final JSONPObject object = new JSONPObject(callback, out.toString());
        return Response.ok(object).build();
    } catch (IOException e) {
        log.error("Error", e);
        return Response.serverError().build();
    }
}
Also used : ArrayList(java.util.ArrayList) JsonGenerator(org.codehaus.jackson.JsonGenerator) JSONPObject(org.codehaus.jackson.map.util.JSONPObject) JSONPObject(org.codehaus.jackson.map.util.JSONPObject) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) DateTime(org.joda.time.DateTime)

Aggregations

ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 JsonGenerator (org.codehaus.jackson.JsonGenerator)1 JSONPObject (org.codehaus.jackson.map.util.JSONPObject)1 DateTime (org.joda.time.DateTime)1