コード例 #1
0
  @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();
  }
コード例 #2
0
 @Override
 public void serialize(ShareFolderJobStatus value, JsonGenerator g)
     throws IOException, JsonGenerationException {
   switch (value.tag()) {
     case IN_PROGRESS:
       {
         g.writeString("in_progress");
         break;
       }
     case COMPLETE:
       {
         g.writeStartObject();
         writeTag("complete", g);
         SharedFolderMetadata.Serializer.INSTANCE.serialize(value.completeValue, g, true);
         g.writeEndObject();
         break;
       }
     case FAILED:
       {
         g.writeStartObject();
         writeTag("failed", g);
         g.writeFieldName("failed");
         ShareFolderError.Serializer.INSTANCE.serialize(value.failedValue, g);
         g.writeEndObject();
         break;
       }
     default:
       {
         throw new IllegalArgumentException("Unrecognized tag: " + value.tag());
       }
   }
 }
コード例 #3
0
 @Override
 public void serialize(FileMemberRemoveActionResult value, JsonGenerator g)
     throws IOException, JsonGenerationException {
   switch (value.tag()) {
     case SUCCESS:
       {
         g.writeStartObject();
         writeTag("success", g);
         MemberAccessLevelResult.Serializer.INSTANCE.serialize(value.successValue, g, true);
         g.writeEndObject();
         break;
       }
     case MEMBER_ERROR:
       {
         g.writeStartObject();
         writeTag("member_error", g);
         g.writeFieldName("member_error");
         FileMemberActionError.Serializer.INSTANCE.serialize(value.memberErrorValue, g);
         g.writeEndObject();
         break;
       }
     default:
       {
         g.writeString("other");
       }
   }
 }
コード例 #4
0
  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();
  }
コード例 #5
0
    @Override
    public void serialize(Volumes volumes, JsonGenerator jsonGen, SerializerProvider serProvider)
        throws IOException, JsonProcessingException {

      jsonGen.writeStartObject();
      for (Volume volume : volumes.getVolumes()) {
        jsonGen.writeFieldName(volume.getPath());
        jsonGen.writeStartObject();
        jsonGen.writeEndObject();
      }
      jsonGen.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();
    }
  }
コード例 #7
0
 @Override
 public void writeCustomTypePrefixForObject(Object value, JsonGenerator jgen, String typeId)
     throws IOException {
   if (typeId == null) {
     jgen.writeStartObject();
   } else if (jgen.canWriteTypeId()) {
     jgen.writeTypeId(typeId);
     jgen.writeStartObject();
   } else {
     jgen.writeStartObject();
     jgen.writeStringField(_typePropertyName, typeId);
   }
 }
コード例 #8
0
 @Override
 public void writeTypePrefixForObject(Object value, JsonGenerator jgen, Class<?> type)
     throws IOException {
   final String typeId = idFromValueAndType(value, type);
   if (typeId == null) {
     jgen.writeStartObject();
   } else if (jgen.canWriteTypeId()) {
     jgen.writeTypeId(typeId);
     jgen.writeStartObject();
   } else {
     jgen.writeStartObject();
     jgen.writeStringField(_typePropertyName, typeId);
   }
 }
コード例 #9
0
  @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());
  }
コード例 #10
0
 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();
 }
コード例 #11
0
  @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();
  }
コード例 #12
0
    @Override
    public void serialize(ThriftReply value, JsonGenerator gen, SerializerProvider provider)
        throws IOException {
      if (value == null) {
        // Oneway function doesn't provide reply
        gen.writeNull();
        return;
      }

      gen.writeStartObject();

      gen.writeObjectField("header", value.header());

      final TBase<?, ?> result;
      final TApplicationException exception;
      if (value.isException()) {
        result = null;
        exception = value.exception();
      } else {
        result = value.result();
        exception = null;
      }

      gen.writeObjectField("result", result);
      gen.writeObjectField("exception", exception);

      gen.writeEndObject();
    }
コード例 #13
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);
   }
 }
コード例 #14
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();
  }
コード例 #15
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();
  }
コード例 #16
0
  @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();
  }
コード例 #17
0
ファイル: HighlightTerm.java プロジェクト: amitdo/jochre
  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);
    }
  }
コード例 #18
0
 @Override
 public void serialize(UserMembershipInfo value, JsonGenerator g, boolean collapse)
     throws IOException, JsonGenerationException {
   if (!collapse) {
     g.writeStartObject();
   }
   g.writeFieldName("access_type");
   AccessLevel.Serializer.INSTANCE.serialize(value.accessType, g);
   g.writeFieldName("user");
   UserInfo.Serializer.INSTANCE.serialize(value.user, g);
   if (value.permissions != null) {
     g.writeFieldName("permissions");
     StoneSerializers.nullable(StoneSerializers.list(MemberPermission.Serializer.INSTANCE))
         .serialize(value.permissions, g);
   }
   if (value.initials != null) {
     g.writeFieldName("initials");
     StoneSerializers.nullable(StoneSerializers.string()).serialize(value.initials, g);
   }
   g.writeFieldName("is_inherited");
   StoneSerializers.boolean_().serialize(value.isInherited, g);
   if (!collapse) {
     g.writeEndObject();
   }
 }
コード例 #19
0
  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;
    }
  }
コード例 #20
0
 @Override
 public void serialize(UploadSessionLookupError value, JsonGenerator g)
     throws IOException, JsonGenerationException {
   switch (value.tag()) {
     case NOT_FOUND:
       {
         g.writeString("not_found");
         break;
       }
     case INCORRECT_OFFSET:
       {
         g.writeStartObject();
         writeTag("incorrect_offset", g);
         UploadSessionOffsetError.Serializer.INSTANCE.serialize(
             value.incorrectOffsetValue, g, true);
         g.writeEndObject();
         break;
       }
     case CLOSED:
       {
         g.writeString("closed");
         break;
       }
     case NOT_CLOSED:
       {
         g.writeString("not_closed");
         break;
       }
     default:
       {
         g.writeString("other");
       }
   }
 }
コード例 #21
0
  @Test
  public void test1() throws IOException {

    MapData ld0 = new MapData();
    ld0.put("Copyright", "\u00A9 2014, David R. Smith. All Rights Reserved");
    ld0.put("License", "http://www.apache.org/licenses/LICENSE-2.0.txt");

    MapData ld1 = new MapData();
    ld1.put("some key", "some data");
    ld1.put("another key", "more data");
    MapDataFormatter format = new MapDataFormatter();
    format.add(ld0);
    format.add(ld1);

    StringWriter writer = new StringWriter();
    JsonFactory f = new JsonFactory();
    JsonGenerator g = null;
    try {
      g = f.createGenerator(writer);
      g.useDefaultPrettyPrinter();
      g.writeStartObject();
      format.format(g, writer);
      g.writeEndObject();
    } finally {
      g.close();
    }

    System.err.println(writer.toString());

    MapIterator iter3 = new MapDataContentsIterator(ld0);
    while (iter3.hasNext()) {
      String label = iter3.next();
      Assert.assertNotNull(iter3.get(label));
    }
  }
コード例 #22
0
  @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();
  }
コード例 #23
0
  @Override
  public void serialize(IResult value, JsonGenerator jgen, SerializerProvider provider)
      throws IOException {
    // output the custom Json
    jgen.writeStartObject();

    // jgen.writeFieldName("rcode");
    jgen.writeFieldName("resultCode");
    jgen.writeNumber(value.getErrcode());

    //		jgen.writeFieldName("errmsg");
    //		jgen.writeString(value.toString());

    String msg;
    if (value.getErrmsg() != null && value.getErrmsg().equals("") == false) {
      msg = value.getErrmsg();
    } else {
      if (value.getErrcode() == 0) {
        msg = succMessages.getMessage(value.toString(), value.getArgs(), value.toString());
      } else {
        msg = failMessages.getMessage(value.toString(), value.getArgs(), value.toString());
      }
    }
    if (msg != null && msg.equals("") == false) {
      jgen.writeFieldName("resultMsg");
      jgen.writeString(msg);
    }

    // end tag
    jgen.writeEndObject();
  }
コード例 #24
0
  @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);
    }
  }
コード例 #25
0
  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);
  }
コード例 #26
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();
    }
  }
コード例 #27
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"} }

  }
コード例 #28
0
ファイル: GraphSONVertex.java プロジェクト: ngbinh/tinkerpop3
    @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();
    }
コード例 #29
0
  @Override
  public void serialize(Link link, JsonGenerator jg, SerializerProvider sp)
      throws IOException, JsonProcessingException {

    jg.writeStartObject();
    jg.writeStringField("href", link.getUri().toString());
    jg.writeEndObject();
  }
コード例 #30
0
  /**
   * The method to be called by {@link ObjectMapper} and {@link ObjectWriter} for serializing given
   * value, using serializers that this provider has access to (via caching and/or creating new
   * serializers as need be).
   */
  public void serializeValue(JsonGenerator jgen, Object value)
      throws IOException, JsonGenerationException {
    JsonSerializer<Object> ser;
    final boolean wrap;

    if (value == null) { // no type provided; must just use the default null serializer
      ser = getDefaultNullValueSerializer();
      wrap = false; // no name to use for wrapping; can't do!
    } else {
      Class<?> cls = value.getClass();
      // true, since we do want to cache root-level typed serializers (ditto for null property)
      ser = findTypedValueSerializer(cls, true, null);

      // Ok: should we wrap result in an additional property ("root name")?
      String rootName = _config.getRootName();
      if (rootName == null) { // not explicitly specified
        // [JACKSON-163]
        wrap = _config.isEnabled(SerializationFeature.WRAP_ROOT_VALUE);
        if (wrap) {
          jgen.writeStartObject();
          jgen.writeFieldName(_rootNames.findRootName(value.getClass(), _config));
        }
      } else if (rootName.length() == 0) {
        wrap = false;
      } else { // [JACKSON-764]
        // empty String means explicitly disabled; non-empty that it is enabled
        wrap = true;
        jgen.writeStartObject();
        jgen.writeFieldName(rootName);
      }
    }
    try {
      ser.serialize(value, jgen, this);
      if (wrap) {
        jgen.writeEndObject();
      }
    } catch (IOException ioe) { // As per [JACKSON-99], pass IOException and subtypes as-is
      throw ioe;
    } catch (Exception e) { // but wrap RuntimeExceptions, to get path information
      String msg = e.getMessage();
      if (msg == null) {
        msg = "[no message for " + e.getClass().getName() + "]";
      }
      throw new JsonMappingException(msg, e);
    }
  }