Example usage for com.fasterxml.jackson.core JsonGenerator writeArrayFieldStart

List of usage examples for com.fasterxml.jackson.core JsonGenerator writeArrayFieldStart

Introduction

In this page you can find the example usage for com.fasterxml.jackson.core JsonGenerator writeArrayFieldStart.

Prototype

public final void writeArrayFieldStart(String fieldName) throws IOException, JsonGenerationException 

Source Link

Document

Convenience method for outputting a field entry ("member") (that will contain a JSON Array value), and the START_ARRAY marker.

Usage

From source file:org.calrissian.mango.json.ser.TupleSerializer.java

@Override
public void serialize(Tuple tuple, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
        throws IOException {
    jsonGenerator.writeStartObject();/*  w  w w.j av a 2s  .  c  o  m*/

    jsonGenerator.writeStringField("key", tuple.getKey());
    Object value = tuple.getValue();
    if (value != null) {
        String type = typeContext.getAlias(value);
        String val_str = typeContext.encode(value);
        jsonGenerator.writeStringField("type", type);
        jsonGenerator.writeStringField("value", val_str);

        jsonGenerator.writeArrayFieldStart("metadata");

        Set<Map.Entry<String, Object>> entries = tuple.getMetadata().entrySet();
        for (Map.Entry<String, Object> objectEntry : entries) {
            jsonGenerator.writeStartObject();
            jsonGenerator.writeObjectField("value", typeContext.encode(objectEntry.getValue()));
            jsonGenerator.writeObjectField("type", typeContext.getAlias(objectEntry.getValue()));
            jsonGenerator.writeObjectField("key", objectEntry.getKey());
            jsonGenerator.writeEndObject();
        }
        jsonGenerator.writeEndArray();

    }

    jsonGenerator.writeEndObject();
}

From source file:com.ning.metrics.action.hdfs.reader.HdfsListing.java

@SuppressWarnings({ "unchecked", "unused" })
public void toJson(final OutputStream out, final boolean pretty) throws IOException {
    final String parentPath = getParentPath() == null ? "" : getParentPath();

    final JsonGenerator generator = new JsonFactory().createJsonGenerator(out);
    generator.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
    if (pretty) {
        generator.setPrettyPrinter(new DefaultPrettyPrinter());
    }/* w ww  . j a v a 2 s  . c  o  m*/

    generator.writeStartObject();
    generator.writeObjectField(JSON_LISTING_PATH, getPath());
    generator.writeObjectField(JSON_LISTING_PARENT_PATH, parentPath);
    generator.writeArrayFieldStart(JSON_LISTING_ENTRIES);
    // Important: need to flush before appending pre-serialized events
    generator.flush();

    for (HdfsEntry entry : getEntries()) {
        entry.toJson(generator);
    }
    generator.writeEndArray();

    generator.writeEndObject();
    generator.close();
}

From source file:com.github.aptd.simulation.elements.train.CTrain.java

@Override
protected void writeState(final JsonGenerator p_generator) throws IOException {
    p_generator.writeStringField("state", m_state.name());
    p_generator.writeNumberField("ttindex", m_ttindex);
    p_generator.writeNumberField("positionontrack", m_positionontrack);
    p_generator.writeArrayFieldStart("doorsclosedlocked");
    for (final IDoor<?> l_door : m_doorsclosedlocked)
        p_generator.writeString(l_door.id());
    p_generator.writeEndArray();//from  w w w  .ja  v  a 2 s  .c  o  m
    p_generator.writeArrayFieldStart("doorsnotclosedlocked");
    for (final IDoor<?> l_door : m_doorsnotclosedlocked)
        p_generator.writeString(l_door.id());
    p_generator.writeEndArray();
    p_generator.writeArrayFieldStart("passengers");
    for (final IPassenger<?> l_passenger : m_passengers)
        p_generator.writeString(l_passenger.id());
    p_generator.writeEndArray();
}

From source file:com.arpnetworking.logback.serialization.BaseSerializationStrategy.java

/**
 * This function assumes the field object has already been started for this throwable, this only fills in
 * the fields in the 'exception' or equivalent object and does not create the field in the containing object.
 *
 * @param throwableProxy Throwable to serialize
 * @param jsonGenerator  <code>JsonGenerator</code> instance after exception object is started
 * @param objectMapper <code>ObjectMapper</code> instance.
 * @throws IOException If writing the <code>Throwable</code> as JSON fails.
 */// w ww. j a v  a2 s .co  m
protected void serializeThrowable(final IThrowableProxy throwableProxy, final JsonGenerator jsonGenerator,
        final ObjectMapper objectMapper) throws IOException {

    jsonGenerator.writeObjectField("type", throwableProxy.getClassName());
    jsonGenerator.writeObjectField("message", throwableProxy.getMessage());
    jsonGenerator.writeArrayFieldStart("backtrace");
    for (StackTraceElementProxy ste : throwableProxy.getStackTraceElementProxyArray()) {
        jsonGenerator.writeString(ste.toString());
    }
    jsonGenerator.writeEndArray();
    jsonGenerator.writeObjectFieldStart("data");
    if (throwableProxy.getSuppressed() != null) {
        jsonGenerator.writeArrayFieldStart("suppressed");
        for (IThrowableProxy suppressed : throwableProxy.getSuppressed()) {
            jsonGenerator.writeStartObject();
            serializeThrowable(suppressed, jsonGenerator, objectMapper);
            jsonGenerator.writeEndObject();
        }
        jsonGenerator.writeEndArray();
    }
    if (throwableProxy.getCause() != null) {
        jsonGenerator.writeObjectFieldStart("cause");
        serializeThrowable(throwableProxy.getCause(), jsonGenerator, objectMapper);
        jsonGenerator.writeEndObject();
    }
    jsonGenerator.writeEndObject();
}

From source file:org.solmix.datax.wmix.serializer.DSResponseSerializer.java

@Override
public void serialize(ResultObject response, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {
    if (response.isDSResponse()) {
        jgen.writeStartObject();/*from   ww w. j  ava2  s .  c  om*/
        jgen.writeFieldName(RESPONSE);
        serialize((DSResponse) response.getReal(), jgen, provider);
        jgen.writeEndObject();
    } else if (response.isDSResponseList()) {
        List<DSResponse> res = (List<DSResponse>) response.getReal();
        jgen.writeStartObject();
        jgen.writeArrayFieldStart(RESPONSES);
        for (DSResponse re : res) {
            serialize(re, jgen, provider);
        }
        jgen.writeEndArray();
        jgen.writeEndObject();

    } else {
        jgen.writeObject(response.getReal());
    }

}

From source file:com.streamsets.datacollector.http.JMXJsonServlet.java

private void listBeans(JsonGenerator jg, ObjectName qry, String attribute, HttpServletResponse response)
        throws IOException {

    Set<ObjectName> names = null;
    names = mBeanServer.queryNames(qry, null);

    jg.writeArrayFieldStart("beans");
    Iterator<ObjectName> it = names.iterator();
    while (it.hasNext()) {
        ObjectName oname = it.next();
        MBeanInfo minfo;/*from   w  ww.j  av  a 2  s  . co  m*/
        String code = "";
        Object attributeinfo = null;
        try {
            minfo = mBeanServer.getMBeanInfo(oname);
            code = minfo.getClassName();
            String prs = "";
            try {
                if ("org.apache.commons.modeler.BaseModelMBean".equals(code)) {
                    prs = "modelerType";
                    code = (String) mBeanServer.getAttribute(oname, prs);
                }
                if (attribute != null) {
                    prs = attribute;
                    attributeinfo = mBeanServer.getAttribute(oname, prs);
                }
            } catch (AttributeNotFoundException e) {
                // If the modelerType attribute was not found, the class name is used
                // instead.

            } catch (MBeanException e) {
                // The code inside the attribute getter threw an exception so 
                // and fall back on the class name

            } catch (RuntimeException e) {
                // For some reason even with an MBeanException available to them
                // Runtime exceptionscan still find their way through, so treat them
                // the same as MBeanException

            } catch (ReflectionException e) {
                // This happens when the code inside the JMX bean (setter?? from the
                // java docs) threw an exception, so 
                // class name

            }
        } catch (InstanceNotFoundException e) {
            //Ignored for some reason the bean was not found so don't output it
            continue;
        } catch (IntrospectionException e) {
            // This is an internal error, something odd happened with reflection so
            // 

            continue;
        } catch (ReflectionException e) {
            // This happens when the code inside the JMX bean threw an exception, so
            // 

            continue;
        }

        jg.writeStartObject();
        jg.writeStringField("name", oname.toString());

        jg.writeStringField("modelerType", code);
        if ((attribute != null) && (attributeinfo == null)) {
            jg.writeStringField("result", "ERROR");
            jg.writeStringField("message", "No attribute with name " + attribute + " was found.");
            jg.writeEndObject();
            jg.writeEndArray();
            jg.close();
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        if (attribute != null) {
            writeAttribute(jg, attribute, attributeinfo);
        } else {
            MBeanAttributeInfo attrs[] = minfo.getAttributes();
            for (int i = 0; i < attrs.length; i++) {
                writeAttribute(jg, oname, attrs[i]);
            }
        }
        jg.writeEndObject();
    }
    jg.writeEndArray();
}

From source file:org.h2gis.drivers.geojson.GeoJsonWriteDriver.java

/**
 * Each element in the geometries array of a GeometryCollection is one of
 * the geometry objects described above:
 *
 * { "type": "GeometryCollection", "geometries": [ { "type": "Point",
 * "coordinates": [100.0, 0.0] }, { "type": "LineString", "coordinates": [
 * [101.0, 0.0], [102.0, 1.0] ] } ] }/*  w w  w .j  a v a  2s.  c o m*/
 *
 * @param coll
 * @param gen
 * @throws IOException
 */
private void write(GeometryCollection coll, JsonGenerator gen) throws IOException {
    gen.writeStringField("type", "GeometryCollection");
    gen.writeArrayFieldStart("geometries");
    for (int i = 0; i < coll.getNumGeometries(); ++i) {
        Geometry geom = coll.getGeometryN(i);
        gen.writeStartObject();
        if (geom instanceof Point) {
            write((Point) geom, gen);
        } else if (geom instanceof MultiPoint) {
            write((MultiPoint) geom, gen);
        } else if (geom instanceof LineString) {
            write((LineString) geom, gen);
        } else if (geom instanceof MultiLineString) {
            write((MultiLineString) geom, gen);
        } else if (geom instanceof Polygon) {
            write((Polygon) geom, gen);
        } else if (geom instanceof MultiPolygon) {
            write((MultiPolygon) geom, gen);
        } else if (geom instanceof GeometryCollection) {
            write((GeometryCollection) geom, gen);
        } else {
            throw new RuntimeException("Unsupported Geomery type");
        }
        gen.writeEndObject();
    }
    gen.writeEndArray();
}

From source file:io.mesosphere.mesos.frameworks.cassandra.scheduler.api.LiveEndpointsController.java

private Response liveEndpoints(final String forTool, final int limit) {
    final List<CassandraFrameworkProtos.CassandraNode> liveNodes = cluster.liveNodes(limit);

    if (liveNodes.isEmpty()) {
        return Response.status(400).build();
    }/*from w ww.j a  v  a2s .  com*/

    final CassandraFrameworkProtos.CassandraFrameworkConfiguration configuration = cluster.getConfiguration()
            .get();

    final int nativePort = CassandraCluster.getPortMapping(configuration, CassandraCluster.PORT_NATIVE);
    final int rpcPort = CassandraCluster.getPortMapping(configuration, CassandraCluster.PORT_RPC);
    final int jmxPort = CassandraCluster.getPortMapping(configuration, CassandraCluster.PORT_JMX);

    final CassandraFrameworkProtos.CassandraNode first = liveNodes.get(0);

    try {
        switch (forTool) {
        case "cqlsh":
            // return a string: "HOST PORT"
            return Response.ok(first.getIp() + ' ' + nativePort).build();
        case "stress":
            // cassandra-stress options:
            // -node NODE1,NODE2,...
            // -port [native=NATIVE_PORT] [thrift=THRIFT_PORT] [jmx=JMX_PORT]
            final StringBuilder sb = new StringBuilder();
            sb.append("-node ");
            for (int i = 0; i < liveNodes.size(); i++) {
                if (i > 0) {
                    sb.append(',');
                }
                sb.append(liveNodes.get(i).getIp());
            }
            sb.append(" -port native=").append(nativePort).append(" thrift=").append(rpcPort).append(" jmx=")
                    .append(jmxPort);
            return Response.ok(sb.toString()).build();
        case "nodetool":
            // nodetool options:
            // -h HOST
            // -p JMX_PORT
            return Response
                    .ok("-h " + first.getJmxConnect().getIp() + " -p " + first.getJmxConnect().getJmxPort())
                    .build();
        case "json":
            // produce a simple JSON with the native port and live node IPs
            return JaxRsUtils.buildStreamingResponse(factory, new StreamingJsonResponse() {
                @Override
                public void write(final JsonGenerator json) throws IOException {
                    json.writeStringField("clusterName", configuration.getFrameworkName());
                    json.writeNumberField("nativePort", nativePort);
                    json.writeNumberField("rpcPort", rpcPort);
                    json.writeNumberField("jmxPort", jmxPort);

                    json.writeArrayFieldStart("liveNodes");
                    for (final CassandraFrameworkProtos.CassandraNode liveNode : liveNodes) {
                        json.writeString(liveNode.getIp());
                    }
                    json.writeEndArray();
                }
            });
        case "text":
            // produce a simple text with the native port in the first line and one line per live node IP
            return JaxRsUtils.buildStreamingResponse(Response.Status.OK, "text/plain",
                    new StreamingTextResponse() {
                        @Override
                        public void write(final PrintWriter pw) {
                            pw.println("NATIVE: " + nativePort);
                            pw.println("RPC: " + rpcPort);
                            pw.println("JMX: " + jmxPort);
                            for (final CassandraFrameworkProtos.CassandraNode liveNode : liveNodes) {
                                pw.println("IP: " + liveNode.getIp());
                            }
                        }
                    });
        }

        return Response.status(404).build();
    } catch (final Exception e) {
        LOGGER.error("Failed to all nodes list", e);
        return Response.serverError().build();
    }
}

From source file:io.protostuff.JsonOutput.java

@Override
public void writeBool(int fieldNumber, boolean value, boolean repeated) throws IOException {
    if (lastNumber == fieldNumber) {
        // repeated field
        generator.writeBoolean(value);//w  ww. java2s  .  c o m
        return;
    }

    final JsonGenerator generator = this.generator;

    if (lastRepeated)
        generator.writeEndArray();

    final String name = numeric ? Integer.toString(fieldNumber) : schema.getFieldName(fieldNumber);

    if (repeated) {
        generator.writeArrayFieldStart(name);
        generator.writeBoolean(value);
    } else
        generator.writeBooleanField(name, value);

    lastNumber = fieldNumber;
    lastRepeated = repeated;
}

From source file:io.protostuff.JsonOutput.java

@Override
public void writeDouble(int fieldNumber, double value, boolean repeated) throws IOException {
    if (lastNumber == fieldNumber) {
        // repeated field
        generator.writeNumber(value);//from  w  w  w. j  av  a2  s.com
        return;
    }

    final JsonGenerator generator = this.generator;

    if (lastRepeated)
        generator.writeEndArray();

    final String name = numeric ? Integer.toString(fieldNumber) : schema.getFieldName(fieldNumber);

    if (repeated) {
        generator.writeArrayFieldStart(name);
        generator.writeNumber(value);
    } else
        generator.writeNumberField(name, value);

    lastNumber = fieldNumber;
    lastRepeated = repeated;
}