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

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

Introduction

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

Prototype

public abstract void writeString(SerializableString text) throws IOException, JsonGenerationException;

Source Link

Document

Method similar to #writeString(String) , but that takes SerializableString which can make this potentially more efficient to call as generator may be able to reuse quoted and/or encoded representation.

Usage

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  w  w. j a  v  a2  s. com*/
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: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();
    }/*ww  w  .  j a  v a  2 s . c  om*/

    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:org.apache.syncope.core.misc.serialization.SyncTokenSerializer.java

@Override
public void serialize(final SyncToken source, final JsonGenerator jgen, final SerializerProvider sp)
        throws IOException {

    jgen.writeStartObject();/*w  ww .j av a2 s  .  c  om*/

    jgen.writeFieldName("value");

    if (source.getValue() == null) {
        jgen.writeNull();
    } else if (source.getValue() instanceof Boolean) {
        jgen.writeBoolean((Boolean) source.getValue());
    } else if (source.getValue() instanceof Double) {
        jgen.writeNumber((Double) source.getValue());
    } else if (source.getValue() instanceof Long) {
        jgen.writeNumber((Long) source.getValue());
    } else if (source.getValue() instanceof Integer) {
        jgen.writeNumber((Integer) source.getValue());
    } else if (source.getValue() instanceof byte[]) {
        jgen.writeString(Base64.encodeBase64String((byte[]) source.getValue()));
    } else {
        jgen.writeString(source.getValue().toString());
    }

    jgen.writeEndObject();
}

From source file:com.cloudera.exhibit.server.json.ExhibitSerializer.java

@Override
public void serialize(Exhibit exhibit, JsonGenerator gen, SerializerProvider provider) throws IOException {
    ExhibitDescriptor desc = exhibit.descriptor();
    // start object
    gen.writeStartObject();/*from   w w  w.  jav  a  2s. com*/

    // Write attrs
    gen.writeObjectFieldStart("attrs");
    serializeObs(exhibit.attributes(), exhibit.attributes().descriptor(), gen);
    gen.writeEndObject();

    // Write frame column names
    gen.writeObjectFieldStart("columns");
    for (Map.Entry<String, ObsDescriptor> fd : desc.frames().entrySet()) {
        gen.writeArrayFieldStart(fd.getKey());
        for (ObsDescriptor.Field f : fd.getValue()) {
            // TODO: type info?
            gen.writeString(f.name);
        }
        gen.writeEndArray();
    }
    gen.writeEndObject();

    // Write frame obs
    gen.writeObjectFieldStart("frames");
    for (Map.Entry<String, ObsDescriptor> fd : desc.frames().entrySet()) {
        gen.writeArrayFieldStart(fd.getKey());
        ObsDescriptor od = fd.getValue();
        for (Obs obs : exhibit.frames().get(fd.getKey())) {
            gen.writeStartArray();
            serializeObsArray(obs, fd.getValue(), gen);
            gen.writeEndArray();
        }
        gen.writeEndArray();
    }
    gen.writeEndObject();

    // finish object
    gen.writeEndObject();
}

From source file:com.cedarsoft.serialization.jackson.ListSerializer.java

protected void serializeElement(@Nonnull JsonGenerator serializeTo, @Nullable Object element, int index)
        throws IOException {
    if (element == null) {
        serializeTo.writeNull();//from   w w w. j  av  a  2  s.c om
    } else if (element instanceof Integer) {
        serializeTo.writeNumber((Integer) element);
    } else if (element instanceof Float) {
        serializeTo.writeNumber((Float) element);
    } else if (element instanceof Double) {
        serializeTo.writeNumber((Double) element);
    } else if (element instanceof Long) {
        serializeTo.writeNumber((Long) element);
    } else if (element instanceof Boolean) {
        serializeTo.writeBoolean((Boolean) element);
    } else {
        serializeTo.writeString(String.valueOf(element));
    }
}

From source file:org.apache.olingo.commons.core.serialization.JsonSerializer.java

private void value(final JsonGenerator jgen, final String type, final Valuable value)
        throws IOException, EdmPrimitiveTypeException {
    final EdmTypeInfo typeInfo = type == null ? null
            : new EdmTypeInfo.Builder().setTypeExpression(type).build();

    if (value.isNull()) {
        jgen.writeNull();// www.ja  v  a2  s  .  c o  m
    } else if (value.isPrimitive()) {
        primitiveValue(jgen, typeInfo, value.asPrimitive());
    } else if (value.isEnum()) {
        jgen.writeString(value.asEnum().toString());
    } else if (value.isGeospatial()) {
        jgen.writeStartObject();
        geoSerializer.serialize(jgen, value.asGeospatial());
        jgen.writeEndObject();
    } else if (value.isCollection()) {
        collection(jgen, typeInfo, value.getValueType(), value.asCollection());
    } else if (value.isLinkedComplex()) {
        complexValue(jgen, typeInfo, value.asLinkedComplex().getValue(), value.asLinkedComplex());
    } else if (value.isComplex()) {
        complexValue(jgen, typeInfo, value.asComplex(), null);
    }
}

From source file:com.cedarsoft.serialization.serializers.jackson.LicenseSerializer.java

@Override
public void serialize(@Nonnull JsonGenerator serializeTo, @Nonnull License object,
        @Nonnull Version formatVersion) throws IOException, JsonProcessingException {
    verifyVersionReadable(formatVersion);

    if (object instanceof CreativeCommonsLicense) {
        serializeTo.writeStringField(PROPERTY_SUB_TYPE, SUB_TYPE_CC);
    }//from w w  w  .j  ava2  s .co m

    //id
    serializeTo.writeStringField(PROPERTY_ID, object.getId());
    //name
    serializeTo.writeStringField(PROPERTY_NAME, object.getName());

    //URL
    serializeTo.writeFieldName(PROPERTY_URL);
    URL url = object.getUrl();
    if (url == null) {
        serializeTo.writeNull();
    } else {
        serializeTo.writeString(url.toString());
    }
}

From source file:de.escalon.hypermedia.spring.de.escalon.hypermedia.spring.jackson.LinkListSerializer.java

private void writeScalarValue(JsonGenerator jgen, Object possibleValue, Class<?> valueType) throws IOException {
    if (Number.class.isAssignableFrom(valueType)) {
        jgen.writeNumber(possibleValue.toString());
    } else if (Boolean.class.isAssignableFrom(valueType)) {
        jgen.writeBoolean((Boolean) possibleValue);
    } else if (Enum.class.isAssignableFrom(valueType)) {
        jgen.writeString(((Enum) possibleValue).name());
    } else {//from   ww  w.  j  ava  2 s.c om
        jgen.writeString(possibleValue.toString());
    }
}

From source file:org.elasticsearch.client.sniff.HostsSnifferTests.java

private static SniffResponse buildSniffResponse(HostsSniffer.Scheme scheme) throws IOException {
    int numNodes = RandomInts.randomIntBetween(getRandom(), 1, 5);
    List<HttpHost> hosts = new ArrayList<>(numNodes);
    JsonFactory jsonFactory = new JsonFactory();
    StringWriter writer = new StringWriter();
    JsonGenerator generator = jsonFactory.createGenerator(writer);
    generator.writeStartObject();//from w ww  . ja  v  a2s . c  o m
    if (getRandom().nextBoolean()) {
        generator.writeStringField("cluster_name", "elasticsearch");
    }
    if (getRandom().nextBoolean()) {
        generator.writeObjectFieldStart("bogus_object");
        generator.writeEndObject();
    }
    generator.writeObjectFieldStart("nodes");
    for (int i = 0; i < numNodes; i++) {
        String nodeId = RandomStrings.randomAsciiOfLengthBetween(getRandom(), 5, 10);
        generator.writeObjectFieldStart(nodeId);
        if (getRandom().nextBoolean()) {
            generator.writeObjectFieldStart("bogus_object");
            generator.writeEndObject();
        }
        if (getRandom().nextBoolean()) {
            generator.writeArrayFieldStart("bogus_array");
            generator.writeStartObject();
            generator.writeEndObject();
            generator.writeEndArray();
        }
        boolean isHttpEnabled = rarely() == false;
        if (isHttpEnabled) {
            String host = "host" + i;
            int port = RandomInts.randomIntBetween(getRandom(), 9200, 9299);
            HttpHost httpHost = new HttpHost(host, port, scheme.toString());
            hosts.add(httpHost);
            generator.writeObjectFieldStart("http");
            if (getRandom().nextBoolean()) {
                generator.writeArrayFieldStart("bound_address");
                generator.writeString("[fe80::1]:" + port);
                generator.writeString("[::1]:" + port);
                generator.writeString("127.0.0.1:" + port);
                generator.writeEndArray();
            }
            if (getRandom().nextBoolean()) {
                generator.writeObjectFieldStart("bogus_object");
                generator.writeEndObject();
            }
            generator.writeStringField("publish_address", httpHost.toHostString());
            if (getRandom().nextBoolean()) {
                generator.writeNumberField("max_content_length_in_bytes", 104857600);
            }
            generator.writeEndObject();
        }
        if (getRandom().nextBoolean()) {
            String[] roles = { "master", "data", "ingest" };
            int numRoles = RandomInts.randomIntBetween(getRandom(), 0, 3);
            Set<String> nodeRoles = new HashSet<>(numRoles);
            for (int j = 0; j < numRoles; j++) {
                String role;
                do {
                    role = RandomPicks.randomFrom(getRandom(), roles);
                } while (nodeRoles.add(role) == false);
            }
            generator.writeArrayFieldStart("roles");
            for (String nodeRole : nodeRoles) {
                generator.writeString(nodeRole);
            }
            generator.writeEndArray();
        }
        int numAttributes = RandomInts.randomIntBetween(getRandom(), 0, 3);
        Map<String, String> attributes = new HashMap<>(numAttributes);
        for (int j = 0; j < numAttributes; j++) {
            attributes.put("attr" + j, "value" + j);
        }
        if (numAttributes > 0) {
            generator.writeObjectFieldStart("attributes");
        }
        for (Map.Entry<String, String> entry : attributes.entrySet()) {
            generator.writeStringField(entry.getKey(), entry.getValue());
        }
        if (numAttributes > 0) {
            generator.writeEndObject();
        }
        generator.writeEndObject();
    }
    generator.writeEndObject();
    generator.writeEndObject();
    generator.close();
    return SniffResponse.buildResponse(writer.toString(), hosts);
}

From source file:org.bedework.carddav.vcard.Card.java

/**
 * @param indent true for pretty/*from  ww  w.java 2  s. c  o m*/
 * @param version V4 or V3
 * @return String json value
 * @throws WebdavException
 */
public String outputJson(final boolean indent, final String version) throws WebdavException {
    if (jsonStrForm != null) {
        return jsonStrForm;
    }

    final StringWriter sw = new StringWriter();

    try {
        final JsonGenerator jgen = jsonFactory.createJsonGenerator(sw);

        if (indent) {
            jgen.useDefaultPrettyPrinter();
        }

        jgen.writeStartArray(); // for vcard

        jgen.writeString("vcard");
        jgen.writeStartArray(); // Array of properties

        /* Version should come before anything else. */
        boolean version4 = false;

        if (version != null) {
            version4 = version.equals("4.0");
        } else {
            final Version v = (Version) vcard.getProperty(Property.Id.VERSION);

            if (v != null) {
                version4 = v.equals(Version.VERSION_4_0);
            }
        }

        final Property pversion;

        if (version4) {
            pversion = Version.VERSION_4_0;
        } else {
            pversion = new Version("3.0");
        }

        JsonProperty.addFields(jgen, pversion);

        final Set<String> pnames = VcardDefs.getPropertyNames();

        /* Output known properties first */

        for (final String pname : pnames) {
            if ("VERSION".equals(pname)) {
                continue;
            }

            final List<Property> props = findProperties(pname);

            if (!props.isEmpty()) {
                for (final Property p : props) {
                    JsonProperty.addFields(jgen, p);
                }
            }
        }

        /* Now output any extra unknown properties */

        final List<Property> props = vcard.getProperties();

        if (props != null) {
            for (final Property p : props) {
                if (!pnames.contains(p.getId().toString())) {
                    JsonProperty.addFields(jgen, p);
                }
            }
        }

        jgen.writeEndArray(); // End event properties

        jgen.writeEndArray(); // for vcard

        jgen.flush();
    } catch (final WebdavException wde) {
        throw wde;
    } catch (final Throwable t) {
        throw new WebdavException(t);
    }

    jsonStrForm = sw.toString();

    return jsonStrForm;
}