Пример #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 byte[] toJSONBytes() {
    try {
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      JsonFactory jsonFactory = new JsonFactory();
      JsonGenerator jsonGenerator =
          jsonFactory.createJsonGenerator(outputStream, JsonEncoding.UTF8);

      jsonGenerator.useDefaultPrettyPrinter();

      jsonGenerator.writeStartObject();
      jsonGenerator.writeStringField("type", ContentType);
      jsonGenerator.writeStringField("version", Version);
      jsonGenerator.writeStringField("uuid", workspaceUUID);
      jsonGenerator.writeStringField("name", workspaceName);
      jsonGenerator.writeStringField("description", workspaceDescription);
      // TODO: More details about who is making the change when and from what previous version?
      // jsonGenerator.writeStringField("timestamp", timestamp);
      // jsonGenerator.writeStringField("user", user);
      // jsonGenerator.writeStringField("previous", previous);
      jsonGenerator.writeEndObject();
      jsonGenerator.close();
      return outputStream.toByteArray();
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
  }
Пример #3
0
 private static FullHttpResponse newHttpResponseWithStackTrace(
     Exception e, HttpResponseStatus status, @Nullable String simplifiedMessage) {
   StringWriter sw = new StringWriter();
   e.printStackTrace(new PrintWriter(sw));
   StringBuilder sb = new StringBuilder();
   try {
     JsonGenerator jg = jsonFactory.createGenerator(CharStreams.asWriter(sb));
     jg.writeStartObject();
     String message;
     if (simplifiedMessage == null) {
       Throwable cause = e;
       Throwable childCause = cause.getCause();
       while (childCause != null) {
         cause = childCause;
         childCause = cause.getCause();
       }
       message = cause.getMessage();
     } else {
       message = simplifiedMessage;
     }
     jg.writeStringField("message", message);
     jg.writeStringField("stackTrace", sw.toString());
     jg.writeEndObject();
     jg.close();
     return HttpServices.createJsonResponse(sb.toString(), status);
   } catch (IOException f) {
     logger.error(f.getMessage(), f);
     return new DefaultFullHttpResponse(HTTP_1_1, INTERNAL_SERVER_ERROR);
   }
 }
  @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();
  }
Пример #6
0
  private void writeSupportedProperty(
      JsonGenerator jgen,
      String currentVocab,
      ActionInputParameter actionInputParameter,
      String propertyName,
      Property property,
      @SuppressWarnings("unused") Object[] possiblePropertyValues)
      throws IOException {

    jgen.writeStartObject();

    if (actionInputParameter.hasCallValue() || actionInputParameter.hasInputConstraints()) {
      // jgen.writeArrayFieldStart("@type");
      // jgen.writeString("hydra:SupportedProperty");

      jgen.writeStringField(
          JsonLdKeywords.AT_TYPE,
          getPropertyOrClassNameInVocab(
              currentVocab,
              "PropertyValueSpecification",
              LdContextFactory.HTTP_SCHEMA_ORG,
              "schema:"));

      // jgen.writeEndArray();
    }
    jgen.writeStringField("hydra:property", propertyName);

    writePossiblePropertyValues(jgen, currentVocab, actionInputParameter, possiblePropertyValues);

    jgen.writeEndObject();
  }
 private void writeApplication(JsonGenerator jgen, Application application) throws IOException {
   jgen.writeStartObject();
   jgen.writeStringField("applicationName", application.getName());
   jgen.writeStringField("serviceType", application.getServiceType().getDesc());
   jgen.writeNumberField("code", application.getServiceTypeCode());
   jgen.writeEndObject();
 }
Пример #8
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();
    }
 private void addServiceData(JsonGenerator json, ServiceInstance localService) throws IOException {
   json.writeObjectFieldStart("origin");
   json.writeStringField("host", localService.getHost());
   json.writeNumberField("port", localService.getPort());
   json.writeStringField("serviceId", localService.getServiceId());
   if (this.properties.isSendId()) {
     json.writeStringField("id", this.context.getId());
   }
   json.writeEndObject();
 }
Пример #10
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);
    }
  }
Пример #11
0
 @Override
 public void serialize(
     final Interval value, final JsonGenerator gen, final SerializerProvider provider)
     throws IOException {
   gen.writeStartObject();
   gen.writeStringField("startdatetime", formatter.print(value.getStart()));
   gen.writeStringField("starttimezone", value.getStart().getZone().toString());
   gen.writeStringField("enddatetime", formatter.print(value.getEnd()));
   gen.writeStringField("endtimezone", value.getEnd().getZone().toString());
   gen.writeEndObject();
 }
Пример #12
0
 @Override
 public void serialize(
     ServiceType serviceTypeCode,
     JsonGenerator jsonGenerator,
     SerializerProvider serializerProvider)
     throws IOException, JsonProcessingException {
   jsonGenerator.writeStartObject();
   jsonGenerator.writeStringField("code", serviceTypeCode.name());
   jsonGenerator.writeStringField("description", serviceTypeCode.getDisplayName());
   jsonGenerator.writeEndObject();
 }
  @Override
  protected ModelAndView handleRequestInternal(
      final HttpServletRequest request, final HttpServletResponse response) throws Exception {
    String accessToken = request.getParameter(OAuthConstants.ACCESS_TOKEN);
    if (StringUtils.isBlank(accessToken)) {
      final String authHeader = request.getHeader("Authorization");
      if (StringUtils.isNotBlank(authHeader)
          && authHeader.toLowerCase().startsWith(OAuthConstants.BEARER_TOKEN.toLowerCase() + ' ')) {
        accessToken = authHeader.substring(OAuthConstants.BEARER_TOKEN.length() + 1);
      }
    }
    LOGGER.debug("{} : {}", OAuthConstants.ACCESS_TOKEN, accessToken);

    try (final JsonGenerator jsonGenerator =
        this.jsonFactory.createJsonGenerator(response.getWriter())) {
      response.setContentType("application/json");
      // accessToken is required
      if (StringUtils.isBlank(accessToken)) {
        LOGGER.error("Missing {}", OAuthConstants.ACCESS_TOKEN);
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("error", OAuthConstants.MISSING_ACCESS_TOKEN);
        jsonGenerator.writeEndObject();
        return null;
      }
      // get ticket granting ticket
      final TicketGrantingTicket ticketGrantingTicket =
          (TicketGrantingTicket) this.ticketRegistry.getTicket(accessToken);
      if (ticketGrantingTicket == null || ticketGrantingTicket.isExpired()) {
        LOGGER.error("expired accessToken : {}", accessToken);
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("error", OAuthConstants.EXPIRED_ACCESS_TOKEN);
        jsonGenerator.writeEndObject();
        return null;
      }
      // generate profile : identifier + attributes
      final Principal principal = ticketGrantingTicket.getAuthentication().getPrincipal();
      jsonGenerator.writeStartObject();
      jsonGenerator.writeStringField(ID, principal.getId());
      jsonGenerator.writeObjectFieldStart(ATTRIBUTES);
      final Map<String, Object> attributes = principal.getAttributes();
      for (final Map.Entry<String, Object> entry : attributes.entrySet()) {
        //                jsonGenerator.writeStartObject();
        jsonGenerator.writeObjectField(entry.getKey(), entry.getValue());
        //                jsonGenerator.writeEndObject();
      }
      //            jsonGenerator.writeEndArray();
      jsonGenerator.writeEndObject();
      return null;
    } finally {
      response.flushBuffer();
    }
  }
 private void writeValue(String field, Object value, JsonGenerator jg) throws IOException {
   if (value instanceof String) jg.writeStringField(field, (String) value);
   else if (value instanceof Long) jg.writeNumberField(field, (Long) value);
   else if (value instanceof Integer) jg.writeNumberField(field, (Integer) value);
   else if (value instanceof Float) jg.writeNumberField(field, (Float) value);
   else if (value instanceof Double) jg.writeNumberField(field, (Double) value);
   else if (value instanceof Boolean) jg.writeBooleanField(field, (Boolean) value);
   else if (value instanceof Iterable<?>) writeIterableToField(field, (Iterable<?>) value, jg);
   else if (value instanceof MapWrapper<?, ?>)
     writeMapWrapperToField(field, (MapWrapper<?, ?>) value, jg);
   else jg.writeStringField(field, "Unknown");
   jg.flush();
 }
Пример #15
0
 @Override
 public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
   gen.writeStartObject();
   gen.writeStringField(ID_FIELD, id);
   gen.writeObjectField(FROM_FIELD, from);
   if (location != null) {
     gen.writeObjectField(LOCATION_FIELD, location);
   }
   gen.writeStringField(QUERY_FIELD, query);
   gen.writeStringField(OFFSET_FIELD, offset);
   gen.writeEndObject();
   gen.flush();
 }
Пример #16
0
  @Override
  public void serialize(LBMember member, JsonGenerator jGen, SerializerProvider serializer)
      throws IOException, JsonProcessingException {
    jGen.writeStartObject();

    jGen.writeStringField("id", member.id);
    jGen.writeStringField("address", String.valueOf(member.address));
    jGen.writeStringField("port", Short.toString(member.port));
    jGen.writeStringField("poolId", member.poolId);
    jGen.writeStringField("vipId", member.vipId);

    jGen.writeEndObject();
  }
  @Override
  public void serialize(JsonGenerator gen, SerializerProvider serializers) throws IOException {
    gen.writeStartObject();
    gen.writeStringField(TYPE_FIELD, type);
    gen.writeStringField(ID_FIELD, id);
    gen.writeStringField(MPEG4URL_FIELD, this.mpeg4Url);

    if (parseMode != null) {
      gen.writeStringField(PARSEMODE_FIELD, this.parseMode);
    }
    if (disableWebPagePreview != null) {
      gen.writeBooleanField(DISABLEWEBPAGEPREVIEW_FIELD, this.disableWebPagePreview);
    }
    if (mpeg4Width != null) {
      gen.writeNumberField(MPEG4WIDTH_FIELD, this.mpeg4Width);
    }
    if (mpeg4Height != null) {
      gen.writeNumberField(MPEG4HEIGHT_FIELD, this.mpeg4Height);
    }
    if (thumbUrl != null) {
      gen.writeStringField(THUMBURL_FIELD, this.thumbUrl);
    }
    if (title != null) {
      gen.writeStringField(TITLE_FIELD, this.title);
    }
    if (caption != null) {
      gen.writeStringField(CAPTION_FIELD, this.caption);
    }
    if (messageText != null) {
      gen.writeStringField(MESSAGETEXT_FIELD, this.messageText);
    }

    gen.writeEndObject();
    gen.flush();
  }
  private void writeQueryDetails(JsonGenerator jg, Query query) throws IOException {
    if (query.getView() != 20) {
      jg.writeStringField("id", query.getId());
      System.out.print("{ id: " + query.getId());
      jg.writeStringField("cql", query.toCQL());
      System.out.print(", cql: " + query.toCQL());
      if (query.toJSON() != null) jg.writeStringField("json", query.toJSON().toString());
      jg.writeStringField("within", query.getWithin());
      System.out.print(", within: " + query.getWithin());
      jg.writeNumberField("number", query.getLimit());
      System.out.print(", number: " + String.valueOf(query.getLimit()));
      jg.writeNumberField("offset", query.getSkip());
      System.out.print(", offset: " + String.valueOf(query.getSkip()));
    }
    jg.writeStringField("filter", query.getFilter());
    System.out.print(", filter: " + query.getFilter());
    jg.writeNumberField("view", query.getView());
    System.out.print(", view: " + String.valueOf(query.getView()));

    String group = query.getGroup();
    if (group != null && group.length() > 0) {
      jg.writeStringField("group", group);
      System.out.print(", group: " + group);
    }

    if (query.getView() != 20) {
      String sort = query.getSort();
      if (sort != null && sort.length() > 0) {
        jg.writeStringField("sort", sort);
        System.out.print(", sort: " + sort);
      }

      String order = query.getOrder();
      if (order != null && order.length() > 0) {
        jg.writeStringField("order", order);
        System.out.print(", order: " + order);
      }

      String docPid = query.getDocpid();
      if (docPid != null && docPid.length() > 0) {
        jg.writeStringField("docpid", docPid);
        System.out.print(", docpid: " + docPid);
      }
      System.out.print(", count: " + String.valueOf(query.isCountQuery()) + " }");
      System.out.println("");
    }

    jg.writeStringField("cypher", query.toCypher());
    jg.flush();
  }
Пример #19
0
    @Override
    public void serialize(Record record, JsonGenerator jgen, SerializerProvider provider)
        throws IOException, JsonProcessingException {
      jgen.writeStartObject();
      jgen.writeStringField("id", record.getId());
      jgen.writeStringField("type", record.getType());
      jgen.writeStringField("creationDate", record.getTime().toString());

      jgen.writeObjectFieldStart("fields");
      for (Map.Entry<String, Field> entry : record.getFieldsEntrySet()) {
        // retrieve event field
        String fieldName = entry.getKey();
        Field field = entry.getValue();
        Object fieldValue = field.getRawValue();
        String fieldType = field.getType().toString();

        // dump event field as record attribute

        try {
          switch (fieldType.toLowerCase()) {
            case "string":
              jgen.writeStringField(fieldName, (String) fieldValue);
              break;
            case "integer":
              jgen.writeNumberField(fieldName, (int) fieldValue);
              break;
            case "long":
              jgen.writeNumberField(fieldName, (long) fieldValue);
              break;
            case "float":
              jgen.writeNumberField(fieldName, (float) fieldValue);
              break;
            case "double":
              jgen.writeNumberField(fieldName, (double) fieldValue);
              break;
            case "boolean":
              jgen.writeBooleanField(fieldName, (boolean) fieldValue);
              break;
            default:
              jgen.writeObjectField(fieldName, fieldValue);
              break;
          }
        } catch (Exception ex) {
          logger.debug("exception while serializing field {}", field);
        }
      }
      jgen.writeEndObject();
      jgen.writeEndObject();
    }
  @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());
  }
Пример #21
0
 @Override
 public void serialize(XmlBody xmlBody, JsonGenerator jgen, SerializerProvider provider)
     throws IOException {
   jgen.writeStartObject();
   if (xmlBody.getNot() != null && xmlBody.getNot()) {
     jgen.writeBooleanField("not", xmlBody.getNot());
   }
   if (xmlBody.getContentType() != null
       && !xmlBody.getContentType().equals(XmlBody.DEFAULT_CONTENT_TYPE.toString())) {
     jgen.writeStringField("contentType", xmlBody.getContentType());
   }
   jgen.writeStringField("type", xmlBody.getType().name());
   jgen.writeStringField("xml", xmlBody.getValue());
   jgen.writeEndObject();
 }
Пример #22
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();
  }
  public void writeServiceDocument(final JsonGenerator gen) throws IOException {
    gen.writeStartObject();

    if (!isODataMetadataNone) {
      final String metadataUri =
          (serviceRoot == null ? "" : serviceRoot.endsWith("/") ? serviceRoot : (serviceRoot + "/"))
              + Constants.METADATA;
      gen.writeObjectField(Constants.JSON_CONTEXT, metadataUri);

      if (metadata != null
          && metadata.getServiceMetadataETagSupport() != null
          && metadata.getServiceMetadataETagSupport().getMetadataETag() != null) {
        gen.writeStringField(
            Constants.JSON_METADATA_ETAG,
            metadata.getServiceMetadataETagSupport().getMetadataETag());
      }
    }

    gen.writeArrayFieldStart(Constants.VALUE);

    final EdmEntityContainer container = metadata.getEdm().getEntityContainer();
    writeEntitySets(gen, container);
    writeFunctionImports(gen, container);
    writeSingletons(gen, container);
  }
 @Override
 public void serialize(HalReference value, JsonGenerator jgen, SerializerProvider provider)
     throws IOException, JsonGenerationException {
   jgen.writeStartObject();
   if (value.getName() != null && value.getName().length() > 0) {
     jgen.writeStringField("name", value.getName());
   }
   jgen.writeStringField("href", value.getHref());
   if (value.getTitle() != null && value.getTitle().length() > 0) {
     jgen.writeStringField("title", value.getTitle());
   }
   if (value.isTemplated()) {
     jgen.writeBooleanField("templated", true);
   }
   jgen.writeEndObject();
 }
  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();
  }
Пример #26
0
  public void toJson(JsonGenerator jsonGen, DecimalFormat df) {
    try {
      jsonGen.writeStartObject();
      jsonGen.writeStringField("field", this.getField());
      jsonGen.writeNumberField("start", this.getStartOffset());
      jsonGen.writeNumberField("end", this.getEndOffset());
      Rectangle rect = this.getPayload().getRectangle();
      jsonGen.writeNumberField("left", rect.x);
      jsonGen.writeNumberField("top", rect.y);
      jsonGen.writeNumberField("width", rect.width);
      jsonGen.writeNumberField("height", rect.height);
      Rectangle secondaryRect = this.getPayload().getSecondaryRectangle();
      if (secondaryRect != null) {
        jsonGen.writeNumberField("left2", secondaryRect.x);
        jsonGen.writeNumberField("top2", secondaryRect.y);
        jsonGen.writeNumberField("width2", secondaryRect.width);
        jsonGen.writeNumberField("height2", secondaryRect.height);
      }
      jsonGen.writeNumberField("pageIndex", this.getPayload().getPageIndex());
      jsonGen.writeNumberField("paragraphIndex", this.getPayload().getParagraphIndex());
      jsonGen.writeNumberField("rowIndex", this.getPayload().getRowIndex());
      double roundedWeight = df.parse(df.format(this.getWeight())).doubleValue();
      jsonGen.writeNumberField("weight", roundedWeight);
      jsonGen.writeEndObject();

      jsonGen.flush();
    } catch (java.text.ParseException e) {
      LOG.error("Failed write highlightTerm to JSON in docId " + docId, e);
      throw new RuntimeException(e);
    } catch (IOException e) {
      LOG.error("Failed write highlightTerm to JSON in docId " + docId, e);
      throw new RuntimeException(e);
    }
  }
Пример #27
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();
   }
 }
Пример #28
0
  @Ignore
  @Test
  public void testBulkUpdate() throws IOException {

    ResetBasicData.reset();

    EbeanServer server = Ebean.getServer(null);
    JsonContext jsonContext = server.json();

    StringWriter writer = new StringWriter();
    JsonGenerator generator = jsonContext.createGenerator(writer);

    List<Customer> customers = Ebean.find(Customer.class).findList();

    for (Customer customer : customers) {

      customer.setName(customer.getName() + "esMod");
      PathProperties updateProps = PathProperties.parse("name");

      generator.writeStartObject();
      generator.writeFieldName("update");
      generator.writeStartObject();
      generator.writeStringField("_id", customer.getId().toString());
      generator.writeStringField("_type", "customer");
      generator.writeStringField("_index", "customer");
      generator.writeEndObject();
      generator.writeEndObject();
      generator.writeRaw("\n");

      generator.writeStartObject();
      generator.writeFieldName("doc");
      jsonContext.toJson(customer, generator, updateProps);
      generator.writeEndObject();
      generator.writeRaw("\n");
    }

    generator.close();
    String json = writer.toString();

    post("http://localhost:9200/_bulk", json);

    // curl -s -XPOST localhost:9200/_bulk

    //    { "update" : {"_id" : "1", "_type" : "type1", "_index" : "index1"} }
    //    { "doc" : {"field2" : "value2"} }

  }
Пример #29
0
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {
    String sid = req.getParameter("sid");
    String gameId = req.getParameter("game");
    String action = req.getParameter("action");

    HanabiUser user = s.getUserBySession(sid);
    HanabiGame game = s.getGame(gameId);

    try {

      String message;
      if (action.equals("play_card")) {
        int slot = Integer.parseInt(req.getParameter("handSlot"));
        HanabiGame.PlayCardResult rv = game.playCard(slot);
        message = "It was a " + rv.card + "; " + (rv.success ? "Success!" : "Oops!");
      } else if (action.equals("discard_card")) {
        int slot = Integer.parseInt(req.getParameter("handSlot"));
        HanabiGame.Card c = game.discardCard(slot);
        message = "It was a " + c;
      } else if (action.equals("give_hint")) {
        doGiveHint(game, req, resp);
        return;
      } else {
        message = "don't know how to " + action;
      }

      JsonGenerator out = new JsonFactory().createJsonGenerator(resp.getOutputStream());

      out.writeStartObject();
      out.writeStringField("message", message);
      out.writeEndObject();
      out.close();

    } catch (HanabiException e) {

      resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

      JsonGenerator out = new JsonFactory().createJsonGenerator(resp.getOutputStream());
      out.writeStartObject();
      out.writeStringField("status", "error");
      out.writeStringField("message", e.toString());
      out.writeEndObject();
      out.close();
    }
  }
  @Override
  public void serialize(Link link, JsonGenerator jg, SerializerProvider sp)
      throws IOException, JsonProcessingException {

    jg.writeStartObject();
    jg.writeStringField("href", link.getUri().toString());
    jg.writeEndObject();
  }