List of usage examples for org.json.simple JSONObject containsKey
boolean containsKey(Object key);
From source file:com.piusvelte.hydra.UnidataConnection.java
@SuppressWarnings("unchecked") @Override/*from www . j a v a2 s.com*/ public JSONObject execute(String statement) { JSONObject response = new JSONObject(); JSONArray errors = new JSONArray(); try { UniCommand uCommand = mSession.command(); uCommand.setCommand(statement); uCommand.exec(); String[] fmValues = uCommand.response().split(UniTokens.AT_FM, -1); JSONArray rows = new JSONArray(); for (String fmValue : fmValues) { JSONArray rowData = new JSONArray(); String[] vmValues = fmValue.split(UniTokens.AT_VM, -1); for (String vmValue : vmValues) rowData.add(vmValue); rows.add(rowData); } response.put("result", rows); } catch (UniSessionException e) { errors.add(e.getMessage()); } catch (UniCommandException e) { errors.add(e.getMessage()); } response.put("errors", errors); if (!response.containsKey("result")) { JSONArray rows = new JSONArray(); JSONArray rowData = new JSONArray(); rows.add(rowData); response.put("result", rows); } return response; }
From source file:com.mcapanel.plugin.PluginConnector.java
@SuppressWarnings("unchecked") private void doMethodAndRespond(String method, String paramStr) { JSONObject out = new JSONObject(); out.put("plugin", "McAdminPanel"); out.put("type", "response"); out.put("method", method); String[] params = paramStr.length() != 0 ? paramStr.split(", ") : new String[0]; try {/* w ww .j av a2s. c o m*/ Class<?>[] paramClasses = new Class<?>[params.length]; for (int i = 0; i < params.length; i++) paramClasses[i] = Class.forName("java.lang.String"); Method m = methodHandler.getClass().getDeclaredMethod(method, paramClasses); String ret = (String) m.invoke(methodHandler, (Object[]) params); if (m.getReturnType().equals(Void.TYPE)) return; out.put("response", ret); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } if (!out.containsKey("response")) out.put("response", "No such method"); String cmd = "mcadminpanelplugincmd " + out.toJSONString(); OutputStream writer = server.getWriter(); try { writer.write((cmd + "\n").getBytes()); writer.flush(); } catch (IOException e) { } }
From source file:com.pearson.eidetic.driver.threads.subthreads.SnapshotVolumeSyncValidator.java
@Override public void run() { isFinished_ = false;//www . j av a2 s .c o m AmazonEC2Client ec2Client = connect(region_, awsAccessKeyId_, awsSecretKey_); for (Volume vol : VolumeSyncValidate_) { try { JSONParser parser = new JSONParser(); String inttagvalue = getIntTagValue(vol); if (inttagvalue == null) { continue; } JSONObject eideticParameters; try { Object obj = parser.parse(inttagvalue); eideticParameters = (JSONObject) obj; } catch (Exception e) { logger.error("awsAccountId=\"" + uniqueAwsAccountIdentifier_ + "\",Event=Error, Error=\"Malformed Eidetic Tag\", Volume_id=\"" + vol.getVolumeId() + "\", stacktrace=\"" + e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e) + "\""); continue; } if (eideticParameters == null) { continue; } //Same Integer keep = getKeep(eideticParameters, vol); if (keep == null) { continue; } JSONObject syncSnapshot = null; if (eideticParameters.containsKey("SyncSnapshot")) { syncSnapshot = (JSONObject) eideticParameters.get("SyncSnapshot"); } if (syncSnapshot == null) { logger.error("awsAccountId=\"" + uniqueAwsAccountIdentifier_ + "\",Event=Error, Error=\"Malformed Eidetic Tag\", Volume_id=\"" + vol.getVolumeId() + "\""); continue; } JSONObject validateParameters; try { validateParameters = (JSONObject) syncSnapshot.get("Validate"); } catch (Exception e) { logger.error("awsAccountId=\"" + uniqueAwsAccountIdentifier_ + "\",Event=Error, Error=\"Malformed Eidetic Tag\", Volume_id=\"" + vol.getVolumeId() + "\", stacktrace=\"" + e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e) + "\""); continue; } Integer createAfter = getCreateAfter(validateParameters, vol); String cluster = getCluster(validateParameters, vol); if (validateCluster_.containsKey(cluster)) { validateCluster_.get(cluster).add(new MutableTriple(vol, createAfter, keep)); } else { validateCluster_.put(cluster, new ArrayList<MutableTriple<Volume, Integer, Integer>>()); validateCluster_.get(cluster).add(new MutableTriple(vol, createAfter, keep)); } } catch (Exception e) { logger.error("awsAccountId=\"" + uniqueAwsAccountIdentifier_ + "\",Event=\"Error\", Error=\"error in SnapshotVolumeSync workflow\", stacktrace=\"" + e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e) + "\""); } } for (String cluster : validateCluster_.keySet()) { try { ArrayList<MutableTriple<Volume, Integer, Integer>> myList = validateCluster_.get(cluster); Boolean snapshotCluster = false; Integer min = Integer.MAX_VALUE; for (MutableTriple trip : myList) { if (((Integer) trip.getMiddle()) < min) { min = (Integer) trip.getMiddle(); } } for (MutableTriple trip : myList) { if (snapshotDecision(ec2Client, (Volume) trip.getLeft(), min)) { snapshotCluster = true; } } if (snapshotCluster) { ArrayList<Volume> vols = new ArrayList<>(); for (MutableTriple trip : myList) { vols.add((Volume) trip.getLeft()); } SnapshotVolumeSync thread = new SnapshotVolumeSync(awsAccessKeyId_, awsSecretKey_, uniqueAwsAccountIdentifier_, maxApiRequestsPerSecond_, ApplicationConfiguration.getAwsCallRetryAttempts(), region_, vols, true); try { thread.run(); } catch (Exception e) { String responseMessage = "Error running cluster validator thread for cluster " + cluster; logger.error("awsAccountId=\"" + uniqueAwsAccountIdentifier_ + "\",Error=\"" + responseMessage + "\"" + e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e) + "\""); } Integer wait = 0; while (!(thread.isFinished()) && (wait <= 200)) { Threads.sleepMilliseconds(250); //break after 50 seconds wait = wait + 1; } } } catch (Exception e) { logger.error("awsAccountId=\"" + uniqueAwsAccountIdentifier_ + "\",Event=\"Error\", Error=\"error in SnapshotVolumeSync workflow\", stacktrace=\"" + e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e) + "\""); } } ec2Client.shutdown(); isFinished_ = true; }
From source file:fr.bmartel.bboxapi.BboxApi.java
@Override public boolean getWirelessData(final IWirelessListener wirelessListener) { ClientSocket clientSocket = new ClientSocket("gestionbbox.lan", 80); clientSocket.addClientSocketEventListener(new IHttpClientListener() { @Override// w w w.j a v a 2 s . c o m public void onIncomingHttpFrame(HttpFrame frame, HttpStates httpStates, IClientSocket clientSocket) { if (httpStates == HttpStates.HTTP_FRAME_OK && frame.isHttpResponseFrame()) { // this is data coming from the server if (frame.getStatusCode() == 200) { String data = new String(frame.getBody().getBytes()); JSONArray obj = (JSONArray) JSONValue.parse(data); if (obj.size() > 0) { JSONObject item = (JSONObject) obj.get(0); if (item.containsKey("wireless")) { JSONObject sub_item_first_element = (JSONObject) item.get("wireless"); if (sub_item_first_element.containsKey("status") && sub_item_first_element.containsKey("radio") && sub_item_first_element.containsKey("ssid") && sub_item_first_element.containsKey("capabilities") && sub_item_first_element.containsKey("standard")) { String status = sub_item_first_element.get("status").toString(); JSONObject radioItem = (JSONObject) sub_item_first_element.get("radio"); Iterator it = radioItem.entrySet().iterator(); HashMap<Integer, RadioObject> radioList = new HashMap<Integer, RadioObject>(); HashMap<Integer, SsidObject> ssidList = new HashMap<Integer, SsidObject>(); while (it.hasNext()) { Map.Entry<String, Object> pair = (Map.Entry) it.next(); JSONObject subItem = (JSONObject) pair.getValue(); boolean enable = false; String standard = ""; int state = 0; int channel = 0; int currentChannel = 0; boolean dfs = false; boolean ht40 = false; if (subItem.containsKey("enable")) enable = Integer.parseInt(subItem.get("enable").toString()) == 1 ? true : false; if (subItem.containsKey("standard")) standard = subItem.get("standard").toString(); if (subItem.containsKey("state")) state = Integer.parseInt(subItem.get("state").toString()); if (subItem.containsKey("channel")) channel = Integer.parseInt(subItem.get("channel").toString()); if (subItem.containsKey("current_channel")) currentChannel = Integer .parseInt(subItem.get("current_channel").toString()); if (subItem.containsKey("dfs")) dfs = Integer.parseInt(subItem.get("dfs").toString()) == 1 ? true : false; if (subItem.containsKey("ht40")) { JSONObject ht40Object = (JSONObject) subItem.get("ht40"); if (ht40Object.containsKey("enable")) ht40 = Integer.parseInt(subItem.get("enable").toString()) == 1 ? true : false; } radioList.put(Integer.parseInt(pair.getKey()), new RadioObject(enable, standard, state, channel, currentChannel, dfs, ht40)); } JSONObject ssidItem = (JSONObject) sub_item_first_element.get("ssid"); Iterator it2 = ssidItem.entrySet().iterator(); while (it2.hasNext()) { Map.Entry<String, Object> pair = (Map.Entry) it2.next(); JSONObject subItem = (JSONObject) pair.getValue(); String id = ""; boolean enabled = false; boolean hidden = false; String bssid = ""; boolean wmmenable = false; boolean wpsenabled = false; String wpsstatus = ""; boolean securityDefault = false; String securityProtocol = ""; String securityEncryption = ""; String securityPassphrase = ""; if (subItem.containsKey("id")) id = subItem.get("id").toString(); if (subItem.containsKey("enable")) enabled = Integer.parseInt(subItem.get("enable").toString()) == 1 ? true : false; if (subItem.containsKey("hidden")) hidden = Integer.parseInt(subItem.get("hidden").toString()) == 1 ? true : false; if (subItem.containsKey("bssid")) bssid = subItem.get("bssid").toString(); if (subItem.containsKey("wmmenable")) wmmenable = Integer.parseInt(subItem.get("wmmenable").toString()) == 1 ? true : false; if (subItem.containsKey("wps")) { JSONObject wpsObject = (JSONObject) subItem.get("wps"); if (wpsObject.containsKey("enable")) wpsenabled = Integer .parseInt(wpsObject.get("enable").toString()) == 1 ? true : false; if (wpsObject.containsKey("status")) wpsstatus = wpsObject.get("status").toString(); } if (subItem.containsKey("security")) { JSONObject securityObject = (JSONObject) subItem.get("security"); if (securityObject.containsKey("isdefault")) securityDefault = Integer .parseInt(securityObject.get("isdefault").toString()) == 1 ? true : false; if (securityObject.containsKey("protocol")) securityProtocol = securityObject.get("protocol").toString(); if (securityObject.containsKey("encryption")) securityEncryption = securityObject.get("encryption").toString(); if (securityObject.containsKey("passphrase")) securityPassphrase = securityObject.get("passphrase").toString(); } ssidList.put(Integer.parseInt(pair.getKey()), new SsidObject(id, enabled, hidden, bssid, wmmenable, wpsenabled, wpsstatus, securityDefault, securityProtocol, securityEncryption, securityPassphrase)); } JSONObject capabilityItems = (JSONObject) sub_item_first_element .get("capabilities"); Iterator it3 = capabilityItems.entrySet().iterator(); HashMap<Integer, List<WirelessCapability>> capabilityRadioList = new HashMap<Integer, List<WirelessCapability>>(); while (it3.hasNext()) { Map.Entry<String, Object> pair = (Map.Entry) it3.next(); JSONArray subItem = (JSONArray) pair.getValue(); List<WirelessCapability> wirelessCapabilityList = new ArrayList<WirelessCapability>(); for (int i = 0; i < subItem.size(); i++) { JSONObject capabilityObj = (JSONObject) subItem.get(i); int channel = 0; String ht40 = ""; boolean nodfs = false; int cactime = 0; int cactime40 = 0; if (capabilityObj.containsKey("channel")) channel = Integer.parseInt(capabilityObj.get("channel").toString()); if (capabilityObj.containsKey("ht40")) ht40 = capabilityObj.get("ht40").toString(); if (capabilityObj.containsKey("nodfs")) nodfs = Boolean.valueOf(capabilityObj.get("nodfs").toString()); if (capabilityObj.containsKey("cactime")) cactime = Integer.parseInt(capabilityObj.get("cactime").toString()); if (capabilityObj.containsKey("cactime40")) cactime40 = Integer .parseInt(capabilityObj.get("cactime40").toString()); wirelessCapabilityList.add(new WirelessCapability(channel, ht40, nodfs, cactime, cactime40)); } capabilityRadioList.put(Integer.parseInt(pair.getKey()), wirelessCapabilityList); } JSONObject standardItems = (JSONObject) sub_item_first_element.get("standard"); Iterator it4 = standardItems.entrySet().iterator(); HashMap<Integer, List<String>> standardTypeList = new HashMap<Integer, List<String>>(); while (it4.hasNext()) { Map.Entry<String, Object> pair = (Map.Entry) it4.next(); JSONArray subItem = (JSONArray) pair.getValue(); List<String> typeList = new ArrayList<String>(); for (int i = 0; i < subItem.size(); i++) { JSONObject typeOject = (JSONObject) subItem.get(i); if (typeOject.containsKey("value")) typeList.add(typeOject.get("value").toString()); } standardTypeList.put(Integer.parseInt(pair.getKey()), typeList); } WirelessData wirelessData = new WirelessData(status, radioList, ssidList, capabilityRadioList, standardTypeList); wirelessListener.onWirelessDataReceived(wirelessData); clientSocket.closeSocket(); return; } } } } wirelessListener.onWirelessDataFailure(); clientSocket.closeSocket(); } } @Override public void onSocketError() { wirelessListener.onWirelessDataFailure(); } }); HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Accept", "*/*"); headers.put("Host", "gestionbbox.lan"); headers.put("Cookie", token_header); HttpFrame frameRequest = new HttpFrame(HttpMethod.GET_REQUEST, new HttpVersion(1, 1), headers, "/api/v1/wireless", new ListOfBytes("")); clientSocket.write(frameRequest.toString().getBytes()); return false; }
From source file:edu.vt.vbi.patric.portlets.CompPathwayMap.java
private void processKeggMap(ResourceRequest request, ResourceResponse response) throws IOException { Map<String, String> key = new HashMap<>(); DataApiHandler dataApi = new DataApiHandler(request); JSONObject ret = new JSONObject(); JSONObject val = new JSONObject(); try {/*w w w . j a v a 2 s .c o m*/ val = (JSONObject) (new JSONParser()).parse(request.getParameter("val").toString()); } catch (ParseException e) { LOGGER.error(e.getMessage(), e); } String need = val.get("need").toString(); String genomeId = null, taxonId = null, map = null, pk = null; if (val.containsKey("genomeId") && val.get("genomeId") != null && !val.get("genomeId").equals("")) { genomeId = val.get("genomeId").toString(); } if (val.containsKey("taxonId") && val.get("taxonId") != null && !val.get("taxonId").equals("")) { taxonId = val.get("taxonId").toString(); } if (val.containsKey("map") && val.get("map") != null && !val.get("map").equals("")) { map = val.get("map").toString(); } if (val.containsKey("pk") && val.get("pk") != null && !val.get("pk").equals("")) { pk = val.get("pk").toString(); } if (need.equals("all")) { if (genomeId != null) { key.put("genomeId", genomeId); } if (taxonId != null) { key.put("taxonId", taxonId); } if (map != null) { key.put("map", map); } Map<String, String> sessKey = null; if (pk != null && !pk.isEmpty()) { sessKey = jsonReader.readValue(SessionHandler.getInstance().get(SessionHandler.PREFIX + pk)); if (sessKey != null && sessKey.containsKey("genomeId") && !sessKey.get("genomeId").equals("")) { genomeId = sessKey.get("genomeId"); } } List<String> annotations = Arrays.asList("PATRIC", "RefSeq"); // getting coordinates try { JSONArray listCoordinates = new JSONArray(); for (String annotation : annotations) { Set<String> ecNumbers = new HashSet<String>(); // step1. genome_count, feature_count // pathway/select?q=pathway_id:00053+AND+annotation:PATRIC&fq={!join+from=genome_id+to=genome_id+fromIndex=genome}taxon_lineage_ids:83332+AND+genome_status:(complete+OR+wgs) // &rows=0&facet=true&json.facet={stat:{field:{field:ec_number,limit:-1,facet:{genome_count:"unique(genome_id)",gene_count:"unique(feature_id)"}}}} SolrQuery query = new SolrQuery("pathway_id:" + map + " AND annotation:" + annotation); if (taxonId != null) { query.addFilterQuery(SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id", "taxon_lineage_ids:" + taxonId)); } if (genomeId != null) { query.addFilterQuery(SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id", "genome_id:(" + genomeId.replaceAll(",", " OR ") + ")")); } query.setRows(0).setFacet(true); query.add("json.facet", "{stat:{field:{field:ec_number,limit:-1,facet:{genome_count:\"unique(genome_id)\",gene_count:\"unique(feature_id)\"}}}}"); LOGGER.debug("step 1. [{}] {}", SolrCore.PATHWAY.getSolrCoreName(), query); String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY, query); Map resp = jsonReader.readValue(apiResponse); Map respBody = (Map) resp.get("response"); int numFound = (Integer) respBody.get("numFound"); if (numFound > 0) { List<Map> buckets = (List<Map>) ((Map) ((Map) resp.get("facets")).get("stat")) .get("buckets"); Map<String, Map> mapStat = new HashMap<>(); for (Map value : buckets) { if (Integer.parseInt(value.get("count").toString()) > 0) { mapStat.put(value.get("val").toString(), value); ecNumbers.add(value.get("val").toString()); } } // step2. coordinates, occurrence // pathway_ref/select?q=pathway_id:00010+AND+map_type:enzyme%+AND+ec_number:("1.2.1.3"+OR+"1.1.1.1")&fl=ec_number,ec_description,map_location,occurrence if (!ecNumbers.isEmpty()) { query = new SolrQuery("pathway_id:" + map + " AND map_type:enzyme AND ec_number:(" + StringUtils.join(ecNumbers, " OR ") + ")"); query.setFields("ec_number,ec_description,map_location,occurrence"); query.setRows(dataApi.MAX_ROWS); LOGGER.trace("genome_x_y: [{}] {}", SolrCore.PATHWAY_REF.getSolrCoreName(), query); apiResponse = dataApi.solrQuery(SolrCore.PATHWAY_REF, query); resp = jsonReader.readValue(apiResponse); respBody = (Map) resp.get("response"); List<Map> sdl = (List<Map>) respBody.get("docs"); for (Map doc : sdl) { String ecNumber = doc.get("ec_number").toString(); Map stat = mapStat.get(ecNumber); if (!stat.get("gene_count").toString().equals("0")) { List<String> locations = (List<String>) doc.get("map_location"); for (String location : locations) { JSONObject coordinate = new JSONObject(); coordinate.put("algorithm", annotation); coordinate.put("description", doc.get("ec_description")); coordinate.put("ec_number", ecNumber); coordinate.put("genome_count", stat.get("genome_count")); String[] loc = location.split(","); coordinate.put("x", loc[0]); coordinate.put("y", loc[1]); listCoordinates.add(coordinate); } } } } } } ret.put("genome_x_y", listCoordinates); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } // get pathways try { SolrQuery query = new SolrQuery("annotation:(" + StringUtils.join(annotations, " OR ") + ")"); if (taxonId != null) { query.addFilterQuery(SolrCore.GENOME.getSolrCoreJoin("genome_id", "genome_id", "taxon_lineage_ids:" + taxonId)); } if (genomeId != null) { query.addFilterQuery("genome_id:(" + genomeId.replaceAll(",", " OR ") + ")"); } query.setFields("pathway_id,pathway_name,annotation").setRows(dataApi.MAX_ROWS); LOGGER.trace("genome_pathway_x_y: [{}] {}", SolrCore.PATHWAY.getSolrCoreName(), query); String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY, query); Map resp = jsonReader.readValue(apiResponse); Map respBody = (Map) resp.get("response"); List<Map> sdl = (List<Map>) respBody.get("docs"); JSONArray listEnzymes = new JSONArray(); Set<String> hash = new HashSet<>(); for (Map doc : sdl) { // TODO: need to improve this using solr String hashKey = doc.get("pathway_id").toString() + ":" + doc.get("annotation").toString(); if (!hash.contains(hashKey)) { hash.add(hashKey); JSONObject enzyme = new JSONObject(); enzyme.put("algorithm", doc.get("annotation")); enzyme.put("map_id", doc.get("pathway_id")); enzyme.put("map_name", doc.get("pathway_name")); listEnzymes.add(enzyme); } } ret.put("genome_pathway_x_y", listEnzymes); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } // map_ids_in_map try { SolrQuery query = new SolrQuery("pathway_id:" + map + " AND map_type:path"); query.setFields("ec_number,ec_description,map_location").setRows(dataApi.MAX_ROWS); LOGGER.trace("map_ids_in_map: [{}] {}", SolrCore.PATHWAY_REF.getSolrCoreName(), query); String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY_REF, query); Map resp = jsonReader.readValue(apiResponse); Map respBody = (Map) resp.get("response"); List<Map> sdl = (List<Map>) respBody.get("docs"); JSONArray listCoordinates = new JSONArray(); for (Map doc : sdl) { List<String> locations = (List<String>) doc.get("map_location"); for (String location : locations) { JSONObject coordinate = new JSONObject(); coordinate.put("source_id", doc.get("ec_number")); String[] loc = location.split(","); coordinate.put("x", loc[0]); coordinate.put("y", loc[1]); coordinate.put("width", loc[2]); coordinate.put("height", loc[3]); listCoordinates.add(coordinate); } } ret.put("map_ids_in_map", listCoordinates); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } // all coordinates try { SolrQuery query = new SolrQuery("pathway_id:" + map + " AND map_type:enzyme"); query.setFields("ec_number,ec_description,map_location").setRows(dataApi.MAX_ROWS); LOGGER.trace("all_coordinates: [{}] {}", SolrCore.PATHWAY_REF.getSolrCoreName(), query); String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY_REF, query); Map resp = jsonReader.readValue(apiResponse); Map respBody = (Map) resp.get("response"); List<Map> sdl = (List<Map>) respBody.get("docs"); JSONArray listCoordinates = new JSONArray(); for (Map doc : sdl) { List<String> locations = (List<String>) doc.get("map_location"); for (String location : locations) { JSONObject coordinate = new JSONObject(); coordinate.put("ec", doc.get("ec_number")); coordinate.put("description", doc.get("ec_description")); String[] loc = location.split(","); coordinate.put("x", loc[0]); coordinate.put("y", loc[1]); listCoordinates.add(coordinate); } } ret.put("all_coordinates", listCoordinates); } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } else { // need: feature_id or ec_number JSONArray coordinates = new JSONArray(); if (need.equals("ec_number")) { try { SolrQuery query = new SolrQuery("*:*"); if (map != null) { query.addFilterQuery("pathway_id:(" + map + ")"); } LOGGER.trace("[{}] {}", SolrCore.PATHWAY_REF.getSolrCoreName(), query); String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY_REF, query); Map resp = jsonReader.readValue(apiResponse); Map respBody = (Map) resp.get("response"); List<Map> sdl = (List<Map>) respBody.get("docs"); for (Map doc : sdl) { List<String> locations = (List<String>) doc.get("map_location"); for (String loc : locations) { JSONObject coordinate = new JSONObject(); coordinate.put("ec_number", doc.get("ec_number")); String[] xy = loc.split(","); coordinate.put("x", xy[0]); coordinate.put("y", xy[1]); coordinates.add(coordinate); } } } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } else { // feature String featureIds = null; if (val.containsKey("value") && val.get("value") != null && !val.get("value").equals("")) { featureIds = val.get("value").toString(); } try { SolrQuery query = new SolrQuery("*:*"); if (map != null) { query.addFilterQuery("pathway_id:(" + map + ")"); } if (featureIds != null) { query.addFilterQuery(SolrCore.PATHWAY.getSolrCoreJoin("ec_number", "ec_number", "feature_id:(" + featureIds.replaceAll(",", " OR ") + ")")); } LOGGER.trace("coordinates: [{}] {}", SolrCore.PATHWAY_REF.getSolrCoreName(), query); String apiResponse = dataApi.solrQuery(SolrCore.PATHWAY_REF, query); Map resp = jsonReader.readValue(apiResponse); Map respBody = (Map) resp.get("response"); List<Map> sdl = (List<Map>) respBody.get("docs"); for (Map doc : sdl) { List<String> locations = (List<String>) doc.get("map_location"); for (String loc : locations) { JSONObject coordinate = new JSONObject(); coordinate.put("ec_number", doc.get("ec_number")); String[] xy = loc.split(","); coordinate.put("x", xy[0]); coordinate.put("y", xy[1]); coordinates.add(coordinate); } } } catch (IOException e) { LOGGER.error(e.getMessage(), e); } } ret.put("coordinates", coordinates); } response.setContentType("application/json"); ret.writeJSONString(response.getWriter()); }
From source file:com.nubits.nubot.trading.wrappers.BterWrapper.java
private ApiResponse getQuery(String url, HashMap<String, String> query_args, boolean needAuth, boolean isGet) { ApiResponse apiResponse = new ApiResponse(); String queryResult = query(url, "", query_args, needAuth, isGet); if (queryResult == null) { apiResponse.setError(errors.nullReturnError); return apiResponse; }/*from www. j a v a 2 s . co m*/ if (queryResult.equals(TOKEN_BAD_RETURN)) { apiResponse.setError(errors.noConnectionError); return apiResponse; } if (queryResult.contains(TOKEN_ERROR_HTML_405)) { ApiError error = errors.apiReturnError; error.setDescription("BTER returned http error 405 - method not allowed"); apiResponse.setError(error); return apiResponse; } JSONParser parser = new JSONParser(); try { JSONObject httpAnswerJson = (JSONObject) (parser.parse(queryResult)); boolean valid; try { valid = Boolean.parseBoolean((String) httpAnswerJson.get("result")); } catch (ClassCastException e) { valid = true; //hack due to bter returning "false" and false at times, depending on the err try { valid = (boolean) httpAnswerJson.get("result"); } catch (ClassCastException ex) { valid = true; } } if (!valid) { String errorMessage = ""; if (httpAnswerJson.containsKey("message")) { errorMessage = (String) httpAnswerJson.get("message"); } else if (httpAnswerJson.containsKey("msg")) { errorMessage = (String) httpAnswerJson.get("msg"); } ApiError apiErr = errors.apiReturnError; apiErr.setDescription(errorMessage); apiResponse.setError(apiErr); } else { apiResponse.setResponseObject(httpAnswerJson); } } catch (ClassCastException cce) { //if casting to a JSON object failed, try a JSON Array try { JSONArray httpAnswerJson = (JSONArray) (parser.parse(queryResult)); apiResponse.setResponseObject(httpAnswerJson); } catch (ParseException pe) { LOG.error("httpResponse: " + queryResult + " \n" + pe.toString()); apiResponse.setError(errors.parseError); } } catch (ParseException ex) { LOG.error("httpresponse: " + queryResult + " \n" + ex.toString()); apiResponse.setError(errors.parseError); return apiResponse; } return apiResponse; }
From source file:mml.handler.get.MMLGetVersionsHandler.java
/** * Get the version listing from the MVD// w ww. ja v a2s. c o m * @param request the request * @param response the response * @param urn the remaining urn being empty * @throws MMLException */ public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws MMLException { try { String docid = request.getParameter(Params.DOCID); if (docid == null) throw new Exception("You must specify a docid parameter"); AeseResource res = doGetResource(Database.CORTEX, docid); JSONArray jVersions = new JSONArray(); if (res != null) { String[] versions = res.listVersions(); HashMap<String, JSONObject> vSet = new HashMap<String, JSONObject>(); for (int i = 0; i < versions.length; i++) { String base = Layers.stripLayer(versions[i]); JSONObject jObj = vSet.get(base); if (jObj == null) jObj = new JSONObject(); String upgraded = Layers.upgradeLayerName(versions, versions[i]); if (!upgraded.equals(versions[i])) { JSONArray repl = (JSONArray) jObj.get("replacements"); if (repl == null) { repl = new JSONArray(); jObj.put("replacements", repl); } JSONObject entry = new JSONObject(); entry.put("old", versions[i]); entry.put("new", upgraded); repl.add(entry); } if (upgraded.endsWith("layer-final")) jObj.put("desc", res.getVersionLongName(i + 1)); // add the layer names if (upgraded.endsWith("layer-final") || upgraded.matches(".*layer-[0-9]+$")) { JSONArray jArr = (JSONArray) jObj.get("layers"); if (jArr == null) jArr = new JSONArray(); int index = upgraded.lastIndexOf("layer"); String layerName = upgraded.substring(index); if (!jArr.contains(layerName)) jArr.add(layerName); if (!jObj.containsKey("layers")) jObj.put("layers", jArr); } if (!vSet.containsKey(base)) vSet.put(base, jObj); } // convert hashmap to array Set<String> keys = vSet.keySet(); Iterator<String> iter = keys.iterator(); while (iter.hasNext()) { String version = iter.next(); JSONObject jObj = vSet.get(version); jObj.put("vid", version); jVersions.add(jObj); } } response.setContentType("application/json"); response.setCharacterEncoding(encoding); String jStr = jVersions.toJSONString().replaceAll("\\\\/", "/"); response.getWriter().println(jStr); } catch (Exception e) { throw new MMLException(e); } }
From source file:com.piusvelte.hydra.MSSQLConnection.java
@SuppressWarnings("unchecked") @Override// www.j a v a 2 s . c om public JSONObject update(String object, String[] columns, String[] values, String selection) { JSONObject response = new JSONObject(); JSONArray errors = new JSONArray(); Statement s = null; ResultSet rs = null; try { StringBuilder sb = new StringBuilder(); for (int i = 0, l = columns.length; i < l; i++) { if (i > 0) sb.append(","); sb.append(columns[i].replaceAll("\\.", "_")); sb.append("="); sb.append(values[i]); } s = mConnection.createStatement(); rs = s.executeQuery(String.format(UPDATE_QUERY, object, sb.toString(), selection).toString()); response.put("result", getResult(rs)); } catch (SQLException e) { errors.add(e.getMessage()); } finally { if (s != null) { if (rs != null) { try { rs.close(); } catch (SQLException e) { errors.add(e.getMessage()); } } try { s.close(); } catch (SQLException e) { errors.add(e.getMessage()); } } } response.put("errors", errors); if (!response.containsKey("result")) { JSONArray rows = new JSONArray(); JSONArray rowData = new JSONArray(); rows.add(rowData); response.put("result", rows); } return response; }
From source file:com.paniclauncher.workers.InstanceInstaller.java
private ArrayList<MojangDownloadable> getNeededResources() { ArrayList<MojangDownloadable> downloads = new ArrayList<MojangDownloadable>(); // All the files // Read in the resources needed if (!isServer) { try {// w w w . j a v a2 s . com boolean isTruncated; String marker = null; String add; do { if (marker == null) { add = ""; } else { add = "?marker=" + marker; } URL resourceUrl = new URL("https://s3.amazonaws.com/Minecraft.Resources/" + add); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(resourceUrl.openStream()); isTruncated = Boolean .parseBoolean(doc.getElementsByTagName("IsTruncated").item(0).getTextContent()); NodeList nodeLst = doc.getElementsByTagName("Contents"); for (int i = 0; i < nodeLst.getLength(); i++) { Node node = nodeLst.item(i); if (node.getNodeType() == 1) { Element element = (Element) node; String key = element.getElementsByTagName("Key").item(0).getChildNodes().item(0) .getNodeValue(); String etag = element.getElementsByTagName("ETag") != null ? element .getElementsByTagName("ETag").item(0).getChildNodes().item(0).getNodeValue() : "-"; etag = getEtag(etag); marker = key; long size = Long.parseLong(element.getElementsByTagName("Size").item(0).getChildNodes() .item(0).getNodeValue()); if (size > 0L) { File file; String filename; if (key.contains("/")) { filename = key.substring(key.lastIndexOf('/') + 1, key.length()); File directory = new File(App.settings.getResourcesDir(), key.substring(0, key.lastIndexOf('/'))); file = new File(directory, filename); } else { file = new File(App.settings.getResourcesDir(), key); filename = file.getName(); } if (!Utils.getMD5(file).equalsIgnoreCase(etag)) downloads.add(new MojangDownloadable( "https://s3.amazonaws.com/Minecraft.Resources/" + key, file, etag, this)); } } } } while (isTruncated); } catch (Exception e) { App.settings.getConsole().logStackTrace(e); } } // Now lets see if we have custom mainclass and extraarguments try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(pack.getXML(version, false))); Document document = builder.parse(is); document.getDocumentElement().normalize(); NodeList nodeList = document.getElementsByTagName("mainclass"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; if (element.hasAttribute("depends")) { boolean found = false; for (Mod mod : selectedMods) { if (element.getAttribute("depends").equalsIgnoreCase(mod.getName())) { found = true; break; } } if (!found) { break; } } NodeList nodeList1 = element.getChildNodes(); this.mainClass = nodeList1.item(0).getNodeValue(); } } } catch (SAXException e) { App.settings.getConsole().logStackTrace(e); } catch (ParserConfigurationException e) { App.settings.getConsole().logStackTrace(e); } catch (IOException e) { App.settings.getConsole().logStackTrace(e); } try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(pack.getXML(version, false))); Document document = builder.parse(is); document.getDocumentElement().normalize(); NodeList nodeList = document.getElementsByTagName("extraarguments"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; if (element.hasAttribute("depends")) { boolean found = false; for (Mod mod : selectedMods) { if (element.getAttribute("depends").equalsIgnoreCase(mod.getName())) { found = true; break; } } if (!found) { break; } } NodeList nodeList1 = element.getChildNodes(); this.extraArguments = nodeList1.item(0).getNodeValue(); } } } catch (SAXException e) { App.settings.getConsole().logStackTrace(e); } catch (ParserConfigurationException e) { App.settings.getConsole().logStackTrace(e); } catch (IOException e) { App.settings.getConsole().logStackTrace(e); } // Now read in the library jars needed from the pack try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(pack.getXML(version, false))); Document document = builder.parse(is); document.getDocumentElement().normalize(); NodeList nodeList = document.getElementsByTagName("library"); for (int i = 0; i < nodeList.getLength(); i++) { Node node = nodeList.item(i); if (node.getNodeType() == Node.ELEMENT_NODE) { Element element = (Element) node; String url = element.getAttribute("url"); String file = element.getAttribute("file"); Download download = Download.direct; if (element.hasAttribute("download")) { download = Download.valueOf(element.getAttribute("download")); } String md5 = "-"; if (element.hasAttribute("md5")) { md5 = element.getAttribute("md5"); } if (element.hasAttribute("depends")) { boolean found = false; for (Mod mod : selectedMods) { if (element.getAttribute("depends").equalsIgnoreCase(mod.getName())) { found = true; break; } } if (!found) { continue; } } if (librariesNeeded == null) { this.librariesNeeded = file; } else { this.librariesNeeded += "," + file; } File downloadTo = null; if (isServer) { if (!element.hasAttribute("server")) { continue; } serverLibraries.add(new File( new File(getLibrariesDirectory(), element.getAttribute("server").substring(0, element.getAttribute("server").lastIndexOf('/'))), element.getAttribute("server").substring( element.getAttribute("server").lastIndexOf('/'), element.getAttribute("server").length()))); } downloadTo = new File(App.settings.getLibrariesDir(), file); if (download == Download.server) { downloads.add(new MojangDownloadable(App.settings.getFileURL(url), downloadTo, md5, this)); } else { downloads.add(new MojangDownloadable(url, downloadTo, md5, this)); } } } } catch (SAXException e) { App.settings.getConsole().logStackTrace(e); } catch (ParserConfigurationException e) { App.settings.getConsole().logStackTrace(e); } catch (IOException e) { App.settings.getConsole().logStackTrace(e); } // Now read in the library jars needed from Mojang if (!isServer) { JSONParser parser = new JSONParser(); try { Object obj = parser.parse(Utils.urlToString("https://s3.amazonaws.com/Minecraft.Download/versions/" + this.minecraftVersion + "/" + this.minecraftVersion + ".json")); JSONObject jsonObject = (JSONObject) obj; if (this.mainClass == null) { this.mainClass = (String) jsonObject.get("mainClass"); } this.minecraftArguments = (String) jsonObject.get("minecraftArguments"); JSONArray msg = (JSONArray) jsonObject.get("libraries"); Iterator<JSONObject> iterator = msg.iterator(); while (iterator.hasNext()) { boolean shouldDownload = false; JSONObject object = iterator.next(); String libraryName = (String) object.get("name"); String[] parts = ((String) object.get("name")).split(":"); String dir = parts[0].replace(".", "/") + "/" + parts[1] + "/" + parts[2]; String filename = null; if (object.containsKey("rules")) { JSONArray ruless = (JSONArray) object.get("rules"); Iterator<JSONObject> itt = ruless.iterator(); while (itt.hasNext()) { JSONObject rules = itt.next(); if (((String) rules.get("action")).equalsIgnoreCase("allow")) { if (rules.containsKey("os")) { JSONObject rule = (JSONObject) rules.get("os"); if (((String) rule.get("name")).equalsIgnoreCase(Utils.getOSName())) { Pattern pattern = Pattern.compile((String) rule.get("version")); Matcher matcher = pattern.matcher(System.getProperty("os.version")); if (matcher.matches()) { shouldDownload = true; } } } else { shouldDownload = true; } } else if (((String) rules.get("action")).equalsIgnoreCase("disallow")) { if (rules.containsKey("os")) { JSONObject rule = (JSONObject) rules.get("os"); if (((String) rule.get("name")).equalsIgnoreCase(Utils.getOSName())) { Pattern pattern = Pattern.compile((String) rule.get("version")); Matcher matcher = pattern.matcher(System.getProperty("os.version")); if (matcher.matches()) { shouldDownload = false; } } } } else { shouldDownload = true; } } } else { shouldDownload = true; } if (shouldDownload) { if (object.containsKey("natives")) { JSONObject nativesObject = (JSONObject) object.get("natives"); String nativesName; if (Utils.isWindows()) { nativesName = (String) nativesObject.get("windows"); } else if (Utils.isMac()) { nativesName = (String) nativesObject.get("osx"); } else { nativesName = (String) nativesObject.get("linux"); } filename = parts[1] + "-" + parts[2] + "-" + nativesName + ".jar"; if (nativesNeeded == null) { this.nativesNeeded = filename; } else { this.nativesNeeded += "," + filename; } } else { filename = parts[1] + "-" + parts[2] + ".jar"; if (librariesNeeded == null) { this.librariesNeeded = filename; } else { this.librariesNeeded += "," + filename; } } String url = "https://s3.amazonaws.com/Minecraft.Download/libraries/" + dir + "/" + filename; File file = new File(App.settings.getLibrariesDir(), filename); downloads.add(new MojangDownloadable(url, file, null, this)); } } } catch (ParseException e) { App.settings.getConsole().logStackTrace(e); } } if (isServer) { downloads.add(new MojangDownloadable( "https://s3.amazonaws.com/Minecraft.Download/versions/" + this.minecraftVersion + "/minecraft_server." + this.minecraftVersion + ".jar", new File(App.settings.getJarsDir(), "minecraft_server." + this.minecraftVersion + ".jar"), null, this)); } else { downloads.add(new MojangDownloadable( "https://s3.amazonaws.com/Minecraft.Download/versions/" + this.minecraftVersion + "/" + this.minecraftVersion + ".jar", new File(App.settings.getJarsDir(), this.minecraftVersion + ".jar"), null, this)); } return downloads; }
From source file:com.piusvelte.hydra.MSSQLConnection.java
@SuppressWarnings("unchecked") @Override//from w w w . j a v a 2 s.c o m public JSONObject query(String object, String[] columns, String selection) { Statement s = null; ResultSet rs = null; JSONObject response = new JSONObject(); JSONArray errors = new JSONArray(); try { StringBuilder sb = new StringBuilder(); for (int i = 0, l = columns.length; i < l; i++) { if (i > 0) sb.append(","); sb.append(columns[i].replaceAll("\\.", "_")); } String columnsStr = sb.toString(); s = mConnection.createStatement(); if (selection != null) rs = s.executeQuery( String.format(SELECTION_QUERY_FORMAT, columnsStr, object, selection).toString()); else rs = s.executeQuery(String.format(SIMPLE_QUERY_FORMAT, columnsStr, object).toString()); response.put("result", getResult(rs)); } catch (SQLException e) { errors.add(e.getMessage()); } finally { if (s != null) { if (rs != null) { try { rs.close(); } catch (SQLException e) { errors.add(e.getMessage()); } } try { s.close(); } catch (SQLException e) { errors.add(e.getMessage()); } } } response.put("errors", errors); if (!response.containsKey("result")) { JSONArray rows = new JSONArray(); JSONArray rowData = new JSONArray(); rows.add(rowData); response.put("result", rows); } return response; }