List of usage examples for org.json.simple JSONValue parse
public static Object parse(String s)
From source file:gribbit.util.RequestBuilder.java
/** * Send a GET request to a given URL with the given key-value URL parameters (with keys in the even indices and * values in the following odd indices). Result is a json-simple object, see * https://code.google.com/p/json-simple/wiki/DecodingExamples * /*from www .j a v a 2 s . c o m*/ * @throws IllegalArgumentException * if request could not be completed or JSON could not be parsed. */ public static Object getFromURLWithJSONResponse(String url, String... keyValuePairs) throws IllegalArgumentException { String jsonStr = (String) makeRequest(url, keyValuePairs, /* isGET = */true, /* isBinaryResponse = */ false); try { return JSONValue.parse(jsonStr); } catch (Exception e) { throw new IllegalArgumentException("Could not parse JSON response: " + e.getMessage(), e); } }
From source file:de.dailab.plistacontest.client.ClientAndContestHandler0MQ.java
/** * Method to handle incoming messages from the server. * /*from w ww . jav a2s . co m*/ * @param messageType * the messageType of the incoming contest server message * @param _jsonString * the incoming contest server message * @return the response to the contest server */ @SuppressWarnings("unused") private String handleTraditionalMessage(final String messageType, final String _jsonMessageBody) { // write all data from the server to a file logger.info(messageType + "\t" + _jsonMessageBody); // create an jSON object from the String final JSONObject jObj = (JSONObject) JSONValue.parse(_jsonMessageBody); // define a response object String response = null; // TODO handle "item_create" // in a complex if/switch statement we handle the differentTypes of // messages if ("item_update".equalsIgnoreCase(messageType)) { // we extract itemID, domainID, text and the timeTime, create/update final RecommenderItem recommenderItem = RecommenderItem.parseItemUpdate(_jsonMessageBody); // we mark this information in the article table if (recommenderItem.getItemID() != null) { recommenderItemTable.handleItemUpdate(recommenderItem); } response = ";item_update successfull"; } else if ("recommendation_request".equalsIgnoreCase(messageType)) { final RecommenderItem recommenderItem = RecommenderItem.parseItemUpdate(_jsonMessageBody); // we handle a recommendation request try { // parse the new recommender request RecommenderItem currentRequest = RecommenderItem.parseRecommendationRequest(_jsonMessageBody); // gather the items to be recommended List<Long> resultList = recommenderItemTable.getLastItems(currentRequest); if (resultList == null) { response = "[]"; System.out.println("invalid resultList"); } else { response = resultList.toString(); } response = getRecommendationResultJSON(response); // TODO? might handle the the request as impressions } catch (Throwable t) { t.printStackTrace(); } } else if ("event_notification".equalsIgnoreCase(messageType)) { // parse the type of the event final RecommenderItem item = RecommenderItem.parseEventNotification(_jsonMessageBody); final String eventNotificationType = item.getNotificationType(); // impression refers to articles read by the user if ("impression".equalsIgnoreCase(eventNotificationType) || "impression_empty".equalsIgnoreCase(eventNotificationType)) { // we mark this information in the article table if (item.getItemID() != null) { // new items shall be added to the list of items recommenderItemTable.handleItemUpdate(item); response = "handle impression eventNotification successful"; } // click refers to recommendations clicked by the user } else if ("click".equalsIgnoreCase(eventNotificationType)) { response = "handle click eventNotification successful"; } else { System.out.println("unknown event-type: " + eventNotificationType + " (message ignored)"); } } else if ("error_notification".equalsIgnoreCase(messageType)) { System.out.println("error-notification: " + _jsonMessageBody); } else { System.out.println("unknown MessageType: " + messageType); // Error handling logger.info(jObj.toString()); // this.contestRecommender.error(jObj.toString()); } return response; }
From source file:be.cytomine.client.Cytomine.java
private JSONArray createJSONArrayResponse(int code, String response) throws CytomineException { Object obj = JSONValue.parse(response); return (JSONArray) obj; }
From source file:fr.bmartel.protocol.google.oauth.device.CalendarNotifManager.java
public void revokeToken(final IRevokeTokenListener revokeTokenListener) { if (oauthRegistration == null) { System.err.println("Error oauth registration not proceeded"); revokeTokenListener.onError("no registration has been processed yet"); return;/* w ww .jav a2 s. c om*/ } if (currentToken == null) { System.err.println("no existing current token to revoke"); revokeTokenListener.onError("no token has been requested yet"); return; } String method = "GET"; String uri = GoogleConst.GOOGLE_REVOKE_TOKEN + "?token=" + currentToken.getAccessToken(); HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); headers.put("Host", GoogleConst.GOOGLE_ACCOUNT_HOST); headers.put("Accept", "*/*"); headers.put("Accept-Encoding", "gzip, deflate, compress"); String body = ""; HttpFrame frame = new HttpFrame(method, new HttpVersion(1, 1), headers, uri, new ListOfBytes(body)); ClientSocket clientSocket = new ClientSocket(GoogleConst.GOOGLE_ACCOUNT_HOST, 443); // set SSL encryption clientSocket.setSsl(true); clientSocket.checkCertificate(false); clientSocket.addClientSocketEventListener(new IHttpClientListener() { @Override public void onIncomingHttpFrame(HttpFrame frame, HttpStates httpStates, IClientSocket clientSocket) { if (httpStates == HttpStates.HTTP_FRAME_OK && frame.isHttpResponseFrame()) { if (frame.getBody() != null && frame.getBody().getSize() > 0) { Object obj = JSONValue.parse(new String(frame.getBody().getBytes())); try { JSONObject mainObject = (JSONObject) obj; if (mainObject.containsKey("error")) { System.err.println("revoke token error. Retry later ..."); if (mainObject.containsKey("error_description")) { revokeTokenListener.onError(mainObject.get("error_description").toString()); clientSocket.closeSocket(); return; } } else { currentToken = null; revokeTokenListener.onSuccess(); clientSocket.closeSocket(); return; } } catch (Exception e) { e.printStackTrace(); } } else { currentToken = null; revokeTokenListener.onSuccess(); clientSocket.closeSocket(); return; } } else { System.err.println("Error occured while requesting token"); } clientSocket.closeSocket(); revokeTokenListener.onError(""); } }); clientSocket.write(frame.toString().getBytes()); }
From source file:bbdn.lti2.LTI2Servlet.java
@SuppressWarnings("unused") protected void doLaunch(HttpServletRequest request, HttpServletResponse response) { Object profile = PERSIST.get("profile"); response.setContentType("text/html"); String output = null;//from w w w . j a v a 2 s.co m if (profile == null) { output = "Missing profile"; } else { JSONObject providerProfile = (JSONObject) JSONValue.parse((Reader) profile); List<Properties> profileTools = new ArrayList<Properties>(); Properties info = new Properties(); String retval = LTI2Util.parseToolProfile(profileTools, info, providerProfile); String launch = null; String parameter = null; for (Properties profileTool : profileTools) { launch = (String) profileTool.get("launch"); parameter = (String) profileTool.get("parameter"); } JSONObject security_contract = (JSONObject) providerProfile.get(LTI2Constants.SECURITY_CONTRACT); String shared_secret = (String) security_contract.get(LTI2Constants.SHARED_SECRET); System.out.println("launch=" + launch); System.out.println("shared_secret=" + shared_secret); Properties ltiProps = LTI2SampleData.getLaunch(); ltiProps.setProperty(BasicLTIConstants.LTI_VERSION, BasicLTIConstants.LTI_VERSION_2); Properties lti2subst = LTI2SampleData.getSubstitution(); String settings_url = getServiceURL(request) + SVC_Settings + "/"; lti2subst.setProperty("LtiLink.custom.url", settings_url + LTI2Util.SCOPE_LtiLink + "/" + ltiProps.getProperty(BasicLTIConstants.RESOURCE_LINK_ID)); lti2subst.setProperty("ToolProxyBinding.custom.url", settings_url + LTI2Util.SCOPE_ToolProxyBinding + "/" + ltiProps.getProperty(BasicLTIConstants.CONTEXT_ID)); lti2subst.setProperty("ToolProxy.custom.url", settings_url + LTI2Util.SCOPE_ToolProxy + "/" + "42"); lti2subst.setProperty("Result.url", getServiceURL(request) + SVC_Result + "/" + ltiProps.getProperty(BasicLTIConstants.RESOURCE_LINK_ID)); // Do the substitutions Properties custom = new Properties(); LTI2Util.mergeLTI2Parameters(custom, parameter); LTI2Util.substituteCustom(custom, lti2subst); // Place the custom values into the launch LTI2Util.addCustomToLaunch(ltiProps, custom); ltiProps = BasicLTIUtil.signProperties(ltiProps, launch, "POST", "42", shared_secret, null, null, null); boolean dodebug = true; output = BasicLTIUtil.postLaunchHTML(ltiProps, launch, dodebug); } try { PrintWriter out = response.getWriter(); out.println(output); } catch (Exception e) { e.printStackTrace(); } }
From source file:at.ac.tuwien.dsg.quelle.sesConfigurationsRecommendationService.control.RequirementsManagementController.java
private void processAddToRequirementsJSONCommand(String json) { //TODO: To actually get the names from somwehere and conditions and etc. I need to do a bit more management //JSON looks like { "command" : "add", "type": "' + type+ '" "trace" : [{"name" : "ServiceReqs_overall_elasticity_multi", "type" : "SERVICE"}]}; Object command = JSONValue.parse(json); JSONObject jSONcommandObject = (JSONObject) command; JSONObject metaInfo = (JSONObject) jSONcommandObject.get("meta"); String whatToAdd = jSONcommandObject.get("type").toString(); JSONArray trace = (JSONArray) jSONcommandObject.get("trace"); JSONObject jSONRootObject = (JSONObject) trace.remove(0); String namejSONRootObject = jSONRootObject.get("name").toString(); String typejSONRootObject = jSONRootObject.get("type").toString(); //in order we traverse from root if (!requirements.getName().equals(namejSONRootObject) || !requirements.getLevel().toString().equals(typejSONRootObject)) { throw new RuntimeException("Something bad, as The requirements root does not match"); }//from w ww. ja v a 2 s . c o m //we go one by one with JSON and get corect requirements children //first we get through the multi level requirements MultiLevelRequirements currentReqs = requirements; while (!currentReqs.getContainedElements().isEmpty() && !trace.isEmpty()) { { Object obj = trace.get(0); boolean discovered = false; JSONObject jSONObject = (JSONObject) obj; String name = jSONObject.get("name").toString(); String type = jSONObject.get("type").toString(); for (MultiLevelRequirements r : currentReqs.getContainedElements()) { if (r.getName().equals(name) && r.getLevel().toString().equals(type)) { currentReqs = r; discovered = true; break; } } //so If for example I want to add Requirement on Requirements from Service, it will not be found in the MultiLevelRequirements (topology) //so, i need to keep it if (discovered) { trace.remove(0); } else { //if not discovered after a run, break while loop break; } } } //here we are at a point in which we need to start looking in individual requirements blocks, then individual requirements, then conditions //only if we add Requirements or Conditions. Otherwise all work on multi level reqs switch (whatToAdd) { case "Strategy": { String strategyType = metaInfo.get("strategy").toString(); Strategy s = new Strategy().withCategoryString(strategyType); if (!currentReqs.getOptimizationStrategies().contains(s)) { currentReqs.addStrategy(s); } break; } case "Topology": { MultiLevelRequirements levelRequirements = new MultiLevelRequirements( MonitoredElement.MonitoredElementLevel.SERVICE_TOPOLOGY); String topologyName = metaInfo.get("name").toString(); levelRequirements.setName(topologyName); if (!currentReqs.getContainedElements().contains(levelRequirements)) { currentReqs.addMultiLevelRequirements(levelRequirements); } } break; case "Unit": { MultiLevelRequirements levelRequirements = new MultiLevelRequirements( MonitoredElement.MonitoredElementLevel.SERVICE_UNIT); String unitName = metaInfo.get("name").toString(); levelRequirements.setName(unitName); if (!currentReqs.getContainedElements().contains(levelRequirements)) { currentReqs.addMultiLevelRequirements(levelRequirements); } } break; case "Requirements": { Requirements requirements = new Requirements(); String name = metaInfo.get("name").toString(); requirements.setName(name); if (!currentReqs.getUnitRequirements().contains(requirements)) { currentReqs.addRequirements(requirements); } } break; case "Requirement": //here we need to continue to get the targeted Requirements block { Object obj = trace.remove(0); JSONObject jSONObject = (JSONObject) obj; String name = jSONObject.get("name").toString(); String type = jSONObject.get("type").toString(); for (Requirements r : currentReqs.getUnitRequirements()) { if (r.getName().equals(name)) { Requirement requirement = new Requirement(); JSONObject metricInfo = (JSONObject) metaInfo.get("metric"); Metric metric = new Metric(metricInfo.get("name").toString(), metricInfo.get("unit").toString()); switch (metricInfo.get("type").toString()) { case "COST": metric.setType(Metric.MetricType.COST); break; case "RESOURCE": metric.setType(Metric.MetricType.RESOURCE); break; case "QUALITY": metric.setType(Metric.MetricType.QUALITY); break; } // + ', "unit": "' + selectedMetric.unit + '", "type":"' + selectedMetric.type + '"}'; requirement.setName(metricInfo.get("name").toString()); requirement.setMetric(metric); r.addRequirement(requirement); break; } } } break; case "Condition": //here we also need to get the requirement { Object obj = trace.remove(0); JSONObject jSONObject = (JSONObject) obj; String name = jSONObject.get("name").toString(); String type = jSONObject.get("type").toString(); for (Requirements r : currentReqs.getUnitRequirements()) { if (r.getName().equals(name)) { Object reqObj = trace.remove(0); JSONObject reqjSONObject = (JSONObject) reqObj; String reqname = reqjSONObject.get("name").toString(); String reqtype = reqjSONObject.get("type").toString(); for (Requirement req : r.getRequirements()) { if (req.getName().equals(reqname)) { Condition condition = new Condition(); // var selectedConditionType = conditionTypeSelect.options[conditionTypeSelect.selectedIndex]; // var conditionData = '{ "type":"' + selectedConditionType.text + '"' // + ', "value": "' + f.conditionValue.text + '"}'; // data = '{' + data + ', "meta" : { "condition":' + conditionData + ' } ' + '}'; JSONObject conditionJSON = (JSONObject) metaInfo.get("condition"); switch (conditionJSON.get("type").toString()) { case "LESS_THAN": condition.setType(Condition.Type.LESS_THAN); break; case "LESS_EQUAL": condition.setType(Condition.Type.LESS_EQUAL); break; case "GREATER_THAN": condition.setType(Condition.Type.GREATER_THAN); break; case "GREATER_EQUAL": condition.setType(Condition.Type.GREATER_EQUAL); break; case "EQUAL": condition.setType(Condition.Type.EQUAL); break; case "RANGE": condition.setType(Condition.Type.RANGE); break; case "ENUMERATION": condition.setType(Condition.Type.ENUMERATION); break; } List<MetricValue> metricValues = new ArrayList<>(); metricValues.add(new MetricValue(conditionJSON.get("value").toString())); condition.setValue(metricValues); req.addCondition(condition); break; } } break; } } } } }
From source file:com.sugarcrm.candybean.webservices.WS.java
/** * Protected method to handle sending and receiving an http request * * @param request The Http request that is being send * @param headers Map of Key Value header pairs * @return Key Value pairs of the response * @throws CandybeanException If the response is null or not an acceptable HTTP code *///from ww w . j ava2 s . com protected static Map<String, Object> handleRequest(HttpUriRequest request, Map<String, String> headers) throws CandybeanException { // Add the request headers and execute the request for (Map.Entry<String, String> header : headers.entrySet()) { request.addHeader(new BasicHeader(header.getKey(), header.getValue())); } CloseableHttpClient httpClient = HttpClientBuilder.create().build(); try { HttpResponse response = httpClient.execute(request); // Check for invalid responses or error return codes if (response == null) { throw new CandybeanException("Http Request failed: Response null"); } // Cast the response into a Map and return JSONObject parse = (JSONObject) JSONValue .parse(new InputStreamReader(response.getEntity().getContent())); @SuppressWarnings("unchecked") Map<String, Object> mapParse = (Map<String, Object>) parse; int code = response.getStatusLine().getStatusCode(); if (!ACCEPTABLE_RETURN_CODE_SET.contains(code)) { throw new CandybeanException( "HTTP request received HTTP code: " + code + "\n" + "Response: " + response.toString()); } else if (mapParse == null) { throw new CandybeanException("Could not format response\n" + "Response: " + response.toString()); } return mapParse; } catch (IOException | IllegalStateException e) { // Cast the other possible exceptions as a CandybeanException throw new CandybeanException(e); } }
From source file:fromgate.obscura.FGUtilCore.java
private void updateLastVersion() { if (!this.project_check_version) return;//ww w .j av a2 s . c om URL url = null; try { url = new URL(this.project_curse_url); } catch (Exception e) { this.log("Failed to create URL: " + this.project_curse_url); return; } try { URLConnection conn = url.openConnection(); conn.addRequestProperty("X-API-Key", this.project_apikey); conn.addRequestProperty("User-Agent", this.project_name + " using FGUtilCore (by fromgate)"); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = reader.readLine(); JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() > 0) { JSONObject latest = (JSONObject) array.get(array.size() - 1); String plugin_name = (String) latest.get("name"); this.project_last_version = plugin_name.replace(this.project_name + " v", "").trim(); //String plugin_jar_url = (String) latest.get("downloadUrl"); //this.project_file_url = plugin_jar_url.replace("http://servermods.cursecdn.com/", "http://dev.bukkit.org/media/"); } } catch (Exception e) { this.log("Failed to check last version"); } }
From source file:de.dailab.plistacontest.client.RecommenderItem.java
/** * Parse the ORP json Messages./*from w ww .jav a2 s. co m*/ * * @param _jsonMessageBody * @return the parsed values encapsulated in a map; null if an error has * been detected. */ public static RecommenderItem parseItemUpdate(String _jsonMessageBody) { try { final JSONObject jsonObj = (JSONObject) JSONValue.parse(_jsonMessageBody); String itemID = jsonObj.get("id") + ""; if ("null".equals(itemID)) { itemID = "0"; } String domainID = jsonObj.get("domainid") + ""; String text = jsonObj.get("text") + ""; String flag = jsonObj.get("flag") + ""; boolean recommendable = ("0".equals(flag)); // parse date, now is default String createdAt = jsonObj.get("created_at") + ""; Long created = System.currentTimeMillis(); // maybe the field is called timeStamp instead of created_at if ("null".equals(createdAt)) { created = (Long) jsonObj.get("timestamp"); } else { // parse the date string and derive the long date number try { SimpleDateFormat sdf; sdf = RecommenderItem.sdf.get(); created = sdf.parse(createdAt).getTime(); } catch (ParseException e) { e.printStackTrace(); } } RecommenderItem result = new RecommenderItem(null /* userID */, Long.valueOf(itemID), Long.valueOf(domainID), created); result.setText(text); result.setRecommendable(recommendable); return result; } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:com.memetix.mst.MicrosoftTranslatorAPI.java
private static Integer[] jsonToIntArr(final String inputString) throws Exception { final JSONArray jsonArr = (JSONArray) JSONValue.parse(inputString); Integer[] intArr = new Integer[jsonArr.size()]; int i = 0;//from w ww .j a v a 2 s.c o m for (Object obj : jsonArr) { intArr[i] = ((Long) obj).intValue(); i++; } return intArr; }