List of usage examples for org.json.simple JSONObject containsKey
boolean containsKey(Object key);
From source file:mml.handler.get.MMLMetadataHandler.java
public void handle(HttpServletRequest request, HttpServletResponse response, String urn) throws MMLException { try {/* w ww. j a va2s. c om*/ Connection conn = Connector.getConnection(); docid = request.getParameter(Params.DOCID); if (docid == null || docid.length() == 0) docid = urn; JSONObject md = new JSONObject(); boolean changed = false; String docId = docid; do { String jStr = conn.getMetadata(docId); if (jStr != null) { JSONObject jObj = (JSONObject) JSONValue.parse(jStr); Set<String> keys = jObj.keySet(); Iterator<String> iter = keys.iterator(); while (iter.hasNext()) { String key = iter.next(); md.put(key, jObj.get(key)); } changed = true; } else { String ctStr = conn.getFromDb(Database.CORTEX, docId); if (ctStr != null) { JSONObject jObj = (JSONObject) JSONValue.parse(ctStr); if (jObj.containsKey(JSONKeys.DESCRIPTION)) { String desc = ((String) jObj.get(JSONKeys.DESCRIPTION)).replaceAll("%20", " "); if (desc.startsWith("\"")) desc = desc.substring(1); if (desc.endsWith("\"")) desc = desc.substring(0, desc.length() - 2); desc = desc.replaceAll("\"\"", "\""); md.put(JSONKeys.TITLE, desc); } else if (!md.containsKey(JSONKeys.TITLE) && DocType.isLetter(docId)) { int index = docId.lastIndexOf("/"); String shortId; if (index != -1) shortId = docId.substring(index + 1); else shortId = docId; String[] parts = shortId.split("-"); StringBuilder sb = new StringBuilder(); String projid = Utils.getProjectId(docId); if (parts.length >= 2) { String from = Acronym.expand(projid, parts[parts.length - 2]); String to = Acronym.expand(projid, parts[parts.length - 1]); sb.append("Letter from " + from); sb.append(" to "); sb.append(to); sb.append(","); } if (parts.length >= 3) { for (int i = 0; i < 3; i++) { if (DocType.isDay(parts[i])) { sb.append(" "); sb.append(trimZeros(parts[i])); } else if (DocType.isMonth(parts[i])) { sb.append(" "); sb.append(Acronym.expand(projid, parts[i])); } else if (DocType.isYear(parts[i])) { sb.append(" "); sb.append(parts[i]); // maybe only a year break; } } md.put(JSONKeys.TITLE, sb.toString()); } } else System.out.println("No metadata found for " + docId); } else System.out.println("No metadata found for " + docId); changed = false; } docId = Utils.chomp(docId); } while (changed); response.setContentType("application/json"); response.setCharacterEncoding(encoding); String mdStr = md.toJSONString(); response.getWriter().println(mdStr); } catch (Exception e) { throw new MMLException(e); } }
From source file:com.nubits.nubot.trading.wrappers.ComkortWrapper.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 w w w. java2 s . c o m*/ if (queryResult.equals(TOKEN_BAD_RETURN)) { apiResponse.setError(errors.noConnectionError); return apiResponse; } //LOG.error(queryResult); JSONParser parser = new JSONParser(); Integer code = 0; try { JSONObject httpAnswerJson = (JSONObject) (parser.parse(queryResult)); if (httpAnswerJson.containsKey("code")) { ApiError error = errors.apiReturnError; error.setDescription(httpAnswerJson.get("error").toString()); apiResponse.setError(error); } 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.warn("httpResponse: " + queryResult + " \n" + pe.toString()); apiResponse.setError(errors.parseError); } } catch (ParseException pe) { LOG.warn("httpResponse: " + queryResult + " \n" + pe.toString()); apiResponse.setError(errors.parseError); return apiResponse; } return apiResponse; }
From source file:eu.seaclouds.platform.discoverer.crawler.CloudTypes.java
private CloudHarmonyService getService(String serviceId, CloudTypes t) { /* computing the query string */ String getServiceQuery = "https://cloudharmony.com/api/service/" + serviceId + "?" + "api-key=" + API_KEY + "&"; JSONObject service = null; try {// www . j a v a 2 s . com service = (JSONObject) query(getServiceQuery); } catch (Exception ex) { // 'no content' possible. dunno why } if (service == null) return null; /* name */ String name = "unknown_name"; if (service.containsKey("name")) name = (String) service.get("name"); /* sla */ Double sla = null; if (service.containsKey("sla")) { Object slaValue = service.get("sla"); if (slaValue.getClass().equals(Long.class)) { sla = ((Long) slaValue).doubleValue(); } else { // Double sla = (Double) slaValue; } } /* locations */ JSONArray locations = null; if (service.containsKey("regions")) locations = (JSONArray) service.get("regions"); /* service features */ Object serviceFeatures; ArrayList<JSONObject> computeInstanceTypes = null; if (t == CloudTypes.IAAS) { serviceFeatures = iaas_getServiceFeatures(serviceId); /* in the service features we can find * all the instance types to use to retrieve * the compute instance types. */ if (serviceFeatures != null && ((JSONArray) (serviceFeatures)).size() != 0) { /* retrieving instance types * up to now only Amazon AWS:EC2 and Aruba ARUBA:COMPUTE * return more than one properties object */ JSONObject oneFeature = (JSONObject) ((JSONArray) (serviceFeatures)).get(0); /* It's actually returned a list of service features apparently equal * (except for id which is -> aws:ec2, aws:ec2-..-..) */ JSONArray instanceTypes = (JSONArray) oneFeature.get("instanceTypes"); Iterator<String> instanceTypesIDs = instanceTypes.iterator(); /* querying each instance type */ computeInstanceTypes = new ArrayList<JSONObject>(); while (instanceTypesIDs.hasNext()) { /* current instance id */ String instanceTypeID = instanceTypesIDs.next(); JSONObject cit = getComputeInstanceType(serviceId, instanceTypeID); computeInstanceTypes.add(cit); } } } else { // t == CloudTypes.PAAS serviceFeatures = paas_getServiceFeatures(serviceId); } /* returning everything */ return new CloudHarmonyService(t, // cloud type serviceId, // service id name, // cloud name sla, // availability locations, // geographics null, // bandwidth pricing (unused) serviceFeatures, // cloudharmony service features computeInstanceTypes); // compute instance types }
From source file:com.opensoc.tagging.TelemetryTaggerBolt.java
@SuppressWarnings("unchecked") public void execute(Tuple tuple) { LOG.trace("[OpenSOC] Starting to process message for alerts"); JSONObject original_message = null; try {//w ww . ja va2 s . c o m original_message = (JSONObject) tuple.getValue(0); if (original_message == null || original_message.isEmpty()) throw new Exception("Could not parse message from byte stream"); LOG.trace("[OpenSOC] Received tuple: " + original_message); JSONObject alerts_tag = new JSONObject(); JSONArray alerts_list = _adapter.tag(original_message); LOG.trace("[OpenSOC] Tagged message: " + alerts_list); if (alerts_list.size() != 0) { if (original_message.containsKey("alerts")) { JSONObject tag = (JSONObject) original_message.get("alerts"); JSONArray already_triggered = (JSONArray) tag.get("triggered"); alerts_list.addAll(already_triggered); LOG.trace("[OpenSOC] Created a new string of alerts"); } alerts_tag.put("identifier", _identifier); alerts_tag.put("triggered", alerts_list); original_message.put("alerts", alerts_tag); LOG.debug("[OpenSOC] Detected alerts: " + alerts_tag); } else { LOG.debug("[OpenSOC] The following messages did not contain alerts: " + original_message); } _collector.ack(tuple); _collector.emit(new Values(original_message)); /*if (metricConfiguration != null) { emitCounter.inc(); ackCounter.inc(); }*/ } catch (Exception e) { e.printStackTrace(); LOG.error("Failed to tag message :" + original_message); e.printStackTrace(); _collector.fail(tuple); /* if (metricConfiguration != null) { failCounter.inc(); }*/ } }
From source file:com.auto.solution.TestManager.TESTRAILTestManager.java
private Object sendRequest(String method, String uri, Object data) throws MalformedURLException, IOException, APIException { URL url = new URL(this.m_url + uri); // Create the connection object and set the required HTTP method // (GET/POST) and headers (content type and basic auth). HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.addRequestProperty("Content-Type", "application/json"); String auth = getAuthorization(this.m_user, this.m_password); conn.addRequestProperty("Authorization", "Basic " + auth); if (method == "POST") { // Add the POST arguments, if any. We just serialize the passed // data object (i.e. a dictionary) and then add it to the // request body. if (data != null) { byte[] block = JSONValue.toJSONString(data).getBytes("UTF-8"); conn.setDoOutput(true);//from w w w . ja v a 2s. c om OutputStream ostream = conn.getOutputStream(); ostream.write(block); ostream.flush(); } } // Execute the actual web request (if it wasn't already initiated // by getOutputStream above) and record any occurred errors (we use // the error stream in this case). int status = conn.getResponseCode(); InputStream istream; if (status != 200) { istream = conn.getErrorStream(); if (istream == null) { throw new APIException( "TestRail API return HTTP " + status + " (No additional error message received)"); } } else { istream = conn.getInputStream(); } // Read the response body, if any, and deserialize it from JSON. String text = ""; if (istream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(istream, "UTF-8")); String line; while ((line = reader.readLine()) != null) { text += line; text += System.getProperty("line.separator"); } reader.close(); } Object result; if (text != "") { result = JSONValue.parse(text); } else { result = new JSONObject(); } // Check for any occurred errors and add additional details to // the exception message, if any (e.g. the error message returned // by TestRail). if (status != 200) { String error = "No additional error message received"; if (result != null && result instanceof JSONObject) { JSONObject obj = (JSONObject) result; if (obj.containsKey("error")) { error = '"' + (String) obj.get("error") + '"'; } } throw new APIException("TestRail API returned HTTP " + status + "(" + error + ")"); } return result; }
From source file:gwap.rest.UserPicture.java
protected ArtResource createPicture(JSONObject payload) { ArtResource artResource = new ArtResource(); Query query = entityManager.createNamedQuery("person.byDeviceId"); query.setParameter("deviceId", payload.get("userid").toString()); Person person = (Person) query.getSingleResult(); artResource.setArtist(person);//from ww w . ja v a 2s . com Calendar now = GregorianCalendar.getInstance(); artResource.setDateCreated(new SimpleDateFormat("dd.MM.yyyy").format(now.getTime())); artResource.setSkip(true); // should not show up for artigo tagging Location location = new Location(); location.setType(LocationType.APP); if (payload.containsKey("name")) location.setName(payload.get("name").toString()); GeoPoint geoPoint = new GeoPoint(); geoPoint.setLatitude(Float.parseFloat(payload.get("latitude").toString())); geoPoint.setLongitude(Float.parseFloat(payload.get("longitude").toString())); entityManager.persist(geoPoint); entityManager.persist(location); entityManager.flush(); LocationGeoPoint locationGeoPoint = new LocationGeoPoint(); locationGeoPoint.setGeoPoint(geoPoint); locationGeoPoint.setLocation(location); entityManager.persist(locationGeoPoint); entityManager.flush(); location.getGeoRepresentation().add(locationGeoPoint); artResource.setShownLocation(location); entityManager.persist(artResource); entityManager.flush(); return artResource; }
From source file:be.appfoundry.custom.google.android.gcm.server.Sender.java
/** * Sends a message without retrying in case of service unavailability. See * {@link #send(Message, String, int)} for more info. * * @return result of the post, or {@literal null} if the GCM service was * unavailable or any network exception caused the request to fail, * or if the response contains more than one result. * @throws InvalidRequestException if GCM didn't returned a 200 status. * @throws IllegalArgumentException if to is {@literal null}. */// w ww.j av a 2s. co m public Result sendNoRetry(Message message, String to) throws IOException { nonNull(to); Map<Object, Object> jsonRequest = new HashMap<Object, Object>(); messageToMap(message, jsonRequest); jsonRequest.put(JSON_TO, to); String responseBody = makeGcmHttpRequest(jsonRequest); if (responseBody == null) { return null; } JSONParser parser = new JSONParser(); JSONObject jsonResponse; try { jsonResponse = (JSONObject) parser.parse(responseBody); Result.Builder resultBuilder = new Result.Builder(); if (jsonResponse.containsKey("results")) { // Handle response from message sent to specific device. JSONArray jsonResults = (JSONArray) jsonResponse.get("results"); if (jsonResults.size() == 1) { JSONObject jsonResult = (JSONObject) jsonResults.get(0); String messageId = (String) jsonResult.get(JSON_MESSAGE_ID); String canonicalRegId = (String) jsonResult.get(TOKEN_CANONICAL_REG_ID); String error = (String) jsonResult.get(JSON_ERROR); resultBuilder.messageId(messageId).canonicalRegistrationId(canonicalRegId).errorCode(error); } else { logger.log(Level.WARNING, "Found null or " + jsonResults.size() + " results, expected one"); return null; } } else if (to.startsWith(TOPIC_PREFIX)) { if (jsonResponse.containsKey(JSON_MESSAGE_ID)) { // message_id is expected when this is the response from a topic message. Long messageId = (Long) jsonResponse.get(JSON_MESSAGE_ID); resultBuilder.messageId(messageId.toString()); } else if (jsonResponse.containsKey(JSON_ERROR)) { String error = (String) jsonResponse.get(JSON_ERROR); resultBuilder.errorCode(error); } else { logger.log(Level.WARNING, "Expected " + JSON_MESSAGE_ID + " or " + JSON_ERROR + " found: " + responseBody); return null; } } else if (jsonResponse.containsKey(JSON_SUCCESS) && jsonResponse.containsKey(JSON_FAILURE)) { // success and failure are expected when response is from group message. int success = getNumber(jsonResponse, JSON_SUCCESS).intValue(); int failure = getNumber(jsonResponse, JSON_FAILURE).intValue(); List<String> failedIds = null; if (jsonResponse.containsKey("failed_registration_ids")) { JSONArray jFailedIds = (JSONArray) jsonResponse.get("failed_registration_ids"); failedIds = new ArrayList<String>(); for (int i = 0; i < jFailedIds.size(); i++) { failedIds.add((String) jFailedIds.get(i)); } } resultBuilder.success(success).failure(failure).failedRegistrationIds(failedIds); } else { logger.warning("Unrecognized response: " + responseBody); throw newIoException(responseBody, new Exception("Unrecognized response.")); } return resultBuilder.build(); } catch (ParseException e) { throw newIoException(responseBody, e); } catch (CustomParserException e) { throw newIoException(responseBody, e); } }
From source file:com.francetelecom.rd.dashboard.pc.DashboardPC.java
private String getIdForType(int idType) { String id = ""; String configFilePath = "configDasboardPC.json"; if (!(new File(configFilePath).isFile())) { // configuration file does not exist // => create default one that contains "{}" try {/*from ww w . j av a2 s . co m*/ // create file FileWriter fstream = new FileWriter(configFilePath); BufferedWriter out = new BufferedWriter(fstream); out.write("{}"); // close the output stream out.close(); } catch (Exception e) { logger.error("Could not initilize configuration file config.json, \nERROR : " + e.getMessage()); return id; } } String idTypeName = ""; switch (idType) { case ID_type_Node: { idTypeName = "nodeId"; break; } case ID_type_Device: { idTypeName = "deviceId"; break; } case ID_type_Rule: { idTypeName = "ruleId"; break; } case ID_type_Service: { idTypeName = "serviceId"; break; } default: {// type of id invalid logger.error("ERROR : Bad id type " + idType); return id; } } // if not existent, generate it and write it to the configuration file try { // parse JSON format file and retrieve parameters JSONParser parser = new JSONParser(); // entire JSON object JSONObject configObj = (JSONObject) parser.parse((new FileReader(configFilePath))); // nodeId and deviceId are generated using hlc-connector-impl Tools.generateId if (!configObj.containsKey(idTypeName)) { // not existent in config file => generate id and write it to file id = Tools.generateId(); configObj.put(idTypeName, new String(id)); } else { // existent (already generated a previous time) id = configObj.get(idTypeName).toString(); } // re-write configObj to the config file // in case the nodeId was generated // so just added to the object // http://www.roseindia.net/tutorial/java/core/files/fileoverwrite.html // 30/04/2013 File configFile = new File(configFilePath); FileOutputStream fos = new FileOutputStream(configFile, false); fos.write((configObj.toJSONString()).getBytes()); fos.close(); } catch (Exception e) { e.printStackTrace(); logger.error("Could not retrieve deviceId!\n" + e.getMessage()); } return id; }
From source file:mml.handler.get.MMLGetMMLHandler.java
/** * Emit the start "tag" of an MML property * @param defn the property definition//from w w w .j a v a 2 s . c o m * @param offset the offset in the text * @return the text associated with tag-start */ String mmlStartTag(JSONObject defn, int offset) { String kind = (String) defn.get("kind"); DialectKeys key = DialectKeys.valueOf(kind); StringBuilder sb; switch (key) { case sections: if (!defn.containsKey("prop") || ((String) defn.get("prop")).length() == 0) return "\n\n\n"; else return "\n\n\n{" + (String) defn.get("prop") + "}\n"; case paragraph: case headings: return ""; case charformats: if (defn.containsKey("tag")) return (String) defn.get("tag"); else return (String) defn.get("leftTag"); case lineformats: return (String) defn.get("leftTag"); case paraformats: return (String) defn.get("leftTag"); default: return ""; } }
From source file:coria2015.server.JsonRPCMethods.java
void handleJSON(JSONObject object) { String requestID = null;//from ww w.j av a2s.com try { requestID = object.get("id").toString(); if (requestID == null) throw new RuntimeException("No id in JSON request"); Object command = object.get("method"); if (command == null) throw new RuntimeException("No method in JSON"); if (!object.containsKey("params")) throw new RuntimeException("No params in JSON"); Object p = object.get("params"); Collection<MethodDescription> candidates = methods.get(command.toString()); int max = Integer.MIN_VALUE; MethodDescription argmax = null; for (MethodDescription candidate : candidates) { int score = Integer.MAX_VALUE; for (int i = 0; i < candidate.types.length && score > max; i++) { score = convert(p, candidate, score, null, i); } if (score > max) { max = score; argmax = candidate; } } if (argmax == null) throw new RuntimeException("Cannot find a matching method"); Object[] args = new Object[argmax.arguments.length]; for (int i = 0; i < args.length; i++) { int score = convert(p, argmax, 0, args, i); assert score > Integer.MIN_VALUE; } Object result = argmax.method.invoke(this, args); mos.endMessage(requestID, result); } catch (Throwable t) { LOGGER.warning("Error while handling JSON request"); try { while (t.getCause() != null) t = t.getCause(); mos.error(requestID, 1, t.getMessage()); } catch (IOException e) { LOGGER.severe("Could not send the return code"); } return; } }