/** 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();
    }
  }
Пример #2
0
 /** 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) {
       }
     }
   }
 }
Пример #3
0
 /**
  * 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) {
       }
     }
   }
 }
  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();
  }
Пример #5
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();
  }
Пример #6
0
  public static String objectToJson(Object object) {

    JsonGenerator jsonGenerator = null;
    ObjectMapper objectMapper = new ObjectMapper();
    ByteArrayOutputStream out = null;
    String json = null;
    try {
      try {

        String jsonStr = "";
        out = new ByteArrayOutputStream();
        jsonGenerator = objectMapper.getFactory().createGenerator(out, JsonEncoding.UTF8);
        jsonGenerator.writeObject(object);
        json = new String(out.toByteArray(), Charset.forName("UTF-8"));
        out.toString();
        System.out.println(json);
      } finally {
        if (jsonGenerator != null) {
          jsonGenerator.flush();
        }
        if (!jsonGenerator.isClosed()) {
          jsonGenerator.close();
        }
        if (out != null) {
          out.close();
        }
        jsonGenerator = null;
        objectMapper = null;
      }
    } catch (Exception e) {

    }
    return json;
  }
  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());
  }
  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());
  }
Пример #9
0
 protected String writeTree(TreeCodec treeCodec, TreeNode treeNode) throws IOException {
   StringWriter writer = new StringWriter();
   JsonGenerator g = _factory.createGenerator(writer);
   treeCodec.writeTree(g, treeNode);
   g.close();
   return writer.toString();
 }
  @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\"}"));
  }
Пример #11
0
  public void jsonSerializeTree(final ObjectMapper mapper, final OutputStream output)
      throws IOException {

    final JsonGenerator generator = mapper.getFactory().createJsonGenerator(output);
    generator.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);

    walkTree(
        new WalkCallback() {

          private int curDepth = 0;

          @Override
          public void onCurrentNode(
              final int depth, final NodeInterval curNode, final NodeInterval parent) {
            final ItemsNodeInterval node = (ItemsNodeInterval) curNode;
            if (node.isRoot()) {
              return;
            }

            try {
              if (curDepth < depth) {
                generator.writeStartArray();
                curDepth = depth;
              } else if (curDepth > depth) {
                generator.writeEndArray();
                curDepth = depth;
              }
              generator.writeObject(node);
            } catch (IOException e) {
              throw new RuntimeException("Failed to deserialize tree", e);
            }
          }
        });
    generator.close();
  }
Пример #12
0
  public void testUtf8Issue462() throws Exception {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    IOContext ioc = new IOContext(new BufferRecycler(), bytes, true);
    JsonGenerator gen = new UTF8JsonGenerator(ioc, 0, null, bytes);
    String str = "Natuurlijk is alles gelukt en weer een tevreden klant\uD83D\uDE04";
    int length = 4000 - 38;

    for (int i = 1; i <= length; ++i) {
      gen.writeNumber(1);
    }
    gen.writeString(str);
    gen.flush();
    gen.close();

    // Also verify it's parsable?
    JsonFactory f = new JsonFactory();
    JsonParser p = f.createParser(bytes.toByteArray());
    for (int i = 1; i <= length; ++i) {
      assertToken(JsonToken.VALUE_NUMBER_INT, p.nextToken());
      assertEquals(1, p.getIntValue());
    }
    assertToken(JsonToken.VALUE_STRING, p.nextToken());
    assertEquals(str, p.getText());
    assertNull(p.nextToken());
    p.close();
  }
Пример #13
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));
    }
  }
  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;
    }
  }
Пример #15
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);
   }
 }
 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()
Пример #17
0
 public String serializeMap(Map<String, T> translator) throws IOException {
   StringWriter stringWriter = new StringWriter();
   JsonGenerator generator = Acela.JSON_FACTORY.createGenerator(stringWriter);
   serializeMap(generator, translator);
   generator.close();
   return stringWriter.toString();
 }
Пример #18
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 final byte[] serialize(MediaContent content) throws IOException {
   ByteArrayOutputStream baos = outputStream(content);
   JsonGenerator generator = constructGenerator(baos);
   writeMediaContent(generator, content);
   generator.close();
   return baos.toByteArray();
 }
 private static String getModuleDescriptions(JavaScriptModulesConfig jsModulesConfig)
     throws IOException {
   JsonFactory jsonFactory = new JsonFactory();
   StringWriter writer = new StringWriter();
   JsonGenerator jg = jsonFactory.createGenerator(writer);
   jsModulesConfig.writeModuleDescriptions(jg);
   jg.close();
   return writer.getBuffer().toString();
 }
 @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();
 }
Пример #22
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);
    }
  }
Пример #23
0
 protected void writeDataTemplate(
     Object data, DataSchema schema, JsonGenerator generator, boolean order) throws IOException {
   if (order) {
     JsonTraverseCallback callback = new SchemaOrderTraverseCallback(schema, generator);
     Data.traverse(data, callback);
     generator.flush();
     generator.close();
   } else {
     writeObject(data, generator);
   }
 }
Пример #24
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();
   }
 }
Пример #25
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();
  }
 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();
 }
Пример #27
0
  /**
   * 把对象转成json格式
   *
   * @param obj 需要转的对象
   * @return String
   */
  @SuppressWarnings("rawtypes")
  public String jsonObject(List list) {
    StringWriter sw = new StringWriter();
    JsonGenerator gen;
    try {
      gen = new JsonFactory().createGenerator(sw);
      getMapper().writeValue(gen, list);
      gen.close();
    } catch (Exception e) {

    }
    return sw.toString();
  }
Пример #28
0
 public void setSource(TreeNode tree) throws IOException {
   JsonFactory jsonFactory = new JsonFactory();
   if (buffer == null) {
     buffer = Unpooled.buffer();
   } else {
     buffer.clear();
   }
   type = QueueMessageType.JSON;
   try (ByteBufOutputStream outputStream = new ByteBufOutputStream(buffer)) {
     JsonGenerator generator = jsonFactory.createGenerator(outputStream);
     generator.setCodec(new ObjectMapper());
     generator.writeTree(tree);
     generator.close();
   }
 }
Пример #29
0
 public static String Object2Json(Object o) {
   try {
     ObjectMapper mapper = new ObjectMapper();
     StringWriter writer = new StringWriter();
     JsonFactory factory = mapper.getFactory();
     JsonGenerator gen = factory.createGenerator(writer);
     mapper.writeValue(gen, o);
     gen.close();
     String json = writer.toString();
     writer.close();
     return json;
   } catch (Exception e) {
     e.printStackTrace();
     return null;
   }
 }
Пример #30
0
 private static FullHttpResponse newHttpResponseWithMessage(
     HttpResponseStatus status, @Nullable String message) {
   // this is an "expected" exception, no need to send back stack trace
   StringBuilder sb = new StringBuilder();
   try {
     JsonGenerator jg = jsonFactory.createGenerator(CharStreams.asWriter(sb));
     jg.writeStartObject();
     jg.writeStringField("message", message);
     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);
   }
 }