public static Namelist fromJSONtoNamelist(JSONObject jsonObj) { logger.info("Convert json object to namelist..."); if (jsonObj != null) { String name = jsonObj.getString("_name"); String species = jsonObj.getString("_species"); if (species == null) { JSONObject metadataJSONObj = jsonObj.getJSONObject("metadata"); if (metadataJSONObj != null) { species = metadataJSONObj.getString("species"); } } int size = jsonObj.getInt("_size"); JSONArray data = jsonObj.containsKey("_data") ? jsonObj.getJSONArray("_data") : jsonObj.getJSONArray("gaggle-data"); String[] names = new String[data.size()]; for (int i = 0; i < data.size(); i++) { logger.info("Data item: " + data.getString(i)); names[i] = data.getString(i); } logger.info("Species: " + species + " Names: " + names); Namelist nl = new Namelist(name, species, names); return nl; } return null; }
public static String[] json2StringArray(String jsonString) { JSONArray jsonArray = JSONArray.fromObject(jsonString); String[] stringArray = new String[jsonArray.size()]; for (int i = 0; i < jsonArray.size(); i++) { stringArray[i] = jsonArray.getString(i); } return stringArray; }
private String getSleepGraph(JSONObject sleepStats) { JSONArray sleepGraphArray = sleepStats.getJSONArray("sleepGraph"); StringBuilder bf = new StringBuilder(); for (int i = 0; i < sleepGraphArray.size(); i++) { String phaseString = sleepGraphArray.getString(i); Phase phase = Enum.valueOf(Phase.class, phaseString); bf.append(String.valueOf(phase.ordinal())); } return bf.toString(); }
public void executeQuery(String query, int pageSize, String index, String docType, int docLimit) { Search search = new Search.Builder(query) .addIndex(index) .addType(docType) .setParameter(Parameters.SEARCH_TYPE, SearchType.SCAN) .setParameter(Parameters.SIZE, pageSize) .setParameter(Parameters.SCROLL, SCROLL) .build(); System.out.println(query + "$$$$"); try { JestResult searchResult = client.execute(search); // System.out.println(searchResult.getJsonString()); String scrollId = searchResult.getJsonObject().get("_scroll_id").getAsString(); int currentResultSize = 0; int numDocs = 0; do { JSONArray jArrayResult = new JSONArray(); SearchScroll scrollRequest = new SearchScroll.Builder(scrollId, SCROLL) .setParameter(Parameters.SIZE, pageSize) .build(); JestResult scrollResult = client.execute(scrollRequest); scrollId = scrollResult.getJsonObject().get("_scroll_id").getAsString(); JSONObject jObj = (JSONObject) JSONSerializer.toJSON(scrollResult.getJsonString()); JSONArray jArrayHits = jObj.getJSONObject("hits").getJSONArray("hits"); for (int i = 0; i < jArrayHits.size(); i++) { jArrayResult.add(extractTika(jArrayHits.getString(i)).toString()); } writeToFile(jArrayResult); // Note: Current result size will be Page Size * number of shards currentResultSize = jArrayHits.size(); numDocs += currentResultSize; System.out.println("num docs:" + String.valueOf(numDocs)); if (docLimit != -1 && numDocs >= docLimit) { break; } } while (currentResultSize != 0); } catch (IOException e) { LOG.error("Error retrieving from Elasticsearch", e); } }
public void find(String binFile, List<SourceFileResult> results) { File bin = new File(binFile); String url = null; String fileDownloaded = null; try { if (canceled) return; InputStream is2 = null; String md5; try { md5 = new String(Hex.encodeHex(Files.getDigest(bin, MessageDigest.getInstance("MD5")))); String serviceUrl = SERVICE + "/rest/libraries?md5=" + md5; is2 = new URL(serviceUrl).openStream(); String str = IOUtils.toString(is2); JSONArray json = JSONArray.fromObject(str); for (int i = 0; i < json.size(); i++) { if (canceled) return; JSONObject obj = (JSONObject) json.get(i); JSONObject source = obj.getJSONObject("source"); if (source != null && !source.isNullObject()) { JSONArray ar = source.getJSONArray("urls"); if (ar != null && !ar.isEmpty()) { String url1 = ar.getString(0); String tmpFile = new UrlDownloader().download(url1); if (tmpFile != null && isSourceCodeFor(tmpFile, bin.getAbsolutePath())) { fileDownloaded = tmpFile; url = url1; break; } } } } if (url != null && fileDownloaded != null) { String name = url.substring(url.lastIndexOf('/') + 1); SourceFileResult object = new SourceFileResult(binFile, fileDownloaded, name, 90); Logger.debug(this.toString() + " FOUND: " + object, null); results.add(object); } } finally { IOUtils.closeQuietly(is2); } } catch (Exception e) { e.printStackTrace(); } }
/** * 从json数组中解析出java Date 型对象数组,使用本方法必须保�? * * @param jsonString * @return * @throws ParseException */ public static Date[] getDateArray4Json(String jsonString, String dataFormat) throws ParseException { JSONArray jsonArray = JSONArray.fromObject(jsonString); Date[] dateArray = new Date[jsonArray.size()]; String dateString; Date date; for (int i = 0; i < jsonArray.size(); i++) { dateString = jsonArray.getString(i); date = FormatUtil.stringToDate(dateString, dataFormat); dateArray[i] = date; } return dateArray; }
public static Date[] json2DateArray(String jsonString, String DataFormat) { JSONArray jsonArray = JSONArray.fromObject(jsonString); Date[] dateArray = new Date[jsonArray.size()]; String dateString; Date date = null; SimpleDateFormat sdf = new SimpleDateFormat(DataFormat); for (int i = 0; i < jsonArray.size(); i++) { dateString = jsonArray.getString(i); try { date = sdf.parse(dateString); } catch (ParseException e) { e.printStackTrace(); } dateArray[i] = date; } return dateArray; }
public ActivitiProcessInstance(JSONObject pJSonObj) { // Lettura parametri formali JSONObject jSonObj = pJSonObj; this.id = jSonObj.getString("id"); this.processDefinitionId = jSonObj.getString("processDefinitionId"); JSONArray activityNamesArr = jSonObj.getJSONArray("activityNames"); this.activityNames = new ArrayList<String>(); for (int i = 0; i < activityNamesArr.size(); i++) { String item = activityNamesArr.getString(i); activityNames.add(item); } this.ended = jSonObj.getString("ended"); }
public static String getZipcode(JSONObject data) { try { JSONArray results = data.getJSONArray("results"); JSONObject address = results.getJSONObject(0); JSONArray address_components = address.getJSONArray("address_components"); for (int i = 0; i < address_components.size(); i++) { JSONObject postal_code = address_components.getJSONObject(i); JSONArray types = postal_code.getJSONArray("types"); if (types.getString(0).equals("postal_code")) { return (String) postal_code.get("long_name"); } } return "0"; } catch (NullPointerException npe) { npe.printStackTrace(); } return null; }
public void testReadArray() throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.registerModule(new JsonLibModule()); JSONArray array = mapper.readValue("[null, 13, false, 1.25, \"abc\", {\"a\":13}, [ ] ]", JSONArray.class); assertEquals(7, array.size()); assertTrue(JSONUtils.isNull(array.get(0))); assertEquals(13, array.getInt(1)); assertFalse(array.getBoolean(2)); assertEquals(Double.valueOf(1.25), array.getDouble(3)); assertEquals("abc", array.getString(4)); JSONObject ob = array.getJSONObject(5); assertEquals(1, ob.size()); assertEquals(13, ob.getInt("a")); JSONArray array2 = array.getJSONArray(6); assertEquals(0, array2.size()); }
private void writeToFile(JSONArray jArray) { try { FileWriter fw = new FileWriter(outputFile, true); BufferedWriter writer = new BufferedWriter(fw); if (outputType == 0) { writer.write(jArray.toString()); } else if (outputType == 1) { for (int i = 0; i < jArray.size(); i++) { writer.write( jArray.getJSONObject(i).getJSONObject("_source").getString("url").trim() + "\t" + jArray.getString(i)); writer.newLine(); } } writer.close(); } catch (Exception e) { System.out.println(e.getMessage()); } }
void sendTokenProperties(MTWebSocket mtws, String inResponseTo, JSONObject data) { String tokenId = data.getString("tokenId"); Token token = findTokenFromId(tokenId); if (token == null) { System.out.println("DEBUG: sendTokenInfo(): Unable to find token " + tokenId); return; // FIXME: log this error } JSONObject jobj = new JSONObject(); jobj.put("tokenId", tokenId); JSONArray properties = new JSONArray(); JSONObject propertiesMap = new JSONObject(); JSONArray propToFetch = data.getJSONArray("propertyNames"); for (int i = 0; i < propToFetch.size(); i++) { String pname = propToFetch.getString(i); String val; if (pname.startsWith(":")) { val = getTokenValue(token, pname); } else { val = token.getProperty(pname) == null ? null : token.getProperty(pname).toString(); } JSONObject jprop = new JSONObject(); jprop.put("name", pname); jprop.put("value", val); properties.add(jprop); propertiesMap.put(pname, val); } jobj.put("properties", properties); jobj.put("propertiesMap", propertiesMap); mtws.sendMessage("tokenProperties", inResponseTo, jobj); }
@Override public ParameterValue createValue(StaplerRequest request, JSONObject jO) { Object value = jO.get("value"); String strValue = ""; if (value instanceof String) { strValue = (String) value; } else if (value instanceof JSONArray) { JSONArray jsonValues = (JSONArray) value; for (int i = 0; i < jsonValues.size(); i++) { strValue += jsonValues.getString(i); if (i < jsonValues.size() - 1) { strValue += ","; } } } if ("".equals(strValue)) { strValue = defaultValue; } GitParameterValue gitParameterValue = new GitParameterValue(jO.getString("name"), strValue); return gitParameterValue; }
private JSONObject reformLastestBikehireData(String sensorURL, JSONArray filterArr) { JSONObject result = new JSONObject(); try { SensorManager sensorManager = new SensorManager(); Sensor sensor = sensorManager.getSpecifiedSensorWithSensorId(sensorURL); if (sensor == null) return result; Observation obs = null; List<String> observations = new ArrayList(); if (filterArr.size() == 0) { obs = sensorManager.getNewestObservationForOneSensor(sensorURL); if (obs != null) observations.add(obs.getId()); } else { Date fromTime = DateUtil.string2Date(filterArr.getString(2), "MM/dd/yyyy HH:mm"); String operator = filterArr.getString(1); observations = sensorManager.getObservationsWithTimeCriteria(sensorURL, operator, fromTime, null); } JSONObject metaJson = new JSONObject(); metaJson.put("name", sensor.getName()); metaJson.put("source", sensor.getSource()); metaJson.put("sourceType", sensor.getSourceType()); metaJson.put("city", sensor.getPlace().getCity()); metaJson.put("country", sensor.getPlace().getCountry()); Calendar today = Calendar.getInstance(); today.add(Calendar.DATE, -15); Date fromTime = new Date(today.getTimeInMillis()); ArrayList historicalJson = sensorManager.getSensorHistoricalData(sensorURL, fromTime); List signs = new ArrayList<String>(); String sign; Map m1 = new LinkedHashMap(); ArrayList readArr = new ArrayList<>(); for (String obsId : observations) { List<ArrayList> readings = sensorManager.getReadingDataOfObservation(obsId); for (ArrayList reading : readings) { sign = reading.get(0).toString().substring(reading.get(0).toString().lastIndexOf("#") + 1); signs.add(sign); String unit = null; String content = null; try { content = reading.get(1).toString(); unit = reading.get(2).toString(); } catch (Exception e) { } if (unit == null) { unit = "no"; } Map m2 = new LinkedHashMap(); m2.put("value", content); m2.put("unit", unit); m1.put(sign, m2); } readArr.add(m1); } JSONObject readingJson = new JSONObject(); readingJson.put("vars", signs); readingJson.put("readings", readArr); OutputStream out = null; out = DatabaseUtilities.getNewestSensorData(sensorURL); JSONObject json = (JSONObject) JSONSerializer.toJSON(out.toString()); json.put("updated", DateUtil.date2StandardString(new Date())); json.put("ntriples", JSONUtil.JSONToNTriple(json.getJSONObject("results"))); json.put("error", "false"); json.put("meta", metaJson); json.put("data", readingJson); json.put("history", historicalJson); System.out.println(json); result = json; } catch (Exception e) { e.printStackTrace(); JSONObject jsonResult = new JSONObject(); jsonResult.put("error", "true"); result = jsonResult; } return result; }
/** * 入口 * * @return */ public String execute() throws Exception { logger.info("id:[" + id + "],index:[" + index + "]"); // 根据id得到URLTitleName URLTitleName item = getURLTitleNameById(id); // 新数据 String newContent = StringUtils.EMPTY; String newTitle = StringUtils.EMPTY; String newAlt = StringUtils.EMPTY; String newImgUrl = StringUtils.EMPTY; String newItemUrl = StringUtils.EMPTY; String newBtnTitle = StringUtils.EMPTY; // 老数据 JSONObject itemImg = JSONObject.fromObject(item.getImg()); // 内容展示类型+图片地址+图片个数 int oldType = itemImg.getInt("type"); // 内容展示类型 JSONArray imgUrlJsonArray = JSONArray.fromObject(itemImg.get("url")); // 图片地址 用户取出老图片 int oldSize = itemImg.getInt("size"); // 图片个数 String oldBigTitle = itemImg.getString("title"); // 大标题 JSONArray btnTitleJsonArray = JSONArray.fromObject(itemImg.get("btntitle")); // 按钮文字 用户取出老按钮文字 JSONArray itemUrlJsonArray = JSONArray.fromObject(item.getUrl()); // 链接地址 JSONObject itemName = JSONObject.fromObject(item.getName()); // 标题+提示+内容 JSONArray titleJsonArray = JSONArray.fromObject(itemName.get("title")); // 标题 JSONArray altJsonArray = JSONArray.fromObject(itemName.get("alt")); // 提示 JSONArray contentJsonArray = JSONArray.fromObject(itemName.get("content")); // 内容 for (int i = 0; i < oldSize; i++) { if (StringUtils.equals(StringUtils.EMPTY + (i + 1), index)) { continue; } if (StringUtils.isNotBlank(newContent)) { newContent += SymbolInterface.SYMBOL_COMMA; newTitle += SymbolInterface.SYMBOL_COMMA; newAlt += SymbolInterface.SYMBOL_COMMA; newImgUrl += SymbolInterface.SYMBOL_COMMA; newItemUrl += SymbolInterface.SYMBOL_COMMA; newBtnTitle += SymbolInterface.SYMBOL_COMMA; } String content = contentJsonArray.getString(i); String title = titleJsonArray.getString(i); String alt = altJsonArray.getString(i); String itemUrl = itemUrlJsonArray.getString(i); String imgUrl = imgUrlJsonArray.getString(i); String btnTitle = btnTitleJsonArray.getString(i); newContent += "\"" + content + "\""; newTitle += "\"" + title + "\""; newAlt += "\"" + alt + "\""; newImgUrl += "\"" + imgUrl + "\""; newItemUrl += "\"" + itemUrl + "\""; newBtnTitle += "\"" + btnTitle + "\""; } /** * 格式如下: { "title":["标题1","标题2","标题3"], "alt":["提示1","提示2","提示3"], "content":["内容1","内容2","内容3"] * } */ item.setName( "{" + "\"title\":[" + newTitle + "]" + ",\"alt\":[" + newAlt + "]" + ",\"content\":[" + newContent + "]" + "}"); /** 格式如下: ["test.jsp","test.jsp","test.jsp"] */ item.setUrl("[" + newItemUrl + "]"); /** * 格式如下: { "type":1, "url":["images/nine/17.jpg","images/nine/18.jpg","images/nine/9.jpg"], * "size":3 } */ item.setImg( "{" + "\"type\":" + oldType + "" + ",\"url\":[" + newImgUrl + "]" + ",\"size\":" + (oldSize - 1) + "" + ",\"title\":\"" + oldBigTitle + "\"" + ",\"btntitle\":[" + newBtnTitle + "]" + "}"); // 其中id和type和dis不变 ysjScrollParamUtil.getInstance().updateParam(item); // 配置缓存刷新 ysjScrollParamUtil.refresh(); message = "删除首页八框内容成功!"; return SUCCESS; }
/** * 保存策略价格 * * @param mapping * @param actionForm * @param request * @param response * @return * @throws Exception */ public ActionForward saveTacticsPrice( ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception { try { VenueUser venueUser = UserUtil.getUserFromSession(request); Long venueId = venueUser.getVenueInfo().getId(); JSONObject jsonObject = readJson(request); String tacticsId = jsonObject.getString("tacticsId"); if (StringUtils.isEmpty(tacticsId)) { throw new TacticsException("没有附属策略对象"); } Tactics tactics = (Tactics) getBaseManager().get(Tactics.class, Long.parseLong(tacticsId)); List<TacticsPrice> pricePojos = new ArrayList<TacticsPrice>(); Object start = jsonObject.get("start"); Object end = jsonObject.get("end"); Object price = jsonObject.get("price"); /** 一个价格 */ if (start instanceof java.lang.String) { TacticsPrice basicPrice = new TacticsPrice(); basicPrice.setTactics(tactics); basicPrice.setFromTime(start.toString()); basicPrice.setToTime(end.toString()); basicPrice.setPrice(new Integer(price.toString())); basicPrice.setVenueId(venueId); pricePojos.add(basicPrice); } /** 多个价格 */ else { JSONArray starts = (JSONArray) start; JSONArray ends = (JSONArray) end; JSONArray prices = (JSONArray) price; for (int i = 0; i < starts.size(); i++) { TacticsPrice basicPrice = new TacticsPrice(); basicPrice.setTactics(tactics); basicPrice.setFromTime(starts.getString(i)); basicPrice.setToTime(ends.getString(i)); basicPrice.setPrice(new Integer(prices.getString(i))); basicPrice.setVenueId(venueId); pricePojos.add(basicPrice); } } tacticsManager.savePrices(tactics.getId(), pricePojos); // 设置更新状态 if (!tactics.getIsModify()) { tactics.setIsModify(true); getBaseManager().insertOrUpdate(tactics); } printSuccess(response); log.info("场馆ID=" + venueId + ",成功添加策略价格;策略ID=" + tactics.getId()); } catch (TacticsException e) { log.error("保存策略价格时:" + e.getMessage(), e); printErrorInfo(e.getMessage(), response); } catch (Exception e) { log.error(e.getMessage(), e); printErrorLabel(response); } return null; }