List of usage examples for com.fasterxml.jackson.core JsonGenerator writeArrayFieldStart
public final void writeArrayFieldStart(String fieldName) throws IOException, JsonGenerationException
From source file:com.joliciel.jochre.search.highlight.HighlightManagerImpl.java
@Override public void highlight(Highlighter highlighter, Set<Integer> docIds, Set<String> fields, Writer out) { try {//from ww w. ja v a 2 s. co m Map<Integer, Set<HighlightTerm>> termMap = highlighter.highlight(docIds, fields); JsonFactory jsonFactory = new JsonFactory(); JsonGenerator jsonGen = jsonFactory.createGenerator(out); jsonGen.writeStartObject(); for (int docId : docIds) { Document doc = indexSearcher.doc(docId); jsonGen.writeObjectFieldStart(doc.get("id")); jsonGen.writeStringField("path", doc.get("path")); jsonGen.writeNumberField("docId", docId); jsonGen.writeArrayFieldStart("terms"); for (HighlightTerm term : termMap.get(docId)) { fields.add(term.getField()); term.toJson(jsonGen, df); } jsonGen.writeEndArray(); if (includeText) { for (String field : fields) { jsonGen.writeObjectFieldStart("field" + field); Set<HighlightTerm> terms = termMap.get(docId); jsonGen.writeStringField("contents", this.displayHighlights(docId, field, terms)); jsonGen.writeEndObject(); } } jsonGen.writeEndObject(); } jsonGen.writeEndObject(); jsonGen.flush(); } catch (IOException ioe) { LogUtils.logError(LOG, ioe); throw new RuntimeException(ioe); } }
From source file:com.msopentech.odatajclient.engine.performance.BasicPerfTest.java
@Test public void writeJSONViaLowerlevelLibs() throws IOException { final StringWriter writer = new StringWriter(); final ObjectMapper mapper = new ObjectMapper(); final JsonGenerator jgen = mapper.getFactory().createGenerator(writer); jgen.writeStartObject();/* w w w . j a v a 2s. c om*/ jgen.writeStringField("odata.type", "Microsoft.Test.OData.Services.AstoriaDefaultService.Customer"); jgen.writeStringField("Name@odata.type", "Edm.String"); jgen.writeStringField("Name", "A name"); jgen.writeStringField("CustomerId@odata.type", "Edm.Int32"); jgen.writeNumberField("CustomerId", 0); jgen.writeArrayFieldStart("BackupContactInfo"); jgen.writeStartObject(); jgen.writeArrayFieldStart("AlternativeNames"); jgen.writeString("myname"); jgen.writeEndArray(); jgen.writeArrayFieldStart("EmailBag"); jgen.writeString("myname@mydomain.com"); jgen.writeEndArray(); jgen.writeObjectFieldStart("ContactAlias"); jgen.writeStringField("odata.type", "Microsoft.Test.OData.Services.AstoriaDefaultService.Aliases"); jgen.writeArrayFieldStart("AlternativeNames"); jgen.writeString("myAlternativeName"); jgen.writeEndArray(); jgen.writeEndObject(); jgen.writeEndObject(); jgen.writeEndArray(); jgen.writeEndObject(); jgen.flush(); assertFalse(writer.toString().isEmpty()); }
From source file:com.joliciel.jochre.search.highlight.Snippet.java
public void toJson(JsonGenerator jsonGen, DecimalFormat df) { try {//from w ww . ja v a 2s .c om jsonGen.writeStartObject(); jsonGen.writeNumberField("docId", docId); jsonGen.writeStringField("field", this.getField()); jsonGen.writeNumberField("start", this.getStartOffset()); jsonGen.writeNumberField("end", this.getEndOffset()); double roundedScore = df.parse(df.format(this.getScore())).doubleValue(); jsonGen.writeNumberField("score", roundedScore); jsonGen.writeArrayFieldStart("terms"); for (HighlightTerm term : this.getHighlightTerms()) { term.toJson(jsonGen, df); } jsonGen.writeEndArray(); // terms jsonGen.writeEndObject(); jsonGen.flush(); } catch (java.text.ParseException e) { LogUtils.logError(LOG, e); throw new RuntimeException(e); } catch (IOException ioe) { LogUtils.logError(LOG, ioe); throw new RuntimeException(ioe); } }
From source file:com.googlecode.jmxtrans.model.output.StackdriverWriter.java
/** * Take query results, make a JSON String * //w ww . j a v a 2s .co m * @param results List of Result objects * @return a String containing a JSON message, or null if there are no values to report * * @throws IOException if there is some problem generating the JSON, should be uncommon */ private String getGatewayMessage(final List<Result> results) throws IOException { int valueCount = 0; Writer writer = new StringWriter(); JsonGenerator g = jsonFactory.createGenerator(writer); g.writeStartObject(); g.writeNumberField("timestamp", System.currentTimeMillis() / 1000); g.writeNumberField("proto_version", STACKDRIVER_PROTOCOL_VERSION); g.writeArrayFieldStart("data"); List<String> typeNames = this.getTypeNames(); for (Result metric : results) { Map<String, Object> values = metric.getValues(); if (values != null) { for (Entry<String, Object> entry : values.entrySet()) { if (isNumeric(entry.getValue())) { // we have a numeric value, write a value into the message StringBuilder nameBuilder = new StringBuilder(); // put the prefix if set if (this.prefix != null) { nameBuilder.append(prefix); nameBuilder.append("."); } // put the class name or its alias if available if (!metric.getKeyAlias().isEmpty()) { nameBuilder.append(metric.getKeyAlias()); } else { nameBuilder.append(metric.getClassName()); } // Wildcard "typeNames" substitution String typeName = com.googlecode.jmxtrans.model.naming.StringUtils .cleanupStr(TypeNameValuesStringBuilder.getDefaultBuilder().build(typeNames, metric.getTypeName())); if (typeName != null && typeName.length() > 0) { nameBuilder.append("."); nameBuilder.append(typeName); } // add the attribute name nameBuilder.append("."); nameBuilder.append(metric.getAttributeName()); // put the value name if it differs from the attribute name if (!entry.getKey().equals(metric.getAttributeName())) { nameBuilder.append("."); nameBuilder.append(entry.getKey()); } // check for Float/Double NaN since these will cause the message validation to fail if (entry.getValue() instanceof Float && ((Float) entry.getValue()).isNaN()) { logger.info("Metric value for " + nameBuilder.toString() + " is NaN, skipping"); continue; } if (entry.getValue() instanceof Double && ((Double) entry.getValue()).isNaN()) { logger.info("Metric value for " + nameBuilder.toString() + " is NaN, skipping"); continue; } valueCount++; g.writeStartObject(); g.writeStringField("name", nameBuilder.toString()); g.writeNumberField("value", Double.valueOf(entry.getValue().toString())); // if the metric is attached to an instance, include that in the message if (instanceId != null && !instanceId.isEmpty()) { g.writeStringField("instance", instanceId); } g.writeNumberField("collected_at", metric.getEpoch() / 1000); g.writeEndObject(); } } } } g.writeEndArray(); g.writeEndObject(); g.flush(); g.close(); // return the message if there are any values to report if (valueCount > 0) { return writer.toString(); } else { return null; } }
From source file:com.cedarsoft.serialization.jackson.AbstractJacksonSerializer.java
protected <T> void serializeArray(@Nonnull Iterable<? extends T> elements, @Nonnull Class<T> type, @Nullable String propertyName, @Nonnull JsonGenerator serializeTo, @Nonnull Version formatVersion) throws IOException { JacksonSerializer<? super T> serializer = getSerializer(type); Version delegateVersion = delegatesMappings.getVersionMappings().resolveVersion(type, formatVersion); if (propertyName == null) { serializeTo.writeStartArray();/* ww w. j ava 2 s.com*/ } else { serializeTo.writeArrayFieldStart(propertyName); } for (T element : elements) { if (serializer.isObjectType()) { serializeTo.writeStartObject(); } serializer.serialize(serializeTo, element, delegateVersion); if (serializer.isObjectType()) { serializeTo.writeEndObject(); } } serializeTo.writeEndArray(); }
From source file:org.commonjava.maven.atlas.graph.jackson.ProjectRelationshipSerializer.java
@SuppressWarnings("incomplete-switch") @Override// w ww .jav a2 s . c o m public void serialize(final T value, final JsonGenerator gen, final SerializerProvider provider) throws IOException, JsonGenerationException { gen.writeStartObject(); gen.writeStringField(RELATIONSHIP_TYPE, value.getType().name()); gen.writeStringField(POM_LOCATION_URI, value.getPomLocation().toString()); gen.writeBooleanField(INHERITED, value.isInherited()); Set<URI> sources = value.getSources(); if (sources != null) { for (Iterator<URI> iter = sources.iterator(); iter.hasNext();) { if (iter.next() == null) { iter.remove(); } } if (!sources.isEmpty()) { gen.writeArrayFieldStart(SOURCE_URIS); for (URI uri : sources) { if (uri == null) { continue; } gen.writeString(uri.toString()); } gen.writeEndArray(); } } provider.defaultSerializeField(DECLARING_REF, value.getDeclaring(), gen); provider.defaultSerializeField(TARGET_REF, value.getTarget(), gen); switch (value.getType()) { case BOM: gen.writeBooleanField(MIXIN, value.isMixin()); break; case DEPENDENCY: { gen.writeStringField(SCOPE, ((DependencyRelationship) value).getScope().realName()); gen.writeBooleanField(MANAGED, value.isManaged()); gen.writeBooleanField(OPTIONAL, ((DependencyRelationship) value).isOptional()); break; } case PLUGIN_DEP: { provider.defaultSerializeField(PLUGIN_REF, ((PluginDependencyRelationship) value).getPlugin(), gen); gen.writeBooleanField(MANAGED, value.isManaged()); break; } case PLUGIN: { gen.writeBooleanField(MANAGED, value.isManaged()); gen.writeBooleanField(REPORTING, ((PluginRelationship) value).isReporting()); break; } } gen.writeNumberField(INDEX, value.getIndex()); gen.writeEndObject(); }
From source file:com.strategicgains.hyperexpress.serialization.jackson.HalResourceSerializer.java
private void writeEmbedded(Resource resource, JsonGenerator jgen) throws JsonGenerationException, IOException { Map<String, List<Resource>> embedded = resource.getResources(); if (embedded.isEmpty()) return;//w w w . j a va2s .c o m jgen.writeObjectFieldStart(EMBEDDED); for (Entry<String, List<Resource>> entry : embedded.entrySet()) { if (entry.getValue().size() == 1 && !resource.isMultipleResources(entry.getKey())) { jgen.writeObjectFieldStart(entry.getKey()); renderJson((HalResource) entry.getValue().iterator().next(), jgen, true); jgen.writeEndObject(); } else { jgen.writeArrayFieldStart(entry.getKey()); for (Resource r : entry.getValue()) { jgen.writeStartObject(); renderJson((HalResource) r, jgen, true); jgen.writeEndObject(); } jgen.writeEndArray(); } } jgen.writeEndObject(); }
From source file:com.joliciel.jochre.search.highlight.HighlightManagerImpl.java
@Override public void findSnippets(Highlighter highlighter, Set<Integer> docIds, Set<String> fields, Writer out) { try {/* w ww. j a v a 2 s . co m*/ Map<Integer, Set<HighlightTerm>> termMap = highlighter.highlight(docIds, fields); Map<Integer, List<Snippet>> snippetMap = this.findSnippets(docIds, fields, termMap, this.getSnippetCount(), this.getSnippetSize()); JsonFactory jsonFactory = new JsonFactory(); JsonGenerator jsonGen = jsonFactory.createGenerator(out); jsonGen.writeStartObject(); for (int docId : docIds) { Document doc = indexSearcher.doc(docId); jsonGen.writeObjectFieldStart(doc.get("id")); jsonGen.writeStringField("path", doc.get("path")); jsonGen.writeNumberField("docId", docId); jsonGen.writeArrayFieldStart("snippets"); for (Snippet snippet : snippetMap.get(docId)) { snippet.toJson(jsonGen, df); } jsonGen.writeEndArray(); if (includeText) { jsonGen.writeArrayFieldStart("snippetText"); for (Snippet snippet : snippetMap.get(docId)) { jsonGen.writeStartObject(); jsonGen.writeStringField("snippet", this.displaySnippet(docId, snippet)); jsonGen.writeEndObject(); } jsonGen.writeEndArray(); } if (includeGraphics) { jsonGen.writeArrayFieldStart("snippetGraphics"); for (Snippet snippet : snippetMap.get(docId)) { jsonGen.writeStartObject(); ImageSnippet imageSnippet = this.getImageSnippet(snippet); jsonGen.writeNumberField("left", imageSnippet.getRectangle().getLeft()); jsonGen.writeNumberField("top", imageSnippet.getRectangle().getTop()); jsonGen.writeNumberField("right", imageSnippet.getRectangle().getRight()); jsonGen.writeNumberField("bottom", imageSnippet.getRectangle().getBottom()); jsonGen.writeArrayFieldStart("highlights"); for (Rectangle highlight : imageSnippet.getHighlights()) { jsonGen.writeStartObject(); jsonGen.writeNumberField("left", highlight.getLeft()); jsonGen.writeNumberField("top", highlight.getTop()); jsonGen.writeNumberField("right", highlight.getRight()); jsonGen.writeNumberField("bottom", highlight.getBottom()); jsonGen.writeEndObject(); } jsonGen.writeEndArray(); jsonGen.writeEndObject(); } jsonGen.writeEndArray(); } jsonGen.writeEndObject(); } // next doc jsonGen.writeEndObject(); jsonGen.flush(); } catch (IOException ioe) { LogUtils.logError(LOG, ioe); throw new RuntimeException(ioe); } }
From source file:com.github.aptd.simulation.elements.train.CDoor.java
@Override protected void writeState(final JsonGenerator p_generator) throws IOException { p_generator.writeStringField("state", m_state.name()); p_generator.writeNumberField("openwidth", m_openwidth); p_generator.writeStringField("station", m_stationid); p_generator.writeStringField("platform", m_platformid); p_generator.writeNumberField("freetime", m_freetime); p_generator.writeArrayFieldStart("entryqueue"); for (final IPassenger<?> l_passenger : m_entryqueue) p_generator.writeString(l_passenger.id()); p_generator.writeEndArray();// www . ja v a 2 s. co m p_generator.writeArrayFieldStart("exitqueue"); for (final IPassenger<?> l_passenger : m_exitqueue) p_generator.writeString(l_passenger.id()); p_generator.writeEndArray(); }
From source file:io.mesosphere.mesos.frameworks.cassandra.scheduler.api.NodeController.java
/** * Retrieve a list of all nodes including their status. * * <pre>{@code {//from w w w . ja v a2 s. c o m * "replaceNodes" : [ ], * "nodesToAcquire" : 0, * "nodes" : [ { * "tasks" : { * "METADATA" : { * "cpuCores" : 0.1, * "diskMb" : 16, * "memMb" : 16, * "taskId" : "cassandra.node.0.executor" * }, * "SERVER" : { * "cpuCores" : 2.0, * "diskMb" : 2048, * "memMb" : 2048, * "taskId" : "cassandra.node.0.executor.server" * } * }, * "executorId" : "cassandra.node.0.executor", * "ip" : "127.0.0.2", * "hostname" : "127.0.0.2", * "targetRunState" : "RUN", * "jmxPort" : 64112, * "seedNode" : true, * "cassandraDaemonPid" : 6104, * "lastHealthCheck" : 1426686217128, * "healthCheckDetails" : { * "healthy" : true, * "msg" : "", * "version" : "2.1.4", * "operationMode" : "NORMAL", * "clusterName" : "cassandra", * "dataCenter" : "DC1", * "rack" : "RAC1", * "endpoint" : "127.0.0.2", * "hostId" : "4207396e-6aa0-432e-97d9-1a4df3c1057f", * "joined" : true, * "gossipInitialized" : true, * "gossipRunning" : true, * "nativeTransportRunning" : true, * "rpcServerRunning" : true, * "tokenCount" : 256, * "uptimeMillis" : 29072 * } * }, { * "tasks" : { * "METADATA" : { * "cpuCores" : 0.1, * "diskMb" : 16, * "memMb" : 16, * "taskId" : "cassandra.node.1.executor" * }, * "SERVER" : { * "cpuCores" : 2.0, * "diskMb" : 2048, * "memMb" : 2048, * "taskId" : "cassandra.node.1.executor.server" * } * }, * "executorId" : "cassandra.node.1.executor", * "ip" : "127.0.0.1", * "hostname" : "localhost", * "targetRunState" : "RUN", * "jmxPort" : 64113, * "seedNode" : false, * "cassandraDaemonPid" : 6127, * "lastHealthCheck" : 1426686217095, * "healthCheckDetails" : { * "healthy" : true, * "msg" : "", * "version" : "2.1.4", * "operationMode" : "JOINING", * "clusterName" : "cassandra", * "dataCenter" : "", * "rack" : "", * "endpoint" : "", * "hostId" : "", * "joined" : true, * "gossipInitialized" : true, * "gossipRunning" : true, * "nativeTransportRunning" : false, * "rpcServerRunning" : false, * "tokenCount" : 0, * "uptimeMillis" : 16936 * } * } ] * }}</pre> */ @GET @Path("/all") public Response nodes() { return JaxRsUtils.buildStreamingResponse(factory, new StreamingJsonResponse() { @Override public void write(final JsonGenerator json) throws IOException { final CassandraFrameworkProtos.CassandraClusterState clusterState = cluster.getClusterState().get(); json.writeArrayFieldStart("replaceNodes"); for (final String ip : clusterState.getReplaceNodeIpsList()) { json.writeString(ip); } json.writeEndArray(); final NodeCounts nodeCounts = cluster.getClusterState().nodeCounts(); json.writeNumberField("nodesToAcquire", CassandraCluster.numberOfNodesToAcquire(nodeCounts, cluster.getConfiguration())); json.writeArrayFieldStart("nodes"); for (final CassandraFrameworkProtos.CassandraNode cassandraNode : clusterState.getNodesList()) { json.writeStartObject(); if (cassandraNode.hasReplacementForIp()) { json.writeStringField("replacementForIp", cassandraNode.getReplacementForIp()); } json.writeObjectFieldStart("tasks"); for (final CassandraFrameworkProtos.CassandraNodeTask cassandraNodeTask : cassandraNode .getTasksList()) { JaxRsUtils.writeTask(json, cassandraNodeTask); } json.writeEndObject(); // TODO cassandraNode.getDataVolumesList(); if (!cassandraNode.hasCassandraNodeExecutor()) { json.writeNullField("executorId"); json.writeNullField("workdir"); } else { json.writeStringField("executorId", cassandraNode.getCassandraNodeExecutor().getExecutorId()); final CassandraFrameworkProtos.ExecutorMetadata executorMetadata = cluster .metadataForExecutor(cassandraNode.getCassandraNodeExecutor().getExecutorId()); if (executorMetadata != null) { json.writeStringField("workdir", executorMetadata.getWorkdir()); } else { json.writeNullField("workdir"); } } json.writeStringField("ip", cassandraNode.getIp()); json.writeStringField("hostname", cassandraNode.getHostname()); json.writeStringField("targetRunState", cassandraNode.getTargetRunState().name()); json.writeNumberField("jmxPort", cassandraNode.getJmxConnect().getJmxPort()); json.writeBooleanField("seedNode", cassandraNode.getSeed()); CassandraFrameworkProtos.RackDc rackDc = cassandraNode.getRackDc(); json.writeObjectFieldStart("rackDc"); json.writeStringField("rack", rackDc.getRack()); json.writeStringField("dc", rackDc.getDc()); json.writeEndObject(); if (!cassandraNode.hasCassandraDaemonPid()) { json.writeNullField("cassandraDaemonPid"); } else { json.writeNumberField("cassandraDaemonPid", cassandraNode.getCassandraDaemonPid()); } final CassandraFrameworkProtos.HealthCheckHistoryEntry lastHealthCheck = cassandraNode .hasCassandraNodeExecutor() ? cluster.lastHealthCheck( cassandraNode.getCassandraNodeExecutor().getExecutorId()) : null; if (lastHealthCheck != null) { json.writeNumberField("lastHealthCheck", lastHealthCheck.getTimestampEnd()); } else { json.writeNullField("lastHealthCheck"); } if (lastHealthCheck != null) { json.writeObjectFieldStart("healthCheckDetails"); final CassandraFrameworkProtos.HealthCheckDetails hcd = lastHealthCheck.getDetails(); json.writeBooleanField("healthy", hcd.getHealthy()); json.writeStringField("msg", hcd.getMsg()); json.writeStringField("version", hcd.getInfo().getVersion()); json.writeStringField("operationMode", hcd.getInfo().getOperationMode()); json.writeStringField("clusterName", hcd.getInfo().getClusterName()); json.writeStringField("dataCenter", hcd.getInfo().getDataCenter()); json.writeStringField("rack", hcd.getInfo().getRack()); json.writeStringField("endpoint", hcd.getInfo().getEndpoint()); json.writeStringField("hostId", hcd.getInfo().getHostId()); json.writeBooleanField("joined", hcd.getInfo().getJoined()); json.writeBooleanField("gossipInitialized", hcd.getInfo().getGossipInitialized()); json.writeBooleanField("gossipRunning", hcd.getInfo().getGossipRunning()); json.writeBooleanField("nativeTransportRunning", hcd.getInfo().getNativeTransportRunning()); json.writeBooleanField("rpcServerRunning", hcd.getInfo().getRpcServerRunning()); json.writeNumberField("tokenCount", hcd.getInfo().getTokenCount()); json.writeNumberField("uptimeMillis", hcd.getInfo().getUptimeMillis()); json.writeEndObject(); } else { json.writeNullField("healthCheckDetails"); } final List<CassandraFrameworkProtos.DataVolume> dataVolumes = cassandraNode .getDataVolumesList(); json.writeArrayFieldStart("dataVolumes"); for (final CassandraFrameworkProtos.DataVolume volume : dataVolumes) { json.writeStartObject(); json.writeStringField("path", volume.getPath()); if (volume.hasSizeMb()) { json.writeNumberField("size", volume.getSizeMb()); } json.writeEndObject(); } json.writeEndArray(); json.writeEndObject(); } json.writeEndArray(); } }); }