public void testMapFilteringViaProps() throws Exception {
   FilterProvider prov =
       new SimpleFilterProvider()
           .addFilter("filterX", SimpleBeanPropertyFilter.filterOutAllExcept("b"));
   String json = MAPPER.writer(prov).writeValueAsString(new MapBean());
   assertEquals(aposToQuotes("{'values':{'b':5}}"), json);
 }
 public static byte[] toBytes(JsonNode rootNode) {
   try {
     return JSON_MAPPER.writer().writeValueAsBytes(rootNode);
   } catch (JsonProcessingException e) {
     throw new RuntimeException(e);
   }
 }
  protected EndpointConfig initWriter(ObjectMapper mapper) {
    // first common config
    if (_activeView != null) {
      _writer = mapper.writerWithView(_activeView);
    } else {
      _writer = mapper.writer();
    }
    if (_rootName != null) {
      _writer = _writer.withRootName(_rootName);
    }
    // Then features
    if (_serEnable != null) {
      _writer = _writer.withFeatures(_serEnable);
    }
    if (_serDisable != null) {
      _writer = _writer.withoutFeatures(_serDisable);
    }
    // then others

    // Finally: couple of features we always set

    /* Important: we are NOT to close the underlying stream after
     * mapping, so we need to instruct parser:
     */
    _writer.getJsonFactory().disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);

    return this;
  }
 public static byte[] toByteArray(Object value) {
   try {
     return OBJECT_MAPPER.writer().writeValueAsBytes(value);
   } catch (JsonProcessingException e) {
     throw new IllegalArgumentException("Unable to serialize to json", e);
   }
 }
  @Test
  public void serializationSimpleSubscribeContext() throws IOException {

    SubscribeContext subscribeContext = null;
    try {
      subscribeContext = createSubscribeContextTemperature();
    } catch (URISyntaxException e) {
      Assert.fail(e.getMessage());
    }

    ObjectMapper mapper = new ObjectMapper();

    ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());

    String json = writer.writeValueAsString(subscribeContext);

    List<EntityId> entityIdList = JsonPath.read(json, "$.entities[*]");
    assertEquals(1, entityIdList.size());
    assertEquals("Room1", JsonPath.read(json, "$.entities[0].id"));
    assertEquals("Room", JsonPath.read(json, "$.entities[0].type"));
    assertEquals(false, JsonPath.read(json, "$.entities[0].isPattern"));
    assertEquals("P1M", JsonPath.read(json, "$.duration"));
    List<String> attributes = JsonPath.read(json, "$.attributes[*]");
    assertEquals(1, attributes.size());
    assertEquals("temperature", JsonPath.read(json, "$.attributes[0]"));
    assertEquals("http://localhost:1028/accumulate", JsonPath.read(json, "$.reference"));
    List<NotifyCondition> notifyConditionList = JsonPath.read(json, "$.notifyConditions[*]");
    assertEquals(1, notifyConditionList.size());
    assertEquals(
        NotifyConditionEnum.ONTIMEINTERVAL.getLabel(),
        JsonPath.read(json, "$.notifyConditions[0].type"));
    List<String> condValues = JsonPath.read(json, "$.notifyConditions[0].condValues[*]");
    assertEquals(1, condValues.size());
    assertEquals("PT10S", JsonPath.read(json, "$.notifyConditions[0].condValues[0]"));
  }
 public static String toJson(Object value) {
   try {
     return OBJECT_MAPPER.writer().writeValueAsString(value);
   } catch (JsonProcessingException e) {
     throw new IllegalArgumentException("Unable to serialize to json", e);
   }
 }
 /**
  * Returns {@code node} serialized to a json string for the {@code node}.
  *
  * @throws RuntimeException if deserialization fails
  */
 public static String toJson(JsonNode node) {
   try {
     ObjectWriter writer = mapper.writer();
     return writer.writeValueAsString(node);
   } catch (Exception e) {
     throw Exceptions.uncheck(e, "Failed to serialize object: {}", node);
   }
 }
Beispiel #8
0
 static {
   MAPPER =
       new ObjectMapper()
           .findAndRegisterModules()
           .registerModule(new JavaTimeModule())
           .registerModule(new Jdk8Module());
   WRITER = MAPPER.writer();
 }
  void writeResponse(HttpServletResponse resp, Iterable<?> iterable) throws IOException {
    setHeaders(resp);

    try (final OutputStream output = resp.getOutputStream()) {
      resp.setStatus(HttpServletResponse.SC_OK);
      objectMapper.writer().writeValue(output, iterable);
    }
  }
 private synchronized void write(ObjectNode tree) throws IOException {
   ObjectMapper mapper = ObjectMapperFactory.create();
   ObjectWriter writer = mapper.writer();
   writer = writer.with(new DefaultPrettyPrinter("\\n"));
   log.debug("writing " + tree + " to " + this.file);
   writer.writeValue(this.file, tree);
   log.debug("write complete");
 }
  @Before
  public void setupMapper() {

    mapper = new ObjectMapper();
    mapper.registerModule(new JtsModule());

    writer = mapper.writer();
  }
Beispiel #12
0
public enum Jackson {
  ;
  private static final ObjectMapper objectMapper = new ObjectMapper();

  static {
    objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
  };

  private static final ObjectWriter writer = objectMapper.writer();
  private static final ObjectWriter prettyWriter = objectMapper.writerWithDefaultPrettyPrinter();

  public static String toJsonPrettyString(Object value) {
    try {
      return prettyWriter.writeValueAsString(value);
    } catch (Exception e) {
      throw new IllegalStateException(e);
    }
  }

  public static String toJsonString(Object value) {
    try {
      return writer.writeValueAsString(value);
    } catch (Exception e) {
      throw new IllegalStateException(e);
    }
  }

  public static <T> T fromJsonString(String json, Class<T> clazz) {
    try {
      return objectMapper.readValue(json, clazz);
    } catch (Exception e) {
      throw new IllegalArgumentException(e);
    }
  }

  public static <T> T loadFrom(File file, Class<T> clazz) throws IOException {
    try {
      return objectMapper.readValue(file, clazz);
    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new IllegalStateException(e);
    }
  }

  public static ObjectMapper getObjectMapper() {
    return objectMapper;
  }

  public static ObjectWriter getWriter() {
    return writer;
  }

  public static ObjectWriter getPrettywriter() {
    return prettyWriter;
  }
}
Beispiel #13
0
  @Override
  protected void configure() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JodaModule());

    bind(ObjectMapper.class).annotatedWith(Ipc.class).toInstance(objectMapper);
    bind(ObjectReader.class).annotatedWith(Ipc.class).toInstance(objectMapper.reader());
    bind(ObjectWriter.class).annotatedWith(Ipc.class).toInstance(objectMapper.writer());
  }
 protected <T, I> T handleCreate(I resource, Class<T> outputType)
     throws ExecutionException, InterruptedException, KubernetesClientException, IOException {
   AsyncHttpClient.BoundRequestBuilder requestBuilder =
       getClient()
           .getHttpClient()
           .preparePost(getNamespacedUrl(checkNamespace(resource)).toString());
   requestBuilder.setBody(OBJECT_MAPPER.writer().writeValueAsString(resource));
   return handleResponse(requestBuilder, 201, outputType);
 }
 protected <T> T handleReplace(T updated, Class<T> type)
     throws ExecutionException, InterruptedException, KubernetesClientException, IOException {
   AsyncHttpClient.BoundRequestBuilder requestBuilder =
       getClient()
           .getHttpClient()
           .preparePut(getResourceUrl(checkNamespace(updated), checkName(updated)).toString());
   requestBuilder.setBody(OBJECT_MAPPER.writer().writeValueAsString(updated));
   return handleResponse(requestBuilder, 200, type);
 }
 public void testMapFilteringViaClass() throws Exception {
   FilteredBean bean = new FilteredBean();
   bean.put("a", 4);
   bean.put("b", 3);
   FilterProvider prov =
       new SimpleFilterProvider()
           .addFilter("filterForMaps", SimpleBeanPropertyFilter.filterOutAllExcept("b"));
   String json = MAPPER.writer(prov).writeValueAsString(bean);
   assertEquals(aposToQuotes("{'b':3}"), json);
 }
Beispiel #17
0
 @JsonIgnore
 @Override
 public String toJSON() {
   ObjectMapper om = new ObjectMapper();
   String rawJson = null;
   try {
     rawJson = om.writer().writeValueAsString(this);
   } catch (JsonProcessingException e) {
     log.error(e.getMessage(), e);
   }
   return rawJson;
 }
  // [JACKSON-212]
  public void testToStringEnum() throws Exception {
    ObjectMapper m = new ObjectMapper();
    m.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
    assertEquals("\"b\"", m.writeValueAsString(LowerCaseEnum.B));

    // [databind#749] but should also be able to dynamically disable
    assertEquals(
        "\"B\"",
        m.writer()
            .without(SerializationFeature.WRITE_ENUMS_USING_TO_STRING)
            .writeValueAsString(LowerCaseEnum.B));
  }
 public void testFormatForGenerators() throws Exception {
   ObjectMapper mapper = new ObjectMapper(new FactoryWithSchema());
   MySchema s = new MySchema();
   StringWriter sw = new StringWriter();
   //  bit ugly, but can't think of cleaner simple way to check this...
   try {
     mapper.writer(s).writeValue(sw, "Foobar");
     fail("Excpected exception");
   } catch (SchemaException e) {
     assertSame(s, e._schema);
   }
 }
 // for [databind#756]
 public void testEmptyBeanSerializability() {
   // with default settings, error
   /*
   assertFalse(MAPPER.writer().with(SerializationFeature.FAIL_ON_EMPTY_BEANS)
           .canSerialize(EmptyBean.class));
           */
   // but with changes
   assertTrue(
       MAPPER
           .writer()
           .without(SerializationFeature.FAIL_ON_EMPTY_BEANS)
           .canSerialize(EmptyBean.class));
 }
Beispiel #21
0
 public void addLogEntry(String id, LogEntry logEntry) {
   try {
     OutputStream outputStream = logStreamCache.getUnchecked(id);
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     objectMapper.writer().writeValue(baos, logEntry);
     synchronized (outputStream) {
       outputStream.write(("\n" + baos.size() + "\n").getBytes());
       outputStream.write(baos.toByteArray());
     }
   } catch (Throwable ignored) {
     // do not log errors when logging
   }
 }
  public void testMediaItemSimple() throws Exception {
    ProtobufSchema schema = ProtobufSchemaLoader.std.parse(PROTOC_MEDIA_ITEM);
    final ObjectWriter w = MAPPER.writer(schema);
    byte[] bytes = w.writeValueAsBytes(MediaItem.buildItem());

    assertNotNull(bytes);

    assertEquals(252, bytes.length);

    // let's read back for fun
    MediaItem output = MAPPER.readerFor(MediaItem.class).with(schema).readValue(bytes);
    assertNotNull(output);
  }
  @RequestMapping(value = "/users/{userId}/positions", method = RequestMethod.POST)
  public ResponseEntity<String> createTrack(
      @PathVariable("userId") Long userId, @RequestBody PositionDTO positionDto)
      throws IncorrectPairingStatusException, UntrackedUserException, TopoosException,
          JsonProcessingException {
    logger.info("POST - /positions");

    positionDto.setUser(userId);

    PositionDTO position = fenceService.createPosition(positionDto);

    return new ResponseEntity<String>(
        objectMapper.writer().writeValueAsString(position), HttpStatus.CREATED);
  }
  // For [databind#689]
  public void testCustomDefaultPrettyPrinter() throws Exception {
    final ObjectMapper m = new ObjectMapper();
    final int[] input = new int[] {1, 2};

    // without anything else, compact:
    assertEquals("[1,2]", m.writeValueAsString(input));

    // or with default, get... defaults:
    m.enable(SerializationFeature.INDENT_OUTPUT);
    assertEquals("[ 1, 2 ]", m.writeValueAsString(input));
    assertEquals("[ 1, 2 ]", m.writerWithDefaultPrettyPrinter().writeValueAsString(input));
    assertEquals("[ 1, 2 ]", m.writer().withDefaultPrettyPrinter().writeValueAsString(input));

    // but then with our custom thingy...
    m.setDefaultPrettyPrinter(new FooPrettyPrinter());
    assertEquals("[1 , 2]", m.writeValueAsString(input));
    assertEquals("[1 , 2]", m.writerWithDefaultPrettyPrinter().writeValueAsString(input));
    assertEquals("[1 , 2]", m.writer().withDefaultPrettyPrinter().writeValueAsString(input));

    // and yet, can disable too
    assertEquals(
        "[1,2]", m.writer().without(SerializationFeature.INDENT_OUTPUT).writeValueAsString(input));
  }
Beispiel #25
0
  /**
   * @param object
   * @return
   * @throws IOException
   */
  private String getJSONString(Object object, boolean isPretty) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);
    mapper.configure(SerializationFeature.WRITE_BIGDECIMAL_AS_PLAIN, true);
    ObjectWriter writer = mapper.writer();
    if (isPretty) {
      writer = writer.with(SerializationFeature.INDENT_OUTPUT); // make the output nicely formatted
      writer = writer.with(new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS"));
    } else {
      writer = writer.with(new SimpleDateFormat("MM/dd/yyyy"));
    }

    String jsonString = writer.writeValueAsString(object);
    return jsonString;
  }
  void writeResponse(HttpServletResponse resp, Response response) throws IOException {
    setHeaders(resp);

    try (final OutputStream output = resp.getOutputStream()) {
      switch (response.getStatus()) {
        case HttpServletResponse.SC_OK:
          resp.setStatus(HttpServletResponse.SC_OK);
          objectMapper.writer().writeValue(output, response.getEntity());
          break;
        case HttpServletResponse.SC_NOT_FOUND:
          resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
          break;
        default:
          resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
          break;
      }
    }
  }
Beispiel #27
0
 public String getSchemaForClass(Class<?> clazz) {
   LOG.debug("Looking up schema for {}", clazz.getCanonicalName());
   String name = clazz.getName();
   try {
     ObjectWriter writer = mapper.writer().withDefaultPrettyPrinter();
     JsonSchema jsonSchema = mapper.generateJsonSchema(clazz);
     customizeSchema(clazz, jsonSchema);
     return writer.writeValueAsString(jsonSchema);
     //            SchemaFactoryWrapper schemaFactoryWrapper = new SchemaFactoryWrapper();
     //            mapper.acceptJsonFormatVisitor(mapper.constructType(clazz),
     // schemaFactoryWrapper);
     //            com.fasterxml.jackson.module.jsonSchema.JsonSchema jsonSchema =
     // schemaFactoryWrapper.finalSchema();
     //            return writer.writeValueAsString(jsonSchema);
   } catch (Exception e) {
     LOG.warn("Failed to generate JSON schema for class " + name, e);
     throw new RuntimeException(e);
   }
 }
  public void putUrlList(UrlList urlList) {
    try {
      // hash url to get key
      String s3Key = Hash.hashKey(urlList.getParentUrl());

      // put document into s3
      ObjectMapper mapper = new ObjectMapper();
      mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
      mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
      ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
      String json = ow.writeValueAsString(urlList);
      ByteArrayInputStream inputStream = new ByteArrayInputStream(json.getBytes());
      ObjectMetadata omd = new ObjectMetadata();
      omd.setContentLength(json.getBytes().length);
      PutObjectRequest request = new PutObjectRequest(bucketName, s3Key, inputStream, omd);
      s3client.putObject(request);

      // No need to put into dynamo as it should already be there

      /*
      ObjectMapper mapper = new ObjectMapper();
      mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
      mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
      ObjectWriter ow = mapper.writer().withDefaultPrettyPrinter();
      String json = ow.writeValueAsString(doc);
      ObjectMetadata omd = new ObjectMetadata();
      omd.setContentType("text/html");
      omd.setContentLength(json.length());
      ByteArrayInputStream inputStream = new ByteArrayInputStream(
      		json.getBytes());
      PutObjectRequest request = new PutObjectRequest(bucketName, s3Key,
      		inputStream, omd);
      s3client.putObject(request);
      dynamo.putItem("documentUrl", doc.getDocumentId(), "s3Key", s3Key);*/
    } catch (JsonProcessingException e) {
      System.out.println("S3UrlListDA : json processing excecption exception");
      e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  private void writeOutConfigFile(final T config, final String configFileLocation)
      throws IOException {
    try (Writer writer =
        new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream(configFileLocation), "UTF-8"))) {
      log.debug("Writing out config file to {}", configFileLocation);

      T configToWrite = config;

      if (configToWrite instanceof PasswordsConfig<?>) {
        configToWrite = ((PasswordsConfig<T>) configToWrite).withEncryptedPasswords(textEncryptor);
      }

      // TODO: This scales badly and needs rethinking
      if (filterProvider != null) {
        mapper.writer(filterProvider).writeValue(writer, configToWrite);
      } else {
        mapper.writeValue(writer, configToWrite);
      }
    } catch (final IOException e) {
      log.error("Error writing out config file", e);
      throw e;
    }
  }
Beispiel #30
0
  public static class ChoiceMarshaller extends JsonMarshaller<List<core.entities.Choice>> {

    private static final ObjectMapper mapper = new ObjectMapper();
    private static final ObjectWriter writer = mapper.writer();

    @Override
    public String marshall(List<Choice> obj) {

      try {
        return writer.writeValueAsString(obj);
      } catch (JsonProcessingException e) {
        throw failure(e, "Unable to marshall the instance of " + obj.getClass() + "into a string");
      }
    }

    @Override
    public List<Choice> unmarshall(Class<List<Choice>> clazz, String json) {
      try {
        return mapper.readValue(json, new TypeReference<List<Choice>>() {});
      } catch (Exception e) {
        throw failure(e, "Unable to unmarshall the string " + json + "into " + clazz);
      }
    }
  }