Java Code Examples for org.codehaus.jackson.JsonGenerator#writeStringField()

The following examples show how to use org.codehaus.jackson.JsonGenerator#writeStringField() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExtensionSerDeserUtils.java    From occurrence with Apache License 2.0 6 votes vote down vote up
@Override
public void serialize(List<Map<Term, String>> value, JsonGenerator jgen, SerializerProvider provider)
  throws IOException {
  if ((value == null || value.isEmpty()) && provider.getConfig().isEnabled(Feature.WRITE_EMPTY_JSON_ARRAYS)) {
    jgen.writeStartArray();
    jgen.writeEndArray();
  } else {
    jgen.writeStartArray();
    for (Map<Term, String> extension : value) {
      jgen.writeStartObject();
      for (Entry<Term, String> entry : extension.entrySet()) {
        jgen.writeStringField(entry.getKey().qualifiedName(), entry.getValue());
      }
      jgen.writeEndObject();
    }
    jgen.writeEndArray();
  }
}
 
Example 2
Source File: DetectedLanguageWriter.java    From stanbol-freeling with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public void writeTo(Collection<Language> detected, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String,Object> httpHeaders, OutputStream entityStream)
        throws IOException, WebApplicationException {
    JsonGenerator jg = getJsonFactory().createJsonGenerator(entityStream);
    jg.writeStartArray();
    for(Language lang : detected){
        jg.writeStartObject();
        jg.writeStringField("lang", lang.getLang());
        if(lang.getProb() > 0){
            jg.writeNumberField("prob", lang.getProb());
        }
        jg.writeEndObject();
    }
    jg.writeEndArray();
    jg.close();
}
 
Example 3
Source File: Helper.java    From NNAnalytics with Apache License 2.0 6 votes vote down vote up
/**
 * Return String representation of enums as a JSON list.
 *
 * @param values the enums
 * @return String representation of enums as a JSON list
 * @throws IOException if parsing or writing fails
 */
public static String toJsonList(Enum[]... values) throws IOException {
  StringWriter sw = new StringWriter();
  JsonGenerator json = new JsonFactory().createJsonGenerator(sw).useDefaultPrettyPrinter();
  try {
    json.writeStartObject();
    for (int i = 0; i < values.length; i++) {
      Enum[] enumList = values[i];
      json.writeArrayFieldStart("Possibilities " + (i + 1));
      for (Enum value : enumList) {
        if (value != null) {
          json.writeStartObject();
          json.writeStringField("Name", value.name());
          json.writeEndObject();
        }
      }
      json.writeEndArray();
    }
    json.writeEndObject();
  } finally {
    IOUtils.closeStream(json);
  }
  return sw.toString();
}
 
Example 4
Source File: RepositoryImpl.java    From bintray-client-java with Apache License 2.0 6 votes vote down vote up
/**
 * PATCH repo only accepts description and label updates, name is needed for URL creation, because of the special
 * ignore and property structure of the RepositoryDetails class this method just uses a json generator to write
 * the update json.
 */
public static String getUpdateJson(RepositoryDetails repositoryDetails) throws IOException {
    StringWriter writer = new StringWriter();
    JsonGenerator jGen = ObjectMapperHelper.get().getJsonFactory().createJsonGenerator(writer);
    jGen.writeStartObject();
    jGen.writeStringField("name", repositoryDetails.getName());
    jGen.writeStringField("desc", repositoryDetails.getDescription());
    if (repositoryDetails.getLabels().size() > 0) {
        jGen.writeArrayFieldStart("labels");
        for (String label : repositoryDetails.getLabels()) {
            jGen.writeString(label);
        }
        jGen.writeEndArray();
    }
    jGen.writeEndObject();
    jGen.close();
    writer.close();
    return writer.toString();
}
 
Example 5
Source File: AppPackage.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(
    PropertyInfo propertyInfo, JsonGenerator jgen, SerializerProvider provider)
  throws IOException, JsonProcessingException
{
  if (provideDescription) {
    jgen.writeStartObject();
    jgen.writeStringField("value", propertyInfo.value);
    jgen.writeStringField("description", propertyInfo.description);
    jgen.writeEndObject();
  } else {
    jgen.writeString(propertyInfo.value);
  }
}
 
Example 6
Source File: Configuration.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 *  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.
 * @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();
}
 
Example 7
Source File: Configuration.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 *  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.
 * @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();
}
 
Example 8
Source File: AppPackage.java    From attic-apex-core with Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(
    PropertyInfo propertyInfo, JsonGenerator jgen, SerializerProvider provider)
  throws IOException, JsonProcessingException
{
  if (provideDescription) {
    jgen.writeStartObject();
    jgen.writeStringField("value", propertyInfo.value);
    jgen.writeStringField("description", propertyInfo.description);
    jgen.writeEndObject();
  } else {
    jgen.writeString(propertyInfo.value);
  }
}
 
Example 9
Source File: Log4Json.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Build a JSON entry from the parameters. This is public for testing.
 *
 * @param writer destination
 * @param loggerName logger name
 * @param timeStamp time_t value
 * @param level level string
 * @param threadName name of the thread
 * @param message rendered message
 * @param ti nullable thrown information
 * @return the writer
 * @throws IOException on any problem
 */
public Writer toJson(final Writer writer,
                     final String loggerName,
                     final long timeStamp,
                     final String level,
                     final String threadName,
                     final String message,
                     final ThrowableInformation ti) throws IOException {
  JsonGenerator json = factory.createJsonGenerator(writer);
  json.writeStartObject();
  json.writeStringField(NAME, loggerName);
  json.writeNumberField(TIME, timeStamp);
  Date date = new Date(timeStamp);
  json.writeStringField(DATE, dateFormat.format(date));
  json.writeStringField(LEVEL, level);
  json.writeStringField(THREAD, threadName);
  json.writeStringField(MESSAGE, message);
  if (ti != null) {
    //there is some throwable info, but if the log event has been sent over the wire,
    //there may not be a throwable inside it, just a summary.
    Throwable thrown = ti.getThrowable();
    String eclass = (thrown != null) ?
        thrown.getClass().getName()
        : "";
    json.writeStringField(EXCEPTION_CLASS, eclass);
    String[] stackTrace = ti.getThrowableStrRep();
    json.writeArrayFieldStart(STACK);
    for (String row : stackTrace) {
      json.writeString(row);
    }
    json.writeEndArray();
  }
  json.writeEndObject();
  json.flush();
  json.close();
  return writer;
}
 
Example 10
Source File: RecordWithMetadataToEnvelopedRecordWithMetadata.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private void writeHeaders(RecordWithMetadata<?> inputRecord, JsonGenerator generator)
    throws IOException {
  generator.writeStringField("mId", inputRecord.getMetadata().getGlobalMetadata().getId());

  if (!inputRecord.getMetadata().getRecordMetadata().isEmpty()) {
    generator.writeObjectField("rMd", inputRecord.getMetadata().getRecordMetadata());
  }
}
 
Example 11
Source File: Configuration.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 *  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.
 * @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 (Map.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();
}
 
Example 12
Source File: GlobalMetadata.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
protected void toJsonUtf8(JsonGenerator generator) throws IOException {
  generator.writeStartObject();
  generator.writeStringField("id", getId());
  bodyToJsonUtf8(generator);
  generator.writeEndObject();
  generator.flush();
}
 
Example 13
Source File: JsonMapper.java    From ReactiveLab with Apache License 2.0 4 votes vote down vote up
static String toJson(Metrics commandMetrics) throws IOException {
    StringWriter jsonString = new StringWriter();
    JsonGenerator json = jsonFactory.createJsonGenerator(jsonString);

    json.writeStartObject();
    json.writeStringField("type", "HystrixCommand"); // act as this as we are hijacking Hystrix for the dashboard
    json.writeStringField("name", commandMetrics.getName());
    json.writeStringField("group", "");
    json.writeNumberField("currentTime", System.currentTimeMillis());

    json.writeBooleanField("isCircuitBreakerOpen", false);

    long errors = commandMetrics.getRollingNumber().getRollingSum(Metrics.EventType.FAILURE);
    long success = commandMetrics.getRollingNumber().getRollingSum(Metrics.EventType.SUCCESS);
    long requests = success + errors;
    int errorPercentage = (int) ((double) errors / requests * 100);

    json.writeNumberField("errorPercentage", errorPercentage);
    json.writeNumberField("errorCount", errors);
    json.writeNumberField("requestCount", requests);

    // rolling counters
    json.writeNumberField("rollingCountCollapsedRequests", 0);
    json.writeNumberField("rollingCountExceptionsThrown", commandMetrics.getRollingNumber().getRollingSum(Metrics.EventType.EXCEPTION_THROWN));
    json.writeNumberField("rollingCountFailure", errors);
    json.writeNumberField("rollingCountFallbackFailure", 0);
    json.writeNumberField("rollingCountFallbackRejection", 0);
    json.writeNumberField("rollingCountFallbackSuccess", 0);
    json.writeNumberField("rollingCountResponsesFromCache", 0);
    json.writeNumberField("rollingCountSemaphoreRejected", 0);
    json.writeNumberField("rollingCountShortCircuited", 0);
    json.writeNumberField("rollingCountSuccess", success);
    json.writeNumberField("rollingCountThreadPoolRejected", 0);
    json.writeNumberField("rollingCountTimeout", 0);

    json.writeNumberField("currentConcurrentExecutionCount", commandMetrics.getRollingNumber().getRollingMaxValue(Metrics.EventType.CONCURRENCY_MAX_ACTIVE));

    // latency percentiles
    json.writeNumberField("latencyExecute_mean", commandMetrics.getRollingPercentile().getMean());
    json.writeObjectFieldStart("latencyExecute");
    json.writeNumberField("0", commandMetrics.getRollingPercentile().getPercentile(0));
    json.writeNumberField("25", commandMetrics.getRollingPercentile().getPercentile(25));
    json.writeNumberField("50", commandMetrics.getRollingPercentile().getPercentile(50));
    json.writeNumberField("75", commandMetrics.getRollingPercentile().getPercentile(75));
    json.writeNumberField("90", commandMetrics.getRollingPercentile().getPercentile(90));
    json.writeNumberField("95", commandMetrics.getRollingPercentile().getPercentile(95));
    json.writeNumberField("99", commandMetrics.getRollingPercentile().getPercentile(99));
    json.writeNumberField("99.5", commandMetrics.getRollingPercentile().getPercentile(99.5));
    json.writeNumberField("100", commandMetrics.getRollingPercentile().getPercentile(100));
    json.writeEndObject();

    json.writeNumberField("latencyTotal_mean", commandMetrics.getRollingPercentile().getMean());
    json.writeObjectFieldStart("latencyTotal");
    json.writeNumberField("0", commandMetrics.getRollingPercentile().getPercentile(0));
    json.writeNumberField("25", commandMetrics.getRollingPercentile().getPercentile(25));
    json.writeNumberField("50", commandMetrics.getRollingPercentile().getPercentile(50));
    json.writeNumberField("75", commandMetrics.getRollingPercentile().getPercentile(75));
    json.writeNumberField("90", commandMetrics.getRollingPercentile().getPercentile(90));
    json.writeNumberField("95", commandMetrics.getRollingPercentile().getPercentile(95));
    json.writeNumberField("99", commandMetrics.getRollingPercentile().getPercentile(99));
    json.writeNumberField("99.5", commandMetrics.getRollingPercentile().getPercentile(99.5));
    json.writeNumberField("100", commandMetrics.getRollingPercentile().getPercentile(100));
    json.writeEndObject();
    
    json.writeNumberField("propertyValue_circuitBreakerRequestVolumeThreshold", 0);
    json.writeNumberField("propertyValue_circuitBreakerSleepWindowInMilliseconds", 0);
    json.writeNumberField("propertyValue_circuitBreakerErrorThresholdPercentage", 0);
    json.writeBooleanField("propertyValue_circuitBreakerForceOpen", false);
    json.writeBooleanField("propertyValue_circuitBreakerForceClosed", false);
    json.writeBooleanField("propertyValue_circuitBreakerEnabled", false);

    json.writeStringField("propertyValue_executionIsolationStrategy", "");
    json.writeNumberField("propertyValue_executionIsolationThreadTimeoutInMilliseconds", 0);
    json.writeBooleanField("propertyValue_executionIsolationThreadInterruptOnTimeout", false);
    json.writeStringField("propertyValue_executionIsolationThreadPoolKeyOverride", "");
    json.writeNumberField("propertyValue_executionIsolationSemaphoreMaxConcurrentRequests", 0);
    json.writeNumberField("propertyValue_fallbackIsolationSemaphoreMaxConcurrentRequests", 0);

    json.writeNumberField("propertyValue_metricsRollingStatisticalWindowInMilliseconds", 10000);

    json.writeBooleanField("propertyValue_requestCacheEnabled", false);
    json.writeBooleanField("propertyValue_requestLogEnabled", false);

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

    json.writeEndObject();
    json.close();

    return jsonString.getBuffer().toString();
}
 
Example 14
Source File: StartupProgressServlet.java    From big-c with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException {
  resp.setContentType("application/json; charset=UTF-8");
  StartupProgress prog = NameNodeHttpServer.getStartupProgressFromContext(
    getServletContext());
  StartupProgressView view = prog.createView();
  JsonGenerator json = new JsonFactory().createJsonGenerator(resp.getWriter());
  try {
    json.writeStartObject();
    json.writeNumberField(ELAPSED_TIME, view.getElapsedTime());
    json.writeNumberField(PERCENT_COMPLETE, view.getPercentComplete());
    json.writeArrayFieldStart(PHASES);

    for (Phase phase: view.getPhases()) {
      json.writeStartObject();
      json.writeStringField(NAME, phase.getName());
      json.writeStringField(DESC, phase.getDescription());
      json.writeStringField(STATUS, view.getStatus(phase).toString());
      json.writeNumberField(PERCENT_COMPLETE, view.getPercentComplete(phase));
      json.writeNumberField(ELAPSED_TIME, view.getElapsedTime(phase));
      writeStringFieldIfNotNull(json, FILE, view.getFile(phase));
      writeNumberFieldIfDefined(json, SIZE, view.getSize(phase));
      json.writeArrayFieldStart(STEPS);

      for (Step step: view.getSteps(phase)) {
        json.writeStartObject();
        StepType type = step.getType();
        if (type != null) {
          json.writeStringField(NAME, type.getName());
          json.writeStringField(DESC, type.getDescription());
        }
        json.writeNumberField(COUNT, view.getCount(phase, step));
        writeStringFieldIfNotNull(json, FILE, step.getFile());
        writeNumberFieldIfDefined(json, SIZE, step.getSize());
        json.writeNumberField(TOTAL, view.getTotal(phase, step));
        json.writeNumberField(PERCENT_COMPLETE, view.getPercentComplete(phase,
          step));
        json.writeNumberField(ELAPSED_TIME, view.getElapsedTime(phase, step));
        json.writeEndObject();
      }

      json.writeEndArray();
      json.writeEndObject();
    }

    json.writeEndArray();
    json.writeEndObject();
  } finally {
    IOUtils.cleanup(LOG, json);
  }
}
 
Example 15
Source File: StartupProgressServlet.java    From hadoop with Apache License 2.0 4 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws IOException {
  resp.setContentType("application/json; charset=UTF-8");
  StartupProgress prog = NameNodeHttpServer.getStartupProgressFromContext(
    getServletContext());
  StartupProgressView view = prog.createView();
  JsonGenerator json = new JsonFactory().createJsonGenerator(resp.getWriter());
  try {
    json.writeStartObject();
    json.writeNumberField(ELAPSED_TIME, view.getElapsedTime());
    json.writeNumberField(PERCENT_COMPLETE, view.getPercentComplete());
    json.writeArrayFieldStart(PHASES);

    for (Phase phase: view.getPhases()) {
      json.writeStartObject();
      json.writeStringField(NAME, phase.getName());
      json.writeStringField(DESC, phase.getDescription());
      json.writeStringField(STATUS, view.getStatus(phase).toString());
      json.writeNumberField(PERCENT_COMPLETE, view.getPercentComplete(phase));
      json.writeNumberField(ELAPSED_TIME, view.getElapsedTime(phase));
      writeStringFieldIfNotNull(json, FILE, view.getFile(phase));
      writeNumberFieldIfDefined(json, SIZE, view.getSize(phase));
      json.writeArrayFieldStart(STEPS);

      for (Step step: view.getSteps(phase)) {
        json.writeStartObject();
        StepType type = step.getType();
        if (type != null) {
          json.writeStringField(NAME, type.getName());
          json.writeStringField(DESC, type.getDescription());
        }
        json.writeNumberField(COUNT, view.getCount(phase, step));
        writeStringFieldIfNotNull(json, FILE, step.getFile());
        writeNumberFieldIfDefined(json, SIZE, step.getSize());
        json.writeNumberField(TOTAL, view.getTotal(phase, step));
        json.writeNumberField(PERCENT_COMPLETE, view.getPercentComplete(phase,
          step));
        json.writeNumberField(ELAPSED_TIME, view.getElapsedTime(phase, step));
        json.writeEndObject();
      }

      json.writeEndArray();
      json.writeEndObject();
    }

    json.writeEndArray();
    json.writeEndObject();
  } finally {
    IOUtils.cleanup(LOG, json);
  }
}
 
Example 16
Source File: QueueManager.java    From hadoop with Apache License 2.0 4 votes vote down vote up
/**
 * method to perform depth-first search and write the parameters of every 
 * queue in JSON format.
 * @param dumpGenerator JsonGenerator object which takes the dump and flushes
 *  to a writer object
 * @param rootQueues the top-level queues
 * @throws JsonGenerationException
 * @throws IOException
 */
private static void dumpConfiguration(JsonGenerator dumpGenerator,
    Set<Queue> rootQueues) throws JsonGenerationException, IOException {
  for (Queue queue : rootQueues) {
    dumpGenerator.writeStartObject();
    dumpGenerator.writeStringField("name", queue.getName());
    dumpGenerator.writeStringField("state", queue.getState().toString());
    AccessControlList submitJobList = null;
    AccessControlList administerJobsList = null;
    if (queue.getAcls() != null) {
      submitJobList =
        queue.getAcls().get(toFullPropertyName(queue.getName(),
            QueueACL.SUBMIT_JOB.getAclName()));
      administerJobsList =
        queue.getAcls().get(toFullPropertyName(queue.getName(),
            QueueACL.ADMINISTER_JOBS.getAclName()));
    }
    String aclsSubmitJobValue = " ";
    if (submitJobList != null ) {
      aclsSubmitJobValue = submitJobList.getAclString();
    }
    dumpGenerator.writeStringField("acl_submit_job", aclsSubmitJobValue);
    String aclsAdministerValue = " ";
    if (administerJobsList != null) {
      aclsAdministerValue = administerJobsList.getAclString();
    }
    dumpGenerator.writeStringField("acl_administer_jobs",
        aclsAdministerValue);
    dumpGenerator.writeFieldName("properties");
    dumpGenerator.writeStartArray();
    if (queue.getProperties() != null) {
      for (Map.Entry<Object, Object>property :
        queue.getProperties().entrySet()) {
        dumpGenerator.writeStartObject();
        dumpGenerator.writeStringField("key", (String)property.getKey());
        dumpGenerator.writeStringField("value", (String)property.getValue());
        dumpGenerator.writeEndObject();
      }
    }
    dumpGenerator.writeEndArray();
    Set<Queue> childQueues = queue.getChildren();
    dumpGenerator.writeFieldName("children");
    dumpGenerator.writeStartArray();
    if (childQueues != null && childQueues.size() > 0) {
      dumpConfiguration(dumpGenerator, childQueues);
    }
    dumpGenerator.writeEndArray();
    dumpGenerator.writeEndObject();
  }
}
 
Example 17
Source File: NameNodeLoader.java    From NNAnalytics with Apache License 2.0 4 votes vote down vote up
private void writeStringFieldIfNotNull(JsonGenerator json, String key, String value)
    throws IOException {
  if (value != null) {
    json.writeStringField(key, value);
  }
}
 
Example 18
Source File: NameNodeLoader.java    From NNAnalytics with Apache License 2.0 4 votes vote down vote up
/**
 * Sends the loading status as JSON to the parameter HTTP response. Copied from NameNode.
 *
 * @param resp the HTTP response
 * @throws IOException error in fetching loading status
 */
public void sendLoadingStatus(HttpServletResponse resp) throws IOException {
  String count = "count";
  String elapsedTime = "elapsedTime";
  String file = "file";
  String name = "name";
  String desc = "desc";
  String percentComplete = "percentComplete";
  String phases = "phases";
  String size = "size";
  String status = "status";
  String steps = "steps";
  String total = "total";

  StartupProgressView view = NameNode.getStartupProgress().createView();
  JsonGenerator json =
      new JsonFactory().createJsonGenerator(resp.getWriter()).useDefaultPrettyPrinter();

  try {
    json.writeStartObject();
    json.writeNumberField(elapsedTime, view.getElapsedTime());
    json.writeNumberField(percentComplete, view.getPercentComplete());
    json.writeArrayFieldStart(phases);

    for (Phase phase : view.getPhases()) {
      json.writeStartObject();
      json.writeStringField(name, phase.getName());
      json.writeStringField(desc, phase.getDescription());
      json.writeStringField(status, view.getStatus(phase).toString());
      json.writeNumberField(percentComplete, view.getPercentComplete(phase));
      json.writeNumberField(elapsedTime, view.getElapsedTime(phase));
      writeStringFieldIfNotNull(json, file, view.getFile(phase));
      writeNumberFieldIfDefined(json, size, view.getSize(phase));
      json.writeArrayFieldStart(steps);

      for (Step step : view.getSteps(phase)) {
        json.writeStartObject();
        StepType stepType = step.getType();
        if (stepType != null) {
          json.writeStringField(name, stepType.getName());
          json.writeStringField(desc, stepType.getDescription());
        }
        json.writeNumberField(count, view.getCount(phase, step));
        writeStringFieldIfNotNull(json, file, step.getFile());
        writeNumberFieldIfDefined(json, size, step.getSize());
        json.writeNumberField(total, view.getTotal(phase, step));
        json.writeNumberField(percentComplete, view.getPercentComplete(phase, step));
        json.writeNumberField(elapsedTime, view.getElapsedTime(phase, step));
        json.writeEndObject();
      }

      json.writeEndArray();
      json.writeEndObject();
    }

    json.writeEndArray();
    json.writeEndObject();
  } finally {
    IOUtils.closeStream(json);
  }
}
 
Example 19
Source File: StartupProgressServlet.java    From hadoop with Apache License 2.0 3 votes vote down vote up
/**
 * Writes a JSON string field only if the value is non-null.
 * 
 * @param json JsonGenerator to receive output
 * @param key String key to put
 * @param value String value to put
 * @throws IOException if there is an I/O error
 */
private static void writeStringFieldIfNotNull(JsonGenerator json, String key,
    String value) throws IOException {
  if (value != null) {
    json.writeStringField(key, value);
  }
}
 
Example 20
Source File: StartupProgressServlet.java    From big-c with Apache License 2.0 3 votes vote down vote up
/**
 * Writes a JSON string field only if the value is non-null.
 * 
 * @param json JsonGenerator to receive output
 * @param key String key to put
 * @param value String value to put
 * @throws IOException if there is an I/O error
 */
private static void writeStringFieldIfNotNull(JsonGenerator json, String key,
    String value) throws IOException {
  if (value != null) {
    json.writeStringField(key, value);
  }
}