List of usage examples for org.json JSONObject getJSONObject
public JSONObject getJSONObject(String key) throws JSONException
From source file:org.eclipse.orion.server.tests.servlets.git.GitMergeTest.java
@Test public void testMergeRemote() throws Exception { URI workspaceLocation = createWorkspace(getMethodName()); String workspaceId = workspaceIdFromLocation(workspaceLocation); // clone1//from w ww .j av a 2 s . c o m JSONObject project1 = createProjectOrLink(workspaceLocation, getMethodName() + "1", null); IPath clonePath1 = getClonePath(workspaceId, project1); clone(clonePath1); // get project1 metadata WebRequest request = getGetRequest(project1.getString(ProtocolConstants.KEY_CONTENT_LOCATION)); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); project1 = new JSONObject(response.getText()); JSONObject gitSection1 = project1.getJSONObject(GitConstants.KEY_GIT); String gitRemoteUri1 = gitSection1.getString(GitConstants.KEY_REMOTE); // clone2 JSONObject project2 = createProjectOrLink(workspaceLocation, getMethodName() + "2", null); IPath clonePath2 = getClonePath(workspaceId, project2); clone(clonePath2); // get project2 metadata request = getGetRequest(project2.getString(ProtocolConstants.KEY_CONTENT_LOCATION)); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); project2 = new JSONObject(response.getText()); JSONObject gitSection2 = project2.getJSONObject(GitConstants.KEY_GIT); String gitRemoteUri2 = gitSection2.getString(GitConstants.KEY_REMOTE); String gitIndexUri2 = gitSection2.getString(GitConstants.KEY_INDEX); String gitHeadUri2 = gitSection2.getString(GitConstants.KEY_HEAD); // clone1: get remote details JSONObject details = getRemoteBranch(gitRemoteUri1, 1, 0, Constants.MASTER); String refId1 = details.getString(ProtocolConstants.KEY_ID); String remoteBranchLocation1 = details.getString(ProtocolConstants.KEY_LOCATION); // clone2: change JSONObject testTxt = getChild(project2, "test.txt"); modifyFile(testTxt, "incoming change"); // clone2: add request = GitAddTest.getPutGitIndexRequest(gitIndexUri2); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // clone2: commit request = GitCommitTest.getPostGitCommitRequest(gitHeadUri2, "incoming change commit", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); // clone2: push ServerStatus pushStatus = push(gitRemoteUri2, 1, 0, Constants.MASTER, Constants.HEAD, false); assertEquals(true, pushStatus.isOK()); // clone1: fetch request = GitFetchTest.getPostGitRemoteRequest(remoteBranchLocation1, true, false); response = webConversation.getResponse(request); ServerStatus status = waitForTask(response); assertTrue(status.toString(), status.isOK()); // clone1: get remote details again JSONObject remoteBranch = getRemoteBranch(gitRemoteUri1, 1, 0, Constants.MASTER); String newRefId1 = remoteBranch.getString(ProtocolConstants.KEY_ID); // an incoming commit assertFalse(refId1.equals(newRefId1)); // clone1: merge into HEAD, "git merge origin/master" //String gitCommitUri = remoteBranch.getString(GitConstants.KEY_COMMIT); // TODO: should fail when POSTing to the above URI, see bug 342845 String gitHeadUri = remoteBranch.getString(GitConstants.KEY_HEAD); // merge JSONObject merge = merge(gitHeadUri, newRefId1); MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT)); assertEquals(MergeStatus.FAST_FORWARD, mergeResult); request = getGetRequest(getChild(project1, "test.txt").getString(ProtocolConstants.KEY_LOCATION)); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); assertEquals("incoming change", response.getText()); }
From source file:org.eclipse.orion.server.tests.servlets.git.GitMergeTest.java
@Test public void testMergeRemovingFolders() throws Exception { // see org.eclipse.jgit.api.MergeCommandTest.testMergeRemovingFolders() URI workspaceLocation = createWorkspace(getMethodName()); IPath[] clonePaths = createTestProjects(workspaceLocation); for (IPath clonePath : clonePaths) { // clone a repo JSONObject clone = clone(clonePath); String cloneContentLocation = clone.getString(ProtocolConstants.KEY_CONTENT_LOCATION); // get project/folder metadata WebRequest request = getGetRequest(cloneContentLocation); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONObject folder = new JSONObject(response.getText()); String folderChildrenLocation = folder.getString(ProtocolConstants.KEY_CHILDREN_LOCATION); String folderLocation = folder.getString(ProtocolConstants.KEY_LOCATION); JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT); String gitIndexUri = gitSection.getString(GitConstants.KEY_INDEX); String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD); String folderName = "folder1"; request = getPostFilesRequest(folderLocation + "/", getNewDirJSON(folderName).toString(), folderName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); JSONObject folder1 = getChild(folder, "folder1"); String fileName = "file1.txt"; request = getPostFilesRequest(folder1.getString(ProtocolConstants.KEY_LOCATION), getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); fileName = "file2.txt"; request = getPostFilesRequest(folder1.getString(ProtocolConstants.KEY_LOCATION), getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); folderName = "folder2"; request = getPostFilesRequest(folderLocation + "/", getNewDirJSON(folderName).toString(), folderName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); JSONObject folder2 = getChild(folder, "folder2"); fileName = "file1.txt"; request = getPostFilesRequest(folder2.getString(ProtocolConstants.KEY_LOCATION), getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); fileName = "file2.txt"; request = getPostFilesRequest(folder2.getString(ProtocolConstants.KEY_LOCATION), getNewFileJSON(fileName).toString(), fileName); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_CREATED, response.getResponseCode()); request = GitAddTest.getPutGitIndexRequest(gitIndexUri); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "folders and files", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); deleteFile(folder1);// ww w .ja v a2 s. co m deleteFile(folder2); request = GitAddTest.getPutGitIndexRequest(gitIndexUri); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); request = GitCommitTest.getPostGitCommitRequest(gitHeadUri, "removing folders", false); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); JSONArray commitsArray = log(gitHeadUri); assertEquals(3, commitsArray.length()); JSONObject commit = commitsArray.getJSONObject(0); assertEquals("removing folders", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); String toMerge = commit.getString(ProtocolConstants.KEY_NAME); commit = commitsArray.getJSONObject(1); assertEquals("folders and files", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); String toCheckout = commit.getString(ProtocolConstants.KEY_NAME); Repository db1 = getRepositoryForContentLocation(cloneContentLocation); Git git = new Git(db1); git.checkout().setName(toCheckout).call(); JSONObject merge = merge(gitHeadUri, toMerge); MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT)); assertEquals(MergeStatus.FAST_FORWARD, mergeResult); request = getGetRequest(folderChildrenLocation); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); List<JSONObject> children = getDirectoryChildren(new JSONObject(response.getText())); assertNull(getChildByName(children, "folder1")); assertNull(getChildByName(children, "folder2")); } }
From source file:com.leanengine.JsonDecode.java
static LeanAccount accountFromJson(JSONObject json) throws LeanException { Long id;/* w w w . j a va 2 s . com*/ try { id = json.getLong("id"); } catch (JSONException e) { throw new LeanException(LeanError.Type.ServerError, "Malformed reply: Entity JSON missing field 'id'."); } String providerId; try { providerId = json.getString("providerId"); } catch (JSONException e) { throw new LeanException(LeanError.Type.ServerError, "Malformed reply: Entity JSON missing field 'providerId'."); } String nickName; try { nickName = json.getString("nickName"); } catch (JSONException e) { throw new LeanException(LeanError.Type.ServerError, "Malformed reply: Entity JSON missing field 'nickName'."); } String provider; try { provider = json.getString("provider"); } catch (JSONException e) { throw new LeanException(LeanError.Type.ServerError, "Malformed reply: Entity JSON missing field 'provider'."); } JSONObject jsonProviderProperties; Map<String, Object> providerProperties; try { jsonProviderProperties = json.getJSONObject("providerProperties"); providerProperties = accountPropsFromJson(jsonProviderProperties); return new LeanAccount(id, nickName, providerId, provider, providerProperties); } catch (JSONException e) { throw new LeanException(LeanError.Type.ServerError, "Malformed reply: Entity JSON missing field 'providerProperties'."); } }
From source file:com.fatsecret.platform.utils.FoodUtility.java
/** * Returns detailed information about the food * //from w ww . ja v a 2s .c o m * @param json json object representing of the food * @return detailed information about the food */ public static Food parseFoodFromJSONObject(JSONObject json) { String name = json.getString("food_name"); String url = json.getString("food_url"); String type = json.getString("food_type"); Long id = Long.parseLong(json.getString("food_id")); String brandName = ""; try { brandName = json.getString("brand_name"); } catch (Exception ignore) { } JSONObject servingsObj = json.getJSONObject("servings"); JSONArray array = null; List<Serving> servings = new ArrayList<Serving>(); try { array = servingsObj.getJSONArray("serving"); servings = ServingUtility.parseServingsFromJSONArray(array); } catch (Exception ignore) { System.out.println("Servings not found"); array = null; } if (array == null) { try { JSONObject servingObj = servingsObj.getJSONObject("serving"); Serving serving = ServingUtility.parseServingFromJSONObject(servingObj); servings.add(serving); } catch (Exception ignore) { System.out.println("Serving not found"); } } Food food = new Food(); food.setName(name); food.setUrl(url); food.setType(type); food.setId(id); food.setBrandName(brandName); food.setServings(servings); return food; }
From source file:com.microsoft.services.sharepoint.OfficeEntity.java
/** * List from json.//from www . j a v a 2s. c om * * @param <E> * the element type * @param json * the json * @param clazz * the clazz * @return the list * @throws org.json.JSONException * the JSON exception */ protected static <E extends OfficeEntity> List<E> listFromJson(JSONObject json, Class<E> clazz) throws JSONException { List<E> list = new ArrayList<E>(); JSONArray results; if (json.has("d")) { results = json.getJSONObject("d").getJSONArray("results"); } else { results = json.getJSONArray("results"); } for (int i = 0; i < results.length(); i++) { JSONObject result = results.getJSONObject(i); E item = null; try { item = clazz.newInstance(); } catch (Throwable e) { } if (item != null) { item.loadFromJson(result); list.add(item); } } return list; }
From source file:com.microsoft.services.sharepoint.OfficeEntity.java
/** * Load from json.//from ww w. j a v a 2s . c om * * @param json * the json * @param isPlainItem * the is plain item */ public void loadFromJson(JSONObject json, boolean isPlainItem) { if (isPlainItem) { loadFromJson(json); } else { JSONObject innerJson; try { innerJson = json.getJSONObject("d"); loadFromJson(innerJson); } catch (JSONException e) { throw new IllegalArgumentException("Expected 'd' element", e); } } }
From source file:de.eorganization.crawler.server.servlets.JSONImportServlet.java
@Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try {//from ww w. ja v a2 s . c o m resp.setContentType("text/plain"); InputStream stream = req.getInputStream(); log.info("Got Upload " + req.getContentType() + " (" + req.getContentLength() + " bytes) from " + req.getRemoteAddr()); String amiId = req.getHeader("AMI-ID"); log.info("Got AMI ID:" + amiId); String repository = req.getHeader("REPO"); log.info("Got REPO:" + repository); if (amiId == null || repository == null || "".equals(amiId) || "".equals(repository)) { log.severe("AMI ID and REPO HTTP Header required."); return; } // Gson gson = new Gson(); // log.info("Parsed Gson " + gson.fromJson(new // InputStreamReader(stream), JsonObject.class)); String jsonString = IOUtils.toString(stream); log.info("Got JSON String " + jsonString.substring(0, jsonString.length() > 128 ? 128 : jsonString.length() - 1)); JSONObject json = new JSONObject(); try { json = new JSONObject(jsonString); log.fine("Parsed Json " + json); log.finer("Json has keys: " + json.names()); } catch (JSONException e) { log.severe("No JSON sent or wrong format."); return; } JSONObject software = json.optJSONObject("software"); if (software != null) { log.finer("Software JSON " + software); JSONArray softwareNames = software.names(); log.finer("Key Array JSON " + softwareNames); for (int i = 0; i < softwareNames.length(); i++) { log.fine("software " + softwareNames.getString(i) + " with version " + software.getJSONObject(softwareNames.getString(i)).getString("version")); Map<String, String> softAttributes = new HashMap<String, String>(); JSONArray softwareAttributes = software.getJSONObject(softwareNames.getString(i)).names(); for (int j = 0; j < softwareAttributes.length(); j++) softAttributes.put(softwareAttributes.getString(j), software.getJSONObject(softwareNames.getString(i)) .getString(softwareAttributes.getString(j))); Software soft = AmiManager.saveSoftware(amiId, repository, softwareNames.getString(i), software.getJSONObject(softwareNames.getString(i)).getString("version"), softAttributes); if (soft != null) { log.fine("Saved/restored software " + soft); // soft.getAttributes().putAll(softAttributes); // AmiManager.updateSoftware(soft); // log.fine("Saved object " + soft); } else log.severe("Not able to save software information for given Ami Id " + amiId + "!"); } List<String> names = new ArrayList<String>(); for (int i = 0; i < softwareNames.length(); i++) names.add(softwareNames.getString(i)); AmiManager.updateSoftwareNames(names); log.info("Saved " + softwareNames.length() + " software objects"); } JSONObject languages = json.optJSONObject("languages"); if (languages != null) { log.finer("Languages JSON " + languages); JSONArray languagesNames = languages.names(); log.finer("Key Array JSON " + languagesNames); for (int i = 0; i < languagesNames.length(); i++) { log.fine("languages " + languagesNames.getString(i) + " with version " + languages.getJSONObject(languagesNames.getString(i)).getString("version")); Map<String, String> langAttributes = new HashMap<String, String>(); JSONArray languageAttributes = languages.getJSONObject(languagesNames.getString(i)).names(); for (int j = 0; j < languageAttributes.length(); j++) langAttributes.put(languageAttributes.getString(j), languages.getJSONObject(languagesNames.getString(i)) .getString(languageAttributes.getString(j))); Language lang = AmiManager.saveLanguage(amiId, repository, languagesNames.getString(i), languages.getJSONObject(languagesNames.getString(i)).getString("version"), langAttributes); if (lang != null) { log.fine("Saved/restored programming language " + lang); lang.getAttributes().putAll(langAttributes); AmiManager.updateLanguage(lang); log.fine("Saved object " + lang); } else log.severe("Not able to save programming language information for given Ami Id " + amiId + "!"); } log.info("Saved " + languagesNames.length() + " programming language objects"); } resp.getWriter().println( "Saving software packages and programming languages for " + amiId + " (" + repository + ")."); } catch (JSONException e) { log.severe("Error while parsing JSON upload" + e.getMessage() + ", trace: " + e.getStackTrace()); log.throwing(JSONImportServlet.class.getName(), "doPost", e); e.printStackTrace(); } catch (Exception ex) { log.severe("Unexpected error" + ex.getMessage() + ", trace: " + ex.getStackTrace()); log.throwing(JSONImportServlet.class.getName(), "doPost", ex); ex.printStackTrace(); } // log.info("returning to referer " + req.getHeader("referer")); // resp.sendRedirect(req.getHeader("referer") != null && // !"".equals(req.getHeader("referer")) ? req.getHeader("referer") : // "localhost:8088"); }
From source file:org.dasein.cloud.joyent.compute.Machine.java
@Override public @Nullable String getPassword(@Nonnull String vmId) throws InternalException, CloudException { final String[] adminUsernames = { "root", "administrator", "admin" }; JoyentMethod method = new JoyentMethod(provider); try {/*www . j a v a 2s. c o m*/ JSONObject ob = new JSONObject( method.doGetJson(provider.getEndpoint(), "machines/" + vmId + "/metadata?credentials=true")); if (ob.has("credentials")) { JSONObject credentials = ob.getJSONObject("credentials"); for (String username : adminUsernames) { if (ob.has(username)) { return ob.getString(username); } } } } catch (JSONException e) { throw new InternalException("Unable to parse the response", e); } return null; }
From source file:org.dasein.cloud.joyent.compute.Machine.java
private VirtualMachine toVirtualMachine(JSONObject ob) throws CloudException, InternalException { if (ob == null) { return null; }/*from w ww. j a v a2 s .co m*/ try { VirtualMachine vm = new VirtualMachine(); vm.setClonable(false); vm.setImagable(false); vm.setLastPauseTimestamp(-1L); vm.setPersistent(true); vm.setProviderDataCenterId(provider.getContext().getRegionId() + "a"); vm.setProviderOwnerId(provider.getContext().getAccountNumber()); vm.setProviderRegionId(provider.getContext().getRegionId()); vm.setTerminationTimestamp(-1L); if (ob.has("id")) { vm.setProviderVirtualMachineId(ob.getString("id")); } if (ob.has("name")) { vm.setName(ob.getString("name")); } if (ob.has("ips")) { JSONArray ips = ob.getJSONArray("ips"); ArrayList<String> pubIp = new ArrayList<String>(); ArrayList<String> privIp = new ArrayList<String>(); for (int i = 0; i < ips.length(); i++) { String addr = ips.getString(i); boolean pub = false; if (!addr.startsWith("10.") && !addr.startsWith("192.168.")) { if (addr.startsWith("172.")) { String[] nums = addr.split("\\."); if (nums.length != 4) { pub = true; } else { try { int x = Integer.parseInt(nums[1]); if (x < 16 || x > 31) { pub = true; } } catch (NumberFormatException ignore) { // ignore } } } else { pub = true; } } if (pub) { pubIp.add(addr); } else { privIp.add(addr); } } if (!pubIp.isEmpty()) { vm.setPublicIpAddresses(pubIp.toArray(new String[pubIp.size()])); } if (!privIp.isEmpty()) { vm.setPrivateIpAddresses(privIp.toArray(new String[privIp.size()])); } } if (ob.has("metadata")) { JSONObject md = ob.getJSONObject("metadata"); JSONArray names = md.names(); if (names != null) { for (int i = 0; i < names.length(); i++) { String name = names.getString(i); if (name.equals("dsnDescription")) { vm.setDescription(md.getString(name)); } else if (name.equals("dsnTrueImage")) { vm.setProviderMachineImageId(md.getString(name)); } else if (name.equals("dsnTrueProduct")) { vm.setProductId(md.getString(name)); } else { vm.addTag(name, md.getString(name)); } } } } if (vm.getProviderMachineImageId() == null && ob.has("dataset")) { vm.setProviderMachineImageId(getImageIdFromUrn(ob.getString("dataset"))); } if (ob.has("created")) { vm.setCreationTimestamp(provider.parseTimestamp(ob.getString("created"))); } vm.setPausable(false); // can't ever pause/resume joyent vms vm.setRebootable(false); if (ob.has("state")) { vm.setCurrentState(toState(ob.getString("state"))); if (VmState.RUNNING.equals(vm.getCurrentState())) { vm.setRebootable(true); } else if (VmState.STOPPED.equals(vm.getCurrentState())) { vm.setImagable(true); } } vm.setLastBootTimestamp(vm.getCreationTimestamp()); if (vm.getName() == null) { vm.setName(vm.getProviderVirtualMachineId()); } if (vm.getDescription() == null) { vm.setDescription(vm.getName()); } discover(vm); boolean isVMSmartOs = (vm.getPlatform().equals(Platform.SMARTOS)); if (vm.getProductId() == null) { VirtualMachineProduct d = null; int disk, ram; disk = ob.getInt("disk"); ram = ob.getInt("memory"); for (VirtualMachineProduct prd : listProducts(vm.getArchitecture())) { d = prd; boolean isProductSmartOs = prd.getName().contains("smartos"); if (prd.getRootVolumeSize().convertTo(Storage.MEGABYTE).intValue() == disk && prd.getRamSize().intValue() == ram) { if (isVMSmartOs && !isProductSmartOs) { continue; } if (!isVMSmartOs && isProductSmartOs) { continue; } vm.setProductId(prd.getProviderProductId()); break; } } if (vm.getProductId() == null) { vm.setProductId(d.getProviderProductId()); } } return vm; } catch (JSONException e) { throw new CloudException(e); } }
From source file:com.sepgil.ral.Node.java
/** * Creates a Node out of a JSON object./*from w ww.j av a2 s . co m*/ * @param object The JSON object that represents the node. * @throws JSONException Can be thrown when a field is missing. */ public Node(JSONObject object) throws JSONException { mNid = object.getInt("nid"); mTitle = object.getString("title"); mBody = object.getJSONObject("body").getString("value"); }