Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: datasync   Source File: AdvancedOptionsPanel.java    License: MIT License 6 votes vote down vote up
private void showEditControlFileDialog() {
    try {
        ObjectMapper mapper = new ObjectMapper().configure(SerializationFeature.INDENT_OUTPUT, true);
        String textAreaContent = mapper.writeValueAsString(model.getControlFile());

        JTextArea controlFileContentTextArea = new JTextArea();
        controlFileContentTextArea.setEditable(false);
        controlFileContentTextArea.setText(textAreaContent);
        JScrollPane scrollPane = new JScrollPane(controlFileContentTextArea);
        controlFileContentTextArea.setLineWrap(true);
        controlFileContentTextArea.setWrapStyleWord(true);
        controlFileContentTextArea.setCaretPosition(0);
        scrollPane.setPreferredSize(CONTROL_FILE_VIEWER_DIMENSIONS);

        JOptionPane.showMessageDialog(this,scrollPane,"View Control File",JOptionPane.PLAIN_MESSAGE);
    }
    catch (IOException e){
         JOptionPane.showMessageDialog(this,"Could not load control file.  Please contact support");
    }

}
 
Example 2
Source Project: blog-sharon   Source File: ApiInterceptor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    if (StrUtil.equals(TrueFalseEnum.TRUE.getDesc(), HaloConst.OPTIONS.get(BlogPropertiesEnum.API_STATUS.getProp()))) {
        if (StrUtil.equals(request.getHeader("token"), HaloConst.OPTIONS.get(BlogPropertiesEnum.API_TOKEN.getProp()))) {
            return true;
        } else {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=utf-8");
            Map<String, Object> map = new HashMap<>(2);
            ObjectMapper mapper = new ObjectMapper();
            map.put("code", 400);
            map.put("msg", "Invalid Token");
            response.getWriter().write(mapper.writeValueAsString(map));
            return false;
        }
    }
    response.sendRedirect("/404");
    return false;
}
 
Example 3
public static ResourceAdd getSampleResourceAdd(List<CORSOrigin> corsOrigins) {

        ObjectMapper mapper = new ObjectMapper();

        ResourceAdd resourceAdd = new ResourceAdd();
        resourceAdd.setName(CORS_ORIGIN_RESOURCE_NAME);
        List<Attribute> attributeList = new ArrayList<>();
        for (CORSOrigin corsOrigin : corsOrigins) {
            Attribute attribute = new Attribute();
            attribute.setKey(String.valueOf(corsOrigin.hashCode()));
            try {
                String corsOriginString = mapper.writeValueAsString(corsOrigin);
                attribute.setValue(corsOriginString);
            } catch (IOException e) {
                if (log.isDebugEnabled()) {
                    log.debug("Error while converting a CORS Origin to a String.", e);
                }
            }
            attributeList.add(attribute);
        }
        resourceAdd.setAttributes(attributeList);

        return resourceAdd;
    }
 
Example 4
Source Project: next-api-v2-examples   Source File: SimpleRestClient.java    License: MIT License 6 votes vote down vote up
public JsonNode login(String user, String password)
    throws InvalidKeyException, NoSuchAlgorithmException, InvalidKeySpecException,
        NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, IOException {

  String authParameters = encryptAuthParameter(user, password);

  // Send login request
  Response response =
      baseResource
          .path("login")
          .queryParam("service", Main.SERVICE)
          .queryParam("auth", authParameters)
          .request(responseType)
          .post(null);

  ObjectNode json = response.readEntity(ObjectNode.class);

  JsonNode node = new ObjectMapper().readTree(json.toString());

  String sessionKey = json.get("session_key").asText();

  // Add the session key to basic auth for all calls
  baseResource.register(HttpAuthenticationFeature.basic(sessionKey, sessionKey));

  return node;
}
 
Example 5
Source Project: onos   Source File: LmWebResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testCreateLm() throws CfmConfigException, SoamConfigException {
    MepEntry mep1 = DefaultMepEntry.builder(MEPID1, DeviceId.deviceId("netconf:1.2.3.4:830"),
            PortNumber.portNumber(1), Mep.MepDirection.UP_MEP, MDNAME1, MANAME1).buildEntry();

    expect(mepService.getMep(MDNAME1, MANAME1, MEPID1)).andReturn(mep1).anyTimes();
    replay(mepService);

    ObjectMapper mapper = new ObjectMapper();
    CfmCodecContext context = new CfmCodecContext();
    ObjectNode node = mapper.createObjectNode();
    node.set("lm", context.codec(LossMeasurementCreate.class).encode(lm1, context));

    final WebTarget wt = target();
    final Response response = wt.path("md/" + MDNAME1.mdName() + "/ma/" +
            MANAME1.maName() + "/mep/" + MEPID1.value() + "/lm")
            .request().post(Entity.json(node.toString()));
    assertEquals(201, response.getStatus());
}
 
Example 6
Source Project: onos   Source File: OpenstackNetworkingUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Adds router interfaces to openstack admin service.
 *
 * @param osPort        port
 * @param adminService  openstack admin service
 */
public static void addRouterIface(Port osPort,
                                  OpenstackRouterAdminService adminService) {
    osPort.getFixedIps().forEach(p -> {
        JsonNode jsonTree = new ObjectMapper().createObjectNode()
                .put("id", osPort.getDeviceId())
                .put("tenant_id", osPort.getTenantId())
                .put("subnet_id", p.getSubnetId())
                .put("port_id", osPort.getId());
        try {
            RouterInterface rIface = getContext(NeutronRouterInterface.class)
                    .readerFor(NeutronRouterInterface.class)
                    .readValue(jsonTree);
            if (adminService.routerInterface(rIface.getPortId()) != null) {
                adminService.updateRouterInterface(rIface);
            } else {
                adminService.addRouterInterface(rIface);
            }
        } catch (IOException e) {
            log.error("IOException occurred because of {}", e);
        }
    });
}
 
Example 7
Source Project: product-emm   Source File: MessageProcessor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Local notification message handler.
 *
 * @param context Context of the application.
 */
public MessageProcessor(Context context) {
	this.context = context;

	deviceId = Preference.getString(context, DEVICE_ID_PREFERENCE_KEY);
	operationProcessor = new OperationProcessor(context.getApplicationContext());
	mapper = new ObjectMapper();
	mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
	this.devicePolicyManager =
			(DevicePolicyManager) context.getSystemService(Context.DEVICE_POLICY_SERVICE);

	if (deviceId == null) {
		DeviceInfo deviceInfo = new DeviceInfo(context.getApplicationContext());
		deviceId = deviceInfo.getDeviceId();
		Preference.putString(context, DEVICE_ID_PREFERENCE_KEY, deviceId);
	}
}
 
Example 8
@Test
public void testPutWithValidationPassing() throws Exception {
    final String tenant = name.getMethodName();
    tenantRegistry.createTenantContext(tenant);

    final RestDataSourceDefinition dataSourceDefinition = new RestDataSourceDefinition();
    dataSourceDefinition.setType("pojo");

    final GetDatasourceResponse resp = dataSourceController.put(tenant, "ds1", true, dataSourceDefinition);

    final ObjectMapper objectMapper = new ObjectMapper();

    assertEquals(
            "[{'name':'information_schema','uri':'/testPutWithValidationPassing/ds1/s/information_schema'},"
                    + "{'name':'Schema','uri':'/testPutWithValidationPassing/ds1/s/Schema'}]",
            objectMapper.writeValueAsString(resp.getSchemas()).replace('\"', '\''));
}
 
Example 9
Source Project: kaif   Source File: VoteResourceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void ignoreDuplicateVote() throws Exception {
  Account account = accountCitizen("foo");
  String token = prepareAccessToken(account);

  VoteResource.VoteArticle voteArticle = new VoteResource.VoteArticle();
  voteArticle.articleId = FlakeId.fromString("a");
  voteArticle.newState = VoteState.DOWN;
  voteArticle.previousCount = 100L;
  voteArticle.previousState = VoteState.EMPTY;

  Mockito.doThrow(new DuplicateKeyException("vote dup"))
      .when(voteService)
      .voteArticle(eq(VoteState.DOWN),
          eq(FlakeId.fromString("a")),
          isA(Authorization.class),
          eq(VoteState.EMPTY),
          eq(100L));

  mockMvc.perform(post("/api/vote/article").header(AccountAccessToken.HEADER_KEY, token)
      .contentType(MediaType.APPLICATION_JSON)
      .content(new ObjectMapper().writeValueAsBytes(voteArticle))).andExpect(status().isOk());
}
 
Example 10
public HttpLocalDownloadServiceFetcher(
  AsyncHttpClient httpClient,
  ObjectMapper objectMapper,
  SingularityExecutorConfiguration executorConfiguration,
  SingularityS3Configuration s3Configuration
) {
  this.httpClient = httpClient;
  this.objectMapper = objectMapper;
  this.executorConfiguration = executorConfiguration;
  this.localDownloadUri =
    String.format(
      LOCAL_DOWNLOAD_STRING_FORMAT,
      s3Configuration.getLocalDownloadHttpPort(),
      s3Configuration.getLocalDownloadPath()
    );
}
 
Example 11
Source Project: heroku-maven-plugin   Source File: HerokuDeployApi.java    License: MIT License 6 votes vote down vote up
private BuildInfo handleBuildInfoResponse(String appName, ObjectMapper mapper, CloseableHttpResponse response) throws IOException, HerokuDeployApiException {
    switch (response.getStatusLine().getStatusCode()) {
        case HttpStatus.SC_NOT_FOUND:
            throw new AppNotFoundException(String.format("App %s could not be found!", appName));

        case HttpStatus.SC_FORBIDDEN:
            throw new InsufficientAppPermissionsException(String.format("Could not access app %s: insufficient permissions", appName));

        case HttpStatus.SC_OK:
        case HttpStatus.SC_CREATED:
            HttpEntity responseEntity = response.getEntity();
            String responseStringBody = Util.readLinesFromInputStream(responseEntity.getContent()).collect(Collectors.joining());

            return mapper.readValue(responseStringBody, BuildInfo.class);

        default:
            throw new HerokuDeployApiException(String.format("Unexpected status code: %d!", response.getStatusLine().getStatusCode()));
    }
}
 
Example 12
@Test
public void testReplaceWithoutLock() throws Exception {
  server.expect().get().withPath("/api/v1/namespaces/test/configmaps/map1").andReturn(200, new ConfigMapBuilder()
    .withNewMetadata().withResourceVersion("1000").and().build()).always();

  server.expect().put().withPath("/api/v1/namespaces/test/configmaps/map1").andReturn(200, new ConfigMapBuilder()
    .withNewMetadata().withResourceVersion("1001").and().build()).once();

  KubernetesClient client = server.getClient();
  ConfigMap map = client.configMaps().withName("map1").replace(new ConfigMapBuilder()
    .withNewMetadata().withName("map1").and().build());
  assertNotNull(map);
  assertEquals("1001", map.getMetadata().getResourceVersion());

  RecordedRequest request = server.getLastRequest();
  ConfigMap replacedMap = new ObjectMapper().readerFor(ConfigMap.class).readValue(request.getBody().inputStream());
  assertEquals("1000", replacedMap.getMetadata().getResourceVersion());
}
 
Example 13
Source Project: joal   Source File: SeedManager.java    License: Apache License 2.0 6 votes vote down vote up
public SeedManager(final String joalConfFolder, final ObjectMapper mapper, final ApplicationEventPublisher publisher) throws IOException {
    this.isSeeding = false;
    this.joalFoldersPath = new JoalFoldersPath(Paths.get(joalConfFolder));
    this.torrentFileProvider = new TorrentFileProvider(joalFoldersPath);
    this.configProvider = new JoalConfigProvider(mapper, joalFoldersPath, publisher);
    this.bitTorrentClientProvider = new BitTorrentClientProvider(configProvider, mapper, joalFoldersPath);
    this.publisher = publisher;
    this.connectionHandler = new ConnectionHandler();


    final SocketConfig sc = SocketConfig.custom()
            .setSoTimeout(30000)
            .build();
    final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager();
    connManager.setDefaultMaxPerRoute(100);
    connManager.setMaxTotal(200);
    connManager.setValidateAfterInactivity(1000);
    connManager.setDefaultSocketConfig(sc);
    this.httpClient = HttpClients.custom()
            .setConnectionTimeToLive(1, TimeUnit.MINUTES)
            .setConnectionManager(connManager)
            .setConnectionManagerShared(true)
            .build();
}
 
Example 14
Source Project: OAuth-2.0-Cookbook   Source File: JweTokenSerializer.java    License: MIT License 6 votes vote down vote up
public Map<String, Object> decode(String base64EncodedKey, String content) {
    try {
        byte[] decodedKey = Base64.getDecoder().decode(base64EncodedKey);
        SecretKey key = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
        JWEObject jwe = JWEObject.parse(content);
        jwe.decrypt(new AESDecrypter(key));

        ObjectMapper objectMapper = new ObjectMapper();
        ObjectReader reader = objectMapper.readerFor(Map.class);
        return reader.with(DeserializationFeature.USE_LONG_FOR_INTS)
                .readValue(jwe.getPayload().toString());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}
 
Example 15
Source Project: xyz-hub   Source File: TestGeometry.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test_validate() throws Exception {
  final ObjectMapper mp = new ObjectMapper();

  String json = "{\"type\":\"GeometryCollection\",\"geometries\":[]}";
  GeometryCollection geometryCollection = mp.readValue(json, GeometryCollection.class);
  geometryCollection.validate();

  json = "{\"type\":\"GeometryCollection\",\"geometries\":[" + //
      "{\"type\":\"Point\",\"coordinates\":[0,0,0]}," + //
      "{\"type\":\"MultiPoint\",\"coordinates\":[]}," + //
      "{\"type\":\"MultiPoint\",\"coordinates\":[[0,0,0], [1,1,1]]}" + //
      "]}";
  geometryCollection = mp.readValue(json, GeometryCollection.class);
  geometryCollection.validate();
}
 
Example 16
Source Project: yfshop   Source File: MapperUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 把 JSON 解析成 List,如果 List 内部的元素存在 jsonString,继续解析
 *
 * @param json
 * @param mapper 解析工具
 * @return
 * @throws Exception
 */
private static List<Object> json2ListRecursion(String json, ObjectMapper mapper) throws Exception {
    if (json == null) {
        return null;
    }

    List<Object> list = mapper.readValue(json, List.class);

    for (Object obj : list) {
        if (obj != null && obj instanceof String) {
            String str = (String) obj;
            if (str.startsWith("[")) {
                obj = json2ListRecursion(str, mapper);
            } else if (obj.toString().startsWith("{")) {
                obj = json2MapRecursion(str, mapper);
            }
        }
    }

    return list;
}
 
Example 17
public List<JsonNode> getEvents(String eventType) {
    try {
        final List<JsonNode> events = new ArrayList<>();
        final ObjectMapper objectMapper = new ObjectMapper();
        for (HttpRequest httpRequest : mockServerContainer.getClient().retrieveRecordedRequests(request(INTAKE_V2_URL))) {
            final String bodyAsString = httpRequest.getBodyAsString();
            for (String ndJsonLine : bodyAsString.split("\n")) {
                final JsonNode ndJson = objectMapper.readTree(ndJsonLine);
                if (ndJson.get(eventType) != null) {
                    // as inferred spans are created only after the profiling session ends
                    // they can leak into another test
                    if (!isInferredSpan(ndJson.get(eventType))) {
                        validateEventMetadata(bodyAsString);
                    }
                    events.add(ndJson.get(eventType));
                }
            }
        }
        return events;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 18
Source Project: data-highway   Source File: JsonPatchApplierTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = PatchApplicationException.class)
public void throwsPatchApplicationExceptionWhenNotAValidPatch() throws Exception {
  JsonNode road = mapper.readTree("{\"description\":\"description1\"}");

  List<PatchOperation> operations = singletonList(PatchOperation.replace("/description", "description2"));

  JsonNode jsonNodePatch = mapper.readTree("{}");

  ObjectMapper mockObjectMapper = mock(ObjectMapper.class);
  when(mockObjectMapper.convertValue(any(), eq(JsonNode.class))).thenReturn(jsonNodePatch);

  underTest = new JsonPatchApplier(mockObjectMapper);
  underTest.apply(road, operations);
}
 
Example 19
@Test
public void testSerializationAsTimestamp04Nanosecond() throws Exception
{
    LocalDateTime time = LocalDateTime.of(2005, Month.NOVEMBER, 5, 22, 31, 5, 829837);

    final ObjectMapper m = newMapperBuilder()
            .enable(SerializationFeature.WRITE_DATE_TIMESTAMPS_AS_NANOSECONDS)
            .build();
    String value = m.writeValueAsString(time);
    assertEquals("The value is not correct.", "[2005,11,5,22,31,5,829837]", value);
}
 
Example 20
Source Project: hawkbit   Source File: AbstractRemoteEventTest.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private Message<String> createJsonMessage(final Object event) {
    final Map<String, MimeType> headers = Maps.newLinkedHashMap();
    headers.put(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON);
    try {
        final String json = new ObjectMapper().writeValueAsString(event);
        final Message<String> message = MessageBuilder.withPayload(json).copyHeaders(headers).build();
        return message;
    } catch (final JsonProcessingException e) {
        fail(e.getMessage());
    }
    return null;
}
 
Example 21
Source Project: metrics-kafka   Source File: KafkaReporter.java    License: Apache License 2.0 5 votes vote down vote up
private KafkaReporter(MetricRegistry registry,
                      String name,
                      MetricFilter filter,
                      TimeUnit rateUnit,
                      TimeUnit durationUnit,
                      String kafkaTopic,
                      Properties kafkaProperties) {
    super(registry, name, filter, rateUnit, durationUnit);
    this.registry = registry;
    mapper = new ObjectMapper().registerModule(new MetricsModule(rateUnit,
                                                                 durationUnit,
                                                                 false));
    this.kafkaTopic = kafkaTopic;
    kafkaProducer = new Producer<String, String>(new ProducerConfig(kafkaProperties));
}
 
Example 22
Source Project: james-project   Source File: JmapResponseWriterImpl.java    License: Apache License 2.0 5 votes vote down vote up
private ObjectMapper newConfiguredObjectMapper(JmapResponse jmapResponse) {
    ObjectMapper objectMapper = objectMapperFactory.forWriting();
    
    FilterProvider filterProvider = jmapResponse
            .getFilterProvider()
            .orElseGet(SimpleFilterProvider::new)
            .setDefaultFilter(SimpleBeanPropertyFilter.serializeAll())
            .addFilter(PROPERTIES_FILTER, getPropertiesFilter(jmapResponse.getProperties()));
    
    objectMapper.setFilterProvider(filterProvider);

    return objectMapper;
}
 
Example 23
Source Project: caravan   Source File: DefaultServerSourceManager.java    License: Apache License 2.0 5 votes vote down vote up
public DefaultServerSourceManager(LoadBalancerContext loadBalancerContext) {
    NullArgumentChecker.DEFAULT.check(loadBalancerContext, "loadBalancerContext");
    _loadBalancerContext = loadBalancerContext;
    _objectMapper = new ObjectMapper();
    _routeListType = _objectMapper.getTypeFactory().constructCollectionType(List.class, LoadBalancerRoute.class);

    String managerId = loadBalancerContext.managerId();
    TypedDynamicCachedCorrectedProperties properties = loadBalancerContext.properties();
    String propertyKey = generateKey(managerId, ConfigurationKeys.DataFolder);
    _managerLevelDataFolderProperty = properties.getStringProperty(propertyKey, null);

    String loadBalancerId = loadBalancerContext.loadBalancerId();
    propertyKey = generateKey(managerId, loadBalancerId, ConfigurationKeys.DataFolder);
    _dataFolderProperty = properties.getStringProperty(propertyKey, null);
}
 
Example 24
Source Project: fish-admin   Source File: JwtAuthenticationTokenFilter.java    License: MIT License 5 votes vote down vote up
@Override
public Authentication attemptAuthentication(
        HttpServletRequest req, HttpServletResponse res)
        throws AuthenticationException, IOException, ServletException {

    Map uMap = new ObjectMapper().readValue(req.getInputStream(), Map.class);

    // 返回一个验证令牌
    return getAuthenticationManager().authenticate(
            new UsernamePasswordAuthenticationToken(
                    uMap.get("username"),
                    uMap.get("password")
                    )
    );
}
 
Example 25
Source Project: java-jwt   Source File: PayloadDeserializerTest.java    License: MIT License 5 votes vote down vote up
@Test
public void shouldNotRemoveKnownPublicClaimsFromTree() throws Exception {
    String payloadJSON = "{\n" +
            "  \"iss\": \"auth0\",\n" +
            "  \"sub\": \"emails\",\n" +
            "  \"aud\": \"users\",\n" +
            "  \"iat\": 10101010,\n" +
            "  \"exp\": 11111111,\n" +
            "  \"nbf\": 10101011,\n" +
            "  \"jti\": \"idid\",\n" +
            "  \"roles\":\"admin\" \n" +
            "}";
    StringReader reader = new StringReader(payloadJSON);
    JsonParser jsonParser = new JsonFactory().createParser(reader);
    ObjectMapper mapper = new ObjectMapper();
    jsonParser.setCodec(mapper);

    Payload payload = deserializer.deserialize(jsonParser, mapper.getDeserializationContext());

    assertThat(payload, is(notNullValue()));
    assertThat(payload.getIssuer(), is("auth0"));
    assertThat(payload.getSubject(), is("emails"));
    assertThat(payload.getAudience(), is(IsCollectionContaining.hasItem("users")));
    assertThat(payload.getIssuedAt().getTime(), is(10101010L * 1000));
    assertThat(payload.getExpiresAt().getTime(), is(11111111L * 1000));
    assertThat(payload.getNotBefore().getTime(), is(10101011L * 1000));
    assertThat(payload.getId(), is("idid"));

    assertThat(payload.getClaim("roles").asString(), is("admin"));
    assertThat(payload.getClaim("iss").asString(), is("auth0"));
    assertThat(payload.getClaim("sub").asString(), is("emails"));
    assertThat(payload.getClaim("aud").asString(), is("users"));
    assertThat(payload.getClaim("iat").asDouble(), is(10101010D));
    assertThat(payload.getClaim("exp").asDouble(), is(11111111D));
    assertThat(payload.getClaim("nbf").asDouble(), is(10101011D));
    assertThat(payload.getClaim("jti").asString(), is("idid"));
}
 
Example 26
Source Project: kayenta   Source File: DatadogFetchTask.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
public DatadogFetchTask(
    ObjectMapper kayentaObjectMapper,
    AccountCredentialsRepository accountCredentialsRepository,
    SynchronousQueryProcessor synchronousQueryProcessor) {
  this.kayentaObjectMapper = kayentaObjectMapper;
  this.accountCredentialsRepository = accountCredentialsRepository;
  this.synchronousQueryProcessor = synchronousQueryProcessor;
}
 
Example 27
@Override
public T deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException {
    T result;
    try {
        result = clazz.getDeclaredConstructor().newInstance();
    } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | SecurityException | IllegalArgumentException | InvocationTargetException ex) {
        throw new IOException("Error deserializing JSON!", ex);
    }
    // need to make subclass of this class for every Entity subclass with custom field to get expected class!!!
    BeanDescription beanDescription = ctxt.getConfig().introspect(ctxt.constructType(clazz));
    ObjectMapper mapper = (ObjectMapper) parser.getCodec();
    JsonNode obj = mapper.readTree(parser);
    List<BeanPropertyDefinition> properties = beanDescription.findProperties();
    Iterator<Map.Entry<String, JsonNode>> i = obj.fields();

    // First check if we know all properties that are present.
    if (ctxt.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) {
        while (i.hasNext()) {
            Map.Entry<String, JsonNode> next = i.next();
            String fieldName = next.getKey();
            Optional<BeanPropertyDefinition> findFirst = properties.stream().filter(p -> p.getName().equals(fieldName)).findFirst();
            if (!findFirst.isPresent()) {
                throw new UnrecognizedPropertyException(parser, "Unknown field: " + fieldName, parser.getCurrentLocation(), clazz, fieldName, null);
            }
        }
    }

    for (BeanPropertyDefinition classProperty : properties) {
        deserialiseProperty(obj, classProperty, properties, mapper, result);
    }
    return result;
}
 
Example 28
Source Project: logbook   Source File: PrettyPrintingJsonBodyFilterTest.java    License: MIT License 5 votes vote down vote up
@Test
void shouldConstructFromObjectMapper() {
    BodyFilter bodyFilter = new PrettyPrintingJsonBodyFilter(new ObjectMapper());
    final String filtered = bodyFilter.filter("application/json", compacted);
    assertThat(filtered, is(pretty));

}
 
Example 29
Source Project: griffin   Source File: JsonUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static String toJsonWithFormat(Object obj)
    throws JsonProcessingException {
    if (obj == null) {
        LOGGER.warn("Object to be formatted cannot be empty!");
        return null;
    }
    ObjectWriter mapper = new ObjectMapper().writer()
        .withDefaultPrettyPrinter();
    return mapper.writeValueAsString(obj);
}
 
Example 30
Source Project: elasticactors   Source File: ObjectMapperBuilderTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testBuildObjectMapper() {
    ActorRefFactory actorRefFactory = mock(ActorRefFactory.class);
    ScheduledMessageRefFactory scheduledMessageRefFactory = mock(ScheduledMessageRefFactory.class);
    ObjectMapper objectMapper = new ObjectMapperBuilder(actorRefFactory,scheduledMessageRefFactory,"1.0.0").build();
    // check if everything was scanned correctly
    assertNotNull(objectMapper);
}