List of usage examples for org.json JSONObject has
public boolean has(String key)
From source file:org.dasein.cloud.joyent.compute.Machine.java
private @Nullable ResourceStatus toStatus(@Nullable JSONObject ob) throws CloudException, InternalException { if (ob == null) { return null; }/*from w ww .j ava 2 s. co m*/ try { VmState state = VmState.PENDING; String vmId = null; if (ob.has("id")) { vmId = ob.getString("id"); } if (ob.has("state")) { state = toState(ob.getString("state")); } if (vmId == null) { return null; } return new ResourceStatus(vmId, state); } catch (JSONException e) { throw new CloudException(e); } }
From source file:com.example.harish.b2bapplication.activity.ProfileFragment.java
public void updateProfile() { Log.d("TAG", "Update Pofile"); /* if (!validate()) { onProfileUpdateFailed("Validation Failed"); return;/*from www . j a v a 2s . c om*/ }*/ progressdialog = new ProgressDialog(getActivity()); progressdialog.setIndeterminate(false); progressdialog.setMessage("Updating Profile"); progressdialog.show(); // TODO: Implement your own signup logic here. new android.os.Handler().postDelayed(new Runnable() { public void run() { JSONObject temp1; JSONObject holder = new JSONObject(); JSONObject userObj = new JSONObject(); String s[] = new StoreAck().readFile(getContext().getApplicationContext()); String ack = s[0]; String userid = s[1]; try { // for updating profile Image holder.put("profile[profileImg]", getContext().getApplicationContext().getFilesDir() + "/" + "profileImg.jsp"); holder.put("filename", "profileImg.jpg"); holder.put("id", userid); // userObj.put("profile", holder); holder.put("lastname", lastname); holder.put("firstname", firstname); holder.put("nameoffirm", nameoffirm); holder.put("estyear", estyear); holder.put("website", website); holder.put("pan", pan); holder.put("tanvat", tanvat); holder.put("bankacc", bankacc); holder.put("billingaddress", billingaddress); holder.put("deliveryaddress", deliveryaddress); holder.put("id", userid); userObj.put("profile", holder); // Http Post for sign_in and receving token and wirting in internal storage String[] ip = getActivity().getResources().getStringArray(R.array.ip_address); HttpPost httpPost = new HttpPost(ip[0] + "api/v1/profiles/updateprofile"); httpPost.setEntity(new StringEntity(userObj.toString())); httpPost.addHeader("Authorization", "Token token=\"" + ack + "\""); httpPost.setHeader("Accept", "application/json"); httpPost.setHeader("Content-type", "application/json"); HttpResponse response = new DefaultHttpClient().execute(httpPost); Log.d("Http Post Response:", response.toString()); String json = EntityUtils.toString(response.getEntity()); temp1 = new JSONObject(json); Log.d("Response status >>>>>>>", temp1.toString()); if (temp1.has("success")) { if (temp1.getString("success").equals("true")) { Context c = getActivity().getApplicationContext(); new StoreAck().writeFile(c, temp1); progressdialog.dismiss(); onProfileUpdateSuccess(); } else { progressdialog.dismiss(); onProfileUpdateFailed(temp1.getString("Updation Failed")); } } else { progressdialog.dismiss(); onProfileUpdateFailed(temp1.getString("Updation Failed")); } } catch (IOException e) { e.printStackTrace(); progressdialog.dismiss(); // onSigninFailed("error"); } catch (JSONException e) { e.printStackTrace(); progressdialog.dismiss(); // onSigninFailed("error"); } catch (Exception e) { e.printStackTrace(); progressdialog.dismiss(); //onSigninFailed("error"); } } }, 3000); }
From source file:com.hp.mqm.atrf.octane.services.OctaneEntityService.java
private OctaneEntityCollection parseCollection(JSONObject jsonObj) { OctaneEntityCollection coll = new OctaneEntityCollection(); int total = jsonObj.getInt("total_count"); coll.setTotalCount(total);/* ww w.j av a2s .c om*/ if (jsonObj.has("exceeds_total_count")) { boolean exceedsTotalCount = jsonObj.getBoolean("exceeds_total_count"); coll.setExceedsTotalCount(exceedsTotalCount); } JSONArray entitiesJArr = jsonObj.getJSONArray("data"); for (int i = 0; i < entitiesJArr.length(); i++) { JSONObject entObj = entitiesJArr.getJSONObject(i); OctaneEntity entity = parseEntity(entObj); coll.getData().add(entity); } return coll; }
From source file:com.hp.mqm.atrf.octane.services.OctaneEntityService.java
private OctaneEntity parseEntity(JSONObject entObj) { String type = entObj.getString("type"); OctaneEntity entity = createEntity(type); for (String key : entObj.keySet()) { Object value = entObj.get(key); if (value instanceof JSONObject) { JSONObject jObj = (JSONObject) value; if (jObj.has("type")) { OctaneEntity valueEntity = parseEntity(jObj); value = valueEntity;//from w w w. ja va 2s . co m } else if (jObj.has("total_count")) { OctaneEntityCollection coll = parseCollection(jObj); value = coll; } else { value = jObj.toString(); } } else if (JSONObject.NULL.equals(value)) { value = null; } entity.put(key, value); } return entity; }
From source file:de.elepferd.web.pushnotifier.server.PushNotifierServlet.java
@JsonRpcMethod(method = PushNotifierProtocol.NotesSync.METHOD, requires_login = true) public JSONObject notesSync(final CallContext context) throws JSONException, JsonRpcException { // This method should return a list of updated notes since a current // date, optionally reconciling/merging a set of a local notes. String clientDeviceId = null; UserInfo userInfo = getCurrentUserInfo(context); Date sinceDate;/*from w w w . java 2s .com*/ try { clientDeviceId = context.getParams().optString(PushNotifierProtocol.ARG_CLIENT_DEVICE_ID); sinceDate = Util .parseDateISO8601(context.getParams().getString(PushNotifierProtocol.NotesSync.ARG_SINCE_DATE)); } catch (ParseException e) { throw new JsonRpcException(400, "Invalid since_date.", e); } catch (JSONException e) { throw new JsonRpcException(400, "Invalid since_date.", e); } JSONObject responseJson = new JSONObject(); JSONArray notesJson = new JSONArray(); Transaction tx = context.getPersistenceManager().currentTransaction(); Date newSinceDate = new Date(); try { tx.begin(); List<Note> localNotes = new ArrayList<Note>(); if (context.getParams().has(PushNotifierProtocol.NotesSync.ARG_LOCAL_NOTES)) { JSONArray localChangesJson = context.getParams() .getJSONArray(PushNotifierProtocol.NotesSync.ARG_LOCAL_NOTES); for (int i = 0; i < localChangesJson.length(); i++) { try { JSONObject noteJson = localChangesJson.getJSONObject(i); if (noteJson.has("id")) { Key existingNoteKey = Note.makeKey(userInfo.getId(), noteJson.get("id").toString()); try { Note existingNote = (Note) context.getPersistenceManager().getObjectById(Note.class, existingNoteKey); if (!existingNote.getOwnerId().equals(userInfo.getId())) { // User doesn't have permission to edit this note. Instead of // throwing an error, just re-create it on the server side. //throw new JsonRpcException(403, // "You do not have permission to modify this note."); noteJson.remove("id"); } } catch (JDOObjectNotFoundException e) { // Note doesn't exist, instead of throwing an error, // just re-create the note on the server side (unassign its ID). //throw new JsonRpcException(404, "Note with ID " // + noteJson.get("id").toString() + " does not exist."); noteJson.remove("id"); } } noteJson.put("owner_id", userInfo.getId()); Note localNote = new Note(noteJson); localNotes.add(localNote); } catch (JSONException e) { throw new JsonRpcException(400, "Invalid local note content.", e); } } } // Query server-side note changes. Query query = context.getPersistenceManager().newQuery(Note.class); query.setFilter("ownerKey == ownerKeyParam && modifiedDate > sinceDate"); query.setOrdering("modifiedDate desc"); query.declareParameters(Key.class.getName() + " ownerKeyParam, java.util.Date sinceDate"); @SuppressWarnings("unchecked") List<Note> notes = (List<Note>) query.execute(userInfo.getKey(), sinceDate); // Now merge the lists and conflicting objects. /*Reconciler<Note> reconciler = new Reconciler<Note>() { @Override public Note reconcile(Note o1, Note o2) { boolean pick1 = o1.getModifiedDate().after(o2.getModifiedDate()); // Make sure only the chosen version of the note is persisted context.getPersistenceManager().makeTransient(pick1 ? o2 : o1); return pick1 ? o1 : o2; } }; Collection<Note> reconciledNotes = reconciler.reconcileLists(notes, localNotes); for (Note note : reconciledNotes) { // Save the note. context.getPersistenceManager().makePersistent(note); // Put it in the response output. notesJson.put(note.toJSON()); } tx.commit();*/ } finally { if (tx.isActive()) { tx.rollback(); } } enqueueDeviceMessage(context.getPersistenceManager(), userInfo, clientDeviceId); responseJson.put(PushNotifierProtocol.NotesSync.RET_NOTES, notesJson); responseJson.put(PushNotifierProtocol.NotesSync.RET_NEW_SINCE_DATE, Util.formatDateISO8601(newSinceDate)); return responseJson; }
From source file:org.loklak.server.AbstractAPIHandler.java
private void process(HttpServletRequest request, HttpServletResponse response, Query query) throws ServletException, IOException { // basic protection BaseUserRole minimalBaseUserRole = getMinimalBaseUserRole() != null ? getMinimalBaseUserRole() : BaseUserRole.ANONYMOUS;/*from w w w. ja v a 2s . co m*/ if (query.isDoS_blackout()) { response.sendError(503, "your request frequency is too high"); return; } // DoS protection if (DAO.getConfig("users.admin.localonly", true) && minimalBaseUserRole == BaseUserRole.ADMIN && !query.isLocalhostAccess()) { response.sendError(503, "access only allowed from localhost, your request comes from " + query.getClientHost()); return; } // danger! do not remove this! // user identification ClientIdentity identity = getIdentity(request, response, query); // user authorization: we use the identification of the user to get the assigned authorization Authorization authorization = new Authorization(identity, DAO.authorization, DAO.userRoles); if (authorization.getBaseUserRole().ordinal() < minimalBaseUserRole.ordinal()) { response.sendError(401, "Base user role not sufficient. Your base user role is '" + authorization.getBaseUserRole().name() + "', your user role is '" + authorization.getUserRole().getDisplayName() + "'"); return; } // user accounting: we maintain static and persistent user data; we again search the accounts using the usder identity string //JSONObject accounting_persistent_obj = DAO.accounting_persistent.has(user_id) ? DAO.accounting_persistent.getJSONObject(anon_id) : DAO.accounting_persistent.put(user_id, new JSONObject()).getJSONObject(user_id); Accounting accounting_temporary = DAO.accounting_temporary.get(identity.toString()); if (accounting_temporary == null) { accounting_temporary = new Accounting(); DAO.accounting_temporary.put(identity.toString(), accounting_temporary); } // the accounting data is assigned to the authorization authorization.setAccounting(accounting_temporary); // extract standard query attributes String callback = query.get("callback", ""); boolean jsonp = callback.length() > 0; boolean minified = query.get("minified", false); try { JSONObject json = serviceImpl(query, response, authorization, authorization.getPermissions(this)); if (json == null) { response.sendError(400, "your request does not contain the required data"); return; } // evaluate special fields if (json.has("$EXPIRES")) { int expires = json.getInt("$EXPIRES"); FileHandler.setCaching(response, expires); json.remove("$EXPIRES"); } // add session information JSONObject session = new JSONObject(true); session.put("identity", identity.toJSON()); json.put("session", session); // write json query.setResponse(response, "application/javascript"); response.setCharacterEncoding("UTF-8"); PrintWriter sos = response.getWriter(); if (jsonp) sos.print(callback + "("); sos.print(json.toString(minified ? 0 : 2)); if (jsonp) sos.println(");"); sos.println(); query.finalize(); } catch (APIException e) { response.sendError(e.getStatusCode(), e.getMessage()); return; } }
From source file:com.github.sommeri.sourcemap.SourceMapConsumerV3.java
/** * Parses the given contents containing a source map. *//*from w w w .j a va 2 s . c o m*/ public void parse(JSONObject sourceMapRoot, SourceMapSupplier sectionSupplier) throws SourceMapParseException { try { // Check basic assertions about the format. int version = sourceMapRoot.getInt("version"); if (version != 3) { throw new SourceMapParseException("Unknown version: " + version); } this.file = sourceMapRoot.getString("file"); if (file.isEmpty()) { //SMS: (source map separation): commented this - I need more tolerant parser //throw new SourceMapParseException("File entry is missing or empty "); } if (sourceMapRoot.has("sourceRoot")) this.sourceRoot = sourceMapRoot.getString("sourceRoot"); if (sourceMapRoot.has("sections")) { // Looks like a index map, try to parse it that way. parseMetaMap(sourceMapRoot, sectionSupplier); return; } lineCount = sourceMapRoot.getInt("lineCount"); String lineMap = sourceMapRoot.getString("mappings"); sources = getJavaStringArray(sourceMapRoot.getJSONArray("sources")); if (sourceMapRoot.has("sourcesContent")) { sourcesContent = getJavaStringArray(sourceMapRoot.getJSONArray("sourcesContent")); } else { sourcesContent = new String[sources.length]; } names = getJavaStringArray(sourceMapRoot.getJSONArray("names")); lines = new ArrayList<ArrayList<Entry>>(lineCount); new MappingBuilder(lineMap).build(); } catch (JSONException ex) { throw new SourceMapParseException("JSON parse exception: " + ex); } }
From source file:com.github.sommeri.sourcemap.SourceMapConsumerV3.java
/** * @param sourceMapRoot//from ww w .ja va 2s.co m * @throws SourceMapParseException */ private void parseMetaMap(JSONObject sourceMapRoot, SourceMapSupplier sectionSupplier) throws SourceMapParseException { if (sectionSupplier == null) { sectionSupplier = new DefaultSourceMapSupplier(); } try { // Check basic assertions about the format. int version = sourceMapRoot.getInt("version"); if (version != 3) { throw new SourceMapParseException("Unknown version: " + version); } String file = sourceMapRoot.getString("file"); if (file.isEmpty()) { throw new SourceMapParseException("File entry is missing or empty"); } if (sourceMapRoot.has("lineCount") || sourceMapRoot.has("mappings") || sourceMapRoot.has("sources") || sourceMapRoot.has("names")) { throw new SourceMapParseException("Invalid map format"); } SourceMapGeneratorV3 generator = new SourceMapGeneratorV3(); JSONArray sections = sourceMapRoot.getJSONArray("sections"); for (int i = 0, count = sections.length(); i < count; i++) { JSONObject section = sections.getJSONObject(i); if (section.has("map") && section.has("url")) { throw new SourceMapParseException( "Invalid map format: section may not have both 'map' and 'url'"); } JSONObject offset = section.getJSONObject("offset"); int line = offset.getInt("line"); int column = offset.getInt("column"); String mapSectionContents; if (section.has("url")) { String url = section.getString("url"); mapSectionContents = sectionSupplier.getSourceMap(url); if (mapSectionContents == null) { throw new SourceMapParseException("Unable to retrieve: " + url); } } else if (section.has("map")) { mapSectionContents = section.getString("map"); } else { throw new SourceMapParseException( "Invalid map format: section must have either 'map' or 'url'"); } generator.mergeMapSection(line, column, mapSectionContents); } StringBuilder sb = new StringBuilder(); try { generator.appendTo(sb, file); } catch (IOException e) { // Can't happen. throw new RuntimeException(e); } parse(sb.toString()); } catch (IOException ex) { throw new SourceMapParseException("IO exception: " + ex); } catch (JSONException ex) { throw new SourceMapParseException("JSON parse exception: " + ex); } }
From source file:org.collectionspace.chain.csp.webui.record.RecordSearchList.java
/** * Retrieve the mini summary information e.g. summary and number and append * the csid and recordType to it/*from w w w . ja v a2 s . c o m*/ * * @param {Storage} storage Type of storage (e.g. AuthorizationStorage, * RecordStorage,...) * @param {String} type The type of record requested (e.g. permission) * @param {String} csid The csid of the record * @return {JSONObject} The JSON string containing the mini record * @throws ExistException * @throws UnimplementedException * @throws UnderlyingStorageException * @throws JSONException */ private JSONObject generateMiniRecord(Storage storage, String type, String csid) throws JSONException { String postfix = "list"; if (this.mode == MODE_SEARCH) { postfix = "search"; } JSONObject restrictions = new JSONObject(); JSONObject out = new JSONObject(); try { if (csid == null || csid.equals("")) { return out; } out = storage.retrieveJSON(type + "/" + csid + "/view/" + postfix, restrictions); out.put("csid", csid); String recordtype = null; if (!r.isType("searchall")) { recordtype = type_to_url.get(type); } else { JSONObject summarylist = out.getJSONObject("summarylist"); String uri = summarylist.getString("uri"); if (uri != null && uri.startsWith("/")) { uri = uri.substring(1); } String[] parts = uri.split("/"); String recordurl = parts[0]; Record itemr = r.getSpec().getRecordByServicesUrl(recordurl); if (itemr == null) { String docType = summarylist.getString("docType"); itemr = r.getSpec().getRecordByServicesDocType(docType); } if (itemr == null) { recordtype = UNKNOWN_RECORD_TYPE; log.warn("Could not get record type for record with services URI " + uri); } else { recordtype = type_to_url.get(itemr.getID()); String refName = null; if (summarylist.has("refName")) { refName = summarylist.getString("refName"); } // For an authority item (i.e. an item in a vocabulary), // include the name of its parent vocabulary in a // "namespace" value within the mini summary. RefName.AuthorityItem item = null; if (refName != null) { item = RefName.AuthorityItem.parse(refName); } // If this refName could be successfully parsed (above) as an // authority item refName, then include the "namespace" value. if (item != null) { String namespace = item.getParentShortIdentifier(); if (namespace != null) { out.put("namespace", namespace); } else { log.warn("Could not get vocabulary namespace for record with services URI " + uri); } } } } out.put("recordtype", recordtype); // CSPACE-2894 if (this.r.getID().equals("permission")) { String summary = out.getString("summary"); String name = Generic.ResourceNameUI(this.r.getSpec(), summary); if (name.contains(WORKFLOW_SUB_RESOURCE)) { return null; } out.put("summary", name); out.put("display", Generic.getPermissionView(this.r.getSpec(), summary)); } } catch (ExistException e) { out.put("csid", csid); out.put("isError", true); JSONObject msg = new JSONObject(); msg.put("severity", "error"); msg.put("message", "Exist Exception:" + e.getMessage()); JSONArray msgs = new JSONArray(); msgs.put(msg); out.put("messages", msgs); } catch (UnimplementedException e) { out.put("csid", csid); out.put("isError", true); JSONObject msg = new JSONObject(); msg.put("severity", "error"); msg.put("message", "Exist Exception:" + e.getMessage()); JSONArray msgs = new JSONArray(); msgs.put(msg); out.put("messages", msgs); } catch (UnderlyingStorageException e) { out.put("csid", csid); out.put("isError", true); JSONObject msg = new JSONObject(); msg.put("severity", "error"); msg.put("message", "Exist Exception:" + e.getMessage()); JSONArray msgs = new JSONArray(); msgs.put(msg); out.put("messages", msgs); } return out; }
From source file:org.collectionspace.chain.csp.webui.record.RecordSearchList.java
/** * This function is the general function that calls the correct funtions to * get all the data that the UI requested and get it in the correct format * for the UI.//from ww w . j a v a2 s .c o m * * @param {Storage} storage The type of storage requested (e.g. * RecordStorage, AuthorizationStorage,...) * @param {UIRequest} ui The request from the ui to which we send a * response. * @param {String} param If a querystring has been added to the * URL(e.g.'?query='), it will be in this param * @param {String} pageSize The amount of results per page requested. * @param {String} pageNum The amount of pages requested. * @throws UIException */ private void search_or_list(Storage storage, UIRequest ui, String path) throws UIException { try { JSONObject restrictedkey = GenericSearch.setRestricted(ui, null, null, null, (mode == MODE_SEARCH), this.r); JSONObject restriction = restrictedkey.getJSONObject("restriction"); String key = restrictedkey.getString("key"); JSONObject results = getResults(ui, storage, restriction, key, path); //cache for record traverser if (results.has("pagination") && results.getJSONObject("pagination").has("separatelists")) { GenericSearch.createTraverser(ui, this.r.getID(), "", results, restriction, key, 1); } ui.sendJSONResponse(results); } catch (JSONException e) { throw new UIException("JSONException during search_or_list", e); } catch (ExistException e) { throw new UIException("ExistException during search_or_list", e); } catch (UnimplementedException e) { throw new UIException("UnimplementedException during search_or_list", e); } catch (UnderlyingStorageException x) { UIException uiexception = new UIException(x.getMessage(), x.getStatus(), x.getUrl(), x); ui.sendJSONResponse(uiexception.getJSON()); } }