List of usage examples for org.json.simple JSONValue parse
public static Object parse(String s)
From source file:com.mobicage.rogerthat.registration.ContentBrandingRegistrationActivity.java
private void registerWithQRUrl(final String qr_url) { if (!mService.getNetworkConnectivityManager().isConnected()) { UIUtils.showNoNetworkDialog(this); return;//from ww w . j av a 2s . c om } final String timestamp = "" + mWiz.getTimestamp(); final String deviceId = mWiz.getDeviceId(); final String registrationId = mWiz.getRegistrationId(); final String installId = mWiz.getInstallationId(); // Make call to Rogerthat webfarm mProgressContainer.setVisibility(View.VISIBLE); mButtonContainer.setVisibility(View.GONE); final SafeRunnable showErrorDialog = new SafeRunnable() { @Override protected void safeRun() throws Exception { T.UI(); mProgressContainer.setVisibility(View.GONE); mButtonContainer.setVisibility(View.VISIBLE); AlertDialog.Builder builder = new AlertDialog.Builder(ContentBrandingRegistrationActivity.this); builder.setMessage(R.string.error_please_try_again); builder.setPositiveButton(R.string.rogerthat, null); AlertDialog dialog = builder.create(); dialog.show(); } }; mWorkerHandler.post(new SafeRunnable() { @Override protected void safeRun() throws Exception { T.REGISTRATION(); String version = "1"; String signature = Security.sha256(version + " " + installId + " " + timestamp + " " + deviceId + " " + registrationId + " " + qr_url + CloudConstants.REGISTRATION_MAIN_SIGNATURE); HttpPost httppost = new HttpPost(CloudConstants.REGISTRATION_QR_URL); try { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(13); nameValuePairs.add(new BasicNameValuePair("version", version)); nameValuePairs.add(new BasicNameValuePair("platform", "android")); nameValuePairs.add(new BasicNameValuePair("registration_time", timestamp)); nameValuePairs.add(new BasicNameValuePair("device_id", deviceId)); nameValuePairs.add(new BasicNameValuePair("registration_id", registrationId)); nameValuePairs.add(new BasicNameValuePair("signature", signature)); nameValuePairs.add(new BasicNameValuePair("install_id", installId)); nameValuePairs.add(new BasicNameValuePair("qr_url", qr_url)); nameValuePairs.add(new BasicNameValuePair("language", Locale.getDefault().getLanguage())); nameValuePairs.add(new BasicNameValuePair("country", Locale.getDefault().getCountry())); nameValuePairs.add(new BasicNameValuePair("app_id", CloudConstants.APP_ID)); nameValuePairs.add( new BasicNameValuePair("use_xmpp_kick", CloudConstants.USE_XMPP_KICK_CHANNEL + "")); nameValuePairs.add(new BasicNameValuePair("GCM_registration_id", mGCMRegistrationId)); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = mHttpClient.execute(httppost); int statusCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (entity == null) { mUIHandler.post(showErrorDialog); return; } @SuppressWarnings("unchecked") final Map<String, Object> responseMap = (Map<String, Object>) JSONValue .parse(new InputStreamReader(entity.getContent())); if (statusCode != 200 || responseMap == null) { if (statusCode == 500 && responseMap != null) { final String errorMessage = (String) responseMap.get("error"); if (errorMessage != null) { mUIHandler.post(new SafeRunnable() { @Override protected void safeRun() throws Exception { T.UI(); mProgressContainer.setVisibility(View.GONE); mButtonContainer.setVisibility(View.VISIBLE); AlertDialog.Builder builder = new AlertDialog.Builder( ContentBrandingRegistrationActivity.this); builder.setMessage(errorMessage); builder.setPositiveButton(R.string.rogerthat, null); AlertDialog dialog = builder.create(); dialog.show(); } }); return; } } mUIHandler.post(showErrorDialog); return; } JSONObject account = (JSONObject) responseMap.get("account"); final String email = (String) responseMap.get("email"); final RegistrationInfo info = new RegistrationInfo(email, new Credentials((String) account.get("account"), (String) account.get("password"))); mUIHandler.post(new SafeRunnable() { @Override protected void safeRun() throws Exception { T.UI(); mWiz.setEmail(email); mWiz.save(); tryConnect(1, getString(R.string.registration_establish_connection, email, getString(R.string.app_name)) + " ", info); } }); } catch (Exception e) { L.d(e); mUIHandler.post(showErrorDialog); } } }); }
From source file:de.fhg.fokus.odp.middleware.ckan.CKANGatewayUtil.java
/** * The function receives the revisions as a JSON string and obtains the * details for the revisions in a list of strings. * //from ww w .jav a 2s .com * @param revisionStr * the string containing the revisions. * * @return a vector with JSON strings describing the updated data sets. */ public static Vector<String> getUpdatedDatasets(String revisionStr) { // check the parameters if (revisionStr == null) { return null; } // the vector to return Vector<String> toreturnVector = new Vector<String>(); // parse the JSON string and obtain an array of JSON objects Object obj = JSONValue.parse(revisionStr); JSONArray array = (JSONArray) obj; // prepare the URL string String CKANurl = url + "/api/rest/revision/"; // iterate over the JSON objects for (int i = 0; i < array.size(); i++) { String revisionUrl = CKANurl + array.get(i).toString(); // read the information for the revision from the CKAN API URL RevisionUrlInstance; String revisionDescriptionStr = ""; try { // open a connection to the CKAN API RevisionUrlInstance = new URL(revisionUrl); URLConnection RevisionUrlInstanceConnection = RevisionUrlInstance.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader(RevisionUrlInstanceConnection.getInputStream())); // read the output from the API String inputLine; while ((inputLine = in.readLine()) != null) { revisionDescriptionStr += inputLine; } in.close(); // the description toreturnVector.add(revisionDescriptionStr); } // process exceptions catch (MalformedURLException e) { log.log(Level.SEVERE, "Failed to realize api call \"" + url + CKANurl + "\" !!!"); toreturnVector.add(null); continue; } catch (IOException e) { toreturnVector.add(null); continue; } } return toreturnVector; }
From source file:ch.simas.jtoggl.JToggl.java
/** * Create a new client.//from w w w .jav a 2 s . co m * * @param clientObject * @return created {@link ch.simas.jtoggl.Client} */ public ch.simas.jtoggl.Client createClient(ch.simas.jtoggl.Client clientObject) { Client client = prepareClient(); WebResource webResource = client.resource(CLIENTS); JSONObject object = createClientRequestParameter(clientObject); String response = webResource.entity(object.toJSONString(), MediaType.APPLICATION_JSON_TYPE) .post(String.class); object = (JSONObject) JSONValue.parse(response); JSONObject data = (JSONObject) object.get(DATA); return new ch.simas.jtoggl.Client(data.toJSONString()); }
From source file:com.tremolosecurity.provisioning.core.providers.SugarCRM.java
@Override public User findUser(String userID, Set<String> attributes, Map<String, Object> request) throws ProvisioningException { try {/*w ww.j a v a 2 s. c o m*/ String sessionId = sugarLogin(); Gson gson = new Gson(); SugarGetEntryList sgel = new SugarGetEntryList(); sgel.setSession(sessionId); sgel.setModule_name("Contacts"); StringBuffer b = new StringBuffer(); b.append( "contacts.id in (SELECT eabr.bean_id FROM email_addr_bean_rel eabr JOIN email_addresses ea ON (ea.id = eabr.email_address_id) WHERE eabr.deleted=0 AND ea.email_address = '") .append(userID).append("')"); sgel.setQuery(b.toString()); sgel.setOrder_by(""); sgel.setOffset(0); ArrayList<String> reqFields = new ArrayList<String>(); reqFields.add("id"); sgel.setSelect_fields(reqFields); sgel.setMax_results(-1); sgel.setDeleted(false); sgel.setLink_name_to_fields_array(new HashMap<String, List<String>>()); String searchJson = gson.toJson(sgel); String respJSON = execJson(searchJson, "get_entry_list"); JSONObject jsonObj = (JSONObject) JSONValue.parse(respJSON); JSONArray jsonArray = (JSONArray) jsonObj.get("entry_list"); String id = (String) ((JSONObject) jsonArray.get(0)).get("id"); SugarGetEntry sge = new SugarGetEntry(); sge.setId(id); sge.setSession(sessionId); sge.setSelect_fields(new ArrayList<String>()); sge.setModule_name("Contacts"); sge.setLink_name_to_fields_array(new HashMap<String, List<String>>()); searchJson = gson.toJson(sge); respJSON = execJson(searchJson, "get_entry"); //System.out.println(respJSON); SugarEntrySet res = gson.fromJson(respJSON, SugarEntrySet.class); User user = new User(userID); SugarContactEntry sce = res.getEntry_list().get(0); for (String attrName : sce.getName_value_list().keySet()) { NVP nvp = sce.getName_value_list().get(attrName); if (attributes.size() > 0 && !attributes.contains(nvp.getName())) { continue; } if (nvp.getValue() != null && !nvp.getValue().isEmpty()) { Attribute attr = new Attribute(nvp.getName(), nvp.getValue()); user.getAttribs().put(nvp.getName(), attr); } } return user; } catch (Exception e) { throw new ProvisioningException("Could not find user", e); } }
From source file:net.sourceforge.fenixedu.presentationTier.Action.gep.a3es.A3ESDegreeProcess.java
protected JSONArray invoke(WebTarget resource) { return (JSONArray) ((JSONObject) JSONValue.parse(resource.request(MediaType.APPLICATION_JSON) .header("Authorization", "Basic " + base64Hash).get(String.class))).get("list"); }
From source file:com.mobicage.rogerthat.registration.RegistrationWizard2.java
public void requestBeaconRegions(final MainService mainService) { if (!mainService.isPermitted(Manifest.permission.ACCESS_COARSE_LOCATION)) { return;/*from ww w . j av a 2 s. co m*/ } new SafeAsyncTask<Object, Object, Object>() { @SuppressWarnings("unchecked") @Override protected Object safeDoInBackground(Object... params) { try { HttpClient httpClient = HTTPUtil.getHttpClient(10000, 3); final HttpPost httpPost = new HttpPost(CloudConstants.REGISTRATION_REGISTER_INSTALL_URL); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); List<NameValuePair> formParams = new ArrayList<NameValuePair>(); formParams.add(new BasicNameValuePair("version", MainService.getVersion(mainService))); formParams.add(new BasicNameValuePair("install_id", mInstallationId)); formParams.add(new BasicNameValuePair("platform", "android")); formParams.add(new BasicNameValuePair("language", Locale.getDefault().getLanguage())); formParams.add(new BasicNameValuePair("country", Locale.getDefault().getCountry())); formParams.add(new BasicNameValuePair("app_id", CloudConstants.APP_ID)); UrlEncodedFormEntity entity; try { entity = new UrlEncodedFormEntity(formParams, HTTP.UTF_8); } catch (UnsupportedEncodingException e) { L.bug(e); return true; } httpPost.setEntity(entity); L.d("Sending installation id: " + mInstallationId); try { HttpResponse response = httpClient.execute(httpPost); L.d("Installation id sent"); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { L.e("HTTP request resulted in status code " + statusCode); return false; } HttpEntity httpEntity = response.getEntity(); if (httpEntity == null) { L.e("Response of '/unauthenticated/mobi/registration/register_install' was null"); return false; } final Map<String, Object> responseMap = (Map<String, Object>) JSONValue .parse(new InputStreamReader(httpEntity.getContent())); if (responseMap == null) { L.e("HTTP request responseMap was null"); return false; } if ("success".equals(responseMap.get("result"))) { JSONObject beaconRegions = (JSONObject) responseMap.get("beacon_regions"); mBeaconRegions = new GetBeaconRegionsResponseTO(beaconRegions); } else { L.e("HTTP request result was not 'success' but: " + responseMap.get("result")); return false; } } catch (ClientProtocolException e) { L.bug(e); return false; } catch (IOException e) { L.bug(e); return false; } mainService.sendBroadcast(new Intent(INTENT_GOT_BEACON_REGIONS)); return true; } catch (Exception e) { L.bug(e); return false; } } @Override protected void safeOnPostExecute(Object result) { T.UI(); Boolean b = (Boolean) result; if (mInstallationIdSent) { mInstallationIdSent = b; save(); } } @Override protected void safeOnCancelled(Object result) { } @Override protected void safeOnProgressUpdate(Object... values) { } @Override protected void safeOnPreExecute() { } }.execute(); }
From source file:de.static_interface.sinklibrary.Updater.java
private boolean isUpdateAvailable() { try {//from ww w . j av a 2 s . com final URLConnection conn = url.openConnection(); conn.setConnectTimeout(5000); String version = SinkLibrary.getInstance().getVersion(); conn.addRequestProperty("User-Agent", "SinkLibrary/v" + version + " (modified by Trojaner)"); conn.setDoOutput(true); final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); final String response = reader.readLine(); final JSONArray array = (JSONArray) JSONValue.parse(response); if (array.size() == 0) { SinkLibrary.getInstance().getLogger() .warning("The updater could not find any files for the project id " + id); result = UpdateResult.FAIL_BADID; return false; } versionName = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TITLE_VALUE); versionLink = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.LINK_VALUE); versionType = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.TYPE_VALUE); versionGameVersion = (String) ((JSONObject) array.get(array.size() - 1)).get(Updater.VERSION_VALUE); return true; } catch (final IOException e) { if (e.getMessage().contains("HTTP response code: 403")) { SinkLibrary.getInstance().getLogger() .warning("dev.bukkit.org rejected the API key provided in plugins/Updater/config.yml"); SinkLibrary.getInstance().getLogger() .warning("Please double-check your configuration to ensure it is correct."); result = UpdateResult.FAIL_APIKEY; } else { SinkLibrary.getInstance().getLogger() .warning("The updater could not contact dev.bukkit.org for updating."); SinkLibrary.getInstance().getLogger().warning( "If you have not recently modified your configuration and this is the first time you are seeing this message, the site may be experiencing temporary downtime."); result = UpdateResult.FAIL_DBO; } e.printStackTrace(); return false; } }
From source file:importer.handler.post.stages.StageThreeXML.java
/** * Convert the corcode using the filter corresponding to its docid * @param pair the stil and its corresponding text - return result here * @param docID the docid of the document * @param enc the encoding/*from w w w . j av a 2s . c o m*/ */ void convertCorcode(StandoffPair pair) { String[] parts = this.docid.split("/"); StringBuilder sb = new StringBuilder("mml.filters"); for (String part : parts) { if (part.length() > 0) { sb.append("."); sb.append(part); } } sb.append(".Filter"); String className = sb.toString(); Filter f = null; while (className.length() > "mml.filters".length()) { try { Class fClass = Class.forName(className); f = (Filter) fClass.newInstance(); break; } catch (Exception e) { System.out.println("no filter for " + className + " popping..."); className = popClassName(className); } } if (f != null) { System.out.println("Applying filter " + className + " to " + pair.vid); // woo hoo! we have a filter baby! try { JSONObject cc = (JSONObject) JSONValue.parse(pair.stil); // if ( pair.vid.equals("A") ) // { // printFile(pair.stil,"/tmp/A-stil.json"); // printFile(pair.text,"/tmp/A.txt"); // } cc = f.translate(cc, pair.text); pair.stil = cc.toJSONString(); pair.text = f.getText(); } catch (Exception e) { //OK it didn't work System.out.println("It failed for " + pair.vid + e.getMessage()); e.printStackTrace(System.out); } } else System.out.println("Couldn't find filter " + className + " for " + this.docid); }
From source file:com.flyingspaniel.nava.request.Request.java
/** * Converts JSON String to a Map. I'm using org.json.simple but subclasses could change * @param jsonString if null or empty return empty map * @return Map, may be empty// w ww . ja v a 2s.c o m */ public Map<String, Object> JSONtoMap(String jsonString) { if ((jsonString == null) || (jsonString.length() == 0)) return Collections.emptyMap(); return (JSONObject) JSONValue.parse(jsonString); }
From source file:fr.bmartel.bboxapi.BboxApi.java
/** * Bbox device api//from www. j a va 2 s. c o m * * @param deviceListener * bbox device listener * @return true if request has been successfully initiated */ @Override public boolean bboxDevice(final IBboxDeviceListener deviceListener) { ClientSocket clientSocket = new ClientSocket("gestionbbox.lan", 80); clientSocket.addClientSocketEventListener(new IHttpClientListener() { @Override 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("device")) { JSONObject sub_item = (JSONObject) item.get("device"); if (sub_item.containsKey("now") && sub_item.containsKey("status") && sub_item.containsKey("numberofboots") && sub_item.containsKey("modelname") && sub_item.containsKey("user_configured") && sub_item.containsKey("display") && sub_item.containsKey("firstusedate") && sub_item.containsKey("uptime")) { // String now = // sub_item.get("now").toString(); int status = Integer.parseInt(sub_item.get("status").toString()); int bootNumber = Integer.parseInt(sub_item.get("numberofboots").toString()); String modelname = sub_item.get("modelname").toString(); int user_configured = Integer .parseInt(sub_item.get("user_configured").toString()); boolean userConfig = (user_configured == 0) ? false : true; JSONObject display = (JSONObject) sub_item.get("display"); int displayLuminosity = Integer.parseInt(display.get("luminosity").toString()); boolean displayState = (displayLuminosity == 100) ? true : false; String firstusedate = sub_item.get("firstusedate").toString(); BBoxDevice device = new BBoxDevice(status, bootNumber, modelname, userConfig, displayState, firstusedate); if (sub_item.containsKey("serialnumber")) { device.setSerialNumber(sub_item.get("serialnumber").toString()); } deviceListener.onBboxDeviceReceived(device); clientSocket.closeSocket(); return; } } } } deviceListener.onBboxDeviceFailure(); clientSocket.closeSocket(); } } @Override public void onSocketError() { deviceListener.onBboxDeviceFailure(); } }); 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/device", new ListOfBytes("")); clientSocket.write(frameRequest.toString().getBytes()); return false; }