/** Unit test to check for regression of [JACKSON-18]. */
  public void testSmallNumbers() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode root = mapper.createArrayNode();
    for (int i = -20; i <= 20; ++i) {
      JsonNode n = root.numberNode(i);
      root.add(n);
      // Hmmh. Not sure why toString() won't be triggered otherwise...
      assertEquals(String.valueOf(i), n.toString());
    }

    // Loop over 2 different serialization methods
    for (int type = 0; type < 2; ++type) {
      StringWriter sw = new StringWriter();
      if (type == 0) {
        JsonGenerator gen = new JsonFactory().createGenerator(sw);
        root.serialize(gen, null);
        gen.close();
      } else {
        mapper.writeValue(sw, root);
      }

      String doc = sw.toString();
      JsonParser p = new JsonFactory().createParser(new StringReader(doc));

      assertEquals(JsonToken.START_ARRAY, p.nextToken());
      for (int i = -20; i <= 20; ++i) {
        assertEquals(JsonToken.VALUE_NUMBER_INT, p.nextToken());
        assertEquals(i, p.getIntValue());
        assertEquals("" + i, p.getText());
      }
      assertEquals(JsonToken.END_ARRAY, p.nextToken());
      p.close();
    }
  }
 /** Method called to configure the generator as necessary and then call write functionality */
 protected final void _configAndWriteValue(JsonGenerator jgen, Object value)
     throws IOException, JsonGenerationException, JsonMappingException {
   _configureJsonGenerator(jgen);
   // [JACKSON-282]: consider Closeable
   if (_config.isEnabled(SerializationFeature.CLOSE_CLOSEABLE) && (value instanceof Closeable)) {
     _writeCloseable(jgen, value, _config);
     return;
   }
   boolean closed = false;
   try {
     if (_rootType == null) {
       _serializerProvider(_config).serializeValue(jgen, value);
     } else {
       _serializerProvider(_config).serializeValue(jgen, value, _rootType, _rootSerializer);
     }
     closed = true;
     jgen.close();
   } finally {
     /* won't try to close twice; also, must catch exception (so it
      * will not mask exception that is pending)
      */
     if (!closed) {
       try {
         jgen.close();
       } catch (IOException ioe) {
       }
     }
   }
 }
  public void testFromArray() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ArrayNode root = mapper.createArrayNode();
    root.add(TEXT1);
    root.add(3);
    ObjectNode obj = root.addObject();
    obj.put(FIELD1, true);
    obj.putArray(FIELD2);
    root.add(false);

    /* Ok, ready... let's serialize using one of two alternate
     * methods: first preferred (using generator)
     * (there are 2 variants here too)
     */
    for (int i = 0; i < 2; ++i) {
      StringWriter sw = new StringWriter();
      if (i == 0) {
        JsonGenerator gen = new JsonFactory().createGenerator(sw);
        root.serialize(gen, null);
        gen.close();
      } else {
        mapper.writeValue(sw, root);
      }
      verifyFromArray(sw.toString());
    }

    // And then convenient but less efficient alternative:
    verifyFromArray(root.toString());
  }
  public void testFromMap() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode root = mapper.createObjectNode();
    root.put(FIELD4, TEXT2);
    root.put(FIELD3, -1);
    root.putArray(FIELD2);
    root.put(FIELD1, DOUBLE_VALUE);

    /* Let's serialize using one of two alternate methods:
     * first preferred (using generator)
     * (there are 2 variants here too)
     */
    for (int i = 0; i < 2; ++i) {
      StringWriter sw = new StringWriter();
      if (i == 0) {
        JsonGenerator gen = new JsonFactory().createGenerator(sw);
        root.serialize(gen, null);
        gen.close();
      } else {
        mapper.writeValue(sw, root);
      }
      verifyFromMap(sw.toString());
    }

    // And then convenient but less efficient alternative:
    verifyFromMap(root.toString());
  }
 /**
  * Helper method used when value to serialize is {@link Closeable} and its <code>close()</code>
  * method is to be called right after serialization has been called
  */
 private final void _writeCloseable(JsonGenerator jgen, Object value, SerializationConfig cfg)
     throws IOException, JsonGenerationException, JsonMappingException {
   Closeable toClose = (Closeable) value;
   try {
     if (_rootType == null) {
       _serializerProvider(cfg).serializeValue(jgen, value);
     } else {
       _serializerProvider(cfg).serializeValue(jgen, value, _rootType, _rootSerializer);
     }
     JsonGenerator tmpJgen = jgen;
     jgen = null;
     tmpJgen.close();
     Closeable tmpToClose = toClose;
     toClose = null;
     tmpToClose.close();
   } finally {
     /* Need to close both generator and value, as long as they haven't yet
      * been closed
      */
     if (jgen != null) {
       try {
         jgen.close();
       } catch (IOException ioe) {
       }
     }
     if (toClose != null) {
       try {
         toClose.close();
       } catch (IOException ioe) {
       }
     }
   }
 }
 /**
  * Method called after an object field has been output, but before the value is output.
  *
  * <p>Default handling (without pretty-printing) will output a single colon to separate the two.
  * Pretty-printer is to output a colon as well, but can surround that with other (white-space)
  * decoration.
  */
 @Override
 public void writeObjectFieldValueSeparator(JsonGenerator jg) throws IOException {
   if (_spacesInObjectEntries) {
     jg.writeRaw(" : ");
   } else {
     jg.writeRaw(':');
   }
 }
 @Override
 public final byte[] serialize(MediaContent content) throws IOException {
   ByteArrayOutputStream baos = outputStream(content);
   JsonGenerator generator = constructGenerator(baos);
   writeMediaContent(generator, content);
   generator.close();
   return baos.toByteArray();
 }
 @Override
 public final void serializeItems(MediaContent[] items, OutputStream out) throws IOException {
   JsonGenerator generator = constructGenerator(out);
   // JSON allows simple sequences, so:
   for (int i = 0, len = items.length; i < len; ++i) {
     writeMediaContent(generator, items[i]);
   }
   generator.close();
 }
  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();
  }
 @Override
 public void writeEndArray(JsonGenerator gen, int nrOfValues) throws IOException {
   if (!_arrayIndenter.isInline()) {
     --_nesting;
   }
   if (nrOfValues > 0) {
     _arrayIndenter.writeIndentation(gen, _nesting);
   } else {
     gen.writeRaw(' ');
   }
   gen.writeRaw(']');
 }
 @Override
 public void writeEndObject(JsonGenerator jg, int nrOfEntries) throws IOException {
   if (!_objectIndenter.isInline()) {
     --_nesting;
   }
   if (nrOfEntries > 0) {
     _objectIndenter.writeIndentation(jg, _nesting);
   } else {
     jg.writeRaw(' ');
   }
   jg.writeRaw('}');
 }
 public void testInvalidArrayWrite() throws Exception {
   StringWriter sw = new StringWriter();
   JsonGenerator gen = new JsonFactory().createGenerator(sw);
   gen.writeStartArray();
   // Mismatch:
   try {
     gen.writeEndObject();
     fail("Expected an exception for mismatched array/object write");
   } catch (JsonGenerationException e) {
     verifyException(e, "Current context not an object");
   }
   gen.close();
 }
Beispiel #13
0
  void doGiveHint(HanabiGame game, HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException, HanabiException {
    String target = req.getParameter("target");
    String hint = req.getParameter("hint");

    game.giveHint(target, hint);

    JsonGenerator out = new JsonFactory().createJsonGenerator(resp.getOutputStream());
    out.writeStartObject();
    out.writeStringField("message", "hint given; " + game.hintsLeft + " hints left");
    out.writeEndObject();
    out.close();
  }
 @Override
 public void writeStartObject(JsonGenerator jg) throws IOException {
   jg.writeRaw('{');
   if (!_objectIndenter.isInline()) {
     ++_nesting;
   }
 }
 @Override
 public void writeStartArray(JsonGenerator jg) throws IOException {
   if (!_arrayIndenter.isInline()) {
     ++_nesting;
   }
   jg.writeRaw('[');
 }
Beispiel #16
0
  private void process(File input) throws IOException {
    JsonFactory jsonF = new JsonFactory();
    JsonParser jp = jsonF.createJsonParser(input);
    TwitterEntry entry = read(jp);

    // let's write to a file, using UTF-8 encoding (only sensible one)
    StringWriter strw = new StringWriter();
    JsonGenerator jg = jsonF.createJsonGenerator(strw);
    jg.useDefaultPrettyPrinter(); // enable indentation just to make debug/testing easier

    // Here we would modify it... for now, will just (re)indent it

    write(jg, entry);

    System.out.println("Result = [" + strw.toString() + "]");
  }
Beispiel #17
0
 private void write(JsonGenerator jg, TwitterEntry entry) throws IOException {
   jg.writeStartObject();
   // can either do "jg.writeFieldName(...) + jg.writeNumber()", or this:
   jg.writeNumberField("id", entry.getId());
   jg.writeStringField("text", entry.getText());
   jg.writeNumberField("fromUserId", entry.getFromUserId());
   jg.writeNumberField("toUserId", entry.getToUserId());
   jg.writeStringField("langugeCode", entry.getLanguageCode());
   jg.writeEndObject();
   jg.close();
 }
 /**
  * Helper method called to set or override settings of passed-in {@link JsonGenerator}
  *
  * @since 2.1
  */
 private final void _configureJsonGenerator(JsonGenerator jgen) {
   if (_prettyPrinter != null) {
     PrettyPrinter pp = _prettyPrinter;
     if (pp == NULL_PRETTY_PRINTER) {
       jgen.setPrettyPrinter(null);
     } else {
       /* [JACKSON-851]: Better take care of stateful PrettyPrinters...
        *   like the DefaultPrettyPrinter.
        */
       if (pp instanceof Instantiatable<?>) {
         pp = (PrettyPrinter) ((Instantiatable<?>) pp).createInstance();
       }
       jgen.setPrettyPrinter(pp);
     }
   } else if (_config.isEnabled(SerializationFeature.INDENT_OUTPUT)) {
     jgen.useDefaultPrettyPrinter();
   }
   // [JACKSON-520]: add support for pass-through schema:
   if (_schema != null) {
     jgen.setSchema(_schema);
   }
 }
 /**
  * Method that can be used to serialize any Java value as JSON output, using provided {@link
  * JsonGenerator}.
  */
 public void writeValue(JsonGenerator jgen, Object value)
     throws IOException, JsonGenerationException, JsonMappingException {
   // 10-Aug-2012, tatu: As per [Issue#12], may need to force PrettyPrinter settings, so:
   _configureJsonGenerator(jgen);
   if (_config.isEnabled(SerializationFeature.CLOSE_CLOSEABLE) && (value instanceof Closeable)) {
     _writeCloseableValue(jgen, value, _config);
   } else {
     if (_rootType == null) {
       _serializerProvider(_config).serializeValue(jgen, value);
     } else {
       _serializerProvider(_config).serializeValue(jgen, value, _rootType, _rootSerializer);
     }
     if (_config.isEnabled(SerializationFeature.FLUSH_AFTER_WRITE_VALUE)) {
       jgen.flush();
     }
   }
 }
 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();
 }
 public void testSimpleArrayWrite() throws Exception {
   StringWriter sw = new StringWriter();
   JsonGenerator gen = new JsonFactory().createGenerator(sw);
   gen.writeStartArray();
   gen.writeNumber(13);
   gen.writeBoolean(true);
   gen.writeString("foobar");
   gen.writeEndArray();
   gen.close();
   String docStr = sw.toString();
   JsonParser jp = createParserUsingReader(docStr);
   assertEquals(JsonToken.START_ARRAY, jp.nextToken());
   assertEquals(JsonToken.VALUE_NUMBER_INT, jp.nextToken());
   assertEquals(13, jp.getIntValue());
   assertEquals(JsonToken.VALUE_TRUE, jp.nextToken());
   assertEquals(JsonToken.VALUE_STRING, jp.nextToken());
   assertEquals("foobar", jp.getText());
   assertEquals(JsonToken.END_ARRAY, jp.nextToken());
   assertEquals(null, jp.nextToken());
   jp.close();
 }
 /**
  * Helper method used when value to serialize is {@link Closeable} and its <code>close()</code>
  * method is to be called right after serialization has been called
  */
 private final void _writeCloseableValue(JsonGenerator jgen, Object value, SerializationConfig cfg)
     throws IOException, JsonGenerationException, JsonMappingException {
   Closeable toClose = (Closeable) value;
   try {
     if (_rootType == null) {
       _serializerProvider(cfg).serializeValue(jgen, value);
     } else {
       _serializerProvider(cfg).serializeValue(jgen, value, _rootType, _rootSerializer);
     }
     if (_config.isEnabled(SerializationFeature.FLUSH_AFTER_WRITE_VALUE)) {
       jgen.flush();
     }
     Closeable tmpToClose = toClose;
     toClose = null;
     tmpToClose.close();
   } finally {
     if (toClose != null) {
       try {
         toClose.close();
       } catch (IOException ioe) {
       }
     }
   }
 }
 @Override
 public void writeIndentation(JsonGenerator jg, int level) throws IOException {
   jg.writeRaw(' ');
 }
Beispiel #24
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();
    }
  }
 /**
  * Method called after an array value has been completely output, and before another value is to
  * be output.
  *
  * <p>Default handling (without pretty-printing) will output a single comma to separate the two.
  * Pretty-printer is to output a comma as well, but can surround that with other (white-space)
  * decoration.
  */
 @Override
 public void writeArrayValueSeparator(JsonGenerator gen) throws IOException {
   gen.writeRaw(',');
   _arrayIndenter.writeIndentation(gen, _nesting);
 }
Beispiel #26
0
  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws IOException, ServletException {
    String sid = req.getParameter("sid");
    String gameId = req.getParameter("game");

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

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

    out.writeStartObject();
    out.writeStringField("id", gameId);
    out.writeStringField("nextEvent", Integer.toString(game.events.getNextId()));
    out.writeNumberField("drawPile", game.drawPile.size());
    out.writeNumberField("hintsLeft", game.hintsLeft);
    out.writeNumberField("errorsMade", game.errorsMade);
    out.writeNumberField("turnNumber", game.turn);
    out.writeStringField("activePlayer", Integer.toString(game.activeSeat));

    out.writeFieldName("seats");
    out.writeStartArray();
    for (int i = 0; i < game.seats.size(); i++) {
      HanabiGame.Seat seat = game.seats.get(i);
      out.writeStartObject();
      out.writeStringField("seat", Integer.toString(i));
      out.writeStringField("playerName", seat.user.name);
      if (seat.user == user) {
        out.writeBooleanField("isYou", true);
      }
      out.writeFieldName("hand");
      out.writeStartArray();
      for (HanabiGame.Card c : seat.hand) {
        if (seat.user == user) {
          out.writeString("unknown");
        } else {
          out.writeString(c.toString());
        }
      }
      out.writeEndArray();
      out.writeEndObject();
    }
    out.writeEndArray(); // end seats

    out.writeFieldName("piles");
    out.writeStartObject();
    for (int i = 0; i < HanabiGame.SUIT_COUNT; i++) {
      HanabiGame.Card c = game.getPileTopCard(i);
      if (c != null) {
        out.writeStringField(c.getSuitName(), c.toString());
      }
    }
    out.writeEndObject(); // end piles

    out.writeFieldName("discards");
    out.writeStartArray();
    for (HanabiGame.Card c : game.discards) {
      out.writeString(c.toString());
    }
    out.writeEndArray();

    out.writeFieldName("hints");
    out.writeStartArray();
    for (HanabiGame.Hint h : game.hints) {
      out.writeStartObject();
      out.writeNumberField("turn", h.whenGiven);
      out.writeStringField("from", Integer.toString(h.from));
      out.writeStringField("to", Integer.toString(h.to));
      out.writeStringField("hintType", h.type.name());
      out.writeStringField("hint", h.getHintString());

      HanabiGame.Seat targetSeat = game.seats.get(h.to);
      out.writeFieldName("applies");
      out.writeStartArray();
      for (int slot = 0; slot < targetSeat.hand.size(); slot++) {
        if (targetSeat.whenReceived.get(slot).intValue() > h.whenGiven) {
          out.writeString("");
        } else if (h.affirms(targetSeat.hand.get(slot))) {
          out.writeString("Y");
        } else {
          out.writeString("N");
        }
      }
      out.writeEndArray();
      out.writeEndObject();
    }
    out.writeEndArray(); // end hints

    out.writeEndObject(); // end game
    out.close();
  }
 /**
  * Method called after an object entry (field:value) has been completely output, and before
  * another value is to be output.
  *
  * <p>Default handling (without pretty-printing) will output a single comma to separate the two.
  * Pretty-printer is to output a comma as well, but can surround that with other (white-space)
  * decoration.
  */
 @Override
 public void writeObjectEntrySeparator(JsonGenerator jg) throws IOException {
   jg.writeRaw(',');
   _objectIndenter.writeIndentation(jg, _nesting);
 }
 private void writeMedia(JsonGenerator generator, Media media) throws IOException {
   generator.writeStartObject();
   generator.writeFieldName(FIELD_PLAYER);
   generator.writeString(media.player.name());
   generator.writeFieldName(FIELD_URI);
   generator.writeString(media.uri);
   if (media.title != null) {
     generator.writeFieldName(FIELD_TITLE);
     generator.writeString(media.title);
   }
   generator.writeFieldName(FIELD_WIDTH);
   generator.writeNumber(media.width);
   generator.writeFieldName(FIELD_HEIGHT);
   generator.writeNumber(media.height);
   generator.writeFieldName(FIELD_FORMAT);
   generator.writeString(media.format);
   generator.writeFieldName(FIELD_DURATION);
   generator.writeNumber(media.duration);
   generator.writeFieldName(FIELD_SIZE);
   generator.writeNumber(media.size);
   if (media.hasBitrate) {
     generator.writeFieldName(FIELD_BITRATE);
     generator.writeNumber(media.bitrate);
   }
   if (media.copyright != null) {
     generator.writeFieldName(FIELD_COPYRIGHT);
     generator.writeString(media.copyright);
   }
   generator.writeFieldName(FIELD_PERSONS);
   generator.writeStartArray();
   for (String person : media.persons) {
     generator.writeString(person);
   }
   generator.writeEndArray();
   generator.writeEndObject();
 }
 private void writeImage(JsonGenerator generator, Image image) throws IOException {
   generator.writeStartObject();
   generator.writeFieldName(FIELD_URI);
   generator.writeString(image.uri);
   if (image.title != null) {
     generator.writeFieldName(FIELD_TITLE);
     generator.writeString(image.title);
   }
   generator.writeFieldName(FIELD_WIDTH);
   generator.writeNumber(image.width);
   generator.writeFieldName(FIELD_HEIGHT);
   generator.writeNumber(image.height);
   generator.writeFieldName(FIELD_SIZE);
   generator.writeString(image.size.name());
   generator.writeEndObject();
 }
 @Override
 public void writeRootValueSeparator(JsonGenerator jg) throws IOException {
   if (_rootSeparator != null) {
     jg.writeRaw(_rootSeparator);
   }
 }