示例#1
0
  @Override
  public void serialize(Item item, JsonGenerator jgen, SerializerProvider provider)
      throws IOException, JsonProcessingException {
    jgen.writeStartArray();

    jgen.writeStartObject();
    jgen.writeStringField("id", "i_" + String.valueOf(item.getId()));
    jgen.writeObjectField("title", item.getName());
    jgen.writeObjectField("type", item.getType());

    String imagePath = "i_image_" + item.getId() + "." + item.getImage().getExtention();

    jgen.writeObjectFieldStart("image");
    jgen.writeObjectField("type", item.getImage().getType());
    jgen.writeObjectField("path", imagePath);
    jgen.writeEndObject();

    jgen.writeObjectFieldStart("values");
    jgen.writeStringField("productName", item.getName());
    jgen.writeStringField("imageFullPath", imagePath);
    for (Description description : item.getDescription()) {
      if (description.getDescription().size() > 1) {
        jgen.writeArrayFieldStart(description.getValue().getKey());
        for (String desc : description.getDescription()) jgen.writeString(desc);
        jgen.writeEndArray();
      } else
        jgen.writeStringField(
            description.getValue().getKey(),
            (description.getDescription().size() == 0) ? "" : description.getDescription().get(0));
    }
    jgen.writeEndObject();

    jgen.writeEndObject();
    jgen.writeEndArray();
  }
  public void serialize(SqlSession sql, JsonGenerator jg)
      throws JsonGenerationException, IOException, IllegalTypeException {
    Map<String, GroupBean> sortedGroups = GroupsIE.getSortedGroups(sql, groupResolver);
    GroupsMapper mapper = sql.getMapper(GroupsMapper.class);

    jg.writeStartArray();
    for (Map.Entry<String, GroupBean> entry : sortedGroups.entrySet()) {
      List<GroupElementBean> members = mapper.getMembers(entry.getValue().getId());

      jg.writeStartObject();
      jg.writeStringField("groupPath", entry.getKey());
      jg.writeFieldName("members");
      jg.writeStartArray();
      for (GroupElementBean member : members) {
        jg.writeStartObject();
        jg.writeNumberField("entity", member.getElementId());
        jg.writeNumberField("groupId", member.getGroupId());
        jg.writeBinaryField("contents", member.getContents());
        jg.writeEndObject();
      }
      jg.writeEndArray();
      jg.writeEndObject();
    }
    jg.writeEndArray();
  }
  @GET("/backend/aggregate/points")
  String getPoints(String content) throws IOException {
    logger.debug("getPoints(): content={}", content);
    PointsRequest request = ObjectMappers.readRequiredValue(mapper, content, PointsRequest.class);
    List<AggregatePoint> points = aggregateDao.readAggregates(request.getFrom(), request.getTo());

    StringBuilder sb = new StringBuilder();
    JsonGenerator jg = mapper.getFactory().createGenerator(CharStreams.asWriter(sb));
    jg.writeStartObject();
    jg.writeArrayFieldStart("points");
    for (AggregatePoint point : points) {
      jg.writeStartArray();
      jg.writeNumber(point.getCaptureTime());
      long durationAverage;
      if (point.getTraceCount() == 0) {
        durationAverage = 0;
      } else {
        durationAverage = point.getDurationTotal() / point.getTraceCount();
      }
      jg.writeNumber(durationAverage / 1000000000.0);
      jg.writeNumber(point.getTraceCount());
      jg.writeEndArray();
    }
    jg.writeEndArray();
    jg.writeNumberField("fixedAggregateIntervalSeconds", fixedAggregateIntervalSeconds);
    jg.writeEndObject();
    jg.close();
    return sb.toString();
  }
示例#4
0
    @Override
    public void serialize(
        final GraphSONVertex directionalVertex,
        final JsonGenerator jsonGenerator,
        final SerializerProvider serializerProvider)
        throws IOException, JsonGenerationException {
      final Vertex vertex = directionalVertex.getVertexToSerialize();
      jsonGenerator.writeStartObject();
      jsonGenerator.writeObjectField(GraphSONTokens.ID, vertex.getId());
      jsonGenerator.writeStringField(GraphSONTokens.LABEL, vertex.getLabel());
      jsonGenerator.writeStringField(GraphSONTokens.TYPE, GraphSONTokens.VERTEX);

      if (normalize) {
        jsonGenerator.writeObjectFieldStart(GraphSONTokens.PROPERTIES);
        vertex
            .getProperties()
            .values()
            .stream()
            .sorted(Comparators.PROPERTY_COMPARATOR)
            .forEachOrdered(
                FunctionUtils.wrapConsumer(
                    e -> jsonGenerator.writeObjectField(e.getKey(), e.get())));
        jsonGenerator.writeEndObject();
      } else {
        jsonGenerator.writeObjectFieldStart(GraphSONTokens.PROPERTIES);
        vertex
            .getProperties()
            .values()
            .forEach(
                FunctionUtils.wrapConsumer(
                    e -> jsonGenerator.writeObjectField(e.getKey(), e.get())));
        jsonGenerator.writeEndObject();
      }

      if (directionalVertex.getDirection() == Direction.BOTH
          || directionalVertex.getDirection() == Direction.OUT) {
        jsonGenerator.writeArrayFieldStart(GraphSONTokens.OUT);
        if (normalize)
          vertex
              .outE()
              .order(Comparators.HELD_EDGE_COMPARATOR)
              .forEach(FunctionUtils.wrapConsumer(jsonGenerator::writeObject));
        else vertex.outE().forEach(FunctionUtils.wrapConsumer(jsonGenerator::writeObject));
        jsonGenerator.writeEndArray();
      }

      if (directionalVertex.getDirection() == Direction.BOTH
          || directionalVertex.getDirection() == Direction.IN) {
        jsonGenerator.writeArrayFieldStart(GraphSONTokens.IN);
        if (normalize)
          vertex
              .inE()
              .order(Comparators.HELD_EDGE_COMPARATOR)
              .forEach(FunctionUtils.wrapConsumer(jsonGenerator::writeObject));
        else vertex.inE().forEach(FunctionUtils.wrapConsumer(jsonGenerator::writeObject));
        jsonGenerator.writeEndArray();
      }
      jsonGenerator.writeEndObject();
    }
  public void testEmptyArrayWrite() throws Exception {
    StringWriter sw = new StringWriter();
    JsonGenerator gen = new JsonFactory().createGenerator(sw);

    JsonStreamContext ctxt = gen.getOutputContext();
    assertTrue(ctxt.inRoot());
    assertFalse(ctxt.inArray());
    assertFalse(ctxt.inObject());
    assertEquals(0, ctxt.getEntryCount());
    assertEquals(0, ctxt.getCurrentIndex());

    gen.writeStartArray();

    ctxt = gen.getOutputContext();
    assertFalse(ctxt.inRoot());
    assertTrue(ctxt.inArray());
    assertFalse(ctxt.inObject());
    assertEquals(0, ctxt.getEntryCount());
    assertEquals(0, ctxt.getCurrentIndex());

    gen.writeEndArray();

    ctxt = gen.getOutputContext();
    assertTrue("Should be in root, was " + ctxt.getTypeDesc(), ctxt.inRoot());
    assertFalse(ctxt.inArray());
    assertFalse(ctxt.inObject());
    assertEquals(1, ctxt.getEntryCount());
    // Index won't yet move
    assertEquals(0, ctxt.getCurrentIndex());

    gen.close();
    String docStr = sw.toString();
    JsonParser jp = createParserUsingReader(docStr);
    assertEquals(JsonToken.START_ARRAY, jp.nextToken());
    assertEquals(JsonToken.END_ARRAY, jp.nextToken());
    jp.close();

    // Ok, then array with nested empty array
    sw = new StringWriter();
    gen = new JsonFactory().createGenerator(sw);
    gen.writeStartArray();
    gen.writeStartArray();
    gen.writeEndArray();
    gen.writeEndArray();
    gen.close();
    docStr = sw.toString();
    jp = createParserUsingReader(docStr);
    assertEquals(JsonToken.START_ARRAY, jp.nextToken());
    assertEquals(JsonToken.START_ARRAY, jp.nextToken());
    assertEquals(JsonToken.END_ARRAY, jp.nextToken());
    assertEquals(JsonToken.END_ARRAY, jp.nextToken());
    assertEquals(null, jp.nextToken());
    jp.close();
  }
  @Test
  public void writeJSONViaLowerlevelLibs() throws IOException {
    final StringWriter writer = new StringWriter();

    final ObjectMapper mapper = new ObjectMapper();

    final JsonGenerator jgen = mapper.getFactory().createGenerator(writer);

    jgen.writeStartObject();

    jgen.writeStringField(
        "odata.type", "Microsoft.Test.OData.Services.AstoriaDefaultService.Customer");

    jgen.writeStringField("*****@*****.**", "Edm.String");
    jgen.writeStringField("Name", "A name");

    jgen.writeStringField("*****@*****.**", "Edm.Int32");
    jgen.writeNumberField("CustomerId", 0);

    jgen.writeArrayFieldStart("BackupContactInfo");

    jgen.writeStartObject();

    jgen.writeArrayFieldStart("AlternativeNames");
    jgen.writeString("myname");
    jgen.writeEndArray();

    jgen.writeArrayFieldStart("EmailBag");
    jgen.writeString("*****@*****.**");
    jgen.writeEndArray();

    jgen.writeObjectFieldStart("ContactAlias");
    jgen.writeStringField(
        "odata.type", "Microsoft.Test.OData.Services.AstoriaDefaultService.Aliases");
    jgen.writeArrayFieldStart("AlternativeNames");
    jgen.writeString("myAlternativeName");
    jgen.writeEndArray();
    jgen.writeEndObject();

    jgen.writeEndObject();

    jgen.writeEndArray();

    jgen.writeEndObject();

    jgen.flush();

    assertFalse(writer.toString().isEmpty());
  }
  @Test
  public void testCreateGenerator() throws Exception {

    EbeanServer server = Ebean.getDefaultServer();

    StringWriter writer = new StringWriter();
    JsonContext json = server.json();
    JsonGenerator generator = json.createGenerator(writer);

    Customer customer = new Customer();
    customer.setId(1);
    customer.setName("Jim");

    // we can use the generator before and after our json.toJson() call
    // ... confirming we are not closing the generator
    generator.writeStartArray();
    json.toJson(customer, generator, PathProperties.parse("id,name"));
    generator.writeEndArray();
    generator.close();

    String jsonString = writer.toString();
    assertTrue(jsonString, jsonString.startsWith("["));
    assertTrue(jsonString, jsonString.endsWith("]"));
    assertTrue(jsonString, jsonString.contains("{\"id\":1,\"name\":\"Jim\"}"));
  }
 public static String dumpConfigurationAsJson() {
   ImmutableCollection<String> keys = CONFIGURATION_SECTIONS.keySet();
   ObjectMapper mapper = new ObjectMapper();
   JsonFactory jfactory = mapper.getJsonFactory();
   StringWriter sw = new StringWriter();
   try {
     JsonGenerator gen = jfactory.createJsonGenerator(sw);
     gen.writeStartArray();
     for (String v : keys) {
       String st = dumpConfigurationAsJson(v);
       ObjectMapper op = new ObjectMapper();
       JsonNode p = op.readTree(st);
       Logger.debug("OBJECT:" + p.toString());
       Logger.debug("STRING:" + st);
       // JsonParser jp = jfactory.createJsonParser(st);
       gen.writeTree(p);
     }
     gen.writeEndArray();
     gen.close();
     return sw.toString();
   } catch (Exception e) {
     Logger.error("Cannot generate a json for the configuration", e);
   }
   return "[]";
 } // dumpConfigurationAsJson()
  @Override
  public void serialize(Request request, JsonGenerator jgen, SerializerProvider provider)
      throws IOException {
    jgen.writeStartObject();
    jgen.writeStringField("uri", request.getUri());
    jgen.writeStringField("method", request.getMethod().name());

    if (request.getHeaders() != null && !request.getHeaders().isEmpty()) {
      jgen.writeArrayFieldStart("headers");

      request
          .getHeaders()
          .forEach(
              httpHeader -> {
                try {
                  jgen.writeStartObject();
                  jgen.writeStringField("name", httpHeader.getName());
                  jgen.writeStringField("value", httpHeader.getValue());
                  jgen.writeEndObject();
                } catch (IOException e) {
                  e.printStackTrace();
                }
              });
      jgen.writeEndArray();
    }
    if (request.getBody() != null && !request.getBody().isEmpty()) {
      jgen.writeStringField("body", request.getBody());
    }
    jgen.writeEndObject();
  }
  @Override
  public void serialize(IndexInput input, JsonGenerator jg, SerializerProvider sp)
      throws IOException {
    jg.writeStartObject();

    // Riak bug ... explicitly specifying "default" as the type breaks things
    if (!input.getNamespace().getBucketTypeAsString().equals(Namespace.DEFAULT_BUCKET_TYPE)) {
      jg.writeArrayFieldStart("bucket");
      jg.writeString(input.getNamespace().getBucketTypeAsString());
      jg.writeString(input.getNamespace().getBucketNameAsString());
      jg.writeEndArray();
    } else {
      jg.writeStringField("bucket", input.getNamespace().getBucketNameAsString());
    }

    jg.writeStringField("index", input.getIndex());
    IndexInput.IndexCriteria criteria = input.getCriteria();
    if (criteria instanceof IndexInput.MatchCriteria) {
      IndexInput.MatchCriteria<?> match = (IndexInput.MatchCriteria) criteria;
      jg.writeObjectField("key", match.getValue());
    } else if (criteria instanceof IndexInput.RangeCriteria) {
      IndexInput.RangeCriteria range = (IndexInput.RangeCriteria) criteria;
      jg.writeObjectField("start", range.getBegin());
      jg.writeObjectField("end", range.getEnd());
    }
    jg.writeEndObject();
  }
  @Override
  public void run() {
    Request request = null;
    try {
      request = transport.prepare();
      jsonOut = jsonFactory.createGenerator(request.getBodyWriter());
      jsonOut.writeStartObject();
      jsonOut.writeFieldName("series");
      jsonOut.writeStartArray();
    } catch (IOException ioe) {
      LOG.error("Could not prepare request", ioe);
      return;
    }

    final long epoch = clock.time() / 1000;
    if (this.printVmMetrics) {
      pushVmMetrics(epoch);
    }
    pushRegularMetrics(epoch);

    try {
      jsonOut.writeEndArray();
      jsonOut.writeEndObject();
      jsonOut.flush();
      request.send();
    } catch (Exception e) {
      LOG.error("Error sending metrics", e);
    }
  }
示例#12
0
 private void writeArray(JsonGenerator jsonGenerator, Iterable<?> value, Deque<Object> objectStack)
     throws IOException {
   jsonGenerator.writeStartArray();
   for (Object item : value) {
     writeFieldValue(jsonGenerator, item, objectStack);
   }
   jsonGenerator.writeEndArray();
 }
  public void writeJsonIfLocal(JsonGenerator g) throws JsonGenerationException, IOException {
    if (this.is_local) {
      g.writeStartObject();
      g.writeFieldName(KEY_LATITUDE);
      g.writeNumber(this.latitude);
      g.writeFieldName(KEY_LONGITUDE);
      g.writeNumber(this.longitude);
      g.writeFieldName(KEY_BUILDING);
      g.writeString(this.buildingName);
      g.writeFieldName(KEY_ROOM);
      g.writeString(this.roomName);
      g.writeFieldName(KEY_RATING);
      g.writeNumber(this.my_productivity);
      g.writeFieldName(KEY_CAPACITY);
      g.writeNumber(this.my_capacity);
      g.writeFieldName(KEY_CROWD);
      g.writeNumber(this.my_crowd);
      g.writeFieldName(KEY_NUM_SURVEYS);
      g.writeNumber(this.my_n_surveys);
      g.writeFieldName(KEY_COMMENTS);
      g.writeStartArray();

      CloseableIterator<CommentEntry> commIterator = this.commentEntries.closeableIterator();
      while (commIterator.hasNext()) commIterator.next().writeJsonIfLocal(g);
      try {
        commIterator.close();
      } catch (SQLException e1) {
        e1.printStackTrace();
      }
      g.writeEndArray();
      g.writeFieldName(KEY_NOISE);
      g.writeStartArray();

      CloseableIterator<NoiseEntry> noiseIterator = this.noiseEntries.closeableIterator();
      while (noiseIterator.hasNext()) noiseIterator.next().writeJsonIfLocal(g);
      try {
        noiseIterator.close();
      } catch (SQLException e) {
        e.printStackTrace();
      }

      g.writeEndArray();
      g.writeEndObject();
    }
  }
示例#14
0
 @Override
 public void serialize(
     Point point, JsonGenerator jsonGenerator, SerializerProvider serializerProvider)
     throws IOException, JsonProcessingException {
   jsonGenerator.writeStartArray();
   jsonGenerator.writeNumber(point.getCoordinate().y); // lat
   jsonGenerator.writeNumber(point.getCoordinate().x); // lng
   jsonGenerator.writeEndArray();
 }
 @Override
 public void serialize(DataNode dataNode, JsonGenerator generator, SerializerProvider provider)
     throws IOException, JsonProcessingException {
   generator.writeStartArray();
   for (DataNode childNode : dataNode) {
     generator.writeObject(childNode);
   }
   generator.writeEndArray();
 }
示例#16
0
 @Override
 public void serialize(ArrayRealVector value, JsonGenerator gen, SerializerProvider serializers)
     throws IOException {
   gen.writeStartArray(value.getDimension());
   for (int i = 0; i < value.getDimension(); i++) {
     gen.writeNumber(value.getEntry(i));
   }
   gen.writeEndArray();
 }
  @Override
  public String handleRequest(ExecutionJobVertex jobVertex, Map<String, String> params)
      throws Exception {
    StringWriter writer = new StringWriter();
    JsonGenerator gen = JsonFactory.jacksonFactory.createGenerator(writer);

    gen.writeStartObject();
    gen.writeStringField("id", jobVertex.getJobVertexId().toString());
    gen.writeNumberField("parallelism", jobVertex.getParallelism());

    gen.writeArrayFieldStart("subtasks");

    int num = 0;
    for (ExecutionVertex vertex : jobVertex.getTaskVertices()) {

      InstanceConnectionInfo location = vertex.getCurrentAssignedResourceLocation();
      String locationString = location == null ? "(unassigned)" : location.getHostname();

      gen.writeStartObject();

      gen.writeNumberField("subtask", num++);
      gen.writeNumberField("attempt", vertex.getCurrentExecutionAttempt().getAttemptNumber());
      gen.writeStringField("host", locationString);

      StringifiedAccumulatorResult[] accs =
          vertex.getCurrentExecutionAttempt().getUserAccumulatorsStringified();
      gen.writeArrayFieldStart("user-accumulators");
      for (StringifiedAccumulatorResult acc : accs) {
        gen.writeStartObject();
        gen.writeStringField("name", acc.getName());
        gen.writeStringField("type", acc.getType());
        gen.writeStringField("value", acc.getValue());
        gen.writeEndObject();
      }
      gen.writeEndArray();

      gen.writeEndObject();
    }
    gen.writeEndArray();

    gen.writeEndObject();
    gen.close();
    return writer.toString();
  }
示例#18
0
  public InputStream verifyDatatype2(Profile p, Profile baseP, String id, String type) {
    String result = "";
    // Datatype dt = p.getDatatypeLibrary().findOne(id);

    try {
      // Create temporary file
      File tmpJsonFile = File.createTempFile("resultTmp", ".json");

      // Generate json file
      JsonFactory factory = new JsonFactory();
      JsonGenerator generator = factory.createGenerator(new FileWriter(tmpJsonFile));
      generator.setPrettyPrinter(new DefaultPrettyPrinter());

      generator.writeStartObject();
      generator.writeStringField("id", id);
      generator.writeStringField("type", type);

      generator.writeArrayFieldStart("eltVerification");

      // for (Component c : dt.getComponents()){
      // generator.writeStartObject();
      // generator.writeStringField("eltName", "usage");
      // generator.writeStringField("eltAtt", c.getUsage().value());
      // result = this.validateChangeUsage(p.getMetaData().getHl7Version(),
      // baseP.getDatatypeLibrary().findOneComponent(c.getId()).getUsage(),
      // p.getDatatypeLibrary().findOneComponent(c.getId()).getUsage());
      // generator.writeStringField("result", result);
      // generator.writeEndObject();
      //
      // generator.writeStartObject();
      // generator.writeStringField("eltName", "minLength");
      // generator.writeStringField("eltAtt", String.valueOf(c.getMinLength()));
      // result = this.validateChangeLength(String.valueOf(c.getMinLength()), c.getMaxLength());
      // generator.writeStringField("result", result);
      // generator.writeEndObject();
      //
      // generator.writeStartObject();
      // generator.writeStringField("eltName", "maxLength");
      // generator.writeStringField("eltAtt", String.valueOf(c.getMaxLength()));
      // result = this.validateChangeLength(String.valueOf(c.getMinLength()), c.getMaxLength());
      // generator.writeStringField("result", result);
      // generator.writeEndObject();
      //
      // }

      generator.writeEndArray();
      generator.writeEndObject();

      generator.close();

      return FileUtils.openInputStream(tmpJsonFile);
    } catch (IOException e) {
      return new NullInputStream(1L);
    }
  }
 @Override
 public void serialize(List<String> value, JsonGenerator jgen, SerializerProvider provider)
     throws IOException, JsonGenerationException {
   jgen.writeStartArray();
   if (_serializer == null) {
     serializeContents(value, jgen, provider);
   } else {
     serializeUsingCustom(value, jgen, provider);
   }
   jgen.writeEndArray();
 }
示例#20
0
  public void serializeArray(JsonGenerator jsonGenerator, T[] translatorTypes) throws IOException {
    jsonGenerator.writeStartArray();
    for (T type : translatorTypes) {
      if (type != null) {
        Acela.getTranslator(getType()).serialize(type, jsonGenerator);
      } else {
        jsonGenerator.writeNull();
      }
    }

    jsonGenerator.writeEndArray();
  }
  @Override
  public void serialize(
      ApplicationGroup applicationGroup, JsonGenerator jgen, SerializerProvider provider)
      throws IOException, JsonProcessingException {
    jgen.writeStartArray();

    List<Application> applicationList = applicationGroup.getApplicationList();
    for (Application application : applicationList) {
      writeApplication(jgen, application);
    }
    jgen.writeEndArray();
  }
示例#22
0
 @Override
 public String toJson(JsonFactory jsonFactory) throws IOException {
   try (StringWriter sw = new StringWriter();
       JsonGenerator jg = jsonFactory.createGenerator(sw)) {
     jg.writeStartArray();
     jg.writeNumber(getTypeId());
     jg.writeString(getTopicURI());
     jg.writeEndArray();
     jg.close();
     return sw.toString();
   }
 }
示例#23
0
 @Override
 public void serialize(
     final GeoJsonPoint value, final JsonGenerator gen, final SerializerProvider serializers)
     throws IOException {
   gen.writeStartObject();
   gen.writeStringField("type", value.getType());
   gen.writeArrayFieldStart("coordinates");
   gen.writeNumber(value.getX());
   gen.writeNumber(value.getY());
   gen.writeEndArray();
   gen.writeEndObject();
 }
 protected void writeMediaContent(JsonGenerator generator, MediaContent content)
     throws IOException {
   generator.writeStartObject();
   generator.writeFieldName(FIELD_MEDIA);
   writeMedia(generator, content.media);
   generator.writeFieldName(FIELD_IMAGES);
   generator.writeStartArray();
   for (Image i : content.images) {
     writeImage(generator, i);
   }
   generator.writeEndArray();
   generator.writeEndObject();
 }
 @Override
 public void serialize(DateMidnight dt, JsonGenerator jgen, SerializerProvider provider)
     throws IOException, JsonGenerationException {
   if (provider.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)) {
     // same as with other date-only values
     jgen.writeStartArray();
     jgen.writeNumber(dt.year().get());
     jgen.writeNumber(dt.monthOfYear().get());
     jgen.writeNumber(dt.dayOfMonth().get());
     jgen.writeEndArray();
   } else {
     jgen.writeString(format.print(dt));
   }
 }
示例#26
0
  public String getGroups(@Name("filter") String filter) {
    StringWriter resultWriter = new StringWriter();
    JsonFactory f = new JsonFactory();
    f.setCodec(om);
    JsonGenerator g;
    try {
      g = f.createGenerator(resultWriter);

      final Node target = DB.getIndex().get("id", "agents").getSingle();
      TraversalDescription td =
          Traversal.description()
              .relationships(RelTypes.SUBGROUP, Direction.OUTGOING)
              .uniqueness(Uniqueness.NODE_PATH);

      Traverser results = td.traverse(target);
      g.writeStartArray();
      Iterator<Path> paths = results.iterator();
      while (paths.hasNext()) {
        Path path = paths.next();
        if (!path.endNode().hasProperty("name")) continue;
        g.writeStartObject();
        g.writeStringField("name", (String) path.endNode().getProperty("name"));
        g.writeArrayFieldStart("path");
        for (Node pathStep : path.nodes()) {
          if (pathStep.hasProperty("name")) g.writeString((String) pathStep.getProperty("name"));
        }
        g.writeEndArray();
        g.writeEndObject();
      }
      g.writeEndArray();
      g.flush();
    } catch (IOException e) {
      e.printStackTrace();
    }
    resultWriter.flush();
    return resultWriter.toString();
  }
示例#27
0
  private static void write(JsonGenerator g, List<List<Tokenizer.Token>> text) throws IOException {
    Stream<Pair<Tokenizer.Token, Integer>> s =
        StreamUtil.zip(text.stream(), Stream.iterate(0, i -> i + 1))
            .flatMap(p -> p.getA().stream().map(t -> Pair.of(t, p.getB())));

    g.writeStartArray();
    for (Pair<Tokenizer.Token, Integer> p : StreamUtil.asIterable(s)) {
      Tokenizer.Token t = p.getA();
      g.writeStartObject();
      g.writeStringField("pos", t.pos());
      g.writeStringField("text", tokenToString(t, p.getB()));
      g.writeEndObject();
    }
    g.writeEndArray();
  }
示例#28
0
 private static void writeIndex(File dst, List<Bible.Book> a, List<Bible.Book> b)
     throws IOException {
   try (JsonGenerator g = gen(dst)) {
     g.writeStartArray();
     for (int i = 0, n = a.size(); i < n; i++) {
       Bible.Book ab = a.get(i);
       Bible.Book bb = b.get(i);
       g.writeStartObject();
       g.writeStringField("abbr", ab.abbr());
       g.writeStringField("name_a", ab.name());
       g.writeStringField("name_b", bb.name());
       g.writeEndObject();
     }
     g.writeEndArray();
   }
 }
  @Override
  public void serialize(LoadCurve curve, JsonGenerator jGenerator, SerializerProvider provider)
      throws IOException {

    jGenerator.writeStartObject();
    jGenerator.writeArrayFieldStart("loadByHoursInMW");

    do {
      jGenerator.writeNumber(curve.getPowerOnTimeInMW(pointer));
      pointer = pointer.plusHours(1);
    } while (pointer != LocalTime.MIDNIGHT);

    jGenerator.writeEndArray();
    jGenerator.writeEndObject();

    logger.debug("Serialized: {} to JSON.", curve);
  }
示例#30
0
 @Override
 public void serialize(PointInTime t, JsonGenerator jgen, SerializerProvider provider)
     throws IOException, JsonGenerationException {
   if (provider.isEnabled(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)) {
     // Timestamp here actually means an array of values
     jgen.writeStartArray();
     jgen.writeNumber(t.getYear());
     if (t.isMonthSet()) jgen.writeNumber(t.getMonth());
     if (t.isDateSet()) jgen.writeNumber(t.getDate());
     if (t.isHourSet()) jgen.writeNumber(t.getHour());
     if (t.isMinuteSet()) jgen.writeNumber(t.getMinute());
     if (t.isSecondSet()) jgen.writeNumber(t.getSecond());
     if (t.isMillisecondSet()) jgen.writeNumber(t.getMillisecond());
     jgen.writeEndArray();
   } else {
     jgen.writeString(t.toString());
   }
 }