com.fasterxml.jackson.databind.ObjectMapper Java Examples

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper. 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 check out the related API usage on the sidebar.
Example #1
Source File: AdvancedOptionsPanel.java    From datasync with 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 File: ApiInterceptor.java    From blog-sharon with 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
Source File: CORSServiceTestHelper.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
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 File: SimpleRestClient.java    From next-api-v2-examples with 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 File: LmWebResourceTest.java    From onos with 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 File: OpenstackNetworkingUtil.java    From onos with 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 File: MessageProcessor.java    From product-emm with 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
Source File: DataSourceControllerTest.java    From metamodel-membrane with Apache License 2.0 6 votes vote down vote up
@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 File: VoteResourceTest.java    From kaif with 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
Source File: HttpLocalDownloadServiceFetcher.java    From Singularity with Apache License 2.0 6 votes vote down vote up
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 File: HerokuDeployApi.java    From heroku-maven-plugin with 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
Source File: CreateOrReplaceResourceTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@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 File: SeedManager.java    From joal with 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 File: JweTokenSerializer.java    From OAuth-2.0-Cookbook with 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 File: TestGeometry.java    From xyz-hub with 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 File: MapperUtils.java    From yfshop with 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
Source File: AbstractServletContainerIntegrationTest.java    From apm-agent-java with Apache License 2.0 6 votes vote down vote up
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 File: JsonPatchApplierTest.java    From data-highway with 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
Source File: LocalDateTimeSerTest.java    From jackson-modules-java8 with Apache License 2.0 5 votes vote down vote up
@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 File: AbstractRemoteEventTest.java    From hawkbit with 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 File: KafkaReporter.java    From metrics-kafka with 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 File: JmapResponseWriterImpl.java    From james-project with 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 File: DefaultServerSourceManager.java    From caravan with 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 File: JwtAuthenticationTokenFilter.java    From fish-admin with 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 File: PayloadDeserializerTest.java    From java-jwt with 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 File: DatadogFetchTask.java    From kayenta with 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
Source File: CustomEntityDeserializer.java    From FROST-Server with GNU Lesser General Public License v3.0 5 votes vote down vote up
@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 File: PrettyPrintingJsonBodyFilterTest.java    From logbook with 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 File: JsonUtil.java    From griffin with 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 File: ObjectMapperBuilderTest.java    From elasticactors with 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);
}