Пример #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
 @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();
 }
Пример #3
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();
  }
  @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();
  }
 private Response.Status optInResource(String resourceId, boolean optIn, JsonGenerator gen)
     throws IOException {
   String op = optIn ? "in" : "out";
   LOGGER.info(String.format("Opt %s resource %s for Janitor Monkey.", op, resourceId));
   Response.Status responseStatus;
   Event evt;
   if (optIn) {
     evt = monkey.optInResource(resourceId);
   } else {
     evt = monkey.optOutResource(resourceId);
   }
   if (evt != null) {
     responseStatus = Response.Status.OK;
     gen.writeStringField("monkeyType", evt.monkeyType().name());
     gen.writeStringField("eventId", evt.id());
     gen.writeNumberField("eventTime", evt.eventTime().getTime());
     gen.writeStringField("region", evt.region());
     for (Map.Entry<String, String> pair : evt.fields().entrySet()) {
       gen.writeStringField(pair.getKey(), pair.getValue());
     }
   } else {
     responseStatus = Response.Status.INTERNAL_SERVER_ERROR;
     gen.writeStringField(
         "message", String.format("Failed to opt %s resource %s", op, resourceId));
   }
   LOGGER.info(String.format("Opt %s operation completed.", op));
   return responseStatus;
 }
Пример #7
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();
  }
Пример #8
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();
 }
Пример #9
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();
 }
 @Override
 public void serialize(Producto producto, JsonGenerator jsonGenerator, SerializerProvider sp)
     throws IOException, org.codehaus.jackson.JsonProcessingException {
   jsonGenerator.writeStartObject();
   jsonGenerator.writeNumberField("idproducto", producto.getIdproducto());
   jsonGenerator.writeStringField("nombre", producto.getNombreProducto());
   if (producto.getImagen() != null) {
     jsonGenerator.writeBinaryField("imagen", producto.getImagen());
   }
   jsonGenerator.writeStringField(
       "categoria", producto.getCategoriaIdCategoria().getNombreCategoria());
   jsonGenerator.writeEndObject();
 }
 @Override
 public void serialize(RichPushMessage message, JsonGenerator jgen, SerializerProvider provider)
     throws IOException {
   jgen.writeStartObject();
   jgen.writeStringField("title", message.getTitle());
   jgen.writeStringField("body", message.getBody());
   jgen.writeStringField("content_type", message.getContentType());
   jgen.writeStringField("content_encoding", message.getContentEncoding());
   if (message.getExpiry().isPresent()) {
     jgen.writeObjectField("expiry", message.getExpiry().get());
   }
   if (message.getExtra().isPresent()) {
     jgen.writeObjectField("extra", message.getExtra().get());
   }
   jgen.writeEndObject();
 }
Пример #12
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());
     }
   }
 }
Пример #13
0
 public void testWriteDateWithDate() throws Exception {
   generator.writeStringField("some_date", "2010-09-06");
   replayMocks();
   nullSafeWriteDateField(
       generator, "some_date", DateTools.createDate(2010, Calendar.SEPTEMBER, 6));
   verifyMocks();
 }
Пример #14
0
 @Override
 public void serializeAsField(Object bean, JsonGenerator jgen, SerializerProvider prov)
     throws Exception {
   // We know the type (although interface can't expose it)
   String value = ((Bean) bean).name;
   // Convert nulls to "", otherwise upper case
   value = (value == null) ? "" : value.toUpperCase();
   jgen.writeStringField("name", value);
 }
    @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();
      }
    }
Пример #16
0
 protected void writeExtendedInfo(JsonGenerator jg, String key, Serializable value)
     throws IOException {
   Class<?> clazz = value.getClass();
   if (Long.class.isAssignableFrom(clazz)) {
     jg.writeNumberField(key, (Long) value);
   } else if (Integer.class.isAssignableFrom(clazz)) {
     jg.writeNumberField(key, (Integer) value);
   } else if (Double.class.isAssignableFrom(clazz)) {
     jg.writeNumberField(key, (Double) value);
   } else if (Date.class.isAssignableFrom(clazz)) {
     jg.writeStringField(key, ISODateTimeFormat.dateTime().print(new DateTime(value)));
   } else if (String.class.isAssignableFrom(clazz)) {
     jg.writeStringField(key, (String) value);
   } else if (Boolean.class.isAssignableFrom(clazz)) {
     jg.writeBooleanField(key, (Boolean) value);
   } else {
     jg.writeStringField(key, value.toString());
   }
 }
Пример #17
0
 @Override
 protected void writeEntityBody(JsonGenerator jg, LogEntry logEntry) throws IOException {
   jg.writeStringField("entity-type", "logEntry");
   jg.writeStringField("category", logEntry.getCategory());
   jg.writeStringField("principalName", logEntry.getPrincipalName());
   jg.writeStringField("comment", logEntry.getComment());
   jg.writeStringField("docLifeCycle", logEntry.getDocLifeCycle());
   jg.writeStringField("docPath", logEntry.getDocPath());
   jg.writeStringField("docType", logEntry.getDocType());
   jg.writeStringField("docUUID", logEntry.getDocUUID());
   jg.writeStringField("eventId", logEntry.getEventId());
   jg.writeStringField("repositoryId", logEntry.getRepositoryId());
   jg.writeStringField(
       "eventDate", ISODateTimeFormat.dateTime().print(new DateTime(logEntry.getEventDate())));
   jg.writeNumberField("id", logEntry.getId());
   jg.writeStringField(
       "logDate", ISODateTimeFormat.dateTime().print(new DateTime(logEntry.getLogDate())));
   writeExtendedInfos(jg, logEntry);
 }
Пример #18
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();
  }
Пример #19
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();
 }
 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();
 }
Пример #21
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();
        }
      }
    }
  }
 /**
  * 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();
 }
  public void dump(OutputStream os, BaseResponse res) {
    D2ResponseMessage d2Response = (D2ResponseMessage) res;

    try {
      OutputStreamWriter writer;

      writer = new OutputStreamWriter(os, charset);

      JsonGenerator generator = objectMapper.getJsonFactory().createJsonGenerator(writer);

      if (pretty) {
        JsonPrettyPrinter pp = new JsonPrettyPrinter();
        generator.setPrettyPrinter(pp);
      }

      //
      generator.writeStartArray();
      {
        List<D2ResponseMessageDoc> list = d2Response.getDocs();

        for (D2ResponseMessageDoc doc : list) {
          generator.writeStartObject();
          {
            generator.writeStringField("md5Lite", Md5Lite.toString(doc.getMd5Lite()));
            generator.writeNumberField("weight", doc.getWeight());

            generator.writeNumberField("indentValue", doc.getIndentValue());
            generator.writeNumberField("indentCount", doc.getIndentCount());
            generator.writeNumberField("indentPage", doc.getIndentPage());

            generator.writeNumberField("po", doc.getPo());
            generator.writeNumberField("ph", doc.getPh());
          }
          generator.writeEndObject();
        }
      }
      generator.writeEndArray();

      //
      generator.flush();
      writer.flush();

    } catch (UnsupportedEncodingException e) {
      logger.error("dump response failed.", e);
    } catch (IOException e) {
      logger.error("dump response failed.", e);
    } finally {

    }
  }
Пример #24
0
 private static void writeRelationships(
     final Map<Trace, Integer> traceIds, final JsonGenerator generator) throws IOException {
   generator.writeArrayFieldStart(JsonTraceCodec.RELATIONSHIPS);
   for (Map.Entry<Trace, Integer> entry : traceIds.entrySet()) {
     final Trace trace = entry.getKey();
     final int fromId = entry.getValue();
     for (Related<Trace> related : trace.getRelated()) {
       final int toId = traceIds.get(related.getRelated());
       final String relationship = related.getRelationship();
       generator.writeStartObject();
       generator.writeStringField(JsonTraceCodec.RELATIONSHIP_RELATIONSHIP, relationship);
       generator.writeNumberField(JsonTraceCodec.RELATIONSHIP_FROM, fromId);
       generator.writeNumberField(JsonTraceCodec.RELATIONSHIP_TO, toId);
       generator.writeEndObject();
     }
   }
   generator.writeEndArray();
 }
Пример #25
0
 /**
  * Writes the response values back to the http response. This allows the calling code to parse the
  * response values for display to the user.
  *
  * @param responseMap the response params to write to the http response
  * @param response the http response
  * @throws IOException
  */
 private void writeToResponse(Map<String, String> responseMap, HttpServletResponse response)
     throws IOException {
   // Note: setting the content-type to text/html because otherwise IE prompt the user to download
   // the result rather than handing it off to the GWT form response handler.
   // See JIRA issue https://issues.jboss.org/browse/SRAMPUI-103
   response.setContentType("text/html; charset=UTF8"); // $NON-NLS-1$
   JsonFactory f = new JsonFactory();
   JsonGenerator g = f.createJsonGenerator(response.getOutputStream(), JsonEncoding.UTF8);
   g.useDefaultPrettyPrinter();
   g.writeStartObject();
   for (java.util.Map.Entry<String, String> entry : responseMap.entrySet()) {
     String key = entry.getKey();
     String val = entry.getValue();
     g.writeStringField(key, val);
   }
   g.writeEndObject();
   g.flush();
   g.close();
 }
Пример #26
0
  @Override
  public void serialize(
      EnumEventField field, JsonGenerator g, SerializerProvider serializerProvider)
      throws IOException {

    // outer objectj
    g.writeStartObject();

    g.writeFieldName(field.interfaceKey);
    // inner object
    g.writeStartObject();
    g.writeStringField("value", field.getValue());
    g.writeFieldName("attributes");
    g.writeObject(field.getAttributes());
    g.writeFieldName("enum");
    g.writeObject(field.getEnums());
    // end inner object
    g.writeEndObject();

    // end outer object
    g.writeEndObject();
  }
Пример #27
0
 private void writeScriptData(OrcsScript model) throws IOException {
   Map<String, Object> binding = OrcsScriptUtil.getBinding(model);
   if (binding != null && !binding.isEmpty()) {
     writer.writeFieldName("parameters");
     writer.writeStartObject();
     for (Entry<String, Object> entry : binding.entrySet()) {
       writer.writeStringField(entry.getKey(), String.valueOf(entry.getValue()));
     }
     writer.writeEndObject();
   }
   writer.writeFieldName("script");
   String value = "N/A";
   try {
     if (model != null && model.eAllContents().hasNext()) {
       ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
       OrcsScriptUtil.saveModel(
           model, "orcs:/unknown.orcs", outputStream, OsStorageOption.NO_VALIDATION_ON_SAVE);
       value = outputStream.toString("UTF-8");
     }
   } catch (Exception ex) {
     value = ex.getMessage();
   }
   writer.writeString(value);
 }
Пример #28
0
  protected void writeBlobProperty(JsonGenerator jg, Property prop) throws IOException {
    Blob blob = (Blob) prop.getValue();
    if (blob == null) {
      jg.writeNull();
      return;
    }
    jg.writeStartObject();
    String v = blob.getFilename();
    if (v == null) {
      jg.writeNullField("name");
    } else {
      jg.writeStringField("name", v);
    }
    v = blob.getMimeType();
    if (v == null) {
      jg.writeNullField("mime-type");
    } else {
      jg.writeStringField("mime-type", v);
    }
    v = blob.getEncoding();
    if (v == null) {
      jg.writeNullField("encoding");
    } else {
      jg.writeStringField("encoding", v);
    }
    v = blob.getDigest();
    if (v == null) {
      jg.writeNullField("digest");
    } else {
      jg.writeStringField("digest", v);
    }
    jg.writeStringField("length", Long.toString(blob.getLength()));

    String blobUrl = getBlobUrl(prop);
    if (blobUrl == null) {
      blobUrl = "";
    }
    jg.writeStringField("data", blobUrl);
    jg.writeEndObject();
  }
Пример #29
0
 public void testWritePrimitiveWithString() throws Exception {
   generator.writeStringField("foo", "n");
   replayMocks();
   nullSafeWritePrimitiveField(generator, "foo", "n");
   verifyMocks();
 }
Пример #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();
  }