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:com.ntsync.shared.RawContact.java

/**
 * Convert the RawContact object into a DTO. From the JSONString interface.
 * //from  www  . ja  va 2s  .c  o  m
 * @return a JSON string representation of the object
 */
public byte[] toDTO(Key secret, String pwdSaltBase64) {
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream(DEFAULT_BYTEARRAY_SIZE);
        AEADBlockCipher ecipher = CryptoHelper.getCipher();

        byte[] iv = new byte[CryptoHelper.IV_LEN];
        SecureRandom random = new SecureRandom();

        StringBuilder hashValue = new StringBuilder();
        hashValue.append(pwdSaltBase64);
        hashValue.append(displayName);
        hashValue.append(lastName);
        hashValue.append(firstName);
        hashValue.append(middleName);

        out.write(ContactConstants.ROWID);
        byte[] rowId = String.valueOf(mRawContactId).getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME);

        SyncDataHelper.writeInt(out, rowId.length);
        out.write(rowId);

        JsonFactory json = new JsonFactory();
        StringWriter writer = new StringWriter();
        JsonGenerator g = json.createGenerator(writer);
        g.writeStartObject();

        writeStructuredName(g);

        writeList(hashValue, g, ContactConstants.PHONE, phones, true);
        writeList(hashValue, g, ContactConstants.EMAIL, emails, true);
        writeList(hashValue, g, ContactConstants.EVENT, events, false);
        writeList(hashValue, g, ContactConstants.RELATION, relations, false);
        writeList(hashValue, g, ContactConstants.SIPADDRESS, sipAddresses, false);
        writeList(hashValue, g, ContactConstants.NICKNAME, nicknames, false);
        writeList(hashValue, g, ContactConstants.WEBSITE, websites, false);
        writeAddress(hashValue, g, addresses);
        writeImList(g, imAddresses);
        writeOrganization(g, organization);

        writeField(g, ContactConstants.NOTE, note);
        if (starred) {
            g.writeBooleanField(ContactConstants.STARRED, true);
        }
        if (sendToVoiceMail) {
            g.writeBooleanField(ContactConstants.SEND_TO_VOICE_MAIL, true);
        }
        writeField(g, ContactConstants.DROID_CUSTOM_RINGTONE, droidCustomRingtone);

        if (photoSuperPrimary) {
            g.writeBooleanField(ContactConstants.PHOTO_SUPERPRIMARY, true);
        }

        writeStringList(g, ContactConstants.GROUPMEMBERSHIP, groupSourceIds);

        g.writeEndObject();
        g.close();

        String textData = writer.toString();

        CryptoHelper.writeValue(secret, out, ecipher, iv, random, ContactConstants.TEXTDATA, textData);
        CryptoHelper.writeValue(secret, out, ecipher, iv, random, ContactConstants.PHOTO, photo);

        if (lastModified != null) {
            writeRawValue(out, ContactConstants.MODIFIED,
                    String.valueOf(lastModified.getTime()).getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME));
        }

        if (mDeleted) {
            writeRawValue(out, ContactConstants.DELETED, "1".getBytes(SyncDataHelper.DEFAULT_CHARSET_NAME));
        }
        writeRawValue(out, ContactConstants.HASH, createHash(hashValue));

        return out.toByteArray();
    } catch (final IOException ex) {
        LOG.error(ERROR_CONVERT_TOJSON + ex.toString(), ex);
    } catch (GeneralSecurityException ex) {
        LOG.error(ERROR_CONVERT_TOJSON + ex.toString(), ex);
    } catch (InvalidCipherTextException ex) {
        LOG.error(ERROR_CONVERT_TOJSON + ex.toString(), ex);
    }
    return null;
}

From source file:com.buaa.cfs.conf.Configuration.java

/**
 * Writes out all the parameters and their properties (final and resource) to the given {@link Writer} The format of
 * the output would be { "properties" : [ {key1,value1,key1.isFinal,key1.resource}, {key2,value2,
 * key2.isFinal,key2.resource}... ] } It does not output the parameters of the configuration object which is loaded
 * from an input stream.//from ww w  . j a va2 s . c  o m
 *
 * @param out the Writer to write to
 *
 * @throws IOException
 */
public static void dumpConfiguration(Configuration config, Writer out) throws IOException {
    JsonFactory dumpFactory = new JsonFactory();
    JsonGenerator dumpGenerator = dumpFactory.createJsonGenerator(out);
    dumpGenerator.writeStartObject();
    dumpGenerator.writeFieldName("properties");
    dumpGenerator.writeStartArray();
    dumpGenerator.flush();
    synchronized (config) {
        for (Entry<Object, Object> item : config.getProps().entrySet()) {
            dumpGenerator.writeStartObject();
            dumpGenerator.writeStringField("key", (String) item.getKey());
            dumpGenerator.writeStringField("value", config.get((String) item.getKey()));
            dumpGenerator.writeBooleanField("isFinal", config.finalParameters.contains(item.getKey()));
            String[] resources = config.updatingResource.get(item.getKey());
            String resource = UNKNOWN_RESOURCE;
            if (resources != null && resources.length > 0) {
                resource = resources[0];
            }
            dumpGenerator.writeStringField("resource", resource);
            dumpGenerator.writeEndObject();
        }
    }
    dumpGenerator.writeEndArray();
    dumpGenerator.writeEndObject();
    dumpGenerator.flush();
}

From source file:com.netflix.hystrix.serial.SerialHystrixDashboardData.java

private static void writeCollapserMetrics(final HystrixCollapserMetrics collapserMetrics, JsonGenerator json)
        throws IOException {
    HystrixCollapserKey key = collapserMetrics.getCollapserKey();

    json.writeStartObject();/*  w  w w  .j a  va 2  s  . c  o  m*/

    json.writeStringField("type", "HystrixCollapser");
    json.writeStringField("name", key.name());
    json.writeNumberField("currentTime", System.currentTimeMillis());

    safelyWriteNumberField(json, "rollingCountRequestsBatched", new Func0<Long>() {
        @Override
        public Long call() {
            return collapserMetrics.getRollingCount(HystrixEventType.Collapser.ADDED_TO_BATCH);
        }
    });
    safelyWriteNumberField(json, "rollingCountBatches", new Func0<Long>() {
        @Override
        public Long call() {
            return collapserMetrics.getRollingCount(HystrixEventType.Collapser.BATCH_EXECUTED);
        }
    });
    safelyWriteNumberField(json, "rollingCountResponsesFromCache", new Func0<Long>() {
        @Override
        public Long call() {
            return collapserMetrics.getRollingCount(HystrixEventType.Collapser.RESPONSE_FROM_CACHE);
        }
    });

    // batch size percentiles
    json.writeNumberField("batchSize_mean", collapserMetrics.getBatchSizeMean());
    json.writeObjectFieldStart("batchSize");
    json.writeNumberField("25", collapserMetrics.getBatchSizePercentile(25));
    json.writeNumberField("50", collapserMetrics.getBatchSizePercentile(50));
    json.writeNumberField("75", collapserMetrics.getBatchSizePercentile(75));
    json.writeNumberField("90", collapserMetrics.getBatchSizePercentile(90));
    json.writeNumberField("95", collapserMetrics.getBatchSizePercentile(95));
    json.writeNumberField("99", collapserMetrics.getBatchSizePercentile(99));
    json.writeNumberField("99.5", collapserMetrics.getBatchSizePercentile(99.5));
    json.writeNumberField("100", collapserMetrics.getBatchSizePercentile(100));
    json.writeEndObject();

    // shard size percentiles (commented-out for now)
    //json.writeNumberField("shardSize_mean", collapserMetrics.getShardSizeMean());
    //json.writeObjectFieldStart("shardSize");
    //json.writeNumberField("25", collapserMetrics.getShardSizePercentile(25));
    //json.writeNumberField("50", collapserMetrics.getShardSizePercentile(50));
    //json.writeNumberField("75", collapserMetrics.getShardSizePercentile(75));
    //json.writeNumberField("90", collapserMetrics.getShardSizePercentile(90));
    //json.writeNumberField("95", collapserMetrics.getShardSizePercentile(95));
    //json.writeNumberField("99", collapserMetrics.getShardSizePercentile(99));
    //json.writeNumberField("99.5", collapserMetrics.getShardSizePercentile(99.5));
    //json.writeNumberField("100", collapserMetrics.getShardSizePercentile(100));
    //json.writeEndObject();

    //json.writeNumberField("propertyValue_metricsRollingStatisticalWindowInMilliseconds", collapserMetrics.getProperties().metricsRollingStatisticalWindowInMilliseconds().get());
    json.writeBooleanField("propertyValue_requestCacheEnabled",
            collapserMetrics.getProperties().requestCacheEnabled().get());
    json.writeNumberField("propertyValue_maxRequestsInBatch",
            collapserMetrics.getProperties().maxRequestsInBatch().get());
    json.writeNumberField("propertyValue_timerDelayInMilliseconds",
            collapserMetrics.getProperties().timerDelayInMilliseconds().get());

    json.writeNumberField("reportingHosts", 1); // this will get summed across all instances in a cluster

    json.writeEndObject();
}

From source file:com.google.openrtb.json.OpenRtbJsonWriter.java

protected void writeImpFields(Imp imp, JsonGenerator gen) throws IOException {
    gen.writeStringField("id", imp.getId());
    if (imp.hasBanner()) {
        gen.writeFieldName("banner");
        writeBanner(imp.getBanner(), gen);
    }//from  ww  w .j ava 2  s  . c  o m
    if (imp.hasVideo()) {
        gen.writeFieldName("video");
        writeVideo(imp.getVideo(), gen);
    }
    if (imp.hasAudio()) {
        gen.writeFieldName("audio");
        writeAudio(imp.getAudio(), gen);
    }
    if (imp.hasNative()) {
        gen.writeFieldName("native");
        writeNative(imp.getNative(), gen);
    }
    if (imp.hasDisplaymanager()) {
        gen.writeStringField("displaymanager", imp.getDisplaymanager());
    }
    if (imp.hasDisplaymanagerver()) {
        gen.writeStringField("displaymanagerver", imp.getDisplaymanagerver());
    }
    if (imp.hasInstl()) {
        writeIntBoolField("instl", imp.getInstl(), gen);
    }
    if (imp.hasTagid()) {
        gen.writeStringField("tagid", imp.getTagid());
    }
    if (imp.hasBidfloor()) {
        gen.writeNumberField("bidfloor", imp.getBidfloor());
    }
    if (imp.hasBidfloorcur()) {
        gen.writeStringField("bidfloorcur", imp.getBidfloorcur());
    }
    if (imp.hasSecure()) {
        writeIntBoolField("secure", imp.getSecure(), gen);
    }
    writeStrings("iframebuster", imp.getIframebusterList(), gen);
    if (imp.hasPmp()) {
        gen.writeFieldName("pmp");
        writePmp(imp.getPmp(), gen);
    }
    if (imp.hasClickbrowser()) {
        gen.writeBooleanField("clickbrowser", imp.getClickbrowser());
    }
    if (imp.hasExp()) {
        gen.writeNumberField("exp", imp.getExp());
    }
}

From source file:net.solarnetwork.web.support.JSONView.java

private void writeJsonValue(JsonGenerator json, String key, Object val, PropertyEditorRegistrar registrar)
        throws JsonGenerationException, IOException {
    if (val instanceof Collection<?> || (val != null && val.getClass().isArray())) {
        Collection<?> col;/*w ww  .  j  a v a  2  s .c  o  m*/
        if (val instanceof Collection<?>) {
            col = (Collection<?>) val;
        } else if (!val.getClass().getComponentType().isPrimitive()) {
            col = Arrays.asList((Object[]) val);
        } else {
            // damn you, primitives
            col = getPrimitiveCollection(val);
        }
        if (key != null) {
            json.writeFieldName(key);
        }
        json.writeStartArray();
        for (Object colObj : col) {
            writeJsonValue(json, null, colObj, registrar);
        }

        json.writeEndArray();
    } else if (val instanceof Map<?, ?>) {
        if (key != null) {
            json.writeFieldName(key);
        }
        json.writeStartObject();
        for (Map.Entry<?, ?> me : ((Map<?, ?>) val).entrySet()) {
            Object propName = me.getKey();
            if (propName == null) {
                continue;
            }
            writeJsonValue(json, propName.toString(), me.getValue(), registrar);
        }
        json.writeEndObject();
    } else if (val instanceof Double) {
        if (key == null) {
            json.writeNumber((Double) val);
        } else {
            json.writeNumberField(key, (Double) val);
        }
    } else if (val instanceof Integer) {
        if (key == null) {
            json.writeNumber((Integer) val);
        } else {
            json.writeNumberField(key, (Integer) val);
        }
    } else if (val instanceof Short) {
        if (key == null) {
            json.writeNumber(((Short) val).intValue());
        } else {
            json.writeNumberField(key, ((Short) val).intValue());
        }
    } else if (val instanceof Float) {
        if (key == null) {
            json.writeNumber((Float) val);
        } else {
            json.writeNumberField(key, (Float) val);
        }
    } else if (val instanceof Long) {
        if (key == null) {
            json.writeNumber((Long) val);
        } else {
            json.writeNumberField(key, (Long) val);
        }
    } else if (val instanceof Boolean) {
        if (key == null) {
            json.writeBoolean((Boolean) val);
        } else {
            json.writeBooleanField(key, (Boolean) val);
        }
    } else if (val instanceof String) {
        if (key == null) {
            json.writeString((String) val);
        } else {
            json.writeStringField(key, (String) val);
        }
    } else {
        // create a JSON object from bean properties
        if (getPropertySerializerRegistrar() != null && val != null) {
            // try whole-bean serialization first
            Object o = getPropertySerializerRegistrar().serializeProperty(key, val.getClass(), val, val);
            if (o != val) {
                if (o != null) {
                    writeJsonValue(json, key, o, registrar);
                }
                return;
            }
        }
        generateJavaBeanObject(json, key, val, registrar);
    }
}

From source file:org.pentaho.pdi.engine.serializers.DataEventSerializer.java

public DataEventSerializer() {
    super(DataEvent.class);

    SimpleModule module = new SimpleModule();
    module.addSerializer(DataEvent.class, new JsonSerializer<DataEvent>() {
        @Override/* w  w w.  ja va 2 s .  c om*/
        public void serialize(DataEvent dataEvent, JsonGenerator jsonGenerator,
                SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
            jsonGenerator.writeStartObject();
            Rows rows = (Rows) dataEvent.getData();
            jsonGenerator.writeStringField("model-id", dataEvent.getSource().getId());
            jsonGenerator.writeStringField("type", rows.getType().toString());
            jsonGenerator.writeStringField("state", rows.getState().toString());

            jsonGenerator.writeArrayFieldStart("rows");
            for (Row row : rows) {
                jsonGenerator.writeStartObject();
                jsonGenerator.writeArrayFieldStart("names");
                for (String name : row.getColumnNames()) {
                    jsonGenerator.writeString(name);
                }
                jsonGenerator.writeEndArray();

                jsonGenerator.writeArrayFieldStart("objects");
                for (Object obj : row.getObjects().get()) {
                    jsonGenerator.writeStartObject();
                    if (obj == null) {
                        jsonGenerator.writeStringField("type", "Null");
                        jsonGenerator.writeEndObject();
                        continue;
                    }
                    switch (obj.getClass().getSimpleName()) {
                    case "String":
                        jsonGenerator.writeStringField("type", "String");
                        jsonGenerator.writeStringField("obj", obj.toString());
                        break;
                    case "Date":
                        jsonGenerator.writeStringField("type", "Date");
                        jsonGenerator.writeStringField("obj", DATE_TIME_INSTANCE.format((Date) obj));
                        break;
                    case "Integer":
                        jsonGenerator.writeStringField("type", "Integer");
                        jsonGenerator.writeNumberField("obj", (Integer) obj);
                        break;
                    case "Long":
                        jsonGenerator.writeStringField("type", "Long");
                        jsonGenerator.writeNumberField("obj", (Long) obj);
                        break;
                    case "Double":
                        jsonGenerator.writeStringField("type", "Double");
                        jsonGenerator.writeNumberField("obj", (Double) obj);
                        break;
                    case "BigDecimal":
                        jsonGenerator.writeStringField("type", "BigDecimal");
                        jsonGenerator.writeStringField("obj", obj.toString());
                        break;
                    case "Boolean":
                        jsonGenerator.writeStringField("type", "Boolean");
                        jsonGenerator.writeBooleanField("obj", (Boolean) obj);
                        break;
                    case "byte[]":
                        jsonGenerator.writeStringField("type", "byte[]");
                        jsonGenerator.writeStringField("obj", new String(((byte[]) obj), "UTF-8"));
                        break;
                    default:
                        if (obj instanceof Serializable) {
                            jsonGenerator.writeStringField("type", "Object");

                            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
                            objectOutputStream.writeObject(obj);
                            objectOutputStream.close();
                            outputStream.close();
                            byte[] bytes = outputStream.toByteArray();
                            jsonGenerator.writeStringField("obj", Base64.encodeBase64String(bytes));
                        }
                    }
                    jsonGenerator.writeEndObject();
                }
                jsonGenerator.writeEndArray();
                jsonGenerator.writeEndObject();

            }
            jsonGenerator.writeEndArray();

            jsonGenerator.writeEndObject();
        }
    });
    module.addDeserializer(DataEvent.class, new StdNodeBasedDeserializer<DataEvent>(DataEvent.class) {
        @Override
        public DataEvent convert(JsonNode jsonNode, DeserializationContext deserializationContext)
                throws IOException {

            Rows.TYPE type = Rows.TYPE.valueOf(jsonNode.get("type").asText());
            Rows.STATE state = Rows.STATE.valueOf(jsonNode.get("state").asText());

            List<Row> rows = new ArrayList<>();

            JsonNode json_rows = jsonNode.get("rows");
            for (JsonNode row : json_rows) {

                List<Class> types = new ArrayList<>();
                List<String> names = new ArrayList<>();
                for (JsonNode name : row.get("names")) {
                    names.add(name.asText());
                }
                List<Object> objects = new ArrayList<>();
                for (JsonNode obj : row.get("objects")) {
                    JsonNode t = obj.get("type");
                    JsonNode rawObject = obj.get("obj");

                    Object object = null;
                    String objType = t.asText();
                    switch (objType) {
                    case "Null":
                        types.add(Void.class);
                        break;
                    case "String":
                        types.add(String.class);
                        object = rawObject.asText();
                        break;
                    case "Integer":
                        types.add(Integer.class);
                        object = rawObject.asInt();
                        break;
                    case "Long":
                        types.add(Long.class);
                        object = rawObject.asLong();
                        break;
                    case "Date":
                        types.add(Date.class);
                        try {
                            object = DATE_TIME_INSTANCE.parse(rawObject.asText());
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        break;
                    case "Double":
                        types.add(Double.class);
                        object = rawObject.asDouble();
                        break;
                    case "BigDecimal":
                        types.add(BigDecimal.class);
                        object = new BigDecimal(rawObject.asText());
                        break;
                    case "Boolean":
                        types.add(Boolean.class);
                        object = rawObject.asBoolean();
                        break;
                    case "byte[]":
                        types.add(byte[].class);
                        object = rawObject.asText().getBytes("UTF-8");
                        break;
                    case "Object":
                        try {
                            types.add(Object.class);
                            object = new ObjectInputStream(
                                    new ByteArrayInputStream(Base64.decodeBase64(rawObject.asText())))
                                            .readObject();
                        } catch (ClassNotFoundException e) {
                            e.printStackTrace();
                        }
                        break;
                    }

                    objects.add(object);
                }

                Row r = new DeserializedRow(names, types, objects);
                rows.add(r);
            }
            Rows rowsObj = new Rows(rows, type, state);

            return new DataEvent(new RemoteSource(jsonNode.get("model-id").asText()), rowsObj);

        }
    });
    mapper.registerModule(module);
}

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  ww .ja  v  a  2  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();
        }
    });
}

From source file:tds.student.web.backing.TestShellScriptsBacking.java

private void addTestSegments() throws IOException, ReturnStatusException {
    TestSession testSession = StudentContext.getSession();
    // _studentSettings = FacesContextHelper.getBean ("studentSettings",
    // StudentSettings.class);
    OpportunitySegments oppSegments = null;

    // load opp segments only if there are any test segments
    if (_testProps.getSegments().size() > 0) {
        oppSegments = this._iOpportunityService.getSegments(this._testOpportunity.getOppInstance(),
                !this._studentSettings.isReadOnly());
    }/* w  w  w. ja va  2 s  .  co  m*/

    StringWriter sw = new StringWriter();
    JsonFactory jsonFactory = new JsonFactory();
    JsonGenerator writer = jsonFactory.createGenerator(sw);

    writer.writeStartArray(); // [

    for (final TestSegment testSegment : _testProps.getSegments()) {
        OpportunitySegment oppSegment = null;

        // find opportunity segment
        if (oppSegments != null) {
            oppSegment = (OpportunitySegment) CollectionUtils.find(oppSegments, new Predicate() {
                @Override
                public boolean evaluate(Object arg0) {
                    if (StringUtils.equals(((OpportunitySegment) arg0).getId(), testSegment.getId()))
                        return true;
                    return false;
                }
            });
        }

        // figure out segment permeability
        int isPermeable = testSegment.getIsPermeable();
        int updatePermeable = isPermeable;

        // these are local override rules (reviewed with Larry)
        if (oppSegment != null) {
            /*
             * if -1, use the defined value for the segment as returned by
             * IB_GetSegments if not -1, then the local value defines the temporary
             * segment permeability
             */
            if (oppSegment.getIsPermeable() != -1) {
                isPermeable = oppSegment.getIsPermeable();

                /*
                 * The default permeability is restored when the student leaves the
                 * segment while testing. Assuming the segment is impermeable, this
                 * allows the student one entry into the segment during the sitting.
                 * When the student leaves the segment, is membrane is enforced by the
                 * student app. The database will restore the default value of the
                 * segment membrane when the test is paused.
                 */
                if (oppSegment.getRestorePermOn() != "segment") {
                    updatePermeable = oppSegment.getIsPermeable();
                }
            }

            // NOTE: When student enters segment, set isPermeable = updatePermeable
        }

        // if read only mode is enabled then we should let user have access
        if (_studentSettings.isReadOnly()) {
            isPermeable = 1;
            updatePermeable = 1;
        }

        // figure out segment approval
        int entryApproval = testSegment.getEntryApproval();
        int exitApproval = testSegment.getExitApproval();

        // NOTE: If proctorless test then don't require entry/exit approval
        // (nobody to approve it)
        if (testSession.isProctorless() || _studentSettings.isReadOnly()) {
            entryApproval = 0;
            exitApproval = 0;
        }
        // BUG #22642: Entry and Exit approvals are not needed from Test level
        // review screen when approval = 2
        else if (getViewPageNumber() > 0) {
            if (testSegment.getEntryApproval() == 2)
                entryApproval = 0;
            if (testSegment.getExitApproval() == 2)
                exitApproval = 0;
        }

        // write segment json
        writer.writeStartObject();
        writer.writeStringField("type", "object"); // {
        writer.writeStringField("id", testSegment.getId());
        writer.writeNumberField("position", testSegment.getPosition());
        writer.writeStringField("label", testSegment.getLabel());
        writer.writeBooleanField("itemReview", testSegment.isItemReview());
        writer.writeNumberField("isPermeable", isPermeable);
        writer.writeNumberField("updatePermeable", updatePermeable);
        writer.writeNumberField("entryApproval", entryApproval);
        writer.writeNumberField("exitApproval", exitApproval);

        // Looks like we don't use this variable in javascript (removed for 2012)
        // Test adaptiveSegment =
        // TestOpportunity.AdaptiveTest.GetSegmentTest(testSegment.ID);
        // writer.WriteObject("length", (adaptiveSegment != null) ?
        // adaptiveSegment.TotalMinLength : 0);

        writer.writeEndObject(); // }
    }

    writer.writeEndArray(); // ]

    writer.close();

    // write out javascript
    StringBuilder javascript = new StringBuilder();
    javascript.append("var tdsSegments = ");
    javascript.append(sw.toString());
    javascript.append("; ");

    this.getClientScript().addToJsCode(javascript.toString());

}