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

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

Introduction

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

Prototype

public abstract void writeStartObject() throws IOException, JsonGenerationException;

Source Link

Document

Method for writing starting marker of a JSON Object value (character '{'; plus possible white space decoration if pretty-printing is enabled).

Usage

From source file:net.opentsdb.meta.UIDMeta.java

/**
 * Formats the JSON output for writing to storage. It drops objects we don't
 * need or want to store (such as the UIDMeta objects or the total dps) to
 * save space. It also serializes in order so that we can make a proper CAS
 * call. Otherwise the POJO serializer may place the fields in any order
 * and CAS calls would fail all the time.
 * @return A byte array to write to storage
 *//*from   ww w . j  a v  a  2 s .  com*/
private byte[] getStorageJSON() {
    // 256 bytes is a good starting value, assumes default info
    final ByteArrayOutputStream output = new ByteArrayOutputStream(256);
    try {
        final JsonGenerator json = JSON.getFactory().createGenerator(output);
        json.writeStartObject();
        json.writeStringField("type", type.toString());
        json.writeStringField("displayName", display_name);
        json.writeStringField("description", description);
        json.writeStringField("notes", notes);
        json.writeNumberField("created", created);
        if (custom == null) {
            json.writeNullField("custom");
        } else {
            json.writeObjectFieldStart("custom");
            for (Map.Entry<String, String> entry : custom.entrySet()) {
                json.writeStringField(entry.getKey(), entry.getValue());
            }
            json.writeEndObject();
        }

        json.writeEndObject();
        json.close();
        return output.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException("Unable to serialize UIDMeta", e);
    }
}

From source file:com.greplin.gec.GecLogbackAppender.java

/**
 * Writes a formatted exception to the given writer.
 *
 * @param message   the log message/* ww  w .  j a  va  2  s .  c om*/
 * @param throwableProxy the exception
 * @param level     the error level
 * @param out       the destination
 * @throws IOException if there are IO errors in the destination
 */
private void writeFormattedException(final String message, final IThrowableProxy throwableProxy,
        final Level level, final Writer out) throws IOException {
    JsonGenerator generator = new JsonFactory().createJsonGenerator(out);

    IThrowableProxy rootThrowable = throwableProxy;
    while (this.passthroughExceptions.contains(rootThrowable.getClassName())
            && rootThrowable.getCause() != null) {
        rootThrowable = rootThrowable.getCause();
    }

    generator.writeStartObject();
    generator.writeStringField("project", this.project);
    generator.writeStringField("environment", this.environment);
    generator.writeStringField("serverName", this.serverName);
    // FIXME this was 'throwable'
    generator.writeStringField("backtrace", getStackTrace(rootThrowable));
    generator.writeStringField("message", rootThrowable.getMessage());
    generator.writeStringField("logMessage", message);
    generator.writeStringField("type", rootThrowable.getClassName());
    if (level != Level.ERROR) {
        generator.writeStringField("errorLevel", level.toString());
    }
    writeContext(generator);
    generator.writeEndObject();
    generator.close();
}

From source file:com.baidubce.services.bmr.BmrClient.java

/**
 * Create a cluster with the specified options.
 *
 * @param request The request containing all options for creating a BMR cluster.
 * @return The response containing the ID of the newly created cluster.
 *///from   ww w .jav  a  2 s.c  om
public CreateClusterResponse createCluster(CreateClusterRequest request) {
    checkNotNull(request, "request should not be null.");
    checkStringNotEmpty(request.getImageType(), "The imageType should not be null or empty string.");
    checkStringNotEmpty(request.getImageVersion(), "The imageVersion should not be null or empty string.");
    checkNotNull(request.getInstanceGroups(), "The instanceGroups should not be null.");

    StringWriter writer = new StringWriter();
    try {
        JsonGenerator jsonGenerator = JsonUtils.jsonGeneratorOf(writer);
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("imageType", request.getImageType());
        jsonGenerator.writeStringField("imageVersion", request.getImageVersion());
        jsonGenerator.writeArrayFieldStart("instanceGroups");
        for (InstanceGroupConfig instanceGroup : request.getInstanceGroups()) {
            jsonGenerator.writeStartObject();
            if (instanceGroup.getName() != null) {
                jsonGenerator.writeStringField("name", instanceGroup.getName());
            }
            jsonGenerator.writeStringField("type", instanceGroup.getType());
            jsonGenerator.writeStringField("instanceType", instanceGroup.getInstanceType());
            jsonGenerator.writeNumberField("instanceCount", instanceGroup.getInstanceCount());
            jsonGenerator.writeEndObject();
        }
        jsonGenerator.writeEndArray();
        if (request.getName() != null) {
            jsonGenerator.writeStringField("name", request.getName());
        }
        if (request.getLogUri() != null) {
            jsonGenerator.writeStringField("logUri", request.getLogUri());
        }
        jsonGenerator.writeBooleanField("autoTerminate", request.getAutoTerminate());

        if (request.getApplications() != null) {
            jsonGenerator.writeArrayFieldStart("applications");
            for (ApplicationConfig application : request.getApplications()) {
                jsonGenerator.writeStartObject();
                jsonGenerator.writeStringField("name", application.getName());
                jsonGenerator.writeStringField("version", application.getVersion());
                if (application.getProperties() != null) {
                    jsonGenerator.writeObjectFieldStart("properties");
                    for (Map.Entry<String, Object> entry : application.getProperties().entrySet()) {
                        jsonGenerator.writeObjectField(entry.getKey(), entry.getValue());
                    }
                    jsonGenerator.writeEndObject();
                }
                jsonGenerator.writeEndObject();
            }
            jsonGenerator.writeEndArray();
        }

        if (request.getSteps() != null) {
            jsonGenerator.writeArrayFieldStart("steps");
            for (StepConfig step : request.getSteps()) {
                jsonGenerator.writeStartObject();
                if (step.getName() != null) {
                    jsonGenerator.writeStringField("name", step.getName());
                }
                jsonGenerator.writeStringField("type", step.getType());
                jsonGenerator.writeStringField("actionOnFailure", step.getActionOnFailure());
                jsonGenerator.writeObjectFieldStart("properties");
                for (Map.Entry<String, String> entry : step.getProperties().entrySet()) {
                    jsonGenerator.writeStringField(entry.getKey(), entry.getValue());
                }
                jsonGenerator.writeEndObject();
                jsonGenerator.writeEndObject();
            }
            jsonGenerator.writeEndArray();
        }

        jsonGenerator.writeEndObject();
        jsonGenerator.close();
    } catch (IOException e) {
        throw new BceClientException("Fail to generate json", e);
    }

    byte[] json = null;
    try {
        json = writer.toString().getBytes(DEFAULT_ENCODING);
    } catch (UnsupportedEncodingException e) {
        throw new BceClientException("Fail to get UTF-8 bytes", e);
    }

    InternalRequest internalRequest = this.createRequest(request, HttpMethodName.POST, CLUSTER);
    internalRequest.addHeader(Headers.CONTENT_LENGTH, String.valueOf(json.length));
    internalRequest.addHeader(Headers.CONTENT_TYPE, "application/json");
    internalRequest.setContent(RestartableInputStream.wrap(json));

    if (request.getClientToken() != null) {
        internalRequest.addParameter("clientToken", request.getClientToken());
    }

    return this.invokeHttpClient(internalRequest, CreateClusterResponse.class);
}

From source file:com.codealot.url2text.Response.java

/**
 * Convenience method for writing header and metadata lists.
 * /*from ww  w .  ja  va  2 s. co m*/
 * @param jsonGenerator
 * @param header
 * @param array
 * @throws JsonGenerationException
 * @throws IOException
 */
private void outputNameAndValueArray(final JsonGenerator jsonGenerator, final String header,
        final List<NameAndValue> array) throws JsonGenerationException, IOException {
    jsonGenerator.writeFieldName(header);
    jsonGenerator.writeStartObject();

    for (final NameAndValue nameAndValue : array) {
        jsonGenerator.writeStringField(nameAndValue.getName(), nameAndValue.getValue());
    }
    jsonGenerator.writeEndObject();
}

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

private void writeHydraVariableMapping(JsonGenerator jgen, @Nullable ActionDescriptor actionDescriptor,
        Collection<String> variableNames) throws IOException {
    for (String requestParamName : variableNames) {
        jgen.writeStartObject();
        jgen.writeStringField("@type", "hydra:IriTemplateMapping");
        jgen.writeStringField("hydra:variable", requestParamName);
        if (actionDescriptor != null) {
            jgen.writeBooleanField("hydra:required",
                    actionDescriptor.getActionInputParameter(requestParamName).isRequired());
            jgen.writeStringField("hydra:property",
                    getExposedPropertyOrParamName(actionDescriptor.getActionInputParameter(requestParamName)));
        }/*from   ww  w. j  a  v  a 2  s . c  o m*/
        jgen.writeEndObject();
    }
}

From source file:org.n52.tamis.core.json.serialize.processes.execute.ExecuteInputSerializer.java

private void writeAsData(JsonGenerator jsonGenerator, ExecuteInput input) throws IOException {
    /*/*from w w  w . j a  va 2 s.c o m*/
     * write the input as WPS "Data" element
     * 
     * expected structure looks like:
     * 
     * { "Data": { "_mimeType": "text/xml", "_schema":
     * "http://schemas.opengis.net/gml/3.2.1/base/feature.xsd",
     * "__text": "value" }, 
     * "_id": "target-variable-point" 
     * }
     * 
     * 
     */
    logger.info("Input \"{}\" is serialized as WPS \"Data\".", input);

    jsonGenerator.writeStartObject();

    jsonGenerator.writeObjectFieldStart("Data");

    jsonGenerator.writeStringField("_text", input.getValue());

    /*
     * TODO parameters "_mimeType" and "_schema"?
     */
    // jsonGenerator.writeStringField("_mimeType", "application/om+xml;
    // version=2.0");
    // jsonGenerator.writeStringField("_schema",
    // "http://schemas.opengis.net/om/2.0/observation.xsd");

    jsonGenerator.writeEndObject();

    jsonGenerator.writeStringField("_id", input.getId());

    jsonGenerator.writeEndObject();
}

From source file:com.zenesis.qx.remote.SimpleQueue.java

@Override
public synchronized void serialize(JsonGenerator gen, SerializerProvider sp)
        throws IOException, JsonProcessingException {
    gen.writeStartArray();//from   w  w w .  jav a2  s.  co m
    while (!values.isEmpty()) {
        CommandId id = values.keySet().iterator().next();
        Object data = values.remove(id);

        if (id.type == CommandType.DEFINE) {
            ProxyType type = (ProxyType) id.object;
            ProxySessionTracker tracker = ((ProxyObjectMapper) gen.getCodec()).getTracker();
            if (tracker.isTypeDelivered(type))
                continue;
        }

        gen.writeStartObject();
        gen.writeStringField("type", id.type.remoteId);
        if (id.object != null)
            gen.writeObjectField("object", id.object);
        if (id.name != null)
            gen.writeObjectField("name", id.name);
        if (data != null)
            gen.writeObjectField("data", data);
        gen.writeEndObject();
    }
    gen.writeEndArray();
    values.clear();
    needsFlush = false;
}

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

private void writeSupportedProperty(JsonGenerator jgen, String currentVocab,
        ActionInputParameter actionInputParameter, String propertyName, Property property,
        Object[] possiblePropertyValues) throws IOException {

    jgen.writeStartObject();

    if (actionInputParameter.hasCallValue() || actionInputParameter.hasInputConstraints()) {
        // jgen.writeArrayFieldStart("@type");
        // jgen.writeString("hydra:SupportedProperty");

        jgen.writeStringField(JacksonHydraSerializer.AT_TYPE, getPropertyOrClassNameInVocab(currentVocab,
                "PropertyValueSpecification", JacksonHydraSerializer.HTTP_SCHEMA_ORG, "schema:"));

        //jgen.writeEndArray();
    }//from  w  ww . j a  va  2s  . c  om
    jgen.writeStringField("hydra:property", propertyName);

    writePossiblePropertyValues(jgen, currentVocab, actionInputParameter, possiblePropertyValues);

    jgen.writeEndObject();
}

From source file:com.castlemock.web.mock.rest.converter.swagger.SwaggerRestDefinitionConverter.java

/**
 * Method used to generate a response body based on a {@link Model} and perhaps related other {@link Model}.
 * @param model The {@link Model} used to generate to the body.
 * @param definitions Other {@link Model} that might be related and required.
 * @param generator generator The {@link JsonGenerator}.
 * @throws IOException/*  ww w  . j  ava  2 s. com*/
 * @since 1.13
 * @see {@link #generateJsonBody(String, Property, Map, JsonGenerator)}
 */
private void generateJsonBody(final Model model, final Map<String, Model> definitions,
        final JsonGenerator generator) throws IOException {
    generator.writeStartObject();
    if (model instanceof ArrayModel) {
        final ArrayModel arrayModel = (ArrayModel) model;
        final Property item = arrayModel.getItems();
        final int maxItems = getMaxItems(arrayModel.getMaxItems());
        generator.writeStartArray();
        for (int index = 0; index < maxItems; index++) {
            generateJsonBody(item.getName(), item, definitions, generator);
        }
        generator.writeEndArray();
    } else if (model instanceof RefModel) {
        final RefModel refModel = (RefModel) model;
        final String simpleRef = refModel.getSimpleRef();
        final Model subModel = definitions.get(simpleRef);
        generateJsonBody(subModel, definitions, generator);
    }

    if (model.getProperties() != null) {
        for (Map.Entry<String, Property> property : model.getProperties().entrySet()) {
            generateJsonBody(property.getKey(), property.getValue(), definitions, generator);
        }
    }

    generator.writeEndObject();
}