Пример #1
0
  private void writeDebug() throws JsonGenerationException, IOException {
    if (debugInfo != null) {
      writer.writeFieldName("debug");
      writer.writeStartObject();

      writer.writeStringField("script-version", debugInfo.getScriptVersion());

      List<LoadDescription> descriptions = debugInfo.getDescriptions();
      List<QueryData> queries = debugInfo.getQueries();
      for (int index = 0; index < descriptions.size(); index++) {
        writer.writeFieldName("query_" + index);
        writer.writeStartObject();

        LoadDescription description = descriptions.get(index);
        OrcsSession session = description.getSession();
        if (session != null) {
          writer.writeStringField("session", session.getGuid());
        }
        Options options = description.getOptions();
        for (String key : new TreeSet<String>(options.getKeys())) {
          writer.writeStringField(key, options.get(key).replaceAll("\\s+", " "));
        }
        writeQuery(queries.get(index));
        writer.writeEndObject();
      }
      writer.writeEndObject();
    }
  }
Пример #2
0
  private static void writeTrace(
      final Trace trace, final int traceId, final JsonGenerator generator) throws IOException {
    generator.writeStartObject();
    generator.writeNumberField(JsonTraceCodec.TRACE_ID, traceId);
    generator.writeStringField(JsonTraceCodec.TRACE_NAME, trace.getName());
    generator.writeStringField(JsonTraceCodec.TRACE_RESULT_TYPE, trace.getResultType().toString());
    generator.writeBooleanField(JsonTraceCodec.TRACE_HIDDEN, trace.getHidden());
    generator.writeBooleanField(JsonTraceCodec.TRACE_SYSTEM_HIDDEN, trace.getSystemHidden());

    if (trace.getValue() != null) {
      generator.writeStringField(JsonTraceCodec.TRACE_VALUE, trace.getValue());
    }

    if (trace.getStartNanos() != null) {
      generator.writeNumberField(JsonTraceCodec.TRACE_START_NANOS, trace.getStartNanos());
    }

    if (trace.getEndNanos() != null) {
      generator.writeNumberField(JsonTraceCodec.TRACE_END_NANOS, trace.getEndNanos());
    }

    if (trace.getAttributes() != null && trace.getAttributes().size() > 0) {
      generator.writeArrayFieldStart(JsonTraceCodec.TRACE_ATTRIBUTES);
      for (Map.Entry<String, String> attribute : trace.getAttributes().entrySet()) {
        generator.writeStartObject();
        generator.writeStringField(JsonTraceCodec.TRACE_ATTRIBUTE_KEY, attribute.getKey());
        generator.writeStringField(JsonTraceCodec.TRACE_ATTRIBUTE_VALUE, attribute.getValue());
        generator.writeEndObject();
      }
      generator.writeEndArray();
    }

    generator.writeEndObject();
  }
Пример #3
0
  /**
   * This method writes the state of the NodeManager to disk
   *
   * @param jsonGenerator The instance of JsonGenerator, which will be used to write JSON to disk
   * @throws IOException
   */
  public void write(JsonGenerator jsonGenerator) throws IOException {
    jsonGenerator.writeStartObject();

    // nameToNode begins
    jsonGenerator.writeFieldName("nameToNode");
    jsonGenerator.writeStartObject();
    for (Map.Entry<String, ClusterNode> entry : nameToNode.entrySet()) {
      jsonGenerator.writeFieldName(entry.getKey());
      entry.getValue().write(jsonGenerator);
    }
    jsonGenerator.writeEndObject();
    // nameToNode ends

    // hostsToSessions begins
    // We create a new Map of type <ClusterNode.name, Set<SessionIds>>.
    // The original hostsToSessions map has the ClusterNode as its key, and
    // we do not need to persist the entire ClusterNode again, since we have
    // already done that with nameToNode.
    Map<String, Set<String>> hostsToSessionsMap = new HashMap<String, Set<String>>();
    for (Map.Entry<ClusterNode, Set<String>> entry : hostsToSessions.entrySet()) {
      hostsToSessionsMap.put(entry.getKey().getName(), entry.getValue());
    }
    jsonGenerator.writeObjectField("hostsToSessions", hostsToSessionsMap);
    // hostsToSessions ends

    jsonGenerator.writeObjectField("nameToApps", nameToApps);

    // faultManager is not required

    // We can rebuild the loadManager
    jsonGenerator.writeEndObject();
  }
    @Override
    public void serialize(
        SimpleEvaluationObject value, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {

      synchronized (value) {
        String id = getUpdateManager().register(value);
        jgen.writeStartObject();
        jgen.writeObjectField("type", "SimpleEvaluationObject");
        jgen.writeStringField("update_id", id);
        jgen.writeStringField("expression", value.getExpression());
        jgen.writeObjectField("status", value.getStatus());
        if (value.getMessage() != null) jgen.writeStringField("message", value.getMessage());
        if (value.getProgressBar() > 0)
          jgen.writeNumberField("progressBar", value.getProgressBar());
        if (value.getPayloadChanged()) {
          EvaluationResult o = value.getPayload();
          if (o != null && o.getValue() != null) {
            jgen.writeFieldName("payload");
            if (!getObjectSerializer().writeObject(o, jgen, true)) jgen.writeObject(o.toString());
          } else if (value.getJsonRes() != null) {
            jgen.writeFieldName("payload");
            if (ControlCharacterUtils.containsControlCharacters(value.getJsonRes())) {
              jgen.writeRawValue(ControlCharacterUtils.escapeControlCharacters(value.getJsonRes()));
            } else {
              jgen.writeRawValue(value.getJsonRes());
            }
          }
        }
        if (value.getJsonRes() != null
            && value.getPayload() != null
            && value.getPayload().getValue() != null) {
          logger.trace("adding raw json data: '" + value.getJsonRes() + "'");
          jgen.writeFieldName("jsonres");
          if (ControlCharacterUtils.containsControlCharacters(value.getJsonRes())) {
            jgen.writeRawValue(ControlCharacterUtils.escapeControlCharacters(value.getJsonRes()));
          } else {
            jgen.writeRawValue(value.getJsonRes());
          }
        }
        jgen.writeArrayFieldStart("outputdata");
        for (Object o : value.getOutputdata()) {
          if (o instanceof EvaluationStdOutput) {
            jgen.writeStartObject();
            jgen.writeStringField("type", "out");
            jgen.writeStringField("value", ((EvaluationStdOutput) o).payload);
            jgen.writeEndObject();
          } else if (o instanceof EvaluationStdError) {
            jgen.writeStartObject();
            jgen.writeStringField("type", "err");
            jgen.writeStringField("value", ((EvaluationStdError) o).payload);
            jgen.writeEndObject();
          }
        }
        jgen.writeEndArray();
        jgen.writeEndObject();
      }
    }
Пример #5
0
  public void toJson(JsonGenerator gen) throws IOException {

    gen.writeStartObject();

    if (type != null) {
      gen.writeStringField("type", type.getName());
    }

    if (tableName != null) {
      gen.writeStringField("tableName", tableName);
    }

    if (versionUpdated != -1) {
      gen.writeNumberField("versionUpdated", versionUpdated);
    }

    if (versionCreated != -1) {
      gen.writeNumberField("versionCreated", versionCreated);
    }

    if (recordTypeChanged) {
      gen.writeBooleanField("recordTypeChanged", true);
    }

    if (updatedFields != null && updatedFields.size() > 0) {
      gen.writeArrayFieldStart("updatedFields");
      for (SchemaId updatedField : updatedFields) {
        gen.writeBinary(updatedField.getBytes());
      }
      gen.writeEndArray();
    }

    if (vtagsToIndex != null && vtagsToIndex.size() > 0) {
      gen.writeArrayFieldStart("vtagsToIndex");
      for (SchemaId vtag : vtagsToIndex) {
        gen.writeBinary(vtag.getBytes());
      }
      gen.writeEndArray();
    }

    if (attributes != null && attributes.size() > 0) {
      gen.writeObjectFieldStart("attributes");
      for (String key : attributes.keySet()) {
        gen.writeStringField(key, attributes.get(key));
      }
      gen.writeEndObject();
    }

    if (indexRecordFilterData != null) {
      gen.writeFieldName("indexFilterData");
      indexRecordFilterData.toJson(gen);
    }

    gen.writeEndObject();
    gen.flush();
  }
Пример #6
0
  void toJson(JsonGenerator gen) throws IOException {
    gen.writeStartObject();
    gen.writeArrayFieldStart("sourceSchemas");
    for (Schema schema : schemas) {
      schema.toJson(gen);
    }
    gen.writeEndArray();
    gen.writeObjectFieldStart("fieldAliases");
    for (Map.Entry<String, Map<String, String>> entry : schemaFieldAliases.entrySet()) {
      String schemaName = entry.getKey();
      Map<String, String> aliases = entry.getValue();
      gen.writeObjectField(schemaName, aliases);
    }
    gen.writeEndObject();

    gen.writeArrayFieldStart("groupByFields");
    for (String field : groupByFields) {
      gen.writeString(field);
    }
    gen.writeEndArray();

    if (customPartitionFields != null && !customPartitionFields.isEmpty()) {
      gen.writeArrayFieldStart("customPartitionFields");
      for (String field : customPartitionFields) {
        gen.writeString(field);
      }
      gen.writeEndArray();
    }

    if (rollupFrom != null) {
      gen.writeFieldName("rollupFrom");
      gen.writeString(rollupFrom);
    }

    gen.writeFieldName("commonOrderBy");
    commonCriteria.toJson(gen);

    gen.writeStringField("schemasOrder", schemasOrder.toString());

    // TODO this code should write a map with sourceName
    if (specificCriterias == null || specificCriterias.isEmpty()) {
      initSecondaryCriteriasWithNull();
    }
    gen.writeArrayFieldStart("specificOrderBys");
    for (Criteria c : specificCriterias) {
      if (c == null) {
        gen.writeNull();
      } else {
        c.toJson(gen);
      }
    }
    gen.writeEndArray();
    gen.writeEndObject();
  }
  public void jacksonTest() throws Exception {
    JsonFactory factory = new JsonFactory();
    StringWriter writer = new StringWriter();
    JsonGenerator generator = factory.createJsonGenerator(writer);
    generator.writeStartObject();
    generator.writeFieldName("bool");
    generator.writeBoolean(true);
    generator.writeFieldName("firstName");
    generator.writeString("john");
    generator.writeFieldName("age");
    generator.writeNumber(1);
    generator.writeFieldName("gg");
    generator.writeStartObject();
    generator.writeFieldName("firstName");
    generator.writeString("john");
    generator.writeEndObject();

    generator.writeEndObject();
    generator.close();
    String generated = writer.toString();
    System.out.print(generated);

    JsonParser parser = factory.createJsonParser(generated);
    assertTrue(parser.nextToken() == JsonToken.START_OBJECT);
    parser.nextToken();

    assertEquals("bool", parser.getCurrentName());
    assertTrue(parser.nextToken() == JsonToken.VALUE_TRUE);
    parser.nextToken();

    assertEquals("firstName", parser.getCurrentName());
    parser.nextToken();
    assertEquals("john", parser.getText());
    parser.nextToken();

    assertEquals("age", parser.getCurrentName());
    parser.nextToken();
    assertTrue(1 == parser.getIntValue());
    parser.nextToken();

    assertEquals("gg", parser.getCurrentName());
    assertTrue(parser.nextToken() == JsonToken.START_OBJECT);
    parser.nextToken();
    assertEquals("firstName", parser.getCurrentName());
    parser.nextToken();
    assertEquals("john", parser.getText());
    assertTrue(parser.nextToken() == JsonToken.END_OBJECT);

    assertTrue(parser.nextToken() == JsonToken.END_OBJECT);

    parser.close();
  }
Пример #8
0
  @Override
  public void serialize(HateoasLinkList value, JsonGenerator jgen, SerializerProvider provider)
      throws IOException {
    jgen.writeStartObject();

    for (HateoasLink link : value) {
      jgen.writeFieldName(link.rel);
      jgen.writeStartObject();
      jgen.writeFieldName("href");
      jgen.writeString(link.href.toExternalForm());
      jgen.writeEndObject();
    }
    jgen.writeEndObject();
  }
Пример #9
0
 @Override
 public void serialize(
     final JobFailure jobFailure, final JsonGenerator jgen, final SerializerProvider provider)
     throws IOException, JsonProcessingException {
   jgen.writeStartObject();
   jgen.writeStringField("worker", jobFailure.getWorker());
   jgen.writeStringField("queue", jobFailure.getQueue());
   jgen.writeFieldName("payload");
   ObjectMapperFactory.get().writeValue(jgen, jobFailure.getPayload());
   jgen.writeStringField(
       "exception",
       (jobFailure.getException() == null)
           ? null
           : jobFailure.getException().getClass().getName());
   jgen.writeStringField(
       "error",
       (jobFailure.getException() == null) ? null : jobFailure.getException().getMessage());
   jgen.writeFieldName("backtrace");
   ObjectMapperFactory.get()
       .writeValue(
           jgen,
           (jobFailure.getException() == null)
               ? null
               : JesqueUtils.createBacktrace(jobFailure.getException()));
   jgen.writeFieldName("failed_at");
   ObjectMapperFactory.get().writeValue(jgen, jobFailure.getFailedAt());
   jgen.writeFieldName("retried_at");
   ObjectMapperFactory.get().writeValue(jgen, jobFailure.getRetriedAt());
   jgen.writeEndObject();
 }
Пример #10
0
  @RequestMapping(value = "/data/dateranges", method = RequestMethod.GET)
  public ResponseEntity<String> getDateRange(
      @RequestParam(value = PARAM_COLLECTION, required = true) String collection)
      throws IOException {

    CollectionSchemaInfo info = collectionsConfig.getSchema(collection);
    ReportData data = collectionsConfig.getReportData(collection);
    StringWriter writer = new StringWriter();

    JsonGenerator g = searchService.writeSearchResponseStart(writer, null);
    if (data != null) {
      for (String dateField : data.getDateFields()) {
        List<Date> dates = searchService.getSolrFieldDateRange(collection, dateField, info);
        if (dates == null || dates.size() != 2) {
          continue;
        }

        g.writeObjectFieldStart(dateField);
        g.writeStringField(DATE_RANGE_START_KEY, dates.get(0).toString());
        g.writeStringField(DATE_RANGE_END_KEY, dates.get(1).toString());
        g.writeEndObject();
      }
    }

    searchService.writeSearchResponseEnd(g);

    HttpHeaders httpHeaders = new HttpHeaders();
    httpHeaders.put(CONTENT_TYPE_HEADER, singletonList(CONTENT_TYPE_VALUE));
    return new ResponseEntity<String>(writer.toString(), httpHeaders, OK);
  }
  /**
   * POST /api/v1/janitor will try a add a new event with the information in the url context.
   *
   * @param content the Json content passed to the http POST request
   * @return the response
   * @throws IOException
   */
  @POST
  public Response addEvent(String content) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    LOGGER.info(String.format("JSON content: '%s'", content));
    JsonNode input = mapper.readTree(content);

    String eventType = getStringField(input, "eventType");
    String resourceId = getStringField(input, "resourceId");

    Response.Status responseStatus;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JsonGenerator gen = JSON_FACTORY.createJsonGenerator(baos, JsonEncoding.UTF8);
    gen.writeStartObject();
    gen.writeStringField("eventType", eventType);
    gen.writeStringField("resourceId", resourceId);

    if (StringUtils.isEmpty(eventType) || StringUtils.isEmpty(resourceId)) {
      responseStatus = Response.Status.BAD_REQUEST;
      gen.writeStringField("message", "eventType and resourceId parameters are all required");
    } else {
      if (eventType.equals("OPTIN")) {
        responseStatus = optInResource(resourceId, true, gen);
      } else if (eventType.equals("OPTOUT")) {
        responseStatus = optInResource(resourceId, false, gen);
      } else {
        responseStatus = Response.Status.BAD_REQUEST;
        gen.writeStringField("message", String.format("Unrecognized event type: %s", eventType));
      }
    }
    gen.writeEndObject();
    gen.close();
    LOGGER.info("entity content is '{}'", baos.toString("UTF-8"));
    return Response.status(responseStatus).entity(baos.toString("UTF-8")).build();
  }
Пример #12
0
 private void writeCollect(SelectSet selectSet) throws IOException {
   writer.writeFieldName("collect");
   writer.writeStartObject();
   writer.writeNumberField("limit", selectSet.getLimit());
   writeDynamicData(selectSet.getData());
   writer.writeEndObject();
 }
Пример #13
0
 private void writeDynamicData(DynamicData data) throws JsonGenerationException, IOException {
   if (data != null) {
     if (data instanceof DynamicObject) {
       DynamicObject obj = (DynamicObject) data;
       if (obj.hasChildren()) {
         writer.writeFieldName(data.getName());
         writer.writeStartObject();
         for (DynamicData child : obj.getChildren()) {
           writeDynamicData(child);
         }
         writer.writeEndObject();
       }
     } else {
       StringBuilder value = new StringBuilder();
       if (data.isHidden()) {
         value.append("hidden->");
       }
       value.append(data.getGuid());
       if (data.isPrimaryKey()) {
         value.append("*");
       }
       writer.writeStringField(data.getName(), value.toString());
     }
   }
 }
 @SuppressWarnings({"unchecked"})
 @Override
 public void serialize(
     final Object value, final JsonGenerator jgen, final SerializerProvider provider)
     throws IOException, JsonGenerationException {
   if (null == value) {
     provider.defaultSerializeNull(jgen);
   } else {
     Class<?> type = value.getClass();
     if (ClassUtils.isAssignable(type, Collection.class)) {
       jgen.writeStartArray();
       for (Object o : (Collection) value) {
         write(o, jgen, provider);
       }
       jgen.writeEndArray();
     } else if (ClassUtils.isAssignable(type, Map.class)) {
       jgen.writeStartObject();
       for (Map.Entry<String, Object> entry : ((Map<String, Object>) value).entrySet()) {
         jgen.writeFieldName(entry.getKey());
         write(entry.getValue(), jgen, provider);
       }
       jgen.writeEndObject();
     } else {
       write(value, jgen, provider);
     }
   }
 }
Пример #15
0
 @Override
 public void serialize(
     final PingMessage ping, final JsonGenerator jgen, final SerializerProvider provider)
     throws IOException, JsonProcessingException {
   jgen.writeStartObject();
   jgen.writeEndObject();
 }
Пример #16
0
    public void toJson(JsonGenerator gen) throws IOException {
      gen.writeStartObject();

      gen.writeBooleanField("old", oldRecordExists);
      gen.writeBooleanField("new", newRecordExists);
      gen.writeBooleanField("includeSubscriptions", includeSubscriptions);

      if (newRecordType != null) {
        gen.writeBinaryField("newRecordType", newRecordType.getBytes());
      }

      if (oldRecordType != null) {
        gen.writeBinaryField("oldRecordType", oldRecordType.getBytes());
      }

      if (fieldChanges != null) {
        gen.writeArrayFieldStart("fields");

        for (FieldChange fieldChange : fieldChanges) {
          fieldChange.toJson(gen);
        }

        gen.writeEndArray();
      }

      if (indexSubscriptionIds != null) {
        gen.writeArrayFieldStart("subscriptions");
        for (String subscriptionId : indexSubscriptionIds) {
          gen.writeString(subscriptionId);
        }
        gen.writeEndArray();
      }

      gen.writeEndObject();
    }
Пример #17
0
 protected void writeComplexProperty(JsonGenerator jg, Property prop) throws IOException {
   jg.writeStartObject();
   for (Property p : prop.getChildren()) {
     jg.writeFieldName(p.getName());
     writeProperty(jg, p);
   }
   jg.writeEndObject();
 }
Пример #18
0
 public static void serialize(Trace root, JsonGenerator generator) throws IOException {
   // Build a map of traces to their unique ids for serialization
   final Map<Trace, Integer> traceIds = buildTraceIdMap(root);
   generator.writeStartObject();
   writeTraces(traceIds, generator);
   writeRelationships(traceIds, generator);
   generator.writeEndObject();
 }
Пример #19
0
 @Override
 public void serialize(
     final AckMessage ack, final JsonGenerator jgen, final SerializerProvider provider)
     throws IOException, JsonProcessingException {
   jgen.writeStartObject();
   jgen.writeFieldName(AckMessage.MESSSAGE_TYPE_FIELD);
   jgen.writeString(ack.getMessageType().toString().toLowerCase());
   jgen.writeArrayFieldStart(AckMessage.UPDATES_FIELD);
   for (Update update : ack.getUpdates()) {
     jgen.writeStartObject();
     jgen.writeFieldName("channelID");
     jgen.writeString(update.getChannelId());
     jgen.writeFieldName(AckMessage.VERSION_FIELD);
     jgen.writeNumber(update.getVersion());
     jgen.writeEndObject();
   }
   jgen.writeEndArray();
   jgen.writeEndObject();
 }
Пример #20
0
  public void testWriteServicePropertiesWithKey() throws Exception {
    generator.writeStartObject();
    OsgiRepresentationHelper.writeServiceProperties(
        generator, "props", serviceReferenceWithProperties(mapBuilder().put("matrix", "4x4")));
    generator.writeEndObject();

    JSONObject actual = outputAsObject();
    assertTrue("Missing key", actual.has("props"));
    assertTrue("Missing properties", actual.getJSONObject("props").has("matrix"));
  }
Пример #21
0
 @Override
 public void serialize(JsonGenerator jg, SerializerProvider provider)
     throws IOException, JsonProcessingException {
   jg.writeStartObject();
   jg.writeStringField(COL_TYPE, getType());
   jg.writeStringField(COL_INFO, getInfo());
   if (isPrimary()) jg.writeBooleanField(COL_PRIMARY, true);
   if (isBinding()) jg.writeBooleanField(COL_BINDING, true);
   if (StringUtils.isNotEmpty(getLabel())) jg.writeStringField(COL_LABEL, getLabel());
   jg.writeEndObject();
 }
Пример #22
0
 private void write(JsonGenerator jg, TwitterEntry entry) throws IOException {
   jg.writeStartObject();
   // can either do "jg.writeFieldName(...) + jg.writeNumber()", or this:
   jg.writeNumberField("id", entry.getId());
   jg.writeStringField("text", entry.getText());
   jg.writeNumberField("fromUserId", entry.getFromUserId());
   jg.writeNumberField("toUserId", entry.getToUserId());
   jg.writeStringField("langugeCode", entry.getLanguageCode());
   jg.writeEndObject();
   jg.close();
 }
Пример #23
0
 @Override
 public void serialize(
     final RegisterMessage register, final JsonGenerator jgen, final SerializerProvider provider)
     throws IOException, JsonProcessingException {
   jgen.writeStartObject();
   jgen.writeFieldName(RegisterMessage.MESSSAGE_TYPE_FIELD);
   jgen.writeString(register.getMessageType().toString().toLowerCase());
   jgen.writeFieldName(RegisterMessage.CHANNEL_ID_FIELD);
   jgen.writeString(register.getChannelId());
   jgen.writeEndObject();
 }
 public void writeJson(JsonGenerator g) throws JsonGenerationException, IOException {
   g.writeStartObject();
   g.writeBooleanField(SUCCESS, success);
   g.writeStringField(MESSAGE, message);
   g.writeArrayFieldStart(DATA);
   if (null != list && !list.isEmpty()) {
     for (T model : list) {
       // write model data
       g.writeStartObject();
       g.writeStringField("key", model.getKey());
       g.writeStringField("label", model.getLabel());
       g.writeEndObject();
     }
   }
   g.writeEndArray();
   // write model data end
   g.writeEndObject();
   g.flush();
   g.close();
 }
Пример #25
0
 public static void writeSignal(
     String name, int bottom, int top, int integer, int fractional, JsonGenerator g)
     throws JsonGenerationException, IOException {
   g.writeStartObject();
   g.writeStringField("name", name);
   g.writeNumberField("bottom", bottom);
   g.writeNumberField("top", top);
   g.writeNumberField("integer", integer);
   g.writeNumberField("fractional", fractional);
   g.writeEndObject();
 }
 /**
  * Gets the janitor status (e.g. to support an AWS ELB Healthcheck on an instance running
  * JanitorMonkey). Creates GET /api/v1/janitor api which responds 200 OK if JanitorMonkey is
  * running.
  *
  * @param uriInfo the uri info
  * @return the chaos events json response
  * @throws IOException Signals that an I/O exception has occurred.
  */
 @GET
 public Response getJanitorStatus(@Context UriInfo uriInfo) throws IOException {
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   JsonGenerator gen = JSON_FACTORY.createJsonGenerator(baos, JsonEncoding.UTF8);
   gen.writeStartArray();
   gen.writeStartObject();
   gen.writeStringField("JanitorMonkeyStatus", "OnLikeDonkeyKong");
   gen.writeEndObject();
   gen.writeEndArray();
   gen.close();
   return Response.status(Response.Status.OK).entity(baos.toString("UTF-8")).build();
 }
  @Override
  public void serialize(T value, JsonGenerator jgen, SerializerProvider provider)
      throws IOException, JsonProcessingException {

    synchronized (value) {
      jgen.writeStartObject();
      jgen.writeObjectField("type", value.getClass().getSimpleName());
      jgen.writeObjectField("borderDisplayed", value.isBorderDisplayed());
      serialize(value, jgen);
      jgen.writeEndObject();
    }
  }
Пример #28
0
 @Override
 public void serialize(
     final NotificationMessage notification,
     final JsonGenerator jgen,
     final SerializerProvider provider)
     throws IOException, JsonProcessingException {
   jgen.writeStartObject();
   jgen.writeFieldName(NotificationMessage.MESSSAGE_TYPE_FIELD);
   jgen.writeString(notification.getMessageType().toString().toLowerCase());
   jgen.writeArrayFieldStart(NotificationMessage.UPDATES_FIELD);
   for (Update update : notification.getUpdates()) {
     jgen.writeStartObject();
     jgen.writeFieldName(RegisterMessage.CHANNEL_ID_FIELD);
     jgen.writeString(update.getChannelId());
     jgen.writeFieldName(NotificationMessage.VERSION_FIELD);
     jgen.writeNumber(update.getVersion());
     jgen.writeEndObject();
   }
   jgen.writeEndArray();
   jgen.writeEndObject();
 }
Пример #29
0
  @Override
  public void writeTo(
      Object object,
      Class<?> type,
      Type genericType,
      Annotation[] annotations,
      MediaType mediaType,
      MultivaluedMap<String, Object> httpHeaders,
      OutputStream entityStream)
      throws IOException, WebApplicationException {
    JsonGenerator writer = null;
    if (type.isAssignableFrom(ArtifactReadable.class)) {
      ArtifactReadable artifact = (ArtifactReadable) object;
      try {
        writer = jsonFactory.createJsonGenerator(entityStream);
        //         writer.setPrettyPrinter(new DefaultPr)
        writer.writeStartObject();
        writer.writeNumberField("uuid", artifact.getLocalId());
        if (matches(IdentityView.class, annotations)) {
          writer.writeStringField("Name", artifact.getName());
        } else {
          AttributeTypes attributeTypes = getAttibuteTypes();
          Collection<? extends IAttributeType> attrTypes = attributeTypes.getAll();
          ResultSet<? extends AttributeReadable<Object>> attributes = artifact.getAttributes();
          if (!attributes.isEmpty()) {
            for (IAttributeType attrType : attrTypes) {
              if (artifact.isAttributeTypeValid(attrType)) {
                List<Object> attributeValues = artifact.getAttributeValues(attrType);
                if (!attributeValues.isEmpty()) {

                  if (attributeValues.size() > 1) {
                    writer.writeArrayFieldStart(attrType.getName());
                    for (Object value : attributeValues) {
                      writer.writeObject(value);
                    }
                    writer.writeEndArray();
                  } else if (attributeValues.size() == 1) {
                    Object value = attributeValues.iterator().next();
                    writer.writeObjectField(attrType.getName(), value);
                  }
                }
              }
            }
          }
        }
        writer.writeEndObject();
      } finally {
        if (writer != null) {
          writer.flush();
        }
      }
    }
  }
Пример #30
-1
  private void serialize(Query query, OutputStream outputStream) throws IOException {
    JsonGenerator g = jsonFactory.createJsonGenerator(outputStream, JsonEncoding.UTF8);
    g.useDefaultPrettyPrinter();
    g.writeStartObject();
    g.writeStringField("name", "jmxtrans");
    g.writeStringField("type", "metric");
    g.writeStringField("handler", sensuhandler);

    StringBuffer jsonoutput = new StringBuffer();
    List<String> typeNames = getTypeNames();
    for (Result result : query.getResults()) {
      Map<String, Object> resultValues = result.getValues();
      if (resultValues != null) {
        for (Map.Entry<String, Object> values : resultValues.entrySet()) {
          if (NumberUtils.isNumeric(values.getValue())) {
            Object value = values.getValue();
            jsonoutput
                .append(JmxUtils.getKeyString(query, result, values, typeNames, null))
                .append(" ")
                .append(value)
                .append(" ")
                .append(TimeUnit.SECONDS.convert(result.getEpoch(), TimeUnit.MILLISECONDS))
                .append(System.getProperty("line.separator"));
          }
        }
      }
    }
    g.writeStringField("output", jsonoutput.toString());
    g.writeEndObject();
    g.flush();
    g.close();
  }