List of usage examples for org.json JSONObject get
public Object get(String key) throws JSONException
From source file:com.epam.gepard.rest.jira.JiraSiteHandler.java
/** * Constructor of the Jira Site Handler object. * * @param tc is the caller test case * @param environment provide the Environment object of Gepard, it must contain connectivity info to JIRA. *///from ww w . j a v a 2 s . co m public JiraSiteHandler(final GepardTestClass tc, final Environment environment) { this.environment = environment; webClient = new WebClient(); webClient.getOptions().setJavaScriptEnabled(false); webClient.getOptions().setThrowExceptionOnScriptError(false); webClient.getOptions().setUseInsecureSSL(true); String phrase = Base64.encode((environment.getProperty(Environment.JIRA_SITE_USERNAME) + ":" + environment.getProperty(Environment.JIRA_SITE_PASSWORD)).getBytes()); webClient.addRequestHeader("Authorization", "Basic " + phrase); try { JSONObject serverInfo = getJiraServerInfo(); String serverTitle = serverInfo.get("serverTitle").toString(); String version = serverInfo.get("version").toString(); tc.logComment("Connected to JIRA Server: \"" + serverTitle + "\", version: " + version); } catch (FailingHttpStatusCodeException | IOException | JSONException e) { throw new SimpleGepardException( "Cannot connect to JIRA properly, pls check the settings, reason: " + e.getMessage(), e); } }
From source file:com.epam.gepard.rest.jira.JiraSiteHandler.java
/** * Update a field of a JIRA ticket to a specified value. * * @param tc is the caller test.//from w w w . java 2s. c o m * @param ticket is the jira ticket id * @param fieldName is the name of the field * @param value is the new value * @throws JSONException in case of problem * @throws IOException in case of problem */ public void updateTicketFieldValue(final GepardTestClass tc, final String ticket, final String fieldName, final String value) throws JSONException, IOException { String ticketFields = getTicketFields(ticket); JSONObject obj = new JSONObject(ticketFields); obj = obj.getJSONObject("fields"); if (obj.has(fieldName)) { Object o = obj.get(fieldName); setTicketFieldValue(tc, ticket, fieldName, value); } else { throw new SimpleGepardException("Ticket: " + ticket + " field: " + fieldName + " cannot find."); } }
From source file:com.epam.gepard.rest.jira.JiraSiteHandler.java
/** * Get a field value of a JIRA ticket./* w ww .j a v a 2s . c o m*/ * * @param tc is the caller test. * @param ticket is the jira ticket id * @param fieldName is the name of the field * @return with the field value * @throws JSONException in case of problem * @throws IOException in case of problem */ public String getTicketFieldValue(final GepardTestClass tc, final String ticket, final String fieldName) throws JSONException, IOException { String ticketFields = getTicketFields(ticket); JSONObject obj = new JSONObject(ticketFields); obj = obj.getJSONObject("fields"); if (obj.has(fieldName)) { return obj.get(fieldName).toString(); } else { throw new SimpleGepardException("Ticket: " + ticket + " field: " + fieldName + " cannot find."); } }
From source file:com.epam.gepard.rest.jira.JiraSiteHandler.java
/** * Detect the actual workflow possibilities of the ticket, from its actual status. * * @param ticket is the id// w w w . j av a2 s .com * @return with String representation of the list of possibilities, in form of statusTransferId;newStatusName strings * @throws IOException in case of problem * @throws JSONException in case of problem */ public String detectWorkflow(final String ticket) throws IOException, JSONException { String jqlURL; //first detect status String ticketFields = getTicketFields(ticket); JSONObject fieldObj = new JSONObject(ticketFields); fieldObj = fieldObj.getJSONObject("fields"); fieldObj = fieldObj.getJSONObject("status"); String status = "@" + fieldObj.get("name").toString(); //then collect possible transactions jqlURL = getIssueTransitionsUrl(ticket); WebRequest requestSettings = new WebRequest(new URL(jqlURL), HttpMethod.GET); requestSettings.setAdditionalHeader("Content-type", "application/json"); UnexpectedPage infoPage = webClient.getPage(requestSettings); if (infoPage.getWebResponse().getStatusCode() == HTTP_RESPONSE_OK) { String ticketList = infoPage.getWebResponse().getContentAsString(); JSONObject obj = new JSONObject(ticketList); JSONArray array = obj.getJSONArray("transitions"); List<String> toList = new ArrayList<>(); toList.add(status); for (int i = 0; i < array.length(); i++) { JSONObject o = (JSONObject) array.get(i); JSONObject o2 = o.getJSONObject("to"); String toPossibility = o2.get("name").toString(); String toPossibilityID = o.get("id").toString(); //it is the transition id not the status id toList.add(toPossibilityID + ";" + toPossibility); } return toList.toString(); } throw new SimpleGepardException("ERROR: Cannot fetch Issue transition possibilities from JIRA, for ticket: " + ticket + ", Status code:" + infoPage.getWebResponse().getStatusCode()); }
From source file:com.epam.gepard.rest.jira.JiraSiteHandler.java
private String detectActualStatus(final String ticket) throws IOException, JSONException { String ticketFields = getTicketFields(ticket); JSONObject fieldObj = new JSONObject(ticketFields); fieldObj = fieldObj.getJSONObject("fields"); fieldObj = fieldObj.getJSONObject("status"); String status = "@" + fieldObj.get("name").toString(); return status; }
From source file:com.samsung.appengine.web.server.RemindMeServlet.java
@JsonRpcMethod(method = RemindMeProtocol.AlertsSync.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;// ww w . j a v a2s . c o m try { clientDeviceId = context.getParams().optString(RemindMeProtocol.ARG_CLIENT_DEVICE_ID); sinceDate = Util .parseDateISO8601(context.getParams().getString(RemindMeProtocol.AlertsSync.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<Alert> localAlerts = new ArrayList<Alert>(); if (context.getParams().has(RemindMeProtocol.AlertsSync.ARG_LOCAL_ALERTS)) { JSONArray localChangesJson = context.getParams() .getJSONArray(RemindMeProtocol.AlertsSync.ARG_LOCAL_ALERTS); for (int i = 0; i < localChangesJson.length(); i++) { try { JSONObject noteJson = localChangesJson.getJSONObject(i); if (noteJson.has("id")) { Key existingAlertKey = Alert.makeKey(userInfo.getId(), noteJson.get("id").toString()); try { Alert existingAlert = (Alert) context.getPersistenceManager() .getObjectById(Alert.class, existingAlertKey); if (!existingAlert.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) { // Alert doesn't exist, instead of throwing an error, // just re-create the note on the server side (unassign its ID). //throw new JsonRpcException(404, "Alert with ID " // + noteJson.get("id").toString() + " does not exist."); noteJson.remove("id"); } } noteJson.put("owner_id", userInfo.getId()); Alert localAlert = new Alert(noteJson); localAlerts.add(localAlert); } catch (JSONException e) { throw new JsonRpcException(400, "Invalid local note content.", e); } } } // Query server-side note changes. Query query = context.getPersistenceManager().newQuery(Alert.class); query.setFilter("ownerKey == ownerKeyParam && modifiedDate > sinceDate"); query.setOrdering("modifiedDate desc"); query.declareParameters(Key.class.getName() + " ownerKeyParam, java.util.Date sinceDate"); @SuppressWarnings("unchecked") List<Alert> alerts = (List<Alert>) query.execute(userInfo.getKey(), sinceDate); // Now merge the lists and conflicting objects. Reconciler<Alert> reconciler = new Reconciler<Alert>() { @Override public Alert reconcile(Alert o1, Alert 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<Alert> reconciledAlerts = reconciler.reconcileLists(alerts, localAlerts); for (Alert alert : reconciledAlerts) { // Save the note. context.getPersistenceManager().makePersistent(alert); // Put it in the response output. notesJson.put(alert.toJSON()); } tx.commit(); } finally { if (tx.isActive()) { tx.rollback(); } } enqueueDeviceMessage(context.getPersistenceManager(), userInfo, clientDeviceId); responseJson.put(RemindMeProtocol.AlertsSync.RET_ALERTS, notesJson); responseJson.put(RemindMeProtocol.AlertsSync.RET_NEW_SINCE_DATE, Util.formatDateISO8601(newSinceDate)); return responseJson; }
From source file:com.voidsearch.data.provider.facebook.objects.GraphObject.java
public GraphObject(JSONObject data) throws Exception { id = (String) data.get("id"); }
From source file:org.eclipse.orion.server.tests.servlets.git.GitTagTest.java
@Test public void testListDeleteTags() throws Exception { 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()); JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT); String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD); String gitTagUri = gitSection.getString(GitConstants.KEY_TAG); JSONArray tags = listTags(gitTagUri); assertEquals(0, tags.length());/*from ww w. j a va 2s . co m*/ // log JSONArray commitsArray = log(gitHeadUri); assertEquals(1, commitsArray.length()); JSONObject commit = commitsArray.getJSONObject(0); String commitId = commit.getString(ProtocolConstants.KEY_NAME); String commitLocation = commit.getString(ProtocolConstants.KEY_LOCATION); tag(gitTagUri, "tag1", commitId); tags = listTags(gitTagUri); assertEquals(1, tags.length()); assertEquals("tag1", tags.getJSONObject(0).get(ProtocolConstants.KEY_NAME)); // update commit with tag tag(commitLocation, "tag2"); tags = listTags(gitTagUri); assertEquals(2, tags.length()); assertEquals("tag2", tags.getJSONObject(0).get(ProtocolConstants.KEY_NAME)); // delete 'tag1' JSONObject tag1 = tags.getJSONObject(1); assertEquals("tag1", tag1.get(ProtocolConstants.KEY_NAME)); String tag1Uri = tag1.getString(ProtocolConstants.KEY_LOCATION); deleteTag(tag1Uri); tags = listTags(gitTagUri); assertEquals(1, tags.length()); assertEquals("tag2", tags.getJSONObject(0).get(ProtocolConstants.KEY_NAME)); // check if the deleted tag is gone request = getGetGitTagRequest(tag1Uri); response = webConversation.getResponse(request); assertEquals(HttpURLConnection.HTTP_NOT_FOUND, response.getResponseCode()); } }
From source file:org.eclipse.orion.server.tests.servlets.git.GitTagTest.java
@Test public void testCheckoutTag() throws Exception { 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); String cloneLocation = clone.getString(ProtocolConstants.KEY_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()); JSONObject testTxt = getChild(folder, "test.txt"); modifyFile(testTxt, "tag me"); addFile(testTxt);/* www . ja v a 2 s.c o m*/ commitFile(testTxt, "tag me", false); // tag HEAD with 'tag' JSONObject gitSection = folder.getJSONObject(GitConstants.KEY_GIT); String gitTagUri = gitSection.getString(GitConstants.KEY_TAG); String gitHeadUri = gitSection.getString(GitConstants.KEY_HEAD); tag(gitTagUri, "tag", Constants.HEAD); modifyFile(testTxt, "after tag"); addFile(testTxt); commitFile(testTxt, "after tag", false); assertEquals("after tag", getFileContent(testTxt)); response = checkoutTag(cloneLocation, "tag"); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); assertEquals("tag me", getFileContent(testTxt)); // check current branch request = getGetRequest(clone.getString(GitConstants.KEY_BRANCH)); response = webConversation.getResponse(request); ServerStatus status = waitForTask(response); assertTrue(status.toString(), status.isOK()); JSONObject branches = status.getJsonData(); assertEquals("tag_tag", GitBranchTest.getCurrentBranch(branches).getString(ProtocolConstants.KEY_NAME)); // log JSONArray commitsArray = log(gitHeadUri); assertEquals(2, commitsArray.length()); JSONObject commit = commitsArray.getJSONObject(0); assertEquals("tag me", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); commit = commitsArray.getJSONObject(1); assertEquals("Initial commit", commit.get(GitConstants.KEY_COMMIT_MESSAGE)); response = checkoutBranch(cloneLocation, Constants.MASTER); assertEquals(HttpURLConnection.HTTP_OK, response.getResponseCode()); assertEquals("after tag", getFileContent(testTxt)); } }
From source file:org.emergent.android.weave.syncadapter.SyncCache.java
/** * In:/* www .j a va 2 s .co m*/ * <p/> * <pre> * { * "id":"global" * "modified": 1.28702415227E9 * "payload": * {"syncID":"JnvqPEn(6~", * "storageVersion":3, * "engines":{"clients":{"version":1,"syncID":"LwjtCQjdsV"}, * "bookmarks":{"version":1,"syncID":"ApPN6v8VY4"}, * "forms":{"version":1,"syncID":"UKeuhB.aOZ"}, * "tabs":{"version":1,"syncID":"G!nU*7H.7j"}, * "history":{"version":1,"syncID":"9Tvy_Vlb44"}, * "passwords":{"version":1,"syncID":"yfBi2v7Pp)"}, * "prefs":{"version":1,"syncID":"*eONx!6GXA"}}} * } * </pre> * <p/> * Out: * <pre> * syncID : ... * storageVersion : ... * clients.version : ... * clients.syncID : ... * ... * </pre> * * @param mgObj * @return */ private static Properties convertMetaGlobalToFlatProperties(JSONObject mgObj) { Properties retval = new Properties(); try { // Log.w(TAG, "mgObj: " + mgObj.toString(2)); JSONObject payload = new JSONObject(String.valueOf(mgObj.get("payload"))); transferIfExists(retval, payload, "syncID", null); transferIfExists(retval, payload, "storageVersion", null); if (payload.has("engines")) { JSONObject enginesObj = payload.getJSONObject("engines"); // Log.w(TAG, "engObj: " + enginesObj.toString(2)); for (Iterator iter = enginesObj.keys(); iter.hasNext();) { String engName = (String) iter.next(); // Log.w(TAG, "engName: " + engName); JSONObject engObj = enginesObj.getJSONObject(engName); transferIfExists(retval, engObj, "syncID", engName + "."); transferIfExists(retval, engObj, "version", engName + "."); } } } catch (JSONException e) { Log.w(TAG, e); } return retval; }