@Test public void testSerializeThenDeSerialize() throws Exception { DeviceTagMap tagMap = new DeviceTagMap(); tagMap.addTag("device1", "tag1"); tagMap.addTag("device1", "tag2"); tagMap.addTag("device1", "tag3"); tagMap.addTag("device1", "tag4"); tagMap.addTag("device2", "tag1"); tagMap.addTag("device2", "tag2"); tagMap.addTag("device2", "tag3"); tagMap.addTag("device2", "tag4"); String marshalledString = toJsonString(tagMap.getTagInfoList()); LOGGER.trace("testSerializeThenSerialize : marshalledString=\n{}", JsonWriter.formatJson(marshalledString)); Object obj = fromJson(marshalledString, new TypeReference<List<DeviceTagInfo>>(){}); LOGGER.trace("testSerializeThenSerialize : unmarshalled object={}", obj); List<DeviceTagInfo> unmarshalledTags = (List<DeviceTagInfo>) obj; assertEquals(tagMap.getTagInfoList(), unmarshalledTags); }
public static List<Application> getApplications( String response ) { List<Application> applications = new ArrayList<>(); ObjectMapper mapper = new ObjectMapper(); try { applications = mapper.readValue( response, new TypeReference<List<Application>>() { } ); } catch ( IOException e ) { e.printStackTrace(); } return applications; }
private boolean addNewFact(){ boolean succeeded = false; try{ String factStr = addFactArea.getText(); Map<String, List<String>> newFact = KRFUtil.objectMapper.readValue(factStr, new TypeReference<Map<String, List<String>>>() {}); if(!isValidFact(newFact)){ throw new Exception("Invalid Format Specified For Fact!"); } inputCaseBase.getInputCaseBase().add(newFact); succeeded = true; message.setText("New Fact added successfully"); }catch(Exception e){ message.setText("Error adding fact {} " + e.getMessage()); } return succeeded; }
@Override public void prepare(Map stormConf, TopologyContext context) { mapper = new ObjectMapper(); this.configParams = (JSONObject) new JSONObject(this.config).get("params"); try { this.configMap = mapper.readValue(this.config,new TypeReference<Map<String, Object>>() {}); mapParams = (Map<String,Object>) configMap.get("params"); } catch (IOException e) { e.printStackTrace(); } field = getParam("field1", true); operator = getParam("operator", true); field2 = getParam("field2", true); entity = getParam("entity"); }
@Override public void prepare(Map stormConf, TopologyContext context) { mapper = new ObjectMapper(); this.configParams = (JSONObject) new JSONObject(this.config).get("params"); try { this.configMap = mapper.readValue(this.config,new TypeReference<Map<String, Object>>() {}); mapParams = (Map<String,Object>) configMap.get("params"); } catch (IOException e) { e.printStackTrace(); } field = getParam("field", true); operator = (String) getParam("operator", true); value = (String) getParam("value", true); entity = (String) getParam("value"); if (operator.equals("RegexExpression")) { pattern = Pattern.compile(value, Pattern.DOTALL); } }
@Override public final void execute(Tuple input, BasicOutputCollector collector) { _collector = collector; if (isTickTuple(input)) { tickTupleCase(); } else { try { this.rawJson = input.getStringByField("map"); this.json = mapper.readValue(input.getStringByField("map"),new TypeReference<Map<String, Object>>() {}); this.userexecute(); } catch (Exception e) { e.printStackTrace(); } } }
@Override public final void execute(Tuple input, BasicOutputCollector collector) { _collector = collector; if (isTickTuple(input)) { tickTupleCase(); } else { try { this.rawJson = input.getStringByField("map"); this.json = mapper.readValue(rawJson, new TypeReference<Map<String, Object>>() {}); this.userexecute(); } catch (Exception e) { e.printStackTrace(); } } }
public static <T> BaseResult<T> parse(String responseStr, Class<T> type) { System.out.println(responseStr); BaseResult<T> result = new BaseResult<T>(); try { BaseResult br = mapper.readValue(responseStr, new TypeReference<BaseResult<T>>() {}); if (br.isSuccess()) { result.setData(mapToObject(br.getData(), type)); } else { result.setCode(br.getCode()); result.setMsg(br.getMsg()); } return result; } catch (Exception ex) { System.err.println("Failed to Parse " + responseStr + " : " + ex.getMessage()); result.setCode(-1); result.setMsg("response parse error"); result.setData(null); } return result; }
/** * Reads a collection of FileTrackingStatus.<br/> * If plain text is a list of line separated plain text.<br/> * If json this should be a json array.<br/> * * @param format * @param reader * @return * @throws JsonParseException * @throws JsonMappingException * @throws IOException */ @SuppressWarnings("unchecked") public Collection<FileTrackingStatus> readList(FORMAT format, Reader reader) throws JsonParseException, JsonMappingException, IOException { Collection<FileTrackingStatus> coll = null; if (format.equals(FORMAT.JSON)) { coll = (Collection<FileTrackingStatus>) mapper.readValue(reader, new TypeReference<Collection<FileTrackingStatus>>() { }); } else { BufferedReader buff = new BufferedReader(reader); coll = new ArrayList<FileTrackingStatus>(); String line = null; while ((line = buff.readLine()) != null) { coll.add(read(FORMAT.TXT, line)); } } return coll; }
public static SolrInputDocument createDocument(String dataStr) throws JsonParseException, JsonMappingException, IOException { Map<String, Object> dataMap = new ObjectMapper().readValue(dataStr, new TypeReference<HashMap<String, Object>>() { }); SolrInputDocument document = new SolrInputDocument(); for (Iterator<String> i = dataMap.keySet().iterator(); i.hasNext();) { String fieldName = i.next(); Object fieldValue = dataMap.get(fieldName); document.addField(fieldName, fieldValue); } return document; }
@Test public void testExecute() throws SolrServerException, IOException { String solrUrl = cluster.getJettySolrRunners().get(0).getBaseUrl() + "/" + COLLECTION; Map<String, Object> attrs = new HashMap<String, Object>(); attrs.put("solr_url", solrUrl); attrs.put("unique_id", "1"); DeleteCommand deleteCommand = new DeleteCommand(); deleteCommand.execute(attrs); System.out.flush(); String expected = "{\"status\":0,\"message\":\"OK\"}\n"; String actual = _baos.toString(); Map<String, Object> expectedMap = new ObjectMapper().readValue(expected, new TypeReference<HashMap<String, Object>>() { }); Map<String, Object> actualMap = new ObjectMapper().readValue(actual, new TypeReference<HashMap<String, Object>>() { }); assertEquals(expectedMap.get("status"), actualMap.get("status")); }
@Test public void testExecute() throws SolrServerException, IOException { String solrUrl = cluster.getJettySolrRunners().get(0).getBaseUrl() + "/" + COLLECTION; Map<String, Object> attrs = new HashMap<String, Object>(); attrs.put("solr_url", solrUrl); attrs.put("query", "SolrJ"); SearchCommand searchCommand = new SearchCommand(); searchCommand.execute(attrs); System.out.flush(); String expected = "{\"status\":0,\"message\":\"OK\"}\n"; String actual = _baos.toString(); Map<String, Object> expectedMap = new ObjectMapper().readValue(expected, new TypeReference<HashMap<String, Object>>() { }); Map<String, Object> actualMap = new ObjectMapper().readValue(actual, new TypeReference<HashMap<String, Object>>() { }); assertEquals(expectedMap.get("status"), actualMap.get("status")); }
/** * JSON串转换为Java泛型对象,可以是各种类型,此方法最为强大。用法看测试用例。 * * @param <T> * @param jsonString * JSON字符串 * @param tr * TypeReference,例如: new TypeReference< List<FamousUser> >(){} * @return List对象列表 */ @SuppressWarnings("unchecked") public static <T> T json2GenericObject(String jsonString, TypeReference<T> tr) { if (jsonString == null || "".equals(jsonString)) { return null; } else { try { return (T) objectMapper.readValue(jsonString, tr); } catch (Exception e) { log.warn("json error:" + e.getMessage()); } } return null; }
public static boolean verifyGoogleRecaptcha(String gRecaptchaResponse, String secretKey) { boolean result = false; try { ClientRequest request = new ClientRequest("https://www.google.com/recaptcha/api/siteverify"); request.formParameter("secret", secretKey); request.formParameter("response", gRecaptchaResponse); request.accept("application/json"); ClientResponse<String> response = request.post(String.class); ObjectMapper mapper = new ObjectMapper(); Map<String, String> map = mapper.readValue(new ByteArrayInputStream( response.getEntity().getBytes()), new TypeReference<Map<String, String>>() {}); return Boolean.parseBoolean(map.get("success")); } catch (Exception e) { log.error("Exception happened while verifying recaptcha ", e); return result; } }
@Override public void getRecentReports(final RecentReportsResponseCallback callback) { final Request request = getRequest(HttpMethod.GET, reportsUrl()); doHttpRequest(request, new ClientResponseCallback() { @Override @SuppressWarnings("unchecked") public void onResponse(InputStream response, SalesforceException ex) { List<RecentReport> recentReports = null; if (response != null) { try { recentReports = unmarshalResponse(response, request, new TypeReference<List<RecentReport>>() { } ); } catch (SalesforceException e) { ex = e; } } callback.onResponse(recentReports, ex); } }); }
@Override public void getReportInstances(String reportId, final ReportInstanceListResponseCallback callback) { final Request request = getRequest(HttpMethod.GET, reportInstancesUrl(reportId)); doHttpRequest(request, new ClientResponseCallback() { @Override @SuppressWarnings("unchecked") public void onResponse(InputStream response, SalesforceException ex) { List<ReportInstance> reportInstances = null; if (response != null) { try { reportInstances = unmarshalResponse(response, request, new TypeReference<List<ReportInstance>>() { } ); } catch (SalesforceException e) { ex = e; } } callback.onResponse(reportInstances, ex); } }); }
public Map<NameNodeKey, String> getNNSpecificKeys() { TypeReference<Map<String, String>> type = new TypeReference<Map<String, String>>() { }; Map<NameNodeKey, String> result = new HashMap<NameNodeKey, String>(); try { Map<String, String> tmp = NamenodeMXBeanHelper.mapper.readValue( (String)values.get(NNSPECIFIC_KEYS), type); for (String key: tmp.keySet()) { result.put(new NameNodeKey(key), tmp.get(key)); } return result; } catch (Exception e) { LOG.error(e); return null; } }
/** * Get the map corresponding to the JSON string. */ public static List<EditLogFile> convertJsonToListManifest(String json) throws IOException { if (json == null || json.isEmpty()) { return new ArrayList<EditLogFile>(); } // get the list of strings from the http response TypeReference<List<String>> type = new TypeReference<List<String>>() { }; List<String> logFilesDesc = mapper.readValue(json, type); // we need to convert the list of strings into edit log files List<EditLogFile> logFiles = new ArrayList<EditLogFile>(); for (String lf : logFilesDesc) { logFiles.add(new EditLogFile(lf)); } return logFiles; }
private String removeZFromGeom(String geomString) { geomString = new String(geomString); JsonFactory factory = new JsonFactory(); ObjectMapper mapper = new ObjectMapper(factory); JsonParser parser; try { parser = factory.createJsonParser(geomString.getBytes()); TypeReference<HashMap<String, Object>> typeRef = new TypeReference<HashMap<String, Object>>() { }; HashMap<String, Object> o = mapper.readValue(parser, typeRef); if (o.containsKey("z")) { o.remove("z"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); mapper.writeValue(baos, o); geomString = baos.toString(); } } catch (Exception e) { throw new RuntimeException(LOGGER.translate("SERVICE_AREA_ERROR_REMOVING_Z", e.getMessage()), e); } return geomString; }
@Test public void testDeSerializeThenSerialize() throws Exception { String jsonString = "[\n" + " {\n" + " \"username\":\"user2\"\n," + " \"tags\":[\n" + " \"tag1\",\n" + " \"tag2\",\n" + " \"tag3\",\n" + " \"tag4\"\n" + " ]\n" + " },\n" + " {\n" + " \"username\":\"user1\"\n,"+ " \"tags\":[\n" + " \"tag1\",\n" + " \"tag2\",\n" + " \"tag3\",\n" + " \"tag4\"\n" + " ]\n" + " }\n" + " ]\n"; Object obj = fromJson(jsonString, new TypeReference<List<UserTagInfo>>(){}); LOGGER.trace("testSerializeThenSerialize : unmarshalled object={}", obj); List<UserTagInfo> unmarshalledTags = (List<UserTagInfo>) obj; LOGGER.trace("testDeSerializeThenSerialize : unmarshalledTags={}", unmarshalledTags); String marshalledString = toJsonString(unmarshalledTags); assertEquals(JsonWriter.formatJson(jsonString), JsonWriter.formatJson(marshalledString)); }
@SuppressWarnings("unchecked") @Override protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException { Map<String, Object> tweet = jsonMapper.readValue(value.toString(), new TypeReference<HashMap<String, Object>>(){}); Map<String, Object> entities = (Map<String, Object>) tweet.get("entities"); List<Map<String, Object>> hashTagEntries = null; if (entities != null) { hashTagEntries = (List<Map<String, Object>>) entities.get("hashtags"); } if (hashTagEntries != null && hashTagEntries.size() > 0) { for (Map<String, Object> hashTagEntry : hashTagEntries) { String hashTag = hashTagEntry.get("text").toString(); context.write(new Text(hashTag), ONE); } } }
public void getUserOrganizations() { final RestRequest userOrganizationsRequest = oauthRequestTo(userOrganizations) .method("GET") .addHeader(new HttpHeader("Accept", V3_ACCEPTABLE_TYPE)) .build(); final RestResponse userOrganizationsResponse = userOrganizationsRequest.fetchResponse(); final CollectionPage<Organization> organizations = read(userOrganizationsResponse).as(new TypeReference<CollectionPage<Organization>>() { }); fromPartnershipLink = linksFrom(organizations.get(0)).get("self").getUri(); System.out.println("From Partnership Link : " + fromPartnershipLink); }
@Post("json") public Map<String,Object> notify(String entity) throws Exception { List<StorageSourceNotification> notifications = null; ObjectMapper mapper = new ObjectMapper(); notifications = mapper.readValue(entity, new TypeReference<List<StorageSourceNotification>>(){}); IStorageSourceService storageSource = (IStorageSourceService)getContext().getAttributes(). get(IStorageSourceService.class.getCanonicalName()); storageSource.notifyListeners(notifications); HashMap<String, Object> model = new HashMap<String,Object>(); model.put("output", "OK"); return model; }
@Test public void testDeSerializeThenSerialize() throws Exception { String jsonString = "[\n" + " {\n" + " \"deviceId\":\"device2\",\n" + " \"tags\":[\n" + " \"tag1\",\n" + " \"tag2\",\n" + " \"tag3\",\n" + " \"tag4\"\n" + " ]\n" + " },\n" + " {\n" + " \"deviceId\":\"device1\",\n" + " \"tags\":[\n" + " \"tag1\",\n" + " \"tag2\",\n" + " \"tag3\",\n" + " \"tag4\"\n" + " ]\n" + " }\n" + " ]\n"; Object obj = fromJson(jsonString, new TypeReference<List<DeviceTagInfo>>(){}); LOGGER.trace("testSerializeThenSerialize : unmarshalled object={}", obj); List<DeviceTagInfo> unmarshalledTags = (List<DeviceTagInfo>) obj; LOGGER.trace("testDeSerializeThenSerialize : unmarshalledTags={}", unmarshalledTags); String marshalledString = toJsonString(unmarshalledTags); assertEquals(JsonWriter.formatJson(jsonString), JsonWriter.formatJson(marshalledString)); }
/** * Gets the list of all configured Devices from the Koubachi server. * @param appKey * @param credentials * @param apiDeviceListUrl * * @return the list of all configured Devices. Is never {@code null}. */ private List<Device> getDevices(String apiDeviceListUrl, String credentials, String appKey) { List<Device> devices = new ArrayList<Device>(); String url = String.format(apiDeviceListUrl, credentials, appKey); Properties headers = new Properties(); headers.put("Accept", "application/json"); String response = HttpUtil.executeUrl("GET", url, headers, null, null, HTTP_REQUEST_TIMEOUT); if (response==null) { logger.error("No response received from '{}'", url); } else { logger.debug("Koubachi returned '{}'", response); List<Map<String, Device>> deviceList = fromJSON(new TypeReference<List<Map<String,Device>>>() {}, response); for (Map<String, Device> element : deviceList) { devices.add(element.get("device")); } } return devices; }
/** * Gets the list of all configured Plants from the Koubachi server. * * @return the list of all configured Plants. Is never {@code null}. */ private List<Plant> getPlants(String apiPlantListUrl, String credentials, String appKey) { List<Plant> plants = new ArrayList<Plant>(); String url = String.format(apiPlantListUrl, credentials, appKey); Properties headers = new Properties(); headers.put("Accept", "application/json"); String response = HttpUtil.executeUrl("GET", url, headers, null, null, HTTP_REQUEST_TIMEOUT); if (response==null) { logger.error("No response received from '{}'", url); } else { logger.debug("Koubachi returned '{}'", response); List<Map<String, Plant>> plantList = fromJSON(new TypeReference<List<Map<String,Plant>>>() {}, response); for (Map<String, Plant> element : plantList) { plants.add(element.get("plant")); } } return plants; }
@DataProvider public Collection<Shoes> getAll(DoradoContext context) throws Exception { Collection<Shoes> items = new ArrayList<Shoes>(); Resource resource = context .getResource("classpath:com/bstek/dorado/sample/touch/shoes/shoes.js"); InputStream in = resource.getInputStream(); try { ObjectMapper mapper = new ObjectMapper(); items = mapper.readValue(in, new TypeReference<List<Shoes>>() { }); for (Shoes item : items) { item.setImage(PathUtils .concatPath(">dorado/res/com/bstek/dorado/sample/touch/shoes/" + item.getId() + ".jpg")); } } finally { in.close(); } return items; }
private void buildCardinalityRangeMaps(String file, HashMap<String, Integer> cardinality, HashMap<String, IntRange> range) throws JsonParseException, JsonMappingException, IOException { List<SchemaAnnotation> saList; if (file == null) { return; // Nothing to do here. } ObjectMapper objectMapper = new ObjectMapper(); saList = objectMapper.readValue(new File(file), new TypeReference<List<SchemaAnnotation>>() { }); for (SchemaAnnotation sa : saList) { String column = sa.getColumn(); if (sa.isRange()) { range.put(column, new IntRange(sa.getRangeStart(), sa.getRangeEnd())); } else { cardinality.put(column, sa.getCardinality()); } } }
@Override public List<Repo> getReposToDeploy(@Nullable Map<String, String> headersMap) throws IOException, BintrayException { UsernamePasswordCredentials creds = getCurrentUserBintrayCreds(); String requestUrl = getBaseBintrayApiUrl() + PATH_REPOS + "/" + creds.getUserName(); InputStream responseStream = null; try { responseStream = executeGet(requestUrl, creds, headersMap); if (responseStream != null) { return JacksonReader.streamAsValueTypeReference(responseStream, new TypeReference<List<Repo>>() { }); } } finally { IOUtils.closeQuietly(responseStream); } return null; }
@Override public BintrayUser getBintrayUser(String username, String apiKey, @Nullable Map<String, String> headersMap) throws IOException, BintrayException { String requestUrl = getBaseBintrayApiUrl() + PATH_USERS + "/" + username; InputStream responseStream = null; try { responseStream = executeGet(requestUrl, new UsernamePasswordCredentials(username, apiKey), headersMap); if (responseStream != null) { return JacksonReader.streamAsValueTypeReference(responseStream, new TypeReference<BintrayUser>() { }); } } finally { IOUtils.closeQuietly(responseStream); } return null; }
/** * Returns a list of shared repository details * * @param remoteUrl URL of remote Artifactory instance * @param headersMap Map of headers to set for client * @return List of shared repository details */ private List<RepoDetails> getSharedRemoteRepoDetails(String remoteUrl, Map<String, String> headersMap) { StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(remoteUrl); if (!remoteUrl.endsWith("/")) { urlBuilder.append("/"); } urlBuilder.append(RestConstants.PATH_API).append("/").append(RepositoriesRestConstants.PATH_ROOT). append("?").append(RepositoriesRestConstants.PARAM_REPO_TYPE).append("="). append(RepoDetailsType.REMOTE.name()); try (CloseableHttpResponse response = executeGetMethod(urlBuilder.toString(), headersMap)) { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { return JacksonReader.streamAsValueTypeReference(response.getEntity().getContent(), new TypeReference<List<RepoDetails>>() { } ); } else { return Lists.newArrayList(); } } catch (Exception e) { throw new RuntimeException(e); } }
@Test public void shouldGetEntityFields() throws Exception { List<MetadataDto> exampleMetadata = new LinkedList<>(); exampleMetadata.add(new MetadataDto("key1", "value1")); exampleMetadata.add(new MetadataDto("key2", "value2")); List<FieldDto> expected = new LinkedList<>(); expected.add( new FieldDto( 14L, 9005L, STRING, new FieldBasicDto("Other", "Other", false, false, "test", null, null), false, exampleMetadata, FieldValidationDto.STRING, null, null ) ); ResultActions actions = controller.perform(get("/entities/9005/fields")) .andExpect(status().isOk()); List<FieldDto> fields = new ObjectMapper().readValue(actions.andReturn().getResponse().getContentAsByteArray(), new TypeReference<List<FieldDto>>() {}); assertEquals(expected, fields); }
private Map<String, String> getMapFromJsonString(String s) { ObjectMapper mapper = new ObjectMapper(); HashMap<String, String> map = null; try { //convert JSON string to Map map = mapper.readValue(s, new TypeReference<HashMap<String,String>>(){}); LOGGER.trace("getMapFromJsonString : {}",map); } catch (Exception e) { e.printStackTrace(); } return map; }
/** * 将json转换为Map<String,String>,不用捕获异常. * * @param jsonString 需要处理的json 字串. * @return Map<String,String> */ public static Map<String, String> getSafeStringMap(String jsonString) { Map<String, String> result = new HashMap<String, String>(); if (!TextUtils.isEmpty(jsonString)) { try { result = sObjectMapper.readValue(jsonString, new TypeReference<Map<String, String>>() { }); } catch (IOException e) { Log.e(TAG, "exception", e); } } return result; }
public static <T> T readValueRefer(String jsonStr, Class<T> clazz) { try { return getInstance().readValue(jsonStr, new TypeReference<T>() { }); } catch (IOException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e); } }
private Map<String, Object> getInfoMap(URL cloudControllerUrl) { if (infoCache.containsKey(cloudControllerUrl)) { return infoCache.get(cloudControllerUrl); } String s = restTemplate.getForObject(cloudControllerUrl + "/v2/info", String.class); try { return objectMapper.readValue(s, new TypeReference<Map<String, Object>>() { }); } catch (IOException e) { throw new RuntimeException("Error getting /v2/info from Cloud Controller", e); } }
public static List<CloudResource> convertJsonToCloudResourceList(String json) { List<CloudResource> retList = new ArrayList<CloudResource>(); if (json != null) { try { retList = mapper.readValue(json, new TypeReference<List<CloudResource>>() { }); } catch (IOException e) { logger.warn("Error while reading Java List from JSON response: " + json, e); } } return retList; }
public static List<String> convertJsonToList(String json) { List<String> retList = new ArrayList<String>(); if (json != null) { try { retList = mapper.readValue(json, new TypeReference<List<String>>() { }); } catch (IOException e) { logger.warn("Error while reading Java List from JSON response: " + json, e); } } return retList; }
public static Map<String, Object> convertJsonToMap(String json) { Map<String, Object> retMap = new HashMap<String, Object>(); if (json != null) { try { retMap = mapper.readValue(json, new TypeReference<Map<String, Object>>() { }); } catch (IOException e) { logger.warn("Error while reading Java Map from JSON response: " + json, e); } } return retMap; }