Java Code Examples for org.codehaus.jettison.json.JSONArray#get()
The following examples show how to use
org.codehaus.jettison.json.JSONArray#get() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CustomerODataIT.java From cloud-espm-v2 with Apache License 2.0 | 6 votes |
/** * Test if Customer URL Select Service Query Option. * * @throws IOException * @throws JSONException */ @Test public void testCustomerUrlSelect() throws IOException, JSONException { HttpResponse resp = RequestExecutionHelper .executeGetRequest( ENTITY_NAME + "?$format=json&$orderby=CustomerId&$skip=1&$top=1&$select=CustomerId,Country", true); JSONArray ja = RequestExecutionHelper.getJSONArrayofResults(resp .getBody()); assertNotNull("Unable to parse JSON response", ja); ja.get(0); assertTrue( "Selected property Country does not exist in the odata service", resp.getBody().contains("Country")); assertTrue( "Non selected property City still exists in the odata service", !resp.getBody().contains("City")); }
Example 2
Source File: SalesOrderHeaderODataIT.java From cloud-espm-v2 with Apache License 2.0 | 6 votes |
/** * Test Create Sales Order Header via URL. * * @throws IOException * @throws JSONException */ @Test public void testCreateSalesOrderHeaderViaREST() throws IOException, JSONException { String salesOrderHeaderXml = StreamHelper.readFromFile(SOH_FILENAME); String id = RequestExecutionHelper.createEntityViaREST(ENTITY_NAME, salesOrderHeaderXml, false); HttpResponse resp = RequestExecutionHelper.executeGetRequest( ENTITY_NAME + "?$format=json&$filter=SalesOrderId%20eq%20'" + id + "'", true); assertEquals("Sales Order not persisted", HttpURLConnection.HTTP_OK, resp.getResponseCode()); JSONArray ja = RequestExecutionHelper.getJSONArrayofResults(resp .getBody()); assertNotNull("Unable to parse JSON response", ja); JSONObject jo = (JSONObject) ja.get(0); assertEquals("Added Sales Order Header via REST not persisted in db", id, jo.getString("SalesOrderId")); resp = RequestExecutionHelper.executeDeleteRequest(ENTITY_NAME + "('" + id + "')", true); assertEquals( "Unable to delete Sales Order Header via REST or incorrect HTTP Response Code:" + resp.getResponseMessage(), HttpURLConnection.HTTP_NO_CONTENT, resp.getResponseCode()); }
Example 3
Source File: SupplierODataIT.java From cloud-espm-v2 with Apache License 2.0 | 6 votes |
/** * Test if Supplier URL Select Service Query Option. * * @throws IOException * @throws JSONException */ @Test public void testSupplierUrlSelect() throws IOException, JSONException { HttpResponse resp = RequestExecutionHelper .executeGetRequest( ENTITY_NAME + "?$format=json&$orderby=SupplierId&$skip=1&$top=1&$select=SupplierId,Country", true); JSONArray ja = RequestExecutionHelper.getJSONArrayofResults(resp .getBody()); assertNotNull("Unable to parse JSON response", ja); ja.get(0); assertTrue( "Selected property Country does not exist in the odata service", resp.getBody().contains("Country")); assertTrue( "Non selected property City still exists in the odata service", !resp.getBody().contains("City")); }
Example 4
Source File: SalesOrderItemODataIT.java From cloud-espm-v2 with Apache License 2.0 | 5 votes |
/** * Test creation of Sales Order Item via URL. * * @throws IOException * @throws JSONException */ @Test public void testCreateSalesOrderItemViaURL() throws IOException, JSONException { String salesOrderItemXml = StreamHelper.readFromFile(FILENAME); String salesOrderHeaderXml = StreamHelper.readFromFile(SOH_FILENAME); String soid = RequestExecutionHelper.createEntityViaREST( "SalesOrderHeaders", salesOrderHeaderXml, false); salesOrderItemXml = salesOrderItemXml.replace( "<d:SalesOrderId>600000001</d:SalesOrderId>", "<d:SalesOrderId>" + soid + "</d:SalesOrderId>"); String id = RequestExecutionHelper.createEntityViaREST(ENTITY_NAME, salesOrderItemXml, true); HttpResponse resp = RequestExecutionHelper.executeGetRequest( ENTITY_NAME + "?$format=json&$filter=SalesOrderId%20eq%20'" + id + "'", true); assertEquals("Sales Order not persisted", HttpURLConnection.HTTP_OK, resp.getResponseCode()); JSONArray ja = RequestExecutionHelper.getJSONArrayofResults(resp .getBody()); assertNotNull("Unable to parse JSON response", ja); JSONObject jo = (JSONObject) ja.get(0); assertEquals("Added Sales Order Header via REST not persisted in db", id, jo.getString("SalesOrderId")); resp = RequestExecutionHelper.executeDeleteRequest(ENTITY_NAME + "(SalesOrderId='" + id + "',ItemNumber=10)", true); assertEquals( "Unable to delete Sales Order Header via REST or incorrect HTTP Response Code:" + resp.getResponseMessage(), HttpURLConnection.HTTP_NO_CONTENT, resp.getResponseCode()); resp = RequestExecutionHelper.executeDeleteRequest( "SalesOrderHeaders('" + soid + "')", true); }
Example 5
Source File: CustomerODataIT.java From cloud-espm-v2 with Apache License 2.0 | 5 votes |
/** * Test Create and Read Customer via URL. * * @throws JSONException * @throws IOException */ @Test public void testCreateCustomerViaREST() throws IOException, JSONException { String email = rand.nextInt(200) + "@sap.com"; String customerXml = StreamHelper.readFromFile(FILENAME); customerXml = customerXml.replace( "<d:EmailAddress>email</d:EmailAddress>", "<d:EmailAddress>" + email + "</d:EmailAddress>"); String id = RequestExecutionHelper.createEntityViaREST(ENTITY_NAME, customerXml, false); HttpResponse resp = RequestExecutionHelper.executeGetRequest( ENTITY_NAME + "?$format=json&$filter=CustomerId%20eq%20'" + id + "'", true); assertEquals("Customer not persisted", HttpURLConnection.HTTP_OK, resp.getResponseCode()); JSONArray ja = RequestExecutionHelper.getJSONArrayofResults(resp .getBody()); assertNotNull("Unable to parse JSON response", ja); JSONObject jo = (JSONObject) ja.get(0); assertEquals("Added Customer via REST not persisted in db", id, jo.getString("CustomerId")); resp = RequestExecutionHelper.executeDeleteRequest(ENTITY_NAME + "('" + id + "')", true); assertEquals( "Unable to delete Customer via REST or incorrect HTTP Response Code:" + resp.getResponseMessage(), HttpURLConnection.HTTP_NO_CONTENT, resp.getResponseCode()); }
Example 6
Source File: CustomerODataIT.java From cloud-espm-v2 with Apache License 2.0 | 5 votes |
/** * Test Update Customer via URL. * * @throws JSONException * @throws IOException */ @Test public void testUpdateCustomerViaURL() throws IOException, JSONException { String email = rand.nextInt(200) + "@sap.com"; String newPhoneNumber = "9565470312"; String customerXml = StreamHelper.readFromFile(FILENAME); customerXml = customerXml.replace( "<d:EmailAddress>email</d:EmailAddress>", "<d:EmailAddress>" + email + "</d:EmailAddress>"); String id = RequestExecutionHelper.createEntityViaREST(ENTITY_NAME, customerXml, false); HttpResponse resp = RequestExecutionHelper.executeGetRequest( ENTITY_NAME + "?$format=json&$filter=CustomerId%20eq%20'" + id + "'", true); assertEquals("Customer not persisted", HttpURLConnection.HTTP_OK, resp.getResponseCode()); customerXml = customerXml.replace( "<d:PhoneNumber>5850428367</d:PhoneNumber>", "<d:PhoneNumber>" + newPhoneNumber + "</d:PhoneNumber>"); resp = RequestExecutionHelper.executePutRequest(ENTITY_NAME + "('" + id + "')", customerXml, true); assertEquals("Unable to update Customer via URL Response Message:" + resp.getResponseMessage(), HttpURLConnection.HTTP_NO_CONTENT, resp.getResponseCode()); resp = RequestExecutionHelper.executeGetRequest(ENTITY_NAME + "?$format=json&$filter=CustomerId%20eq%20'" + id + "'", true); JSONArray ja = RequestExecutionHelper.getJSONArrayofResults(resp .getBody()); assertNotNull("Unable to parse JSON response", ja); JSONObject jo = (JSONObject) ja.get(0); assertEquals("Updated Customer via REST not persisted in db", newPhoneNumber, jo.getString("PhoneNumber")); resp = RequestExecutionHelper.executeDeleteRequest(ENTITY_NAME + "('" + id + "')", true); assertEquals( "Unable to delete Customer via REST or incorrect HTTP Response Code:" + resp.getResponseMessage(), HttpURLConnection.HTTP_NO_CONTENT, resp.getResponseCode()); }
Example 7
Source File: ReleasePlanWebServiceTest.java From ezScrum with GNU General Public License v2.0 | 5 votes |
@Test public void testGetAllReleasePlan() throws LogonException, JSONException { String username = "admin"; String userpwd = "admin"; String projectID = mProject.getName(); mReleasePlanWebService = new ReleasePlanWebService(username, userpwd, projectID); // create sprint CreateSprint CS = new CreateSprint(mSprintCount, mCP); CS.exe(); // 從ReleasePlanHelper拿出release做assert List<ReleaseObject> releasePlanDescs = mReleasePlanHelper.getReleases(); JSONArray releasesJSONArray = new JSONArray(mReleasePlanWebService.getAllReleasePlan()); for (int i = 0; i < mReleaseCount; i++) { JSONObject releaseJson = (JSONObject) releasesJSONArray.get(i); assertEquals(releasePlanDescs.get(i).getId(), releaseJson.get(ReleaseEnum.ID)); assertEquals(releasePlanDescs.get(i).getName(), releaseJson.get(ReleaseEnum.NAME)); assertEquals(releasePlanDescs.get(i).getDescription(), releaseJson.get(ReleaseEnum.DESCRIPTION)); JSONArray sprintJsonArray = new JSONArray(releaseJson.get("sprints").toString()); ArrayList<SprintObject> sprints = releasePlanDescs.get(i).getSprints(); // assert ReleasePlan中的SprintPlan for(int j = 0; j < sprintJsonArray.length(); j++) { JSONObject sprintJson = (JSONObject) sprintJsonArray.get(j); assertEquals(sprints.get(j).getId(), sprintJson.getLong(SprintEnum.ID)); assertEquals(sprints.get(j).getGoal(), sprintJson.get(SprintEnum.GOAL)); assertEquals(sprints.get(j).getInterval(), sprintJson.get(SprintEnum.INTERVAL)); assertEquals(sprints.get(j).getTeamSize(), sprintJson.get(SprintEnum.TEAM_SIZE)); assertEquals(sprints.get(j).getFocusFactor(), sprintJson.get(SprintEnum.FOCUS_FACTOR)); assertEquals(sprints.get(j).getAvailableHours(), sprintJson.get(SprintEnum.AVAILABLE_HOURS)); assertEquals(sprints.get(j).getDemoPlace(), sprintJson.get(SprintEnum.DEMO_PLACE)); assertEquals(sprints.get(j).getDailyInfo(), sprintJson.get(SprintEnum.DAILY_INFO)); } } }
Example 8
Source File: SalesOrderHeaderODataIT.java From cloud-espm-v2 with Apache License 2.0 | 5 votes |
/** * Test ConfirmSalesOrder Function Import * * @throws JSONException * @throws IOException */ @Test public void testConfirmSalesOrder() throws JSONException, IOException { String salesOrderXml = StreamHelper.readFromFile(SO_FILENAME); String id = RequestExecutionHelper.createSalesOrderViaREST(ENTITY_NAME, salesOrderXml, true); HttpResponse resp = RequestExecutionHelper.executeGetRequest( ENTITY_NAME + "?$format=json&$filter=SalesOrderId%20eq%20'" + id + "'", true); assertEquals("Sales Order not persisted", HttpURLConnection.HTTP_OK, resp.getResponseCode()); resp = RequestExecutionHelper.executeGetRequest( "ConfirmSalesOrder?SalesOrderId='" + id + "'&$format=json", true); assertEquals("Sales Order not confirmed", HttpURLConnection.HTTP_OK, resp.getResponseCode()); resp = RequestExecutionHelper.executeGetRequest(ENTITY_NAME + "?$format=json&$filter=SalesOrderId%20eq%20'" + id + "'", true); JSONArray ja = RequestExecutionHelper.getJSONArrayofResults(resp .getBody()); assertNotNull("Unable to parse JSON response", ja); JSONObject jo = (JSONObject) ja.get(0); assertEquals("Added Sales Order Header via REST not persisted in db", "P", jo.getString("LifeCycleStatus")); resp = RequestExecutionHelper.executeDeleteRequest(ENTITY_NAME + "('" + id + "')", true); assertEquals( "Unable to delete Sales Order Header via REST or incorrect HTTP Response Code:" + resp.getResponseMessage(), HttpURLConnection.HTTP_NO_CONTENT, resp.getResponseCode()); }
Example 9
Source File: ZeppelinhubClient.java From zeppelin with Apache License 2.0 | 5 votes |
boolean runAllParagraph(String noteId, String hubMsg) { LOG.info("Running paragraph with noteId {}", noteId); try { JSONObject data = new JSONObject(hubMsg); if (data.equals(JSONObject.NULL) || !(data.get("data") instanceof JSONArray)) { LOG.error("Wrong \"data\" format for RUN_NOTEBOOK"); return false; } Client client = Client.getInstance(); if (client == null) { LOG.warn("Base client isn't initialized, returning"); return false; } Message zeppelinMsg = new Message(OP.RUN_PARAGRAPH); JSONArray paragraphs = data.getJSONArray("data"); String principal = data.getJSONObject("meta").getString("owner"); for (int i = 0; i < paragraphs.length(); i++) { if (!(paragraphs.get(i) instanceof JSONObject)) { LOG.warn("Wrong \"paragraph\" format for RUN_NOTEBOOK"); continue; } zeppelinMsg.data = gson.fromJson(paragraphs.getString(i), new TypeToken<Map<String, Object>>(){}.getType()); zeppelinMsg.principal = principal; zeppelinMsg.ticket = TicketContainer.instance.getTicket(principal); client.relayToZeppelin(zeppelinMsg, noteId); LOG.info("\nSending RUN_PARAGRAPH message to Zeppelin "); } } catch (JSONException e) { LOG.error("Failed to parse RUN_NOTEBOOK message from ZeppelinHub ", e); return false; } return true; }
Example 10
Source File: SupplierODataIT.java From cloud-espm-v2 with Apache License 2.0 | 5 votes |
/** * Test Create and Read Supplier via URL. * * @throws IOException * @throws JSONException */ @Test public void testCreateSupplierViaREST() throws IOException, JSONException { String supplierXml = StreamHelper.readFromFile(FILENAME); String email = rand.nextInt(200) + "@sap.com"; supplierXml = supplierXml.replace( "<d:EmailAddress>email</d:EmailAddress>", "<d:EmailAddress>" + email + "</d:EmailAddress>"); String id = RequestExecutionHelper.createEntityViaREST(ENTITY_NAME, supplierXml, true); HttpResponse resp = RequestExecutionHelper.executeGetRequest( ENTITY_NAME + "?$format=json&$filter=SupplierId%20eq%20'" + id + "'", true); assertEquals("Supplier not persisted", HttpURLConnection.HTTP_OK, resp.getResponseCode()); JSONArray ja = RequestExecutionHelper.getJSONArrayofResults(resp .getBody()); assertNotNull("Unable to parse JSON response", ja); JSONObject jo = (JSONObject) ja.get(0); assertEquals("Added Supplier via REST not persisted in db", id, jo.getString("SupplierId")); resp = RequestExecutionHelper.executeDeleteRequest(ENTITY_NAME + "('" + id + "')", true); assertEquals( "Unable to delete Supplier via REST or incorrect HTTP Response Code:" + resp.getResponseMessage(), HttpURLConnection.HTTP_NO_CONTENT, resp.getResponseCode()); }
Example 11
Source File: SupplierODataIT.java From cloud-espm-v2 with Apache License 2.0 | 5 votes |
/** * Test Update Supplier via URL. * * @throws IOException * @throws JSONException */ @Test public void testUpdateSupplierViaREST() throws IOException, JSONException { String supplierXml = StreamHelper.readFromFile(FILENAME); String newPhoneNumber = "111111"; String email = rand.nextInt(200) + "@sap.com"; supplierXml = supplierXml.replace( "<d:EmailAddress>email</d:EmailAddress>", "<d:EmailAddress>" + email + "</d:EmailAddress>"); String id = RequestExecutionHelper.createEntityViaREST(ENTITY_NAME, supplierXml, true); HttpResponse resp = RequestExecutionHelper.executeGetRequest( ENTITY_NAME + "?$format=json&$filter=SupplierId%20eq%20'" + id + "'", true); assertEquals("Supplier not persisted", HttpURLConnection.HTTP_OK, resp.getResponseCode()); supplierXml = supplierXml.replace( "<d:PhoneNumber>5899428367</d:PhoneNumber>", "<d:PhoneNumber>" + newPhoneNumber + "</d:PhoneNumber>"); resp = RequestExecutionHelper.executePutRequest(ENTITY_NAME + "('" + id + "')", supplierXml, true); assertEquals("Unable to update Supplier via URL Response Message:" + resp.getResponseMessage(), HttpURLConnection.HTTP_NO_CONTENT, resp.getResponseCode()); resp = RequestExecutionHelper.executeGetRequest(ENTITY_NAME + "?$format=json&$filter=SupplierId%20eq%20'" + id + "'", true); JSONArray ja = RequestExecutionHelper.getJSONArrayofResults(resp .getBody()); assertNotNull("Unable to parse JSON response", ja); JSONObject jo = (JSONObject) ja.get(0); assertEquals("Updated Supplier via URL not persisted in db", newPhoneNumber, jo.getString("PhoneNumber")); resp = RequestExecutionHelper.executeDeleteRequest(ENTITY_NAME + "('" + id + "')", true); assertEquals( "Unable to delete Supplier via REST or incorrect HTTP Response Code:" + resp.getResponseMessage(), HttpURLConnection.HTTP_NO_CONTENT, resp.getResponseCode()); }
Example 12
Source File: AtlasClient.java From incubator-atlas with Apache License 2.0 | 5 votes |
protected <T, U> List<T> extractResults(JSONObject jsonResponse, String key, ExtractOperation<T, U> extractInterafce) throws AtlasServiceException { try { JSONArray results = jsonResponse.getJSONArray(key); ArrayList<T> resultsList = new ArrayList<>(); for (int index = 0; index < results.length(); index++) { Object element = results.get(index); resultsList.add(extractInterafce.extractElement((U) element)); } return resultsList; } catch (JSONException e) { throw new AtlasServiceException(e); } }
Example 13
Source File: WorkMgrServiceTest.java From batfish with Apache License 2.0 | 4 votes |
@Test public void testGetAnswerRowsAnalysis() throws Exception { initNetwork(); initSnapshot(); String analysis = "analysis1"; String question = "question1"; Question questionObj = new TestQuestion(); String questionContent = BatfishObjectMapper.writeString(questionObj); String columnName = "col"; AnswerRowsOptions answersRowsOptions = new AnswerRowsOptions( ImmutableSet.of(columnName), ImmutableList.of(new ColumnFilter(columnName, "")), Integer.MAX_VALUE, 0, ImmutableList.of(new ColumnSortOption(columnName, false)), false); String answerRowsOptionsStr = BatfishObjectMapper.writePrettyString(answersRowsOptions); int value = 5; Answer testAnswer = new Answer(); testAnswer.addAnswerElement( new TableAnswerElement( new TableMetadata( ImmutableList.of(new ColumnMetadata(columnName, Schema.INTEGER, "foobar")), new DisplayHints().getTextDesc())) .addRow(Row.of(columnName, value))); testAnswer.setStatus(AnswerStatus.SUCCESS); String answer = BatfishObjectMapper.writePrettyString(testAnswer); String analysisJsonString = String.format("{\"%s\":%s}", question, questionContent); File analysisFile = _networksFolder.newFile(analysis); FileUtils.writeStringToFile(analysisFile, analysisJsonString, StandardCharsets.UTF_8); _service.configureAnalysis( CoordConsts.DEFAULT_API_KEY, BatfishVersion.getVersionStatic(), _networkName, "new", analysis, new FileInputStream(analysisFile), "", null); AnalysisId analysisId = idm().getAnalysisId(analysis, _networkId).get(); QuestionId questionId = idm().getQuestionId(question, _networkId, analysisId).get(); AnswerId answerId = idm() .getBaseAnswerId( _networkId, _snapshotId, questionId, DEFAULT_QUESTION_SETTINGS_ID, DEFAULT_NETWORK_NODE_ROLES_ID, null, analysisId); Main.getWorkMgr().getStorage().storeAnswer(answer, answerId); Main.getWorkMgr() .getStorage() .storeAnswerMetadata( AnswerMetadataUtil.computeAnswerMetadata(testAnswer, Main.getLogger()), answerId); JSONArray answerOutput = _service.getAnswerRows( CoordConsts.DEFAULT_API_KEY, BatfishVersion.getVersionStatic(), _networkName, _snapshotName, null, question, analysis, answerRowsOptionsStr, null); assertThat(answerOutput.get(0), equalTo(CoordConsts.SVC_KEY_SUCCESS)); JSONObject answerJsonObject = (JSONObject) answerOutput.get(1); String answersJsonString = answerJsonObject.getString(CoordConsts.SVC_KEY_ANSWER); Answer processedAnswer = BatfishObjectMapper.mapper().readValue(answersJsonString, new TypeReference<Answer>() {}); TableAnswerElement processedTable = (TableAnswerElement) processedAnswer.getAnswerElements().get(0); assertThat(processedTable.getRowsList(), equalTo(ImmutableList.of(Row.of(columnName, value)))); }
Example 14
Source File: WorkMgrServiceTest.java From batfish with Apache License 2.0 | 4 votes |
@Test public void testGetAnalysisAnswer() throws Exception { initNetwork(); initSnapshot(); String analysisName = "analysis1"; String questionName = "question1"; Question questionObj = new TestQuestion(); String questionContent = BatfishObjectMapper.writeString(questionObj); String question2Name = "question2Name"; String analysisJsonString = String.format("{\"%s\":%s}", questionName, questionContent); File analysisFile = _networksFolder.newFile(analysisName); FileUtils.writeStringToFile(analysisFile, analysisJsonString, StandardCharsets.UTF_8); _service.configureAnalysis( CoordConsts.DEFAULT_API_KEY, BatfishVersion.getVersionStatic(), _networkName, "new", analysisName, new FileInputStream(analysisFile), "", null); AnalysisId analysisId = idm().getAnalysisId(analysisName, _networkId).get(); QuestionId questionId = idm().getQuestionId(questionName, _networkId, analysisId).get(); AnswerId answerId = idm() .getBaseAnswerId( _networkId, _snapshotId, questionId, DEFAULT_QUESTION_SETTINGS_ID, DEFAULT_NETWORK_NODE_ROLES_ID, null, analysisId); Answer testAnswer = new Answer(); testAnswer.setStatus(AnswerStatus.SUCCESS); TableAnswerElement table = new TableAnswerElement(MOCK_TABLE_METADATA); table.postProcessAnswer(questionObj, table.getRows().getData()); testAnswer.addAnswerElement(table); testAnswer.setQuestion(questionObj); String testAnswerStr = BatfishObjectMapper.writeString(testAnswer); AnswerMetadata answerMetadata = AnswerMetadataUtil.computeAnswerMetadata(testAnswer, Main.getLogger()); Main.getWorkMgr().getStorage().storeAnswer(testAnswerStr, answerId); Main.getWorkMgr().getStorage().storeAnswerMetadata(answerMetadata, answerId); WorkItem workItem = new WorkItem(_networkName, _snapshotName); String workItemString = BatfishObjectMapper.mapper().writeValueAsString(workItem); JSONArray answer1Output = _service.getAnalysisAnswer( CoordConsts.DEFAULT_API_KEY, BatfishVersion.getVersionStatic(), _networkName, _snapshotName, null, analysisName, questionName, workItemString); JSONArray answer2Output = _service.getAnalysisAnswer( CoordConsts.DEFAULT_API_KEY, BatfishVersion.getVersionStatic(), _networkName, _snapshotName, null, analysisName, question2Name, null); assertThat(answer1Output.get(0), equalTo(CoordConsts.SVC_KEY_SUCCESS)); assertThat(answer2Output.get(0), equalTo(CoordConsts.SVC_KEY_FAILURE)); JSONObject answerJsonObject = (JSONObject) answer1Output.get(1); String answerJsonString = answerJsonObject.getString(CoordConsts.SVC_KEY_ANSWER); String answerString = BatfishObjectMapper.mapper().readValue(answerJsonString, new TypeReference<String>() {}); assertThat( BatfishObjectMapper.mapper().readTree(answerString), equalTo(BatfishObjectMapper.mapper().readTree(testAnswerStr))); }
Example 15
Source File: WorkMgrServiceTest.java From batfish with Apache License 2.0 | 4 votes |
@Test public void testGetAnalysisAnswerInContainer() throws Exception { initNetwork(); initSnapshot(); String analysisName = "analysis1"; String questionName = "question1"; Question questionObj = new TestQuestion(); String questionContent = BatfishObjectMapper.writeString(questionObj); String question2Name = "question2Name"; String analysisJsonString = String.format("{\"%s\":%s}", questionName, questionContent); File analysisFile = _networksFolder.newFile(analysisName); FileUtils.writeStringToFile(analysisFile, analysisJsonString, StandardCharsets.UTF_8); _service.configureAnalysis( CoordConsts.DEFAULT_API_KEY, BatfishVersion.getVersionStatic(), _networkName, "new", analysisName, new FileInputStream(analysisFile), "", null); AnalysisId analysisId = idm().getAnalysisId(analysisName, _networkId).get(); QuestionId questionId = idm().getQuestionId(questionName, _networkId, analysisId).get(); AnswerId answerId = idm() .getBaseAnswerId( _networkId, _snapshotId, questionId, DEFAULT_QUESTION_SETTINGS_ID, DEFAULT_NETWORK_NODE_ROLES_ID, null, analysisId); Answer testAnswer = new Answer(); testAnswer.setStatus(AnswerStatus.SUCCESS); testAnswer.addAnswerElement(new StringAnswerElement("foo")); String testAnswerStr = BatfishObjectMapper.writeString(testAnswer); Main.getWorkMgr().getStorage().storeAnswer(testAnswerStr, answerId); Main.getWorkMgr() .getStorage() .storeAnswerMetadata( AnswerMetadataUtil.computeAnswerMetadata(testAnswer, Main.getLogger()), answerId); WorkItem workItem = new WorkItem(_networkName, _snapshotName); String workItemString = BatfishObjectMapper.mapper().writeValueAsString(workItem); JSONArray answer1Output = _service.getAnalysisAnswer( CoordConsts.DEFAULT_API_KEY, BatfishVersion.getVersionStatic(), _networkName, _snapshotName, null, analysisName, questionName, workItemString); JSONArray answer2Output = _service.getAnalysisAnswer( CoordConsts.DEFAULT_API_KEY, BatfishVersion.getVersionStatic(), _networkName, _snapshotName, null, analysisName, question2Name, null); assertThat(answer1Output.get(0), equalTo(CoordConsts.SVC_KEY_SUCCESS)); assertThat(answer2Output.get(0), equalTo(CoordConsts.SVC_KEY_FAILURE)); JSONObject answerJsonObject = (JSONObject) answer1Output.get(1); String answerJsonString = answerJsonObject.getString(CoordConsts.SVC_KEY_ANSWER); String answerString = BatfishObjectMapper.mapper().readValue(answerJsonString, new TypeReference<String>() {}); assertThat(answerString, equalTo(testAnswerStr)); }
Example 16
Source File: JsonReader.java From vespa with Apache License 2.0 | 4 votes |
public SetRequestData getStateRequestData(HttpRequest request) throws Exception { JSONObject json = new JSONObject(request.getPostContent().toString()); final boolean probe = json.has("probe") && json.getBoolean("probe"); final SetUnitStateRequest.Condition condition; if (json.has("condition")) { condition = SetUnitStateRequest.Condition.fromString(json.getString("condition")); } else { condition = SetUnitStateRequest.Condition.FORCE; } final SetUnitStateRequest.ResponseWait responseWait = json.has("response-wait") ? SetUnitStateRequest.ResponseWait.fromString(json.getString("response-wait")) : SetUnitStateRequest.ResponseWait.WAIT_UNTIL_CLUSTER_ACKED; Map<String, UnitState> stateMap = new HashMap<>(); if (!json.has("state")) { throw new InvalidContentException("Set state requests must contain a state object"); } Object o = json.get("state"); if (!(o instanceof JSONObject)) { throw new InvalidContentException("value of state is not a json object"); } JSONObject state = (JSONObject) o; JSONArray stateTypes = state.names(); for (int i=0; i<stateTypes.length(); ++i) { o = stateTypes.get(i); String type = (String) o; o = state.get(type); if (!(o instanceof JSONObject)) { throw new InvalidContentException("value of state->" + type + " is not a json object"); } JSONObject userState = (JSONObject) o; String code = "up"; if (userState.has("state")) { o = userState.get("state"); if (!(o instanceof String)) { throw new InvalidContentException("value of state->" + type + "->state is not a string"); } code = o.toString(); } String reason = ""; if (userState.has("reason")) { o = userState.get("reason"); if (!(o instanceof String)) { throw new InvalidContentException("value of state->" + type + "->reason is not a string"); } reason = o.toString(); } stateMap.put(type, new UnitStateImpl(code, reason)); } return new SetRequestData(probe, stateMap, condition, responseWait); }
Example 17
Source File: WorkMgrServiceTest.java From batfish with Apache License 2.0 | 4 votes |
@Test public void testGetAnswerRows2AdHoc() throws Exception { initNetwork(); initSnapshot(); String question = "question1"; QuestionId questionId = new QuestionId(question + "_id"); Question questionObj = new TestQuestion(); String questionContent = BatfishObjectMapper.writeString(questionObj); String columnName = "col"; AnswerRowsOptions answersRowsOptions = new AnswerRowsOptions( ImmutableSet.of(columnName), ImmutableList.of(new ColumnFilter(columnName, "")), Integer.MAX_VALUE, 0, ImmutableList.of(new ColumnSortOption(columnName, false)), false); String answerRowsOptionsStr = BatfishObjectMapper.writePrettyString(answersRowsOptions); int value = 5; Answer testAnswer = new Answer(); testAnswer.addAnswerElement( new TableAnswerElement( new TableMetadata( ImmutableList.of(new ColumnMetadata(columnName, Schema.INTEGER, "foobar")), new DisplayHints().getTextDesc())) .addRow(Row.of(columnName, value))); testAnswer.setStatus(AnswerStatus.SUCCESS); String answer = BatfishObjectMapper.writePrettyString(testAnswer); Main.getWorkMgr().getStorage().storeQuestion(questionContent, _networkId, questionId, null); idm().assignQuestion(question, _networkId, questionId, null); AnswerId answerId = idm() .getBaseAnswerId( _networkId, _snapshotId, questionId, DEFAULT_QUESTION_SETTINGS_ID, DEFAULT_NETWORK_NODE_ROLES_ID, null, null); Main.getWorkMgr().getStorage().storeAnswer(answer, answerId); Main.getWorkMgr() .getStorage() .storeAnswerMetadata( AnswerMetadataUtil.computeAnswerMetadata(testAnswer, Main.getLogger()), answerId); JSONArray answerOutput = _service.getAnswerRows2( CoordConsts.DEFAULT_API_KEY, BatfishVersion.getVersionStatic(), _networkName, _snapshotName, null, question, null, answerRowsOptionsStr, null); assertThat(answerOutput.get(0), equalTo(CoordConsts.SVC_KEY_SUCCESS)); JSONObject answerJsonObject = (JSONObject) answerOutput.get(1); String answersJsonString = answerJsonObject.getString(CoordConsts.SVC_KEY_ANSWER); Answer processedAnswer = BatfishObjectMapper.mapper().readValue(answersJsonString, new TypeReference<Answer>() {}); TableView processedTable = (TableView) processedAnswer.getAnswerElements().get(0); assertThat(processedTable.getInnerRows(), equalTo(ImmutableList.of(Row.of(columnName, value)))); }
Example 18
Source File: WorkMgrServiceTest.java From batfish with Apache License 2.0 | 4 votes |
@Test public void testGetAnswerMetricsAnalysis() throws Exception { initNetwork(); initSnapshot(); String analysisName = "analysis1"; String questionName = "question1"; Question questionObj = new TestQuestion(); String questionContent = BatfishObjectMapper.writeString(questionObj); String analysisJsonString = String.format("{\"%s\":%s}", questionName, questionContent); File analysisFile = _networksFolder.newFile(analysisName); FileUtils.writeStringToFile(analysisFile, analysisJsonString, StandardCharsets.UTF_8); _service.configureAnalysis( CoordConsts.DEFAULT_API_KEY, BatfishVersion.getVersionStatic(), _networkName, "new", analysisName, new FileInputStream(analysisFile), "", null); AnalysisId analysisId = idm().getAnalysisId(analysisName, _networkId).get(); QuestionId questionId = idm().getQuestionId(questionName, _networkId, analysisId).get(); AnswerId answerId = idm() .getBaseAnswerId( _networkId, _snapshotId, questionId, DEFAULT_QUESTION_SETTINGS_ID, DEFAULT_NETWORK_NODE_ROLES_ID, null, analysisId); Answer testAnswer = new Answer(); testAnswer.setStatus(AnswerStatus.SUCCESS); testAnswer.addAnswerElement(new TableAnswerElement(MOCK_TABLE_METADATA)); String testAnswerStr = BatfishObjectMapper.writeString(testAnswer); AnswerMetadata answerMetadata = AnswerMetadataUtil.computeAnswerMetadata(testAnswer, Main.getLogger()); Main.getWorkMgr().getStorage().storeAnswer(testAnswerStr, answerId); Main.getWorkMgr().getStorage().storeAnswerMetadata(answerMetadata, answerId); JSONArray answerOutput = _service.getAnswerMetrics( CoordConsts.DEFAULT_API_KEY, BatfishVersion.getVersionStatic(), _networkName, _snapshotName, null, analysisName, questionName, null); assertThat(answerOutput.get(0), equalTo(CoordConsts.SVC_KEY_SUCCESS)); JSONObject answerJsonObject = (JSONObject) answerOutput.get(1); String answerJsonString = answerJsonObject.getString(CoordConsts.SVC_KEY_ANSWER); AnswerMetadata structuredAnswer = BatfishObjectMapper.mapper() .readValue(answerJsonString, new TypeReference<AnswerMetadata>() {}); assertThat(structuredAnswer, equalTo(answerMetadata)); }
Example 19
Source File: SolrFulltextSearchImpl.java From database with GNU General Public License v2.0 | 3 votes |
/** * Flattens a JSON result item, i.e. if the item is an array, it is * (non-recursively) flattened, applying toString() to sub items, * otherwise toString() is called directly. * * @param obj the json result item * @return */ String flattenJsonResult(Object obj) { if (obj instanceof JSONArray) { StringBuffer buf = new StringBuffer(); final JSONArray arr = (JSONArray)obj; for (int i=0; i<arr.length(); i++) { try { final Object cur = arr.get(i); if (cur!=null) { buf.append(cur.toString()); } } catch (Exception e) { // ignoring is probably the best we can do here } } return buf.toString(); } else { return obj.toString(); } }