List of usage examples for org.json JSONObject length
public int length()
From source file:org.eclipse.orion.server.tests.servlets.git.GitMergeSquashTest.java
@Test public void testMergeSquashIntoLocalFailedDirtyWorkTree() throws Exception { // clone a repo URI workspaceLocation = createWorkspace(getMethodName()); String workspaceId = workspaceIdFromLocation(workspaceLocation); JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null); IPath clonePath = getClonePath(workspaceId, project); clone(clonePath);/*from w w w.j a v a 2s. c o m*/ // get project metadata WebRequest request = getGetRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION)); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); project = new JSONObject(response.getText()); JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT); String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD); String gitRemoteUri = gitSection.getString(GitConstants.KEY_REMOTE); // add a parallel commit in secondary clone and push it to the remote 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); JSONObject testTxt = getChild(project2, "test.txt"); modifyFile(testTxt, "change in secondary"); addFile(testTxt); commitFile(testTxt, "commit on branch", false); ServerStatus pushStatus = push(gitRemoteUri2, 1, 0, Constants.MASTER, Constants.HEAD, false); assertEquals(true, pushStatus.isOK()); // modify on master and try to merge testTxt = getChild(project, "test.txt"); modifyFile(testTxt, "dirty"); JSONObject masterDetails = getRemoteBranch(gitRemoteUri, 1, 0, Constants.MASTER); String masterLocation = masterDetails.getString(ProtocolConstants.KEY_LOCATION); fetch(masterLocation); JSONObject merge = merge(gitHeadUri, Constants.DEFAULT_REMOTE_NAME + "/" + Constants.MASTER, true); MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT)); assertEquals(MergeStatus.FAILED, mergeResult); JSONObject failingPaths = merge.getJSONObject(GitConstants.KEY_FAILING_PATHS); assertEquals(1, failingPaths.length()); assertEquals(MergeFailureReason.DIRTY_WORKTREE, MergeFailureReason.valueOf(failingPaths.getString("test.txt"))); }
From source file:org.eclipse.orion.server.tests.servlets.git.GitMergeSquashTest.java
@Test public void testMergeSquashFailedDirtyWorkTree() throws Exception { // clone a repo URI workspaceLocation = createWorkspace(getMethodName()); String workspaceId = workspaceIdFromLocation(workspaceLocation); JSONObject project = createProjectOrLink(workspaceLocation, getMethodName(), null); IPath clonePath = getClonePath(workspaceId, project); JSONObject clone = clone(clonePath); String cloneLocation = clone.getString(ProtocolConstants.KEY_LOCATION); String branchesLocation = clone.getString(GitConstants.KEY_BRANCH); // get project metadata WebRequest request = getGetRequest(project.getString(ProtocolConstants.KEY_CONTENT_LOCATION)); WebResponse response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); project = new JSONObject(response.getText()); JSONObject gitSection = project.getJSONObject(GitConstants.KEY_GIT); final String branch = "branch"; branch(branchesLocation, branch);/*from w ww . j av a 2 s .co m*/ checkoutBranch(cloneLocation, branch); // create commit on branch JSONObject testTxt = getChild(project, "test.txt"); modifyFile(testTxt, "change in a"); addFile(testTxt); commitFile(testTxt, "commit on branch", false); // assert clean gitSection = project.getJSONObject(GitConstants.KEY_GIT); String gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS); assertStatus(StatusResult.CLEAN, gitStatusUri); // checkout 'master' checkoutBranch(cloneLocation, Constants.MASTER); // modify the same file on master modifyFile(testTxt, "change in master"); gitSection = project.getJSONObject(GitConstants.KEY_GIT); gitStatusUri = gitSection.getString(GitConstants.KEY_STATUS); String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD); addFile(testTxt); commitFile(testTxt, "commit on master", false); // modify again modifyFile(testTxt, "change in the working dir"); // assert clean assertStatus(new StatusResult().setModified(1), gitStatusUri); // merge: "git merge branch" JSONObject merge = merge(gitHeadUri, branch, true); MergeStatus mergeResult = MergeStatus.valueOf(merge.getString(GitConstants.KEY_RESULT)); assertEquals(MergeStatus.FAILED, mergeResult); JSONObject failingPaths = merge.getJSONObject(GitConstants.KEY_FAILING_PATHS); assertEquals(1, failingPaths.length()); assertEquals(MergeFailureReason.DIRTY_WORKTREE, MergeFailureReason.valueOf(failingPaths.getString("test.txt"))); }
From source file:com.serli.open.data.poitiers.jobs.configuration.GenerateConfigurationFiles.java
public static void generateConfFile(String JsonFile) throws JSONException, IOException { JSONObject obj = new JSONObject(JsonFile); JSONObject properties = obj.getJSONObject("properties"); Settings settings = SettingsRepository.INSTANCE.getAllSettings(); Map<String, Object> parsing = new HashMap<>(); for (int i = 0; i < properties.length() - 1; i++) { parsing.put(properties.getJSONObject("" + i).getString("champES"), properties.getJSONObject("" + i).getString("champJson")); }/*from w ww . j a v a2s. co m*/ parsing.put("location", "location"); settings.conf.put(obj.getString("type"), parsing); SettingsRepository.INSTANCE.updateSettings(settings); }
From source file:com.serli.open.data.poitiers.jobs.configuration.GenerateConfigurationFiles.java
public static void generateESMapping(String jsonFile) throws JSONException { Settings settings = SettingsRepository.INSTANCE.getAllSettings(); JSONObject json = new JSONObject(jsonFile); String type = json.getString("type"); JSONObject properties = json.getJSONObject("properties"); String content;//from w w w. j a v a 2 s .co m content = "{\n" + " \"" + type + "\" : {\n" + " \"properties\" : {\n"; for (int i = 0; i < properties.length(); i++) { if (!properties.getJSONObject("" + i + "").getString("champES").equals("location")) { //Only "not-analyzed" fields if (properties.getJSONObject("" + i + "").getString("mapping").equals("true")) { content += " \"" + properties.getJSONObject("" + i + "").getString("champES") + "\" : { \n" + " \"type\" : \"string\", \n" + " \"index\" : \"not_analyzed\" \n" + " }, \n"; } } else { //Location is always a "geo-point" content += " \"location\" : { \n" + " \"type\" : \"geo_point\"\n" + " } \n" + " } \n" + " } \n" + "} \n"; } } settings.mapping.put(type, content); SettingsRepository.INSTANCE.updateSettings(settings); }
From source file:ti.notificare.NotificareTitaniumAndroidModule.java
/** * Transform a JSONObject into a Map/*www .j a v a 2 s.co m*/ * @see NotificareTitaniumAndroidModule#jsonToObject(Object) for mapping details * @param json * @return */ private static KrollDict jsonToMap(JSONObject json) { KrollDict map = new KrollDict(json.length()); for (Iterator<String> iter = json.keys(); iter.hasNext();) { String key = iter.next(); try { Object value = json.get(key); map.put(key, jsonToObject(value)); } catch (JSONException e) { Log.e(TAG, "JSON error: " + e.getMessage()); } } return map; }
From source file:com.brainasylum.andruid.UniqueIdentifierManager.java
public synchronized void clearUdid(Context context) { // if permissions are granted, remove the identifier from // the storage bundle... if (canWriteExternalStorage(context)) { File file = new File(Environment.getExternalStorageDirectory() + "/" + FILE_DIR, FILE_NAME); if (file.exists()) { try { // FileInputStream fis = new FileInputStream(file); byte[] buffer = new byte[(int) file.length()]; fis.read(buffer);/*w w w . j av a2s . c o m*/ fis.close(); JSONObject root = new JSONObject(new String(buffer)); // String applicationName = context.getApplicationInfo().packageName; // if (root.has(applicationName)) { JSONObject values = root.getJSONObject(applicationName); if (values.has(_identifier.getKey())) { // remove the identifier value and if it's the // last one in the object remove the application // node itself values.remove(_identifier.getKey()); if (values.length() == 0) { root.remove(applicationName); } // FileOutputStream fos = new FileOutputStream(file); fos.write(root.toString().getBytes()); fos.close(); } } } catch (IOException e) { Log.e(TAG, "I/O error with file " + file.getAbsolutePath(), e); e.printStackTrace(); } catch (JSONException e) { Log.e(TAG, "JSON error with file " + file.getAbsolutePath(), e); e.printStackTrace(); } } } // ... then remove it from the shared preferences... SharedPreferences prefs = context.getSharedPreferences(_identifier.getTag(), Context.MODE_PRIVATE); prefs.edit().remove(_identifier.getKey()).commit(); // ... and clear the instance cached value. _udid = null; }
From source file:isbnfilter.ISBNConverter.java
public void createNewFile(List<String[]> isbns) throws IOException, JSONException { int contCorrectos = 0, contIncorrectos = 0, cont = 1; String finalLine = "ISBN|-|TITULO|-|AUTORES|-|DESCRIPCION|-|GENEROS|-|IMAGEN|-|ANIO|-|PUBLISHER"; List<String> finalLines = new ArrayList(); finalLines.add(finalLine);// w w w . j a v a 2 s . co m for (int i = 0; i < isbns.size(); i++) { if (cont % 1000 == 0) //Para que avise cada X cantidad { System.out.println("van " + cont + " isbns"); } JSONObject jobj = getJSON(isbns.get(i)[0], cont); if (jobj.length() != 0) { if (i == 11) { i = i + 1; i = i - 1; } try { String[] fileValues = isbns.get(i); contCorrectos++; String line = isbns.get(i)[0] + "|-|"; JSONObject objobj = jobj.getJSONObject("ISBN:" + isbns.get(i)[0]); if (!objobj.isNull("title")) { String title = objobj.getString("title"); line += title; } else { //line += "NOTITLE"; line += fileValues[1]; } line += "|-|"; if (!objobj.isNull("authors")) { List<String> authors = new ArrayList(); JSONArray arrayAuthors = objobj.getJSONArray("authors"); for (int j = 0; j < arrayAuthors.length(); j++) { JSONObject subjectObj = arrayAuthors.getJSONObject(j); authors.add(subjectObj.getString("name")); } for (String author : authors) { line += author + "|"; } line = line.substring(0, line.length() - 1); } else { //line += "NOAUTHOR"; line += fileValues[2]; } line += "|-|"; if (!objobj.isNull("excerpts")) { List<String> authors = new ArrayList(); JSONArray arrayAuthors = objobj.getJSONArray("excerpts"); for (int j = 0; j < arrayAuthors.length(); j++) { JSONObject subjectObj = arrayAuthors.getJSONObject(j); authors.add(subjectObj.getString("text")); } for (String author : authors) { line += author + "|"; } line = line.substring(0, line.length() - 1); } else { line += "NODESCRIPTION"; } line += "|-|"; if (!objobj.isNull("subjects")) { List<String> genres = new ArrayList(); JSONArray arraySubjects = objobj.getJSONArray("subjects"); for (int j = 0; j < arraySubjects.length(); j++) { JSONObject subjectObj = arraySubjects.getJSONObject(j); genres.add(subjectObj.getString("name")); } for (String genre : genres) { line += genre + "|"; } line = line.substring(0, line.length() - 1); } else { line += "NOGENRE"; } line += "|-|"; if (!objobj.isNull("cover")) { String img = "NOIMAGE"; JSONObject covers = objobj.getJSONObject("cover"); if (!covers.isNull("medium")) img = covers.getString("medium"); else { if (!covers.isNull("large")) img = covers.getString("large"); else { if (!covers.isNull("small")) img = covers.getString("small"); } } line += img; } else line += "NOIMAGE"; line += "|-|"; line += fileValues[3]; line += "|-|"; line += fileValues[4]; finalLines.add(line); } catch (Exception e) { System.out.println("algo raro pas"); } } else { contIncorrectos++; } cont++; if (cont > 10000) i = isbns.size(); } //De aqu para abajo imprime los ISBN (slo eso imprime) PrintWriter writer = new PrintWriter("C:\\Users\\jcdur\\Desktop\\ISBN\\siSirven.txt", "UTF-8"); //Cambiar path for (String theISBN1 : finalLines) { writer.println(theISBN1); } writer.close(); System.out.println("terminado"); System.out.println("correctos: " + contCorrectos + "/" + cont); System.out.println("incorrectos: " + contIncorrectos + "/" + cont); }
From source file:com.reignite.parser.QueryParser.java
/** * Where has either and / or or a field eg: where:{and:[...,...]} or * where:{or:[...,...]} or where:{id:{eq:23}} * /*from w w w. j a v a 2 s . c o m*/ * @param query * @param jobj * @throws JSONException */ private void addWhereClause(JSONObject jobj) throws ParserException { if (jobj.has("where")) { JSONObject where; try { where = jobj.getJSONObject("where"); } catch (JSONException e) { throw new ParserException("the where clause must be a JSON Object: " + query.toString()); } if (where.length() == 0) { return; } query.addWhere(createCriterion(where)); } }
From source file:waveimport.RobotApi.java
private JSONObject callRobotApi(String method, Map<String, Object> params) throws IOException { JSONArray ops = new JSONArray(); try {// ww w . j ava 2 s . c o m JSONObject jsonParams = new JSONObject(); for (Map.Entry<String, Object> e : params.entrySet()) { jsonParams.put(e.getKey(), e.getValue()); } JSONObject op = new JSONObject(); op.put("params", jsonParams); op.put("method", method); op.put("id", OP_ID); ops.put(op); } catch (JSONException e) { throw new RuntimeException("Failed to construct JSON object", e); } HTTPRequest req = new HTTPRequest(new URL(baseUrl), HTTPMethod.POST, FetchOptions.Builder.disallowTruncate().followRedirects().validateCertificate().setDeadline(20.0)); log.info("payload=" + ops); req.setHeader(new HTTPHeader("Content-Type", "application/json; charset=UTF-8")); req.setPayload(ops.toString().getBytes(Charsets.UTF_8)); System.out.println("req: " + ops.toString()); JSONObject result = parseJsonResponseBody(fetch.fetch(req, robotErrorCode401Detector)); log.info("result=" + ValueUtils.abbrev("" + result, 500)); try { if (result.has("error")) { log.warning("Error result: " + result); JSONObject error = result.getJSONObject("error"); throw new RuntimeException("Error from robot API: " + error); } else if (result.has("data")) { JSONObject data = result.getJSONObject("data"); if (data.length() == 0) { // Apparently, the server often sends {"id":"op_id", "data":{}} when // something went wrong on the server side, so we translate that to an // IOException. throw new IOException("Robot API response looks like an error: " + result); } else { return data; } } else { throw new RuntimeException("Result has neither error nor data: " + result); } } catch (JSONException e) { throw new RuntimeException("JSONException parsing result: " + result, e); } }
From source file:org.official.json.JSONML.java
/** * Parse XML values and store them in a JSONArray. * @param x The XMLTokener containing the source string. * @param arrayForm true if array form, false if object form. * @param ja The JSONArray that is containing the current tag or null * if we are at the outermost level. * @return A JSONArray if the value is the outermost tag, otherwise null. * @throws JSONException/*w w w . ja va 2s . c o m*/ */ private static Object parse(XMLTokener x, boolean arrayForm, JSONArray ja) throws JSONException { String attribute; char c; String closeTag = null; int i; JSONArray newja = null; JSONObject newjo = null; Object token; String tagName = null; // Test for and skip past these forms: // <!-- ... --> // <![ ... ]]> // <! ... > // <? ... ?> while (true) { if (!x.more()) { throw x.syntaxError("Bad XML"); } token = x.nextContent(); if (token == XML.LT) { token = x.nextToken(); if (token instanceof Character) { if (token == XML.SLASH) { // Close tag </ token = x.nextToken(); if (!(token instanceof String)) { throw new JSONException("Expected a closing name instead of '" + token + "'."); } if (x.nextToken() != XML.GT) { throw x.syntaxError("Misshaped close tag"); } return token; } else if (token == XML.BANG) { // <! c = x.next(); if (c == '-') { if (x.next() == '-') { x.skipPast("-->"); } else { x.back(); } } else if (c == '[') { token = x.nextToken(); if (token.equals("CDATA") && x.next() == '[') { if (ja != null) { ja.put(x.nextCDATA()); } } else { throw x.syntaxError("Expected 'CDATA['"); } } else { i = 1; do { token = x.nextMeta(); if (token == null) { throw x.syntaxError("Missing '>' after '<!'."); } else if (token == XML.LT) { i += 1; } else if (token == XML.GT) { i -= 1; } } while (i > 0); } } else if (token == XML.QUEST) { // <? x.skipPast("?>"); } else { throw x.syntaxError("Misshaped tag"); } // Open tag < } else { if (!(token instanceof String)) { throw x.syntaxError("Bad tagName '" + token + "'."); } tagName = (String) token; newja = new JSONArray(); newjo = new JSONObject(); if (arrayForm) { newja.put(tagName); if (ja != null) { ja.put(newja); } } else { newjo.put("tagName", tagName); if (ja != null) { ja.put(newjo); } } token = null; for (;;) { if (token == null) { token = x.nextToken(); } if (token == null) { throw x.syntaxError("Misshaped tag"); } if (!(token instanceof String)) { break; } // attribute = value attribute = (String) token; if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) { throw x.syntaxError("Reserved attribute."); } token = x.nextToken(); if (token == XML.EQ) { token = x.nextToken(); if (!(token instanceof String)) { throw x.syntaxError("Missing value"); } newjo.accumulate(attribute, XML.stringToValue((String) token)); token = null; } else { newjo.accumulate(attribute, ""); } } if (arrayForm && newjo.length() > 0) { newja.put(newjo); } // Empty tag <.../> if (token == XML.SLASH) { if (x.nextToken() != XML.GT) { throw x.syntaxError("Misshaped tag"); } if (ja == null) { if (arrayForm) { return newja; } else { return newjo; } } // Content, between <...> and </...> } else { if (token != XML.GT) { throw x.syntaxError("Misshaped tag"); } closeTag = (String) parse(x, arrayForm, newja); if (closeTag != null) { if (!closeTag.equals(tagName)) { throw x.syntaxError("Mismatched '" + tagName + "' and '" + closeTag + "'"); } tagName = null; if (!arrayForm && newja.length() > 0) { newjo.put("childNodes", newja); } if (ja == null) { if (arrayForm) { return newja; } else { return newjo; } } } } } } else { if (ja != null) { ja.put(token instanceof String ? XML.stringToValue((String) token) : token); } } } }