Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper#convertValue()

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#convertValue() . 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: JacksonUtil.java    From litemall with MIT License 6 votes vote down vote up
public static List<String> parseStringList(String body, String field) {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node;
    try {
        node = mapper.readTree(body);
        JsonNode leaf = node.get(field);

        if (leaf != null)
            return mapper.convertValue(leaf, new TypeReference<List<String>>() {
            });
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}
 
Example 2
Source File: GraphQLHandle.java    From elide-spring-boot with Apache License 2.0 6 votes vote down vote up
private ElideResponse buildErrorResponse(HttpStatusException error, boolean isVerbose) {
  ObjectMapper mapper = elide.getMapper().getObjectMapper();
  JsonNode errorNode;
  if (!(error instanceof CustomErrorException) && elideSettings.isReturnErrorObjects()) {
    ErrorObjects errors = ErrorObjects.builder().addError()
        .with("message", isVerbose ? error.getVerboseMessage() : error.toString()).build();
    errorNode = mapper.convertValue(errors, JsonNode.class);
  } else {
    errorNode = isVerbose
        ? error.getVerboseErrorResponse().getRight()
        : error.getErrorResponse().getRight();
  }
  String errorBody;
  try {
    errorBody = mapper.writeValueAsString(errorNode);
  } catch (JsonProcessingException e) {
    errorBody = errorNode.toString();
  }
  return new ElideResponse(error.getStatus(), errorBody);
}
 
Example 3
Source File: CustomerController.java    From Software-Architecture-with-Spring-5.0 with MIT License 6 votes vote down vote up
@PostMapping("/customer")
public void createCustomer(@RequestBody CustomerData customerData) throws Exception {

    ObjectMapper objectMapper = new ObjectMapper();
    Map<String, Object> map = objectMapper.convertValue(customerData,
            new TypeReference<Map<String, Object>>() {
            }
    );

    JSONObject customerDataAsJson = new JSONObject(map);

    Command createCustomerCommand = new CreateCustomerCommand(customerDataAsJson, commandRepository, eventRepository, eventProcessor);
    CommandInvoker commandInvoker = new CommandInvoker();
    commandInvoker.invoke(createCustomerCommand);

    log.info("COMMAND INFORMATION");
    commandRepository.findAll().stream().forEach(command -> {
        log.info("id: {} , name: {} , data: {} ", command.getCommandId(), command.getCommandName(), command.getCommandData().toJSONString());
    });

    log.info("EVENT INFORMATION");
    eventRepository.findAll().stream().forEach(event -> {
        log.info("id: {} , name: {} , command id: {} , data: {} ", event.getEventId(), event.getEventName(), event.getCommandId(), event.getEventData().toJSONString());
    });
}
 
Example 4
Source File: FromJsonUtil.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * convert JsonNode into the returnType of methods in OvsdbRPC class.
 * @param resultJsonNode the result JsonNode
 * @param methodName the method name of methods in OvsdbRPC class
 * @param objectMapper ObjectMapper entity
 * @return Object
 * @throws UnsupportedException this is an unsupported exception
 */
private static Object convertResultType(JsonNode resultJsonNode, String methodName,
                                        ObjectMapper objectMapper) {
    switch (methodName) {
    case "getSchema":
    case "monitor":
        return resultJsonNode;
    case "echo":
    case "listDbs":
        return objectMapper.convertValue(resultJsonNode, objectMapper.getTypeFactory()
                .constructParametricType(List.class, String.class));
    case "transact":
        return objectMapper.convertValue(resultJsonNode, objectMapper.getTypeFactory()
                .constructParametricType(List.class, JsonNode.class));
    default:
        throw new UnsupportedException("does not support this rpc method" + methodName);
    }
}
 
Example 5
Source File: UserBulkMigrationActor.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
private void insertRecord(BulkMigrationUser bulkMigrationUser) {
  long insertStartTime = System.currentTimeMillis();
  ObjectMapper mapper = new ObjectMapper();
  ProjectLogger.log(
      "UserBulkMigrationActor:insertRecord:record started inserting with "
          .concat(bulkMigrationUser.getId() + ""),
      LoggerEnum.INFO.name());
  Map<String, Object> record = mapper.convertValue(bulkMigrationUser, Map.class);
  long createdOn = System.currentTimeMillis();
  record.put(JsonKey.CREATED_ON, new Timestamp(createdOn));
  record.put(JsonKey.LAST_UPDATED_ON, new Timestamp(createdOn));
  Util.DbInfo dbInfo = Util.dbInfoMap.get(JsonKey.BULK_OP_DB);
  Response response =
      cassandraOperation.insertRecord(dbInfo.getKeySpace(), dbInfo.getTableName(), record);
  response.put(JsonKey.PROCESS_ID, bulkMigrationUser.getId());
  ProjectLogger.log(
      "UserBulkMigrationActor:insertRecord:time taken by cassandra to insert record of size "
              .concat(record.size() + "")
          + "is(ms):".concat((System.currentTimeMillis() - insertStartTime) + ""));
  sender().tell(response, self());
}
 
Example 6
Source File: AWSUtil.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Set all prefixed properties on {@link ClientConfiguration}.
 * @param config
 * @param configProps
 */
public static void setAwsClientConfigProperties(ClientConfiguration config,
												Properties configProps) {

	Map<String, Object> awsConfigProperties = new HashMap<>();
	for (Map.Entry<Object, Object> entry : configProps.entrySet()) {
		String key = (String) entry.getKey();
		if (key.startsWith(AWS_CLIENT_CONFIG_PREFIX)) {
			awsConfigProperties.put(key.substring(AWS_CLIENT_CONFIG_PREFIX.length()), entry.getValue());
		}
	}
	// Jackson does not like the following properties
	String[] ignorableProperties = {"secureRandom"};
	BeanDeserializerModifier modifier = new BeanDeserializerModifierForIgnorables(
		ClientConfiguration.class, ignorableProperties);
	DeserializerFactory factory = BeanDeserializerFactory.instance.withDeserializerModifier(
		modifier);
	ObjectMapper mapper = new ObjectMapper(null, null,
		new DefaultDeserializationContext.Impl(factory));

	JsonNode propTree = mapper.convertValue(awsConfigProperties, JsonNode.class);
	try {
		mapper.readerForUpdating(config).readValue(propTree);
	} catch (IOException ex) {
		throw new RuntimeException(ex);
	}
}
 
Example 7
Source File: JacksonUtil.java    From dts-shop with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static List<Integer> parseIntegerList(String body, String field) {
	ObjectMapper mapper = new ObjectMapper();
	JsonNode node = null;
	try {
		node = mapper.readTree(body);
		JsonNode leaf = node.get(field);

		if (leaf != null)
			return mapper.convertValue(leaf, new TypeReference<List<Integer>>() {
			});
	} catch (IOException e) {
		e.printStackTrace();
	}
	return null;
}
 
Example 8
Source File: DefaultUpdate.java    From elepy with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private T setParamsOnObject(Request request, ObjectMapper objectMapper, T object, Class<T> modelClass) {
    Map<String, Object> map = objectMapper.convertValue(object, Map.class);

    Map<String, Object> params = new HashMap<>();
    request.queryParams().forEach(queryParam -> params.put(queryParam, request.queryParams(queryParam)));

    return MapperUtils.objectFromMaps(objectMapper, map, params, modelClass);
}
 
Example 9
Source File: AWSUtil.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Set all prefixed properties on {@link ClientConfiguration}.
 * @param config
 * @param configProps
 */
public static void setAwsClientConfigProperties(ClientConfiguration config,
												Properties configProps) {

	Map<String, Object> awsConfigProperties = new HashMap<>();
	for (Map.Entry<Object, Object> entry : configProps.entrySet()) {
		String key = (String) entry.getKey();
		if (key.startsWith(AWS_CLIENT_CONFIG_PREFIX)) {
			awsConfigProperties.put(key.substring(AWS_CLIENT_CONFIG_PREFIX.length()), entry.getValue());
		}
	}
	// Jackson does not like the following properties
	String[] ignorableProperties = {"secureRandom"};
	BeanDeserializerModifier modifier = new BeanDeserializerModifierForIgnorables(
		ClientConfiguration.class, ignorableProperties);
	DeserializerFactory factory = BeanDeserializerFactory.instance.withDeserializerModifier(
		modifier);
	ObjectMapper mapper = new ObjectMapper(null, null,
		new DefaultDeserializationContext.Impl(factory));

	JsonNode propTree = mapper.convertValue(awsConfigProperties, JsonNode.class);
	try {
		mapper.readerForUpdating(config).readValue(propTree);
	} catch (IOException ex) {
		throw new RuntimeException(ex);
	}
}
 
Example 10
Source File: LogSearchApiSteps.java    From ambari-logsearch with Apache License 2.0 5 votes vote down vote up
@Then("The api query result is <jsonResult>")
public void verifyRestApiCall(@Named("jsonResult") String jsonResult) throws IOException, URISyntaxException {
  ObjectMapper mapper = new ObjectMapper();
  Path jsonFilePath = new File(Resources.getResource("test-output/" + jsonResult).toURI()).toPath();
  String jsonExpected = new String(Files.readAllBytes(jsonFilePath));

  JsonNode expected = mapper.readTree(jsonExpected);
  JsonNode result = mapper.readTree(response);
  JsonNode patch = JsonDiff.asJson(expected, result);
  List<?> diffObjects = mapper.convertValue(patch, List.class);
  assertDiffs(diffObjects, expected);

}
 
Example 11
Source File: AWSUtil.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Set all prefixed properties on {@link ClientConfiguration}.
 * @param config
 * @param configProps
 */
public static void setAwsClientConfigProperties(ClientConfiguration config,
												Properties configProps) {

	Map<String, Object> awsConfigProperties = new HashMap<>();
	for (Map.Entry<Object, Object> entry : configProps.entrySet()) {
		String key = (String) entry.getKey();
		if (key.startsWith(AWS_CLIENT_CONFIG_PREFIX)) {
			awsConfigProperties.put(key.substring(AWS_CLIENT_CONFIG_PREFIX.length()), entry.getValue());
		}
	}
	// Jackson does not like the following properties
	String[] ignorableProperties = {"secureRandom"};
	BeanDeserializerModifier modifier = new BeanDeserializerModifierForIgnorables(
		ClientConfiguration.class, ignorableProperties);
	DeserializerFactory factory = BeanDeserializerFactory.instance.withDeserializerModifier(
		modifier);
	ObjectMapper mapper = new ObjectMapper(null, null,
		new DefaultDeserializationContext.Impl(factory));

	JsonNode propTree = mapper.convertValue(awsConfigProperties, JsonNode.class);
	try {
		mapper.readerForUpdating(config).readValue(propTree);
	} catch (IOException ex) {
		throw new RuntimeException(ex);
	}
}
 
Example 12
Source File: JacksonUtil.java    From yshopmall with Apache License 2.0 5 votes vote down vote up
public static List<String> parseStringList(String body, String field) {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node;
    try {
        node = mapper.readTree(body);
        JsonNode leaf = node.get(field);

        if (leaf != null)
            return mapper.convertValue(leaf, new TypeReference<List<String>>() {
            });
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    return null;
}
 
Example 13
Source File: OASParserUtil.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
/**
 * This method returns extension of CORS config related to micro-gw
 *
 * @param extensions Map<String, Object>
 * @return CORSConfiguration
 * @throws APIManagementException throws if an error occurred
 */
public static CORSConfiguration getCorsConfigFromSwagger(Map<String, Object> extensions) throws APIManagementException {
    boolean corsConfigurationEnabled = false;
    boolean accessControlAllowCredentials = false;
    List<String> accessControlAllowOrigins = new ArrayList<>();
    List<String> accessControlAllowHeaders = new ArrayList<>();
    List<String> accessControlAllowMethods = new ArrayList<>();
    CORSConfiguration corsConfig = new CORSConfiguration(corsConfigurationEnabled,
            accessControlAllowOrigins, accessControlAllowCredentials, accessControlAllowHeaders,
            accessControlAllowMethods);
    ObjectMapper mapper = new ObjectMapper();

    if (extensions.containsKey(APIConstants.X_WSO2_CORS)) {
        Object corsConfigObject = extensions.get(APIConstants.X_WSO2_CORS);
        JsonNode objectNode = mapper.convertValue(corsConfigObject, JsonNode.class);
        corsConfigurationEnabled = Boolean.parseBoolean(String.valueOf(objectNode.get("corsConfigurationEnabled")));
        accessControlAllowCredentials = Boolean.parseBoolean(String.valueOf(objectNode.get("accessControlAllowCredentials")));
        accessControlAllowHeaders = mapper.convertValue(objectNode.get("accessControlAllowHeaders"), ArrayList.class);
        accessControlAllowOrigins = mapper.convertValue(objectNode.get("accessControlAllowOrigins"), ArrayList.class);
        accessControlAllowMethods = mapper.convertValue(objectNode.get("accessControlAllowMethods"), ArrayList.class);
        corsConfig.setCorsConfigurationEnabled(corsConfigurationEnabled);
        corsConfig.setAccessControlAllowCredentials(accessControlAllowCredentials);
        corsConfig.setAccessControlAllowHeaders(accessControlAllowHeaders);
        corsConfig.setAccessControlAllowOrigins(accessControlAllowOrigins);
        corsConfig.setAccessControlAllowMethods(accessControlAllowMethods);
    }
    return corsConfig;
}
 
Example 14
Source File: RecordController.java    From java-crud-api with MIT License 5 votes vote down vote up
@RequestMapping(value = "/{table}", method = RequestMethod.POST, headers = "Content-Type=application/x-www-form-urlencoded")
public ResponseEntity<?> create(@PathVariable("table") String table,
		@RequestBody LinkedMultiValueMap<String, String> record,
		@RequestParam LinkedMultiValueMap<String, String> params) {
	ObjectMapper mapper = new ObjectMapper();
	Object pojo = mapper.convertValue(convertToSingleValueMap(record), Object.class);
	return create(table, pojo, params);
}
 
Example 15
Source File: JacksonUtil.java    From mall with MIT License 5 votes vote down vote up
public static List<Integer> parseIntegerList(String body, String field) {
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = null;
    try {
        node = mapper.readTree(body);
        JsonNode leaf = node.get(field);

        if (leaf != null)
            return mapper.convertValue(leaf, new TypeReference<List<Integer>>() {
            });
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 16
Source File: Multifield.java    From bobcat with Apache License 2.0 5 votes vote down vote up
/**
 * Sets next element in dialog multifield.
 *
 * @param value yaml configuration containing list of {@link MultifieldEntry} representation.
 */
@Override
public void setValue(Object value) {
  ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
  List<MultifieldEntry> cfg =
      mapper.convertValue(value, new TypeReference<List<MultifieldEntry>>() {
      });

  while(items.size() < cfg.size()) {
    addField();
  }

  Iterator<MultifieldItem> itemsIterator = items.iterator();
  cfg.forEach(entry -> itemsIterator.next().setValue(entry));
}
 
Example 17
Source File: OrgBulkUploadBackgroundJobActor.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
private void callCreateOrg(
    Organisation org, BulkUploadProcessTask task, List<String> locationCodes)
    throws JsonProcessingException {
  ObjectMapper mapper = new ObjectMapper();
  Map<String, Object> row = mapper.convertValue(org, Map.class);
  row.put(JsonKey.LOCATION_CODE, locationCodes);
  String orgId;
  try {
    orgId = orgClient.createOrg(getActorRef(ActorOperations.CREATE_ORG.getValue()), row);
  } catch (Exception ex) {
    ProjectLogger.log(
        "OrgBulkUploadBackgroundJobActor:callCreateOrg: Exception occurred with error message = "
            + ex.getMessage(),
        LoggerEnum.INFO);
    setTaskStatus(
        task, ProjectUtil.BulkProcessStatus.FAILED, ex.getMessage(), row, JsonKey.CREATE);
    return;
  }

  if (StringUtils.isEmpty(orgId)) {
    ProjectLogger.log(
        "OrgBulkUploadBackgroundJobActor:callCreateOrg: Org ID is null !", LoggerEnum.ERROR);
    setTaskStatus(
        task,
        ProjectUtil.BulkProcessStatus.FAILED,
        ResponseCode.internalError.getErrorMessage(),
        row,
        JsonKey.CREATE);
  } else {
    row.put(JsonKey.ORGANISATION_ID, orgId);
    setSuccessTaskStatus(task, ProjectUtil.BulkProcessStatus.COMPLETED, row, JsonKey.CREATE);
  }
}
 
Example 18
Source File: TypeGeneratorWithFieldsGenIntegrationTest.java    From graphql-java-type-generator with MIT License 4 votes vote down vote up
public void testClassWithListOrArray(String debug, Object testObject, Class<?> clazzUnderTest) {
    logger.debug("{}", debug);
    Object testType = testContext.getOutputType(clazzUnderTest);
    Assert.assertThat(testType, instanceOf(GraphQLOutputType.class));
    
    GraphQLObjectType queryType = newObject()
            .name("testQuery")
            .field(newFieldDefinition()
                    .type((GraphQLOutputType) testType)
                    .name("testObj")
                    .staticValue(testObject)
                    .build())
            .build();
    GraphQLSchema testSchema = GraphQLSchema.newSchema()
            .query(queryType)
            .build();
    
    String queryString = 
    "{"
    + "  testObj {"
    + "    strings"
    + "    ints"
    + "    objects {"
    + "      objName"
    + "      objIndex"
    + "      simple"
    + "      littleBBoolean"
    + "    }"
    + "  }"
    + "}";
    ExecutionResult queryResult = new GraphQL(testSchema).execute(queryString);
    assertThat(queryResult.getErrors(), is(empty()));
    Map<String, Object> resultMap = (Map<String, Object>) queryResult.getData();
    logger.debug("{} results {}", debug, TypeGeneratorTest.prettyPrint(resultMap));
    
    final ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> expectedQueryData = mapper
            .convertValue(testObject, Map.class);
    assertThat(((Map<String, Object>)resultMap.get("testObj")),
            equalTo(expectedQueryData));
}
 
Example 19
Source File: CBOR.java    From mcumgr-android with Apache License 2.0 4 votes vote down vote up
public static <T> T getObject(@NotNull byte[] data, @NotNull String key, @NotNull Class<T> type) throws IOException {
    ObjectMapper mapper = new ObjectMapper(sFactory);
    return mapper.convertValue(mapper.readTree(data).get(key), type);
}
 
Example 20
Source File: CentralizedManagement.java    From light-4j with Apache License 2.0 4 votes vote down vote up
private static Object convertMapToObj(Map<String, Object> map, Class clazz) {
    ObjectMapper mapper = new ObjectMapper();
    Object obj = mapper.convertValue(map, clazz);
    return obj;
}