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

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#readValue() . 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: ActionHistoryProvider.java    From seldon-server with Apache License 2.0 6 votes vote down vote up
@Override
public void configUpdated(String client, String configKey,
		String configValue) {
	if (configKey.equals(ACTION_HISTORY_KEY)){
		logger.info("Received new action provider config for "+ client+": "+ configValue);
		try {
			ObjectMapper mapper = new ObjectMapper();
			ActionHistoryConfig config = mapper.readValue(configValue, ActionHistoryConfig.class);
			ActionHistory provider = applicationContext.getBean(config.type,ActionHistory.class);
			ActionProvider ap = new ActionProvider(provider, config.addActions);
			providers.put(client, ap);
			logger.info("Successfully added new action provider config for "+client);
            } catch (IOException | BeansException e) {
                logger.error("Couldn't update action provider for client " +client, e);
            }
	}
}
 
Example 2
Source File: AnimalsTest.java    From raml-java-tools with Apache License 2.0 6 votes vote down vote up
@Test
public void doUndo() throws Exception {

    PetResponse response = new PetResponseImpl();
    CatImpl cat = new CatImpl();
    cat.setLegs(4);

    response.setMyPet(cat);
    ObjectMapper mapper = new ObjectMapper();
    StringWriter out = new StringWriter();
    mapper.writeValue(out, response);

    System.err.println(out.toString());

    PetResponse b = mapper.readValue(new StringReader(out.toString()), PetResponse.class);

    assertEquals(4, ((Cat)b.getMyPet()).getLegs());
}
 
Example 3
Source File: IndexOperationResponse.java    From nifi with Apache License 2.0 5 votes vote down vote up
public static IndexOperationResponse fromJsonResponse(String response) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    Map<String, Object> parsedResponse = mapper.readValue(response, Map.class);
    int took = (int) parsedResponse.get("took");
    boolean hasErrors = (boolean) parsedResponse.get("errors");
    List<Map<String, Object>> items = (List<Map<String, Object>>)parsedResponse.get("items");

    IndexOperationResponse retVal = new IndexOperationResponse(took);
    retVal.hasErrors = hasErrors;
    retVal.items = items;

    return retVal;
}
 
Example 4
Source File: JsonHelper.java    From FrameworkBenchmarks with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static Map toMap(String json) {
    ObjectMapper mapper = new ObjectMapper();
    try {
        return mapper.readValue(json, Map.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 5
Source File: AbstractTrainer.java    From ltr4l with Apache License 2.0 5 votes vote down vote up
/**
 * This returns the appropriate implementation of Trainer depending on the algorithm.
 * @param trainingSet The QuerySet containing the data to be used for training.
 * @param validationSet The QuerySet containing the data to be used for validation.
 * @param reader The Config Reader containing parameters needed for Ranker class.
 * @param override Set another Config that overrides reader Config.
 * @return new class which implements trainer.
 */
public static AbstractTrainer getTrainer(QuerySet trainingSet, QuerySet validationSet, Reader reader, Config override) {
  String algorithm;
  ObjectMapper mapper = new ObjectMapper();
  mapper.disable(JsonParser.Feature.AUTO_CLOSE_SOURCE);
  try{
    Map model = mapper.readValue(reader, Map.class);
    algorithm = ((String)model.get("algorithm")).toLowerCase();
    reader.reset();
    return getTrainer(algorithm, trainingSet, validationSet, reader, override);
  }
  catch (IOException e){
    throw new IllegalArgumentException(e);
  }
}
 
Example 6
Source File: KnoxSession.java    From knox with Apache License 2.0 5 votes vote down vote up
public static <T> Map<String, T> getMapFromJsonString(String json) throws IOException {
  Map<String, T> obj;
  JsonFactory factory = new JsonFactory();
  ObjectMapper mapper = new ObjectMapper(factory);
  TypeReference<Map<String, T>> typeRef = new TypeReference<Map<String, T>>() {};
  obj = mapper.readValue(json, typeRef);
  return obj;
}
 
Example 7
Source File: DynamicSettingsTest.java    From openapi-generator with Apache License 2.0 5 votes vote down vote up
@Test
public void testDynamicSettingsSetsConstructorDefaultsOnDeserialization() throws Exception {
    ObjectMapper mapper = Yaml.mapper();
    mapper.registerModule(new GuavaModule());

    String gitHost = "test.com";
    String gitUserId = "openapitools";
    String spec =
            "supportPython2: true" + System.lineSeparator() +
            "gitHost: '" + gitHost + "'" + System.lineSeparator() +
            "gitUserId: '" + gitUserId + "'" + System.lineSeparator();

    DynamicSettings dynamicSettings = mapper.readValue(spec, DynamicSettings.class);
    GeneratorSettings generatorSettings = dynamicSettings.getGeneratorSettings();
    WorkflowSettings workflowSettings = dynamicSettings.getWorkflowSettings();

    assertNotNull(dynamicSettings);
    assertNotNull(generatorSettings);
    assertNotNull(workflowSettings);

    assertEquals(generatorSettings.getGitHost(), gitHost);
    assertEquals(generatorSettings.getGitUserId(), gitUserId);
    assertEquals(generatorSettings.getGitRepoId(), "GIT_REPO_ID");
    assertEquals(generatorSettings.getReleaseNote(), "Minor update");

    assertEquals(generatorSettings.getAdditionalProperties().size(), 5);
    assertEquals(generatorSettings.getAdditionalProperties().get("supportPython2"), true);
    assertEquals(generatorSettings.getAdditionalProperties().get("gitHost"), gitHost);
    assertEquals(generatorSettings.getAdditionalProperties().get("gitUserId"), gitUserId);
    assertEquals(generatorSettings.getAdditionalProperties().get("gitRepoId"), "GIT_REPO_ID");
    assertEquals(generatorSettings.getAdditionalProperties().get("releaseNote"), "Minor update");
}
 
Example 8
Source File: CBOR.java    From mcumgr-android with Apache License 2.0 5 votes vote down vote up
public static Map<String, String> toStringMap(byte[] data) throws IOException {
    ObjectMapper mapper = new ObjectMapper(sFactory);
    TypeReference<HashMap<String, String>> typeRef =
            new TypeReference<HashMap<String, String>>() {};
    ByteArrayInputStream inputStream = new ByteArrayInputStream(data);
    return mapper.readValue(inputStream, typeRef);
}
 
Example 9
Source File: LoggingServletTest.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Test
public void testGet() throws Exception {
  ServletCaller caller = new ServletCaller();

  ILoggingEvent e = createEvent("test");

  events.add(e);
  caller.doGet(new LoggingServlet(logging));

  ObjectMapper mapper = new ObjectMapper();
  @SuppressWarnings("rawtypes")
  List list = mapper.readValue(caller.getResponseBody(), List.class);
  assertEquals(1, list.size());
}
 
Example 10
Source File: ProjectSerDeserTest.java    From usergrid with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmbedded() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    BaseResult result = mapper.readValue( EMBEDDED, BaseResult.class );
    assertNotNull( result );
    assertNotNull( result.getProject() );
}
 
Example 11
Source File: TranslationSyncAPITest.java    From singleton with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testUpdateTranslation() throws Exception{
	UpdateTranslationDTO updateTranslationDTO = new UpdateTranslationDTO();
	UpdateTranslationDataDTO updateTranslationDataDTO = new UpdateTranslationDataDTO();
	List<TranslationDTO> translationDTOList = new ArrayList<TranslationDTO>();
	TranslationDTO translationDTO = new TranslationDTO();
	translationDTO.setComponent(ConstantsForTest.CIM);
	translationDTO.setLocale(ConstantsForTest.ZH_CN);
	String key = "Partner_Name";
	String translation = "合作伙伴名称";
	Map<String,String> messages = new HashMap<String,String>();
	messages.put(key, translation);
	translationDTO.setMessages(messages);
	translationDTOList.add(translationDTO);
	updateTranslationDataDTO.setProductName(ConstantsForTest.VCG);
	updateTranslationDataDTO.setTranslation(translationDTOList);
	updateTranslationDataDTO.setVersion(ConstantsForTest.VERSION);
	updateTranslationDTO.setData(updateTranslationDataDTO);
	updateTranslationDTO.setRequester(ConstantsForTest.GRM);
	ObjectMapper mapper = new ObjectMapper();
       String requestJson = mapper.writeValueAsString(updateTranslationDTO);
	RequestUtil.sendRequest(webApplicationContext,ConstantsForTest.PUT,ConstantsForTest.StringUpdateTranslationAPIURI,requestJson);
	String content = RequestUtil.sendRequest(webApplicationContext,ConstantsForTest.GET, ConstantsForTest.StringValidateUpdateTranslationAPIURI);
	APIResponseDTO apiResponseDTO = mapper.readValue(content, APIResponseDTO.class);
	Map dataMap = (Map)apiResponseDTO.getData();
	String bundleTranslation = (String)dataMap.get("translation");
	//assertEquals("equals",translation,bundleTranslation);
}
 
Example 12
Source File: ExecuteQueryAction.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
public static List<ModelFieldPaths> deserializeList(String serialized, Collection<Relationship> relationShips, IModelStructure modelStructure, Query query)
		throws SerializationException {
	ObjectMapper mapper = new ObjectMapper();
	SimpleModule simpleModule = new SimpleModule("SimpleModule", new Version(1, 0, 0, null));
	simpleModule.addDeserializer(ModelFieldPaths.class, new ModelFieldPathsJSONDeserializer(relationShips, modelStructure, query));
	mapper.registerModule(simpleModule);
	TypeReference<List<ModelFieldPaths>> type = new TypeReference<List<ModelFieldPaths>>() {
	};
	try {
		return mapper.readValue(serialized, type);
	} catch (Exception e) {
		throw new SerializationException("Error deserializing the list of ModelFieldPaths", e);
	}
}
 
Example 13
Source File: ValidateTwitterFollowerCount.java    From Azure-Serverless-Computing-Cookbook-Second-Edition with MIT License 5 votes vote down vote up
/**
  * This function listens at endpoint "/api/ValidateTwitterFollowerCount". Two ways to invoke it using "curl" command in bash:
  * 1. curl -d "HTTP Body" {your host}/api/ValidateTwitterFollowerCount
  * 2. curl {your host}/api/ValidateTwitterFollowerCount?name=HTTP%20Query
  */
 @FunctionName("ValidateTwitterFollowerCount")
 public HttpResponseMessage run(
         @HttpTrigger(name = "request", methods = {HttpMethod.GET, HttpMethod.POST}, authLevel = AuthorizationLevel.ANONYMOUS) HttpRequestMessage<Optional<String>> request,
         @SendGridOutput(name = "outputEmail", 
         apiKey = "SendGridAPIKey",  
         from = "[email protected]", 
         to = "your_email_address",
         subject = "{Name} with {followersCount} followers has posted a tweet",
         text = "{tweettext}") OutputBinding<Mail> outputEmail,
             final ExecutionContext context) {
     context.getLogger().info("Java HTTP trigger processed a request.");

     TwitterMessage twitterMessage = null;

     String json = request.getBody().orElse(null);
     if (json != null) {
         ObjectMapper mapper = new ObjectMapper();
         try {
             twitterMessage = mapper.readValue(json, TwitterMessage.class);
         } catch (IOException e) {
	twitterMessage = new TwitterMessage();
}
     }
     else {
         twitterMessage = new TwitterMessage();
         twitterMessage.setFollowersCount(Integer.parseInt(request.getQueryParameters().get("followersCount")));
         twitterMessage.setTweetText(request.getQueryParameters().get("tweettext"));
         twitterMessage.setName(request.getQueryParameters().get("Name"));
     }

     if (twitterMessage.getFollowersCount() == 0 
             || StringUtils.isBlank(twitterMessage.getTweetText()) 
             || StringUtils.isBlank(twitterMessage.getName())) {
         return request.createResponseBuilder(HttpStatus.BAD_REQUEST).body("Please pass a name on the query string or in the request body").build();
     } else {
         outputEmail.setValue(new Mail());
         return request.createResponseBuilder(HttpStatus.OK).body("Success").build();
     }
 }
 
Example 14
Source File: SeqTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void test2() throws IOException {
    ObjectMapper mapper = mapper().addMixIn(clz(), WrapperObject.class);
    Seq<?> src = of(1);
    String plainJson = mapper().writeValueAsString(src);
    String wrappedJson = mapper.writeValueAsString(src);
    Assertions.assertEquals(wrappedJson, wrapToObject(implClzName(), plainJson));
    Seq<?> restored = (Seq<?>) mapper.readValue(wrappedJson, clz());
    Assertions.assertEquals(src, restored);
}
 
Example 15
Source File: JsonUtil.java    From pandaria with MIT License 4 votes vote down vote up
public static Map<String, Object> jsonToMap(String content) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    return objectMapper.readValue(content, new TypeReference<Map<String, Object>>() {
    });
}
 
Example 16
Source File: ShortAnswerItemProcessor.java    From judgels with GNU General Public License v2.0 4 votes vote down vote up
@Override
public ItemConfig parseItemConfigFromString(ObjectMapper objectMapper, String json) throws IOException {
    return objectMapper.readValue(json, ShortAnswerItemConfig.class);
}
 
Example 17
Source File: TestBulkSearchEWithQBE.java    From java-client-api with Apache License 2.0 4 votes vote down vote up
@Test
public void testBulkSearchQBEResponseInParserHandle() throws KeyManagementException, NoSuchAlgorithmException, IOException, ParserConfigurationException, SAXException,
    TransformerException {
  int count;

  // Creating a xml document manager for bulk search
  XMLDocumentManager docMgr = client.newXMLDocumentManager();
  // using QBE for query definition and set the search criteria

  QueryManager queryMgr = client.newQueryManager();
  String queryAsString = "{\"$query\": { \"says\": {\"$word\":\"woof\",\"$exact\": false}}}";
  RawQueryByExampleDefinition qd = queryMgr.newRawQueryByExampleDefinition(new StringHandle(queryAsString).withFormat(Format.JSON));

  // set document manager level settings for search response
  docMgr.setPageLength(25);
  docMgr.setSearchView(QueryView.RESULTS);
  docMgr.setNonDocumentFormat(Format.JSON);

  // Search for documents where content has bar and get first result record,
  // get JacksonParserHandle on it,Use DOMHandle to read results
  JacksonParserHandle sh = new JacksonParserHandle();
  DocumentPage page;

  long pageNo = 1;
  do {
    count = 0;
    page = docMgr.search(qd, pageNo, sh);
    if (pageNo > 1) {
      assertFalse("Is this first Page", page.isFirstPage());
      assertTrue("Is page has previous page ?", page.hasPreviousPage());
    }
    while (page.hasNext()) {
      DocumentRecord rec = page.next();
      rec.getFormat();
      validateRecord(rec, Format.JSON);
      System.out.println(rec.getContent(new StringHandle()).get().toString());
      count++;
    }

    assertEquals("document count", page.size(), count);
    pageNo = pageNo + page.getPageSize();
  } while (!page.isLastPage() && page.hasContent());

  ObjectMapper mapper = new ObjectMapper();
  JsonParser jsonParser = sh.get();

  JsonNode jnode = null;
  jnode = mapper.readValue(jsonParser, JsonNode.class);

  assertTrue("Page start in results and on page", jnode.get("start").asLong() == page.getStart());

  assertEquals("page count is  ", 5, page.getTotalPages());
  assertTrue("Page has previous page ?", page.hasPreviousPage());
  assertEquals("page size", 25, page.getPageSize());
  assertEquals("document count", 102, page.getTotalSize());
  sh.close();
}
 
Example 18
Source File: JacksonLombokAnnotationIntrospectorTest.java    From jackson-lombok with MIT License 4 votes vote down vote up
@Test(expected = JsonMappingException.class)
public void testJacksonUnableToDeserialize() throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(instance);
    mapper.readValue(json, ImmutablePojo.class);
}
 
Example 19
Source File: IntegrationTestHelper.java    From ServiceCutter with Apache License 2.0 4 votes vote down vote up
public static <T> List<T> readListFromFile(final String filepath, final Class<T> type) throws URISyntaxException, UnsupportedEncodingException, IOException {
	ObjectMapper mapper = new ObjectMapperContextResolver().getContext(null);
	List<T> result = mapper.readValue(readFromFile(filepath), new TypeReference<List<T>>() {
	});
	return result;
}
 
Example 20
Source File: OperationProcessor.java    From product-emm with Apache License 2.0 4 votes vote down vote up
/**
 * Set policy bundle.
 *
 * @param operation - Operation object.
 */
public void setPolicyBundle(org.wso2.emm.agent.beans.Operation operation) throws AndroidAgentException {
	if (isDeviceAdminActive()) {
		if (Preference.getString(context, Constants.PreferenceFlag.APPLIED_POLICY) != null) {
			operationManager.revokePolicy(operation);
		}
		String payload = operation.getPayLoad().toString();
		if (Constants.DEBUG_MODE_ENABLED) {
			Log.d(TAG, "Policy payload: " + payload);
		}
		PolicyOperationsMapper operationsMapper = new PolicyOperationsMapper();
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

		try {
			if (payload != null) {
				Preference.putString(context, Constants.PreferenceFlag.APPLIED_POLICY, payload);
			}

			List<Operation> operations = mapper.readValue(
					payload,
					mapper.getTypeFactory().
							constructCollectionType(List.class, org.wso2.emm.agent.beans.Operation.class));

			for (org.wso2.emm.agent.beans.Operation op : operations) {
				op = operationsMapper.getOperation(op);
				this.doTask(op);
			}
			operation.setStatus(context.getResources().getString(R.string.operation_value_completed));
			operationManager.setPolicyBundle(operation);

			if (Constants.DEBUG_MODE_ENABLED) {
				Log.d(TAG, "Policy applied");
			}
		} catch (IOException e) {
			operation.setStatus(context.getResources().getString(R.string.operation_value_error));
			operation.setOperationResponse("Error occurred while parsing policy bundle stream.");
			operationManager.setPolicyBundle(operation);
			throw new AndroidAgentException("Error occurred while parsing stream", e);
		}
	} else {
		operation.setStatus(context.getResources().getString(R.string.operation_value_error));
		operation.setOperationResponse("Device administrator is not activated, hence cannot execute policies.");
		operationManager.setPolicyBundle(operation);
		throw new AndroidAgentException("Device administrator is not activated, hence cannot execute policies");
	}
}