@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);
     }
   }
 }
Beispiel #2
0
  @Override
  public void onEvalStart() {
    super.onEvalStart();
    initalizeData();
    try {
      ObjectMapper mapper = new ObjectMapper();
      mapper.setDateFormat(new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a"));
      mapper.configure(SerializationConfig.Feature.SORT_PROPERTIES_ALPHABETICALLY, true);
      mapper.configure(SerializationConfig.Feature.WRAP_EXCEPTIONS, true);
      mapper.configure(SerializationConfig.Feature.WRITE_EMPTY_JSON_ARRAYS, false);
      mapper.configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, true);

      SimpleModule module = new SimpleModule("DataProxy", new Version(1, 0, 0, null));
      module.addSerializer(DataProxy.class, new DataProxySerializer(DataProxy.class));
      mapper.registerModule(module);

      JsonFactory jsonFactory = mapper.getJsonFactory();
      writer = jsonFactory.createJsonGenerator(context.getWriter());
      writer.setPrettyPrinter(new DefaultPrettyPrinter());

      writer.writeStartObject();
    } catch (IOException ex) {
      throw new OseeCoreException(ex);
    }
  }
  @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);
  }
Beispiel #4
0
  @Test
  public void testSerialization() throws IOException, ClassNotFoundException {
    Condition cond = new Condition();
    Set<UUID> ids = new HashSet<>();
    ids.add(UUID.randomUUID());
    ids.add(UUID.randomUUID());
    cond.inPortIds = ids;
    cond.portGroup = UUID.randomUUID();
    cond.tpSrc = new Range<>(40000, 41000);
    cond.tpSrcInv = false;
    cond.tpDst = new Range<>(42000, 43000);
    cond.tpDstInv = true;
    cond.etherType = 0x86DD;

    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    OutputStream out = new BufferedOutputStream(bos);
    JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(new OutputStreamWriter(out));
    jsonGenerator.writeObject(cond);
    out.close();
    byte[] data = bos.toByteArray();
    ByteArrayInputStream bis = new ByteArrayInputStream(data);
    InputStream in = new BufferedInputStream(bis);
    JsonParser jsonParser = jsonFactory.createJsonParser(new InputStreamReader(in));
    Condition c = jsonParser.readValueAs(Condition.class);
    in.close();
    Assert.assertTrue(cond.equals(c));
  }
 @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();
 }
 @Override
 public int run(InputStream stdin, PrintStream out, PrintStream err, List<String> args)
     throws Exception {
   if (args.size() != 2) {
     err.println("Expected 2 arguments: schema binary_data_file");
     err.println("Use '-' as binary_data_file for stdin.");
     return 1;
   }
   Schema schema = Schema.parse(args.get(0));
   InputStream input;
   boolean needsClosing;
   if (args.get(1).equals("-")) {
     input = stdin;
     needsClosing = false;
   } else {
     input = new FileInputStream(args.get(1));
     needsClosing = true;
   }
   try {
     DatumReader<Object> reader = new GenericDatumReader<Object>(schema);
     Object datum = reader.read(null, DecoderFactory.get().binaryDecoder(input, null));
     DatumWriter<Object> writer = new GenericDatumWriter<Object>(schema);
     JsonGenerator g = new JsonFactory().createJsonGenerator(out, JsonEncoding.UTF8);
     g.useDefaultPrettyPrinter();
     writer.write(datum, EncoderFactory.get().jsonEncoder(schema, g));
     g.flush();
     out.println();
     out.flush();
   } finally {
     if (needsClosing) {
       input.close();
     }
   }
   return 0;
 }
 @Override
 public void serialize(
     final PingMessage ping, final JsonGenerator jgen, final SerializerProvider provider)
     throws IOException, JsonProcessingException {
   jgen.writeStartObject();
   jgen.writeEndObject();
 }
Beispiel #8
0
 private void writeCollect(SelectSet selectSet) throws IOException {
   writer.writeFieldName("collect");
   writer.writeStartObject();
   writer.writeNumberField("limit", selectSet.getLimit());
   writeDynamicData(selectSet.getData());
   writer.writeEndObject();
 }
Beispiel #9
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());
     }
   }
 }
 @Override
 public void appendTo(JsonGenerator generator) throws IOException {
   generator.writeStartArray();
   generator.writeString(this.bucket);
   generator.writeString(this.key);
   appendKeyData(generator);
   generator.writeEndArray();
 }
 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();
 }
 @Override
 public void serialize(Date value, JsonGenerator jgen, SerializerProvider provider)
     throws IOException, JsonProcessingException {
   if (value == null) {
     jgen.writeString("");
   }
   jgen.writeString(new SimpleDateFormat("yyyy-MM-dd HH:mm:SS").format(value));
 }
 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();
 }
Beispiel #14
0
 public static void toJson(Object pojo, Writer writer, boolean prettyPrint)
     throws JsonMappingException, JsonGenerationException, IOException {
   JsonGenerator jg = jf.createJsonGenerator(writer);
   if (prettyPrint) {
     jg.useDefaultPrettyPrinter();
   }
   m.writeValue(jg, pojo);
 }
 public String marshall(String definitions)
     throws IOException { // TODO fix this when we have the EPN ecore model
   StringWriter writer = new StringWriter();
   JsonFactory f = new JsonFactory();
   JsonGenerator generator = f.createJsonGenerator(writer);
   // TODO do the heavy lifting here passing in the writer and the json generator
   generator.close();
   return writer.toString();
 }
Beispiel #16
0
 private String readBody(JsonParser jp) throws IOException {
   JsonNode node = mapper.readTree(jp);
   StringWriter out = new StringWriter();
   JsonGenerator gen = jsonFactory.createJsonGenerator(out);
   mapper.writeTree(gen, node);
   gen.flush();
   gen.close();
   return out.toString();
 }
  /**
   * Executes a query.
   *
   * @param command Name of the command to execute
   * @param parameters Parameters
   * @param manager Reference back to business layer
   * @return Parsed JSON object, empty object on error.
   */
  public JsonNode query(String command, JsonNode parameters, INotifiableManager manager) {
    URLConnection uc = null;
    try {
      final ObjectMapper mapper = Client.MAPPER;

      if (mUrlSuffix == null) {
        throw new NoSettingsException();
      }

      final URL url = new URL(mUrlSuffix + XBMC_JSONRPC_BOOTSTRAP);
      uc = url.openConnection();
      uc.setConnectTimeout(SOCKET_CONNECTION_TIMEOUT);
      uc.setReadTimeout(mSocketReadTimeout);
      if (authEncoded != null) {
        uc.setRequestProperty("Authorization", "Basic " + authEncoded);
      }
      uc.setRequestProperty("Content-Type", "application/json");
      uc.setDoOutput(true);

      final ObjectNode data = Client.obj().p("jsonrpc", "2.0").p("method", command).p("id", "1");
      if (parameters != null) {
        data.put("params", parameters);
      }

      final JsonFactory jsonFactory = new JsonFactory();
      final JsonGenerator jg =
          jsonFactory.createJsonGenerator(uc.getOutputStream(), JsonEncoding.UTF8);
      jg.setCodec(mapper);

      // POST data
      jg.writeTree(data);
      jg.flush();

      final JsonParser jp = jsonFactory.createJsonParser(uc.getInputStream());
      jp.setCodec(mapper);
      final JsonNode ret = jp.readValueAs(JsonNode.class);
      return ret;

    } catch (MalformedURLException e) {
      manager.onError(e);
    } catch (IOException e) {
      int responseCode = -1;
      try {
        responseCode = ((HttpURLConnection) uc).getResponseCode();
      } catch (IOException e1) {
      } // do nothing, getResponse code failed so treat as default i/o exception.
      if (uc != null && responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
        manager.onError(new HttpException(Integer.toString(HttpURLConnection.HTTP_UNAUTHORIZED)));
      } else {
        manager.onError(e);
      }
    } catch (NoSettingsException e) {
      manager.onError(e);
    }
    return new ObjectNode(null);
  }
Beispiel #18
0
 public static String toJson(Object pojo, boolean prettyPrint)
     throws JsonMappingException, JsonGenerationException, IOException {
   StringWriter sw = new StringWriter();
   JsonGenerator jg = jf.createJsonGenerator(sw);
   if (prettyPrint) {
     jg.useDefaultPrettyPrinter();
   }
   m.writeValue(jg, pojo);
   return sw.toString();
 }
  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"));
  }
 private static void writeTraces(final Map<Trace, Integer> traceIds, final JsonGenerator generator)
     throws IOException {
   generator.writeArrayFieldStart(JsonTraceCodec.TRACES);
   for (Map.Entry<Trace, Integer> entry : traceIds.entrySet()) {
     final Trace trace = entry.getKey();
     final int traceId = entry.getValue();
     writeTrace(trace, traceId, generator);
   }
   generator.writeEndArray();
 }
Beispiel #21
0
 private void writeCriterias(CriteriaSet criteriaSet) throws IOException {
   writer.writeArrayFieldStart("criteria");
   for (Criteria criteria : criteriaSet.getCriterias()) {
     String value = criteria.toString();
     value = value.replaceAll("\\[", "");
     value = value.replaceAll("\\]", "");
     writer.writeObject(value);
   }
   writer.writeEndArray();
 }
Beispiel #22
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();
    }
  }
 @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();
 }
 private JsonNode write(Map<String, Object> row) throws IOException, JsonParseException {
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   JsonGenerator json = jsonFactory.createJsonGenerator(out);
   json.writeStartObject();
   try {
     new GraphExtractionWriter().write(json, row.keySet(), new MapRow(row));
   } finally {
     json.writeEndObject();
     json.flush();
   }
   return JsonHelper.jsonNode(out.toString("UTF-8"));
 }
 public static String beanToJson(Object bean) {
   StringWriter sw = new StringWriter();
   try {
     JsonGenerator jsongenerator = objmapper.getJsonFactory().createJsonGenerator(sw);
     objmapper.writeValue(jsongenerator, bean);
     jsongenerator.close();
   } catch (IOException e) {
     LOG.error("", e);
     return "";
   }
   return sw.toString();
 }
  @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();
    }
  }
Beispiel #27
0
 public String toJSON(T object) throws IOException {
   JsonFactory jsonFactory = new JsonFactory();
   ObjectMapper mapper = new ObjectMapper(jsonFactory);
   mapper.getSerializationConfig().setAnnotationIntrospector(new JacksonAnnotationIntrospector());
   mapper.getSerializationConfig().setSerializationInclusion(JsonSerialize.Inclusion.NON_NULL);
   jsonFactory.setCodec(mapper);
   StringWriter writer = new StringWriter();
   JsonGenerator jsonGenerator = jsonFactory.createJsonGenerator(writer);
   jsonGenerator.useDefaultPrettyPrinter();
   jsonGenerator.writeObject(object);
   return writer.getBuffer().toString();
 }
Beispiel #28
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();
        }
      }
    }
  }
Beispiel #29
0
 protected String toJson(boolean pretty) {
   try {
     StringWriter writer = new StringWriter();
     JsonGenerator gen = FACTORY.createJsonGenerator(writer);
     if (pretty) gen.useDefaultPrettyPrinter();
     toJson(gen);
     gen.flush();
     return writer.toString();
   } catch (IOException e) {
     throw new RuntimeException(e);
   }
 }
Beispiel #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();
  }