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

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

Introduction

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

Prototype

public final void writeBooleanField(String fieldName, boolean value)
        throws IOException, JsonGenerationException 

Source Link

Document

Convenience method for outputting a field entry ("member") that has a boolean value.

Usage

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

private void writeHydraVariableMapping(JsonGenerator jgen, @Nullable ActionDescriptor annotatedParameters,
        Collection<String> variableNames) throws IOException {
    if (annotatedParameters != null) {
        for (String variableName : variableNames) {
            // TODO: find also @Input
            ActionInputParameter annotatedParameter = annotatedParameters.getActionInputParameter(variableName);
            // TODO access @Input parameter, too
            // only unsatisfied parameters become hydra variables
            if (annotatedParameter != null && annotatedParameter.getValue() == null) {
                jgen.writeStartObject();
                jgen.writeStringField("@type", "hydra:IriTemplateMapping");
                jgen.writeStringField("hydra:variable", variableName);
                jgen.writeBooleanField("hydra:required", annotatedParameter.isRequired());
                jgen.writeStringField("hydra:property", getExposedPropertyOrParamName(annotatedParameter));
                jgen.writeEndObject();/*from  w w w  . j  a v  a2s.c o  m*/
            }
        }
    }
}

From source file:com.spotify.docker.client.DefaultDockerClient.java

@Override
public LogStream execStart(String execId, ExecStartParameter... params)
        throws DockerException, InterruptedException {
    WebTarget resource = resource().path("exec").path(execId).path("start");

    final StringWriter writer = new StringWriter();
    try {// ww  w .  j a  v a 2 s . c  o m
        final JsonGenerator generator = objectMapper().getFactory().createGenerator(writer);
        generator.writeStartObject();

        for (ExecStartParameter param : params) {
            generator.writeBooleanField(param.getName(), true);
        }

        generator.writeEndObject();
        generator.close();
    } catch (IOException e) {
        throw new DockerException(e);
    }

    try {
        return request(POST, LogStream.class, resource, resource.request("application/vnd.docker.raw-stream"),
                Entity.json(writer.toString()));
    } catch (DockerRequestException e) {
        switch (e.status()) {
        case 404:
            throw new ExecNotFoundException(execId);
        default:
            throw e;
        }
    }
}

From source file:com.basho.riak.client.query.MapReduce.java

/**
 * @param jg/*from   w ww.j a v a2  s  .com*/
 */
private void writeMapReducePhases(JsonGenerator jg) throws IOException {
    int cnt = 0;
    synchronized (phases) {
        final int lastPhase = phases.size();
        for (MapReducePhase phase : phases) {
            cnt++;
            jg.writeStartObject();
            jg.writeFieldName(phase.getType().toString());
            jg.writeStartObject();

            switch (phase.getType()) {
            case MAP:
            case REDUCE:
                MapPhase mapPhase = (MapPhase) phase;
                FunctionToJson.newWriter(mapPhase.getPhaseFunction(), jg).write();
                if (mapPhase.getArg() != null) {
                    jg.writeObjectField("arg", mapPhase.getArg());
                }
                break;
            case LINK:
                jg.writeStringField("bucket", ((LinkPhase) phase).getBucket());
                jg.writeStringField("tag", ((LinkPhase) phase).getTag());
                break;
            }

            //the final phase results should be returned, unless specifically set otherwise
            if (cnt == lastPhase) {
                jg.writeBooleanField("keep", isKeepResult(true, phase.isKeep()));
            } else {
                jg.writeBooleanField("keep", isKeepResult(false, phase.isKeep()));
            }

            jg.writeEndObject();
            jg.writeEndObject();
        }
    }
}

From source file:com.spotify.docker.client.DefaultDockerClient.java

@Override
public String execCreate(String containerId, String[] cmd, ExecParameter... params)
        throws DockerException, InterruptedException {
    WebTarget resource = resource().path("containers").path(containerId).path("exec");

    final StringWriter writer = new StringWriter();
    try {//  w  w  w  .ja  v  a 2  s .c  o m
        final JsonGenerator generator = objectMapper().getFactory().createGenerator(writer);
        generator.writeStartObject();

        for (ExecParameter param : params) {
            generator.writeBooleanField(param.getName(), true);
        }

        generator.writeArrayFieldStart("Cmd");
        for (String s : cmd) {
            generator.writeString(s);
        }
        generator.writeEndArray();

        generator.writeEndObject();
        generator.close();
    } catch (IOException e) {
        throw new DockerException(e);
    }

    String response;
    try {
        response = request(POST, String.class, resource, resource.request(APPLICATION_JSON_TYPE),
                Entity.json(writer.toString()));
    } catch (DockerRequestException e) {
        switch (e.status()) {
        case 404:
            throw new ContainerNotFoundException(containerId);
        default:
            throw e;
        }
    }

    try {
        JsonNode json = objectMapper().readTree(response);
        return json.findValue("Id").textValue();
    } catch (IOException e) {
        throw new DockerException(e);
    }
}

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

private void writePossiblePropertyValues(JsonGenerator jgen, String currentVocab,
        ActionInputParameter actionInputParameter, Object[] possiblePropertyValues) throws IOException {
    // Enable the following to list possible values.
    // Problem: how to express individuals only for certain hydra:options
    // not all hydra:options should be taken as uris, sometimes they might be just literals
    // how to make that clear to the client?
    // maybe we must write them out for options
    //        if (possiblePropertyValues.length > 0) {
    //            jgen.writeArrayFieldStart("hydra:option");
    ///*from  w  ww  . j  a v a2 s. c om*/
    //            for (Object possibleValue : possiblePropertyValues) {
    //                // TODO: apply "hydra:option" : { "@type": "@vocab"} to context for enums
    //                writeScalarValue(jgen, possibleValue, actionInputParameter.getParameterType());
    //            }
    //            jgen.writeEndArray();
    //        }

    if (actionInputParameter.isArrayOrCollection()) {
        jgen.writeBooleanField(getPropertyOrClassNameInVocab(currentVocab, "multipleValues",
                JacksonHydraSerializer.HTTP_SCHEMA_ORG, "schema:"), true);
    }

    //  valueRequired (hard to say, using @Access on Event is for all update requests - or make
    //     specific request beans for different
    //     purposes rather than always passing an instance of e.g. Event?)
    //       -> update is a different use case than create - or maybe have an @Requires("eventStatus")
    //          annotation alongside requestBody to tell which attributes are required or writable, and use Requires over
    //          bean structure, where ctor with least length of args is required and setters are supported
    //          but optional? The bean structure does say what is writable for updates, but not what is required for creation. Right now setters are supportedProperties. For creation we would have to add constructor arguments as supportedProperties.
    //  (/) defaultValue (pre-filled value, e.g. list of selected items for option)
    //  valueName (for iri templates only)
    //  (/) readonlyValue (true for final public field or absence of setter, send fixed value like hidden field?) -> use hydra:readable, hydra:writable
    //  (/) multipleValues
    //  (/) valueMinLength
    //  (/) valueMaxLength
    //  (/) valuePattern
    //  minValue (DateTime support)
    //  maxValue (DateTime support)
    //  (/) stepValue
    final Map<String, Object> inputConstraints = actionInputParameter.getInputConstraints();

    if (actionInputParameter.hasCallValue()) {
        if (actionInputParameter.isArrayOrCollection()) {
            Object[] callValues = actionInputParameter.getCallValues();
            Class<?> componentType = callValues.getClass().getComponentType();
            // only write defaultValue for array of scalars
            if (DataType.isScalar(componentType)) {
                jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab, "defaultValue",
                        JacksonHydraSerializer.HTTP_SCHEMA_ORG, "schema:"));
                jgen.writeStartArray();
                for (Object callValue : callValues) {
                    writeScalarValue(jgen, callValue, componentType);
                }
                jgen.writeEndArray();
            }
        } else {
            jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab, "defaultValue",
                    JacksonHydraSerializer.HTTP_SCHEMA_ORG, "schema:"));

            writeScalarValue(jgen, actionInputParameter.getCallValueFormatted(),
                    actionInputParameter.getNestedParameterType());
        }
    }

    if (!inputConstraints.isEmpty()) {
        final List<String> keysToAppendValue = Arrays.asList(ActionInputParameter.MAX, ActionInputParameter.MIN,
                ActionInputParameter.STEP);
        for (String keyToAppendValue : keysToAppendValue) {
            final Object constraint = inputConstraints.get(keyToAppendValue);
            if (constraint != null) {
                jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab, keyToAppendValue + "Value",
                        JacksonHydraSerializer.HTTP_SCHEMA_ORG, "schema:"));
                jgen.writeNumber(constraint.toString());
            }
        }

        final List<String> keysToPrependValue = Arrays.asList(ActionInputParameter.MAX_LENGTH,
                ActionInputParameter.MIN_LENGTH, ActionInputParameter.PATTERN);
        for (String keyToPrependValue : keysToPrependValue) {
            final Object constraint = inputConstraints.get(keyToPrependValue);
            if (constraint != null) {
                jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab,
                        "value" + StringUtils.capitalize(keyToPrependValue),
                        JacksonHydraSerializer.HTTP_SCHEMA_ORG, "schema:"));
                if (ActionInputParameter.PATTERN.equals(keyToPrependValue)) {
                    jgen.writeString(constraint.toString());
                } else {
                    jgen.writeNumber(constraint.toString());
                }
            }
        }

    }

}

From source file:net.opentsdb.tree.Tree.java

/**
 * Converts the object to a JSON byte array, necessary for CAS calls and to
 * keep redundant data down/*  ww  w . j  a  v  a 2 s.  c o  m*/
 * @return A byte array with the serialized tree
 */
private byte[] toStorageJson() {
    // TODO - precalc how much memory to grab
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    try {
        final JsonGenerator json = JSON.getFactory().createGenerator(output);

        json.writeStartObject();

        // we only need to write a small amount of information
        //json.writeNumberField("treeId", tree_id);
        json.writeStringField("name", name);
        json.writeStringField("description", description);
        json.writeStringField("notes", notes);
        json.writeBooleanField("strictMatch", strict_match);
        json.writeNumberField("created", created);
        json.writeBooleanField("enabled", enabled);
        json.writeBooleanField("storeFailures", store_failures);
        json.writeEndObject();
        json.close();

        // TODO zero copy?
        return output.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.graylog.plugins.nats.output.AbstractGelfNatsOutput.java

protected byte[] toGELFMessage(final Message message) throws IOException {
    final HashMap<String, Object> fields = new HashMap<>(message.getFields());

    final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(512);
    final JsonFactory jsonFactory = new JsonFactory();
    final JsonGenerator generator = jsonFactory.createGenerator(outputStream);
    generator.writeStartObject();//w  w w .j a  v  a  2 s  .  com
    generator.writeStringField("version", "1.1");
    generator.writeStringField("host", (String) fields.remove(Message.FIELD_SOURCE));
    generator.writeStringField("short_message", (String) fields.remove(Message.FIELD_MESSAGE));

    final String fullMessage = (String) fields.remove(Message.FIELD_FULL_MESSAGE);
    if (fullMessage != null) {
        generator.writeStringField("full_message", fullMessage);
    }

    final Object fieldTimeStamp = fields.remove(Message.FIELD_TIMESTAMP);
    final DateTime timestamp;
    if (fieldTimeStamp instanceof DateTime) {
        timestamp = (DateTime) fieldTimeStamp;
    } else {
        timestamp = Tools.nowUTC();
    }
    generator.writeNumberField("timestamp", timestamp.getMillis() / 1000d);

    final Object fieldLevel = fields.remove(Message.FIELD_TIMESTAMP);
    final Integer level = extractLevel(fieldLevel);
    if (level != null) {
        generator.writeNumberField("level", level);
    }

    for (Map.Entry<String, Object> field : fields.entrySet()) {
        final String key = field.getKey();
        final Object value = field.getValue();

        if (value instanceof String) {
            generator.writeStringField(key, (String) value);
        } else if (value instanceof Boolean) {
            generator.writeBooleanField(key, (Boolean) value);
        } else if (value instanceof Integer) {
            generator.writeNumberField(key, (Integer) value);
        } else if (value instanceof Long) {
            generator.writeNumberField(key, (Long) value);
        } else if (value instanceof Float) {
            generator.writeNumberField(key, (Float) value);
        } else if (value instanceof Double) {
            generator.writeNumberField(key, (Double) value);
        } else if (value instanceof BigDecimal) {
            generator.writeNumberField(key, (BigDecimal) value);
        } else if (value == null) {
            generator.writeNullField(key);
        }
    }

    generator.writeStringField("_forwarder_cluster_id", clusterId);
    generator.writeStringField("_forwarder_node_id", nodeId);

    generator.writeEndObject();

    generator.flush();

    return outputStream.toByteArray();
}

From source file:com.baasbox.configuration.PropertiesConfigurationHelper.java

/***
 *
 * Returns a json representation of the Enumerator
 * The Enumerator must implements the IProperties interface
 * @param en    the Enumerator to serialize. It must implements the IProperties interface
 * @return       the representation of the Enumerator 
 *///from   ww  w.j  ava  2 s  .  c  om
@SuppressWarnings("unchecked")
public static String dumpConfigurationAsJson(String section) {
    Class en = CONFIGURATION_SECTIONS.get(section);
    try {
        JsonFactory jfactory = new JsonFactory();
        StringWriter sw = new StringWriter();
        String enumDescription = "";
        JsonGenerator gen = jfactory.createJsonGenerator(sw);

        Method getEnumDescription = en.getMethod("getEnumDescription");
        if (getEnumDescription != null && getEnumDescription.getReturnType() == String.class
                && Modifier.isStatic(getEnumDescription.getModifiers()))
            enumDescription = (String) getEnumDescription.invoke(null);
        gen.writeStartObject(); //{
        gen.writeStringField("section", section); //    "configuration":"EnumName"
        gen.writeStringField("description", enumDescription); //   ,"description": "EnumDescription"
        gen.writeFieldName("sub sections"); //  ,"sections":
        gen.writeStartObject(); //      {
        String lastSection = "";
        EnumSet values = EnumSet.allOf(en);
        for (Object v : values) {
            String key = (String) (en.getMethod("getKey")).invoke(v);
            boolean isVisible = (Boolean) (en.getMethod("isVisible")).invoke(v);
            String valueAsString;
            if (isVisible)
                valueAsString = (String) (en.getMethod("getValueAsString")).invoke(v);
            else
                valueAsString = "--HIDDEN--";
            boolean isEditable = (Boolean) (en.getMethod("isEditable")).invoke(v);
            String valueDescription = (String) (en.getMethod("getValueDescription")).invoke(v);
            Class type = (Class) en.getMethod("getType").invoke(v);
            String subsection = key.substring(0, key.indexOf('.'));
            if (!lastSection.equals(subsection)) {
                if (gen.getOutputContext().inArray())
                    gen.writeEndArray();
                gen.writeFieldName(subsection); //         "sectionName":
                gen.writeStartArray(); //            [
                lastSection = subsection;
            }
            boolean isOverridden = (Boolean) (en.getMethod("isOverridden")).invoke(v);
            gen.writeStartObject(); //               {
            gen.writeStringField(key, valueAsString); //                     "key": "value"   
            gen.writeStringField("description", valueDescription); //                  ,"description":"description"
            gen.writeStringField("type", type.getSimpleName()); //                  ,"type":"type"
            gen.writeBooleanField("editable", isEditable); //                  ,"editable":"true|false"
            gen.writeBooleanField("visible", isVisible); //                  ,"visible":"true|false"
            gen.writeBooleanField("overridden", isOverridden); //                  ,"overridden":"true|false"
            gen.writeEndObject(); //               }
        }
        if (gen.getOutputContext().inArray())
            gen.writeEndArray(); //            ]
        gen.writeEndObject(); //      }
        gen.writeEndObject(); //}
        gen.close();
        return sw.toString();
    } catch (Exception e) {
        BaasBoxLogger.error("Cannot generate a json for " + en.getSimpleName()
                + " Enum. Is it an Enum that implements the IProperties interface?", e);
    }
    return "{}";
}

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

private void writePossiblePropertyValues(JsonGenerator jgen, String currentVocab,
        ActionInputParameter actionInputParameter, @SuppressWarnings("unused") Object[] possiblePropertyValues)
        throws IOException {
    // Enable the following to list possible values.
    // Problem: how to express individuals only for certain hydra:options
    // not all hydra:options should be taken as uris, sometimes they might be just literals
    // how to make that clear to the client?
    // maybe we must write them out for options
    //        if (possiblePropertyValues.length > 0) {
    //            jgen.writeArrayFieldStart("hydra:option");
    ///*from   w w w  .  j av  a 2 s.com*/
    //            for (Object possibleValue : possiblePropertyValues) {
    //                // TODO: apply "hydra:option" : { "@type": "@vocab"} to context for enums
    //                writeScalarValue(jgen, possibleValue, rootParameter.getParameterType());
    //            }
    //            jgen.writeEndArray();
    //        }

    if (actionInputParameter.isArrayOrCollection()) {
        jgen.writeBooleanField(getPropertyOrClassNameInVocab(currentVocab, "multipleValues",
                LdContextFactory.HTTP_SCHEMA_ORG, "schema:"), true);
    }

    //  valueRequired (hard to say, using @Access on Event is for all update requests - or make
    //     specific request beans for different
    //     purposes rather than always passing an instance of e.g. Event?)
    //       -> update is a different use case than create - or maybe have an @Requires("eventStatus")
    //          annotation alongside requestBody to tell which attributes are required or writable, and use
    // Requires over
    //          bean structure, where ctor with least length of args is required and setters are supported
    //          but optional? The bean structure does say what is writable for updates, but not what is required
    // for creation. Right now setters are supportedProperties. For creation we would have to add constructor
    // arguments as supportedProperties.
    //  (/) defaultValue (pre-filled value, e.g. list of selected items for option)
    //  valueName (for iri templates only)
    //  (/) readonlyValue (true for final public field or absence of setter, send fixed value like hidden field?)
    // -> use hydra:readable, hydra:writable
    //  (/) multipleValues
    //  (/) valueMinLength
    //  (/) valueMaxLength
    //  (/) valuePattern
    //  minValue (DateTime support)
    //  maxValue (DateTime support)
    //  (/) stepValue
    final Map<String, Object> inputConstraints = actionInputParameter.getInputConstraints();

    if (actionInputParameter.hasValue()) {
        if (actionInputParameter.isArrayOrCollection()) {
            Object[] callValues = actionInputParameter.getValues();
            Class<?> componentType = callValues.getClass().getComponentType();
            // only write defaultValue for array of scalars
            if (DataType.isSingleValueType(componentType)) {
                jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab, "defaultValue",
                        LdContextFactory.HTTP_SCHEMA_ORG, "schema:"));
                jgen.writeStartArray();
                for (Object callValue : callValues) {
                    writeScalarValue(jgen, callValue, componentType);
                }
                jgen.writeEndArray();
            }
        } else {
            jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab, "defaultValue",
                    LdContextFactory.HTTP_SCHEMA_ORG, "schema:"));

            writeScalarValue(jgen, actionInputParameter.getValue(), actionInputParameter.getParameterType());
        }
    }

    if (!inputConstraints.isEmpty()) {
        final List<String> keysToAppendValue = Arrays.asList(Input.MAX, Input.MIN, Input.STEP);
        for (String keyToAppendValue : keysToAppendValue) {
            final Object constraint = inputConstraints.get(keyToAppendValue);
            if (constraint != null) {
                jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab, keyToAppendValue + "Value",
                        LdContextFactory.HTTP_SCHEMA_ORG, "schema:"));
                jgen.writeNumber(constraint.toString());
            }
        }

        final List<String> keysToPrependValue = Arrays.asList(Input.MAX_LENGTH, Input.MIN_LENGTH,
                Input.PATTERN);
        for (String keyToPrependValue : keysToPrependValue) {
            final Object constraint = inputConstraints.get(keyToPrependValue);
            if (constraint != null) {
                jgen.writeFieldName(getPropertyOrClassNameInVocab(currentVocab,
                        "value" + StringUtils.capitalize(keyToPrependValue), LdContextFactory.HTTP_SCHEMA_ORG,
                        "schema:"));
                if (Input.PATTERN.equals(keyToPrependValue)) {
                    jgen.writeString(constraint.toString());
                } else {
                    jgen.writeNumber(constraint.toString());
                }
            }
        }

    }

}

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.
 */// w ww.  j  ava  2 s.c o m
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);
}