List of usage examples for com.fasterxml.jackson.core JsonGenerator writeEndArray
public abstract void writeEndArray() throws IOException, JsonGenerationException;
From source file:org.apache.olingo.commons.core.serialization.JsonSerializer.java
private void collection(final JsonGenerator jgen, final EdmTypeInfo typeInfo, final ValueType valueType, final List<?> value) throws IOException, EdmPrimitiveTypeException { jgen.writeStartArray();/* w ww . jav a 2 s . co m*/ for (Object item : value) { final EdmTypeInfo itemTypeInfo = typeInfo == null ? null : new EdmTypeInfo.Builder().setTypeExpression(typeInfo.getFullQualifiedName().toString()) .build(); switch (valueType) { case COLLECTION_PRIMITIVE: primitiveValue(jgen, itemTypeInfo, item); break; case COLLECTION_GEOSPATIAL: jgen.writeStartObject(); geoSerializer.serialize(jgen, (Geospatial) item); jgen.writeEndObject(); break; case COLLECTION_ENUM: jgen.writeString(item.toString()); break; case COLLECTION_COMPLEX: @SuppressWarnings("unchecked") final List<Property> complexItem = (List<Property>) item; complexValue(jgen, itemTypeInfo, complexItem, null); break; case COLLECTION_LINKED_COMPLEX: final LinkedComplexValue complexItem2 = (LinkedComplexValue) item; complexValue(jgen, itemTypeInfo, complexItem2.getValue(), complexItem2); break; default: } } jgen.writeEndArray(); }
From source file:com.attribyte.essem.model.StoredGraph.java
/** * Generates JSON for this key./*from w w w . ja v a 2s . com*/ * @param generator The generator. * @throws java.io.IOException on generation error. */ public void generateJSON(final JsonGenerator generator) throws IOException { generator.writeStartObject(); generator.writeStringField("id", id); generator.writeStringField("uid", uid); generator.writeStringField("index", index); generator.writeStringField("application", key.application); generator.writeStringField("host", key.host); generator.writeStringField("instance", key.instance); generator.writeStringField("name", key.name); generator.writeStringField("field", key.field); generator.writeStringField("range", range); generator.writeNumberField("startTimestamp", startTimestamp); generator.writeNumberField("endTimestamp", endTimestamp); generator.writeStringField("downsampleFn", downsampleFn); if (rateUnit != null) generator.writeStringField("rateUnit", rateUnit); generator.writeStringField("title", title); generator.writeStringField("description", description); generator.writeStringField("xLabel", xLabel); generator.writeStringField("yLabel", yLabel); generator.writeArrayFieldStart("tag"); for (String tag : tags) { generator.writeString(tag); } generator.writeEndArray(); generator.writeStringField("created", DateTime.standardFormat(this.createTime)); generator.writeEndObject(); }
From source file:net.opentsdb.tsd.HttpSampleSerializer.java
/** * Format the results from a timeseries data query * @param data_query The TSQuery object used to fetch the results * @param results The data fetched from storage * @param globals An optional list of global annotation objects * @return A ChannelBuffer object to pass on to the caller *//*w w w . ja v a 2 s . c om*/ public ChannelBuffer formatQueryV1(final TSQuery data_query, final List<DataPoints[]> results, final List<Annotation> globals) { final boolean as_arrays = this.query.hasQueryStringParam("arrays"); final String jsonp = this.query.getQueryStringParam("jsonp"); // todo - this should be streamed at some point since it could be HUGE final ChannelBuffer response = ChannelBuffers.dynamicBuffer(); final OutputStream output = new ChannelBufferOutputStream(response); try { // don't forget jsonp if (jsonp != null && !jsonp.isEmpty()) { output.write((jsonp + "(").getBytes(query.getCharset())); } JsonGenerator json = JSON.getFactory().createGenerator(output); json.writeStartArray(); for (DataPoints[] separate_dps : results) { for (DataPoints dps : separate_dps) { json.writeStartObject(); json.writeStringField("metric", dps.metricName()); json.writeFieldName("tags"); json.writeStartObject(); if (dps.getTags() != null) { for (Map.Entry<String, String> tag : dps.getTags().entrySet()) { json.writeStringField(tag.getKey(), tag.getValue()); } } json.writeEndObject(); json.writeFieldName("aggregateTags"); json.writeStartArray(); if (dps.getAggregatedTags() != null) { for (String atag : dps.getAggregatedTags()) { json.writeString(atag); } } json.writeEndArray(); if (data_query.getShowTSUIDs()) { json.writeFieldName("tsuids"); json.writeStartArray(); final List<String> tsuids = dps.getTSUIDs(); Collections.sort(tsuids); for (String tsuid : tsuids) { json.writeString(tsuid); } json.writeEndArray(); } if (!data_query.getNoAnnotations()) { final List<Annotation> annotations = dps.getAnnotations(); if (annotations != null) { Collections.sort(annotations); json.writeArrayFieldStart("annotations"); for (Annotation note : annotations) { json.writeObject(note); } json.writeEndArray(); } if (globals != null && !globals.isEmpty()) { Collections.sort(globals); json.writeArrayFieldStart("globalAnnotations"); for (Annotation note : globals) { json.writeObject(note); } json.writeEndArray(); } } // now the fun stuff, dump the data json.writeFieldName("dps"); // default is to write a map, otherwise write arrays if (as_arrays) { json.writeStartArray(); for (final DataPoint dp : dps) { if (dp.timestamp() < data_query.startTime() || dp.timestamp() > data_query.endTime()) { continue; } final long timestamp = data_query.getMsResolution() ? dp.timestamp() : dp.timestamp() / 1000; json.writeStartArray(); json.writeNumber(timestamp); json.writeNumber(dp.isInteger() ? dp.longValue() : dp.doubleValue()); json.writeEndArray(); } json.writeEndArray(); } else { json.writeStartObject(); for (final DataPoint dp : dps) { if (dp.timestamp() < (data_query.startTime()) || dp.timestamp() > (data_query.endTime())) { continue; } final long timestamp = data_query.getMsResolution() ? dp.timestamp() : dp.timestamp() / 1000; json.writeNumberField(Long.toString(timestamp), dp.isInteger() ? dp.longValue() : dp.doubleValue()); } json.writeEndObject(); } // close the results for this particular query json.writeEndObject(); } } // close json.writeEndArray(); json.close(); if (jsonp != null && !jsonp.isEmpty()) { output.write(")".getBytes()); } return response; } catch (IOException e) { LOG.error("Unexpected exception", e); throw new RuntimeException(e); } }
From source file:com.msopentech.odatajclient.engine.data.json.DOMTreeUtilsV4.java
public static void writeSubtree(final ODataClient client, final JsonGenerator jgen, final Node content, final boolean propType) throws IOException { for (Node child : XMLUtils.getChildNodes(content, Node.ELEMENT_NODE)) { final String childName = XMLUtils.getSimpleName(child); final Node typeAttr = child.getAttributes().getNamedItem(ODataConstants.ATTR_M_TYPE); if (typeAttr != null && EdmSimpleType.isGeospatial(typeAttr.getTextContent())) { jgen.writeStringField(// w ww.j a v a2 s .c o m propType ? ODataConstants.JSON_TYPE : childName + "@" + ODataConstants.JSON_TYPE, typeAttr.getTextContent()); jgen.writeObjectFieldStart(childName); GeospatialJSONHandler.serialize(jgen, (Element) child, typeAttr.getTextContent()); jgen.writeEndObject(); } else if (XMLUtils.hasOnlyTextChildNodes(child)) { if (child.hasChildNodes()) { final String out; if (typeAttr == null) { out = child.getChildNodes().item(0).getNodeValue(); } else { if (typeAttr.getTextContent().startsWith("Edm.")) { final EdmSimpleType type = EdmSimpleType.fromValue(typeAttr.getTextContent()); final ODataPrimitiveValue value = client.getPrimitiveValueBuilder().setType(type) .setText(child.getChildNodes().item(0).getNodeValue()).build(); out = value.toString(); jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE, type.toString()); } else { // enum out = child.getTextContent(); jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE, typeAttr.getTextContent()); } } jgen.writeStringField(childName, out); } else { if (child.getAttributes().getNamedItem(ODataConstants.ATTR_NULL) == null) { if (typeAttr != null && EdmSimpleType.String.toString().equals(typeAttr.getTextContent())) { jgen.writeStringField(childName + "@" + ODataConstants.JSON_TYPE, typeAttr.getTextContent()); jgen.writeStringField(childName, StringUtils.EMPTY); } else { jgen.writeArrayFieldStart(childName); jgen.writeEndArray(); } } else { jgen.writeNullField(childName); } } } else { if (XMLUtils.hasElementsChildNode(child)) { jgen.writeArrayFieldStart(childName); for (Node nephew : XMLUtils.getChildNodes(child, Node.ELEMENT_NODE)) { if (XMLUtils.hasOnlyTextChildNodes(nephew)) { jgen.writeString(nephew.getChildNodes().item(0).getNodeValue()); } else { jgen.writeStartObject(); DOMTreeUtils.writeSubtree(client, jgen, nephew); jgen.writeEndObject(); } } jgen.writeEndArray(); } else { jgen.writeObjectFieldStart(childName); if (typeAttr != null) { jgen.writeStringField("@" + ODataConstants.JSON_TYPE, typeAttr.getTextContent()); } DOMTreeUtils.writeSubtree(client, jgen, child); jgen.writeEndObject(); } } } }
From source file:org.apache.olingo.server.core.serializer.json.ODataJsonSerializer.java
protected void writeEntitySet(final ServiceMetadata metadata, final EdmEntityType entityType, final AbstractEntityCollection entitySet, final ExpandOption expand, Integer toDepth, final SelectOption select, final boolean onlyReference, final Set<String> ancestors, String name, final JsonGenerator json) throws IOException, SerializerException, DecoderException { json.writeStartArray();/*from w ww . ja v a 2s . c o m*/ for (final Entity entity : entitySet) { if (onlyReference) { json.writeStartObject(); json.writeStringField(constants.getId(), getEntityId(entity, entityType, name)); json.writeEndObject(); } else { writeEntity(metadata, entityType, entity, null, expand, toDepth, select, false, ancestors, name, json); } } json.writeEndArray(); }
From source file:org.talend.dataprep.schema.xls.serialization.XlsxStreamRunnable.java
/** * @see Runnable#run()//from w ww. j av a2 s . co m */ @Override public void run() { try { JsonGenerator generator = jsonFactory.createGenerator(jsonOutput); Workbook workbook = StreamingReader.builder() // .bufferSize(4096) // .rowCacheSize(1) // .open(rawContent); try { Sheet sheet = StringUtils.isEmpty(metadata.getSheetName()) ? // workbook.getSheetAt(0) : workbook.getSheet(metadata.getSheetName()); generator.writeStartArray(); for (Row row : sheet) { if (limit > 0 && row.getRowNum() > limit) { break; } if (!XlsSerializer.isHeaderLine(row.getRowNum(), metadata.getRowMetadata().getColumns())) { generator.writeStartObject(); // data quality Analyzer doesn't like to not have all columns even if we don't have any values // so create so field with empty value otherwise we get exceptions int i = 0; for (ColumnMetadata columnMetadata : metadata.getRowMetadata().getColumns()) { Cell cell = row.getCell(i); String cellValue = cell == null ? null : cell.getStringCellValue(); // StringUtils.EMPTY generator.writeFieldName(columnMetadata.getId()); if (cellValue != null) { generator.writeString(cellValue); } else { generator.writeNull(); } i++; } generator.writeEndObject(); } } generator.writeEndArray(); generator.flush(); } finally { workbook.close(); } } catch (Exception e) { // Consumer may very well interrupt consumption of stream (in case of limit(n) use for sampling). // This is not an issue as consumer is allowed to partially consumes results, it's up to the // consumer to ensure data it consumed is consistent. LOG.debug("Unable to continue serialization for {}. Skipping remaining content.", metadata.getId(), e); } finally { try { jsonOutput.close(); } catch (IOException e) { LOG.error("Unable to close output", e); } } }
From source file:ratpack.codahale.metrics.internal.WebSocketReporter.java
private void writeTimers(JsonGenerator json, SortedMap<String, Timer> timers) throws IOException { json.writeArrayFieldStart("timers"); for (Map.Entry<String, Timer> entry : timers.entrySet()) { Timer timer = entry.getValue(); json.writeStartObject();/*from w w w. j ava 2s. c o m*/ json.writeStringField("name", entry.getKey()); json.writeNumberField("count", timer.getCount()); json.writeNumberField("meanRate", convertRate(timer.getMeanRate())); json.writeNumberField("oneMinuteRate", convertRate(timer.getOneMinuteRate())); json.writeNumberField("fiveMinuteRate", convertRate(timer.getFiveMinuteRate())); json.writeNumberField("fifteenMinuteRate", convertRate(timer.getFifteenMinuteRate())); Snapshot snapshot = timer.getSnapshot(); json.writeNumberField("min", convertDuration(snapshot.getMin())); json.writeNumberField("max", convertDuration(snapshot.getMax())); json.writeNumberField("mean", convertDuration(snapshot.getMean())); json.writeNumberField("stdDev", convertDuration(snapshot.getStdDev())); json.writeNumberField("50thPercentile", convertDuration(snapshot.getMedian())); json.writeNumberField("75thPercentile", convertDuration(snapshot.get75thPercentile())); json.writeNumberField("95thPercentile", convertDuration(snapshot.get95thPercentile())); json.writeNumberField("98thPercentile", convertDuration(snapshot.get98thPercentile())); json.writeNumberField("99thPercentile", convertDuration(snapshot.get99thPercentile())); json.writeNumberField("999thPercentile", convertDuration(snapshot.get999thPercentile())); json.writeEndObject(); } json.writeEndArray(); }
From source file:org.n52.ar.layar.LayarResponse.java
/** * // ww w. ja v a 2 s. com * "hotspots": [{ * * "id": "test_1", * * "anchor": { "geolocation": { "lat": 52.3729, "lon": 4.93 } }, * * "text": { "title": "The Layar Office", "description": "The Location of the Layar Office", "footnote": * "Powered by Layar" }, * * "imageURL": "http:\/\/custom.layar.nl\/layarimage.jpeg", } * * ] * * See http://layar.com/documentation/browser/api/getpois-response/hotspots/ * * @param generator * @param hotspots2 * @throws IOException * @throws JsonGenerationException */ private void createHotspots(JsonGenerator generator) throws JsonGenerationException, IOException { generator.writeFieldName("hotspots"); generator.writeStartArray(); for (Hotspot poi : this.hotspots) { generator.writeStartObject(); generator.writeStringField("id", poi.id); // generator.writeFieldName("actions"); // generator.writeStartArray(); // if (layarPOI.actions != null) { // for (final LayarAction layarAction : layarPOI.actions) { // layarAction.toJSON(generator); // } // } // generator.writeEndArray(); generator.writeObjectFieldStart("anchor"); generator.writeObjectFieldStart("geolocation"); generator.writeNumberField("lat", poi.lat); generator.writeNumberField("lon", poi.lon); generator.writeNumberField("alt", poi.alt); generator.writeEndObject(); generator.writeEndObject(); // generator.writeNumberField("distance", layarPOI.distance); // generator.writeNumberField("type", layarPOI.type); // generator.writeStringField("title", layarPOI.title); generator.writeObjectFieldStart("text"); generator.writeStringField("title", poi.title); generator.writeStringField("description", poi.description); generator.writeStringField("footnote", "Service URL: ..."); generator.writeEndObject(); generator.writeStringField("attribution", poi.attribution); if (poi.imageURL != null) { generator.writeStringField("imageURL", poi.imageURL.toString()); } else { generator.writeNullField("imageURL"); } generator.writeEndObject(); } generator.writeEndArray(); }
From source file:net.opentsdb.tsd.HttpJsonSerializer.java
/** * Format the results from a timeseries data query * @param data_query The TSQuery object used to fetch the results * @param results The data fetched from storage * @param globals An optional list of global annotation objects * @return A ChannelBuffer object to pass on to the caller *///from w w w .j a va2 s . co m public ChannelBuffer formatQueryV1(final TSQuery data_query, final List<DataPoints[]> results, final List<Annotation> globals) { final boolean as_arrays = this.query.hasQueryStringParam("arrays"); final String jsonp = this.query.getQueryStringParam("jsonp"); // todo - this should be streamed at some point since it could be HUGE final ChannelBuffer response = ChannelBuffers.dynamicBuffer(); final OutputStream output = new ChannelBufferOutputStream(response); try { // don't forget jsonp if (jsonp != null && !jsonp.isEmpty()) { output.write((jsonp + "(").getBytes(query.getCharset())); } JsonGenerator json = JSON.getFactory().createGenerator(output); json.writeStartArray(); for (DataPoints[] separate_dps : results) { for (DataPoints dps : separate_dps) { json.writeStartObject(); json.writeStringField("metric", dps.metricName()); json.writeFieldName("tags"); json.writeStartObject(); if (dps.getTags() != null) { for (Map.Entry<String, String> tag : dps.getTags().entrySet()) { json.writeStringField(tag.getKey(), tag.getValue()); } } json.writeEndObject(); json.writeFieldName("aggregateTags"); json.writeStartArray(); if (dps.getAggregatedTags() != null) { for (String atag : dps.getAggregatedTags()) { json.writeString(atag); } } json.writeEndArray(); if (data_query.getShowTSUIDs()) { json.writeFieldName("tsuids"); json.writeStartArray(); final List<String> tsuids = dps.getTSUIDs(); Collections.sort(tsuids); for (String tsuid : tsuids) { json.writeString(tsuid); } json.writeEndArray(); } if (!data_query.getNoAnnotations()) { final List<Annotation> annotations = dps.getAnnotations(); if (annotations != null) { Collections.sort(annotations); json.writeArrayFieldStart("annotations"); for (Annotation note : annotations) { json.writeObject(note); } json.writeEndArray(); } if (globals != null && !globals.isEmpty()) { Collections.sort(globals); json.writeArrayFieldStart("globalAnnotations"); for (Annotation note : globals) { json.writeObject(note); } json.writeEndArray(); } } // now the fun stuff, dump the data json.writeFieldName("dps"); // default is to write a map, otherwise write arrays if (as_arrays) { json.writeStartArray(); for (final DataPoint dp : dps) { if (dp.timestamp() < data_query.startTime() || dp.timestamp() > data_query.endTime()) { continue; } final long timestamp = data_query.getMsResolution() ? dp.timestamp() : dp.timestamp() / 1000; json.writeStartArray(); json.writeNumber(timestamp); if (dp.isInteger()) { json.writeNumber(dp.longValue()); } else { json.writeNumber(dp.doubleValue()); } json.writeEndArray(); } json.writeEndArray(); } else { json.writeStartObject(); for (final DataPoint dp : dps) { if (dp.timestamp() < (data_query.startTime()) || dp.timestamp() > (data_query.endTime())) { continue; } final long timestamp = data_query.getMsResolution() ? dp.timestamp() : dp.timestamp() / 1000; if (dp.isInteger()) { json.writeNumberField(Long.toString(timestamp), dp.longValue()); } else { json.writeNumberField(Long.toString(timestamp), dp.doubleValue()); } } json.writeEndObject(); } // close the results for this particular query json.writeEndObject(); } } // close json.writeEndArray(); json.close(); if (jsonp != null && !jsonp.isEmpty()) { output.write(")".getBytes()); } return response; } catch (IOException e) { LOG.error("Unexpected exception", e); throw new RuntimeException(e); } }
From source file:org.apache.olingo.commons.core.data.JSONEntrySerializer.java
@Override protected void doSerialize(final JSONEntryImpl entry, final JsonGenerator jgen, final SerializerProvider provider) throws IOException, JsonProcessingException { jgen.writeStartObject();/* w w w . j a v a2 s. c o m*/ if (entry.getMetadata() != null) { jgen.writeStringField(Constants.JSON_METADATA, entry.getMetadata().toASCIIString()); } if (entry.getId() != null) { jgen.writeStringField(Constants.JSON_ID, entry.getId()); } final Map<String, List<String>> entitySetLinks = new HashMap<String, List<String>>(); for (Link link : entry.getNavigationLinks()) { ODataLinkType type = null; try { type = ODataLinkType.fromString(version, link.getRel(), link.getType()); } catch (IllegalArgumentException e) { // ignore } if (type == ODataLinkType.ENTITY_SET_NAVIGATION) { final List<String> uris; if (entitySetLinks.containsKey(link.getTitle())) { uris = entitySetLinks.get(link.getTitle()); } else { uris = new ArrayList<String>(); entitySetLinks.put(link.getTitle(), uris); } uris.add(link.getHref()); } else { if (StringUtils.isNotBlank(link.getHref())) { jgen.writeStringField(link.getTitle() + Constants.JSON_BIND_LINK_SUFFIX, link.getHref()); } } if (link.getInlineEntry() != null) { jgen.writeObjectField(link.getTitle(), link.getInlineEntry()); } else if (link.getInlineFeed() != null) { jgen.writeArrayFieldStart(link.getTitle()); for (Entry subEntry : link.getInlineFeed().getEntries()) { jgen.writeObject(subEntry); } jgen.writeEndArray(); } } for (Map.Entry<String, List<String>> entitySetLink : entitySetLinks.entrySet()) { jgen.writeArrayFieldStart(entitySetLink.getKey() + Constants.JSON_BIND_LINK_SUFFIX); for (String uri : entitySetLink.getValue()) { jgen.writeString(uri); } jgen.writeEndArray(); } for (Link link : entry.getMediaEditLinks()) { if (link.getTitle() == null) { jgen.writeStringField(Constants.JSON_MEDIAEDIT_LINK, link.getHref()); } if (link.getInlineEntry() != null) { jgen.writeObjectField(link.getTitle(), link.getInlineEntry()); } if (link.getInlineFeed() != null) { jgen.writeArrayFieldStart(link.getTitle()); for (Entry subEntry : link.getInlineFeed().getEntries()) { jgen.writeObject(subEntry); } jgen.writeEndArray(); } } for (Property property : entry.getProperties()) { property(jgen, property, property.getName()); } jgen.writeEndObject(); }