private <T> JSONArray getJSONArray(Collection<T> elements) throws JSONException { JSONArray jsonArray = new JSONArray(); for (T element : elements) { jsonArray.put(new JSONObject(element.toString())); } return jsonArray; }
private boolean parseStructuredClause(JSONArray clauses, String hqlOperator) throws JSONException { boolean doOr = OPERATOR_OR.equals(hqlOperator); boolean doAnd = OPERATOR_AND.equals(hqlOperator); for (int i = 0; i < clauses.length(); i++) { final JSONObject clause = clauses.getJSONObject(i); if (clause.has(VALUE_KEY) && clause.get(VALUE_KEY) != null && clause.getString(VALUE_KEY).equals("")) { continue; } final boolean clauseResult = parseCriteria(clause); if (doOr && clauseResult) { return true; } if (doAnd && !clauseResult) { return false; } } if (doOr) { return false; } else if (doAnd) { return true; } return mainOperatorIsAnd; }
@PostConstruct public void listarGrupos() { JSONArray lista = null; try { JSONObject respuesta = new IGrupo().listarGrupos(sesion.getTokenId()); lista = respuesta.getJSONArray("lista"); listaGrupos.clear(); if (lista != null) { int len = lista.length(); for (int i = 0; i < len; i++) { try { JSONObject ob = lista.getJSONObject(i); JSONObject ob2 = ob.getJSONObject("grupo"); listaGrupos.add(ob2.getString("nombre")); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else { listaGrupos.clear(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@Override public JSONObject convertToATSJSON() throws JSONException { JSONObject jsonObject = new JSONObject(); jsonObject.put(ATSConstants.ENTITY, "tez_" + applicationAttemptId.toString()); jsonObject.put(ATSConstants.ENTITY_TYPE, EntityTypes.TEZ_APPLICATION_ATTEMPT.name()); // Related Entities JSONArray relatedEntities = new JSONArray(); JSONObject appEntity = new JSONObject(); appEntity.put(ATSConstants.ENTITY, applicationAttemptId.getApplicationId().toString()); appEntity.put(ATSConstants.ENTITY_TYPE, ATSConstants.APPLICATION_ID); JSONObject appAttemptEntity = new JSONObject(); appAttemptEntity.put(ATSConstants.ENTITY, applicationAttemptId.toString()); appAttemptEntity.put(ATSConstants.ENTITY_TYPE, ATSConstants.APPLICATION_ATTEMPT_ID); relatedEntities.put(appEntity); relatedEntities.put(appAttemptEntity); jsonObject.put(ATSConstants.RELATED_ENTITIES, relatedEntities); // TODO decide whether this goes into different events, // event info or other info. JSONArray events = new JSONArray(); JSONObject startEvent = new JSONObject(); startEvent.put(ATSConstants.TIMESTAMP, startTime); startEvent.put(ATSConstants.EVENT_TYPE, HistoryEventType.AM_STARTED.name()); events.put(startEvent); jsonObject.put(ATSConstants.EVENTS, events); return jsonObject; }
@Test(dependsOnMethods = "testSubmit") public void testGetTypeNames() throws Exception { WebResource resource = service.path("api/atlas/types"); ClientResponse clientResponse = resource .accept(Servlets.JSON_MEDIA_TYPE) .type(Servlets.JSON_MEDIA_TYPE) .method(HttpMethod.GET, ClientResponse.class); assertEquals(clientResponse.getStatus(), Response.Status.OK.getStatusCode()); String responseAsString = clientResponse.getEntity(String.class); Assert.assertNotNull(responseAsString); JSONObject response = new JSONObject(responseAsString); Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID)); final JSONArray list = response.getJSONArray(AtlasClient.RESULTS); Assert.assertNotNull(list); // Verify that primitive and core types are not returned String typesString = list.join(" "); Assert.assertFalse(typesString.contains(" \"__IdType\" ")); Assert.assertFalse(typesString.contains(" \"string\" ")); }
public void testNodeHelper(String path, String media) throws JSONException, Exception { WebResource r = resource(); Application app = new MockApp(1); nmContext.getApplications().put(app.getAppId(), app); HashMap<String, String> hash = addAppContainers(app); Application app2 = new MockApp(2); nmContext.getApplications().put(app2.getAppId(), app2); HashMap<String, String> hash2 = addAppContainers(app2); ClientResponse response = r.path("ws").path("v1").path("node").path(path).accept(media).get(ClientResponse.class); assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType()); JSONObject json = response.getEntity(JSONObject.class); JSONObject info = json.getJSONObject("apps"); assertEquals("incorrect number of elements", 1, info.length()); JSONArray appInfo = info.getJSONArray("app"); assertEquals("incorrect number of elements", 2, appInfo.length()); String id = appInfo.getJSONObject(0).getString("id"); if (id.matches(app.getAppId().toString())) { verifyNodeAppInfo(appInfo.getJSONObject(0), app, hash); verifyNodeAppInfo(appInfo.getJSONObject(1), app2, hash2); } else { verifyNodeAppInfo(appInfo.getJSONObject(0), app2, hash2); verifyNodeAppInfo(appInfo.getJSONObject(1), app, hash); } }
public static List<String> parseJSON(JSONArray idJSON) throws JSONException { List<String> ids = new ArrayList<String>(); for (int i = 0; i < idJSON.length(); i++) { ids.add(idJSON.getString(i)); } return ids; }
@Test public void testTasksQueryReduce() throws JSONException, Exception { WebResource r = resource(); Map<JobId, Job> jobsMap = appContext.getAllJobs(); for (JobId id : jobsMap.keySet()) { String jobId = MRApps.toString(id); String type = "r"; ClientResponse response = r.path("ws") .path("v1") .path("history") .path("mapreduce") .path("jobs") .path(jobId) .path("tasks") .queryParam("type", type) .accept(MediaType.APPLICATION_JSON) .get(ClientResponse.class); assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType()); JSONObject json = response.getEntity(JSONObject.class); assertEquals("incorrect number of elements", 1, json.length()); JSONObject tasks = json.getJSONObject("tasks"); JSONArray arr = tasks.getJSONArray("task"); assertEquals("incorrect number of elements", 1, arr.length()); verifyHsTask(arr, jobsMap.get(id), type); } }
private JSONArray enrichProperties(String operatorClass, JSONArray properties) throws JSONException { JSONArray result = new JSONArray(); for (int i = 0; i < properties.length(); i++) { JSONObject propJ = properties.getJSONObject(i); String propName = WordUtils.capitalize(propJ.getString("name")); String getPrefix = (propJ.getString("type").equals("boolean") || propJ.getString("type").equals("java.lang.Boolean")) ? "is" : "get"; String setPrefix = "set"; OperatorClassInfo oci = getOperatorClassWithGetterSetter( operatorClass, setPrefix + propName, getPrefix + propName); if (oci == null) { result.put(propJ); continue; } MethodInfo setterInfo = oci.setMethods.get(setPrefix + propName); MethodInfo getterInfo = oci.getMethods.get(getPrefix + propName); if ((getterInfo != null && getterInfo.omitFromUI) || (setterInfo != null && setterInfo.omitFromUI)) { continue; } if (setterInfo != null) { addTagsToProperties(setterInfo, propJ); } else if (getterInfo != null) { addTagsToProperties(getterInfo, propJ); } result.put(propJ); } return result; }
private ComboAvailableList() { this.playerCombos = new HashMap<>(); try { JSONObject configs = new JSONObject(FilesTools.readFile(ConfigPath.comboAvailableList)); Iterator iterator = configs.keys(); while (iterator.hasNext()) { String name = (String) iterator.next(); EGameObject player = EGameObject.getEnumByValue(name); if (player != EGameObject.NULL) { this.playerCombos.put(player, new ArrayList<>()); JSONArray combos = configs.getJSONArray(name); for (int i = 0; i < combos.length(); ++i) { this.playerCombos .get(player) .add( new Pair<>( combos.getJSONObject(i).getString("name"), combos.getJSONObject(i).getString("combo"))); } } } } catch (JSONException e) { e.printStackTrace(); } }
public static FinancialAccounting fromJSON(JSONObject jObj) throws JSONException, ParseException { if (jObj.has("result") && nullStringToNull(jObj, "result") != null) { jObj = jObj.getJSONObject("result"); } final FinancialAccounting financialAccounting = new FinancialAccounting.Builder().revision(jObj.getLong("revision")).build(); if (!jObj.isNull("items")) { final List<FinancialAccountingItem> items = new ArrayList<FinancialAccountingItem>(); final JSONArray jItems = jObj.getJSONArray("items"); for (int i = 0; i < jItems.length(); i++) { final JSONObject jItem = jItems.getJSONObject(i); final FinancialAccountingItem financialAccountingItem = FinancialAccountingItem.fromJSON(jItem); items.add(financialAccountingItem); } financialAccounting.setItems(items); } return financialAccounting; }
@Test public void getMBean() throws JSONException { JSONObject jo = r.path(MBeanServerSetup.TESTDOMAIN_NAME_TEST_BEAN) .accept("application/json") .get(JSONObject.class); assertEquals( "Not correct mbean name", jo.get("name"), MBeanServerSetup.TESTDOMAIN_NAME_TEST_BEAN); assertEquals( "Not correct attribute value " + jo, MBeanServerSetup.DEFAULT, jo.getJSONObject("attributes").getJSONObject("MyAttr").get("value")); boolean isWritable = ((Boolean) jo.getJSONObject("attributes").getJSONObject("MyAttr").get("writable")) .booleanValue(); assertTrue("Attrubute should be writable " + jo, isWritable); JSONArray operations = jo.getJSONArray("operations"); for (int i = 0; i < operations.length(); i++) { JSONObject op = operations.getJSONObject(i); if (op.getString("name").equals("simpleMethod")) { return; } } fail("Should contain simpleMethod " + jo); }
/** * 20141022. * * @param jObj the j obj * @param projectionStr the projection str * @return the FQDN value list cms * @throws JSONException the JSON exception */ static List<String> getFQDNValueListCMS(JSONObject jObj, String projectionStr) throws JSONException { final List<String> labelList = new ArrayList<String>(); if (!jObj.has("result")) { logger.error( "!!CMS_ERROR! result key is not in jOBJ in getFQDNValueListCMS!!: \njObj:" + PcStringUtils.renderJson(jObj)); return labelList; } JSONArray jArr = (JSONArray) jObj.get("result"); if (jArr == null || jArr.length() == 0) { return labelList; } for (int i = 0; i < jArr.length(); ++i) { JSONObject agentObj = jArr.getJSONObject(i); // properties can be null if (!agentObj.has(projectionStr)) { continue; } String label = (String) agentObj.get(projectionStr); if (label != null && !label.trim().isEmpty()) { labelList.add(label); } } return labelList; }
/** * In ode code, component names are used to identify a component though the variables storing * component names appear to be "type". While there's no harm in ode, here in build server, they * need to be separated. This method returns a name-type map, mapping the component names used in * ode to the corresponding type, aka fully qualified name. The type will be used to build apk. */ private static Map<String, String> createNameTypeMap(File assetsDir) throws IOException, JSONException { Map<String, String> nameTypeMap = Maps.newHashMap(); JSONArray simpleCompsJson = new JSONArray( Resources.toString( ProjectBuilder.class.getResource("/files/simple_components.json"), Charsets.UTF_8)); for (int i = 0; i < simpleCompsJson.length(); ++i) { JSONObject simpleCompJson = simpleCompsJson.getJSONObject(i); nameTypeMap.put(simpleCompJson.getString("name"), simpleCompJson.getString("type")); } File extCompsDir = new File(assetsDir, "external_comps"); if (!extCompsDir.exists()) { return nameTypeMap; } for (File extCompDir : extCompsDir.listFiles()) { if (!extCompDir.isDirectory()) { continue; } File extCompJsonFile = new File(extCompDir, "component.json"); JSONObject extCompJson = new JSONObject(Resources.toString(extCompJsonFile.toURI().toURL(), Charsets.UTF_8)); nameTypeMap.put(extCompJson.getString("name"), extCompJson.getString("type")); } return nameTypeMap; }
@Test public void testJSONArrayRepresentation() throws Exception { JSONArray array = new JSONArray(); array.put(CONTENT).put("Two").put("Three").put(1).put(2.0); _test(array, JSONOArrayResource.class, MediaType.APPLICATION_JSON_TYPE); }
@POST @Path("/addNewParentTestField") @Produces("text/plain") @Consumes(MediaType.APPLICATION_JSON) public String addNewParentField(JSONObject obj) { try { JSONArray data = obj.getJSONArray("parentfileds"); Set<ParentTestFields> ParentFieldList = new HashSet<ParentTestFields>(); for (int curr = 0; curr < data.length(); curr++) { ParentTestFields pf = new ParentTestFields(); pf.setParentField_IDName("PF"); pf.setParent_FieldName(data.getJSONObject(curr).getString("parent_FieldName")); // pf.setfTest_RangeID(testFieldsRangeDBDriver.getTestFieldRangeByID(Integer.parseInt(data.getJSONObject(curr).getString("fTest_RangeID")))); pf.setfTest_NameID( testNamesDBDriver.getTestNameByID( Integer.parseInt(data.getJSONObject(curr).getString("fTest_NameID")))); ParentFieldList.add(pf); } for (ParentTestFields pf : ParentFieldList) { parentfieldDBDriver.addNewParentTestField(pf); } } catch (JSONException e) { e.printStackTrace(); return null; } catch (Exception e) { System.out.println(e.getMessage()); return null; } return "TRUE"; }
@GET @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.TEXT_PLAIN) @Path("/userList") public String getHotTalkList() throws Exception { JSONObject jsonData = new JSONObject(); JSONArray jsonArray = new JSONArray(); try { List<Map<String, Object>> lst = new ArrayList<Map<String, Object>>(); lst = m_userDao.getUserList(); if (lst.isEmpty()) { jsonData.put("err", "데이터가 없습니다."); return jsonData.toString(); } Iterator<Map<String, Object>> itr = lst.iterator(); int i = 0; while (itr.hasNext()) { itr.next(); jsonArray.put(lst.get(i++)); } jsonData.put("userList", jsonArray); jsonData.put("err", ""); } catch (Exception ex) { ex.printStackTrace(); System.out.println(ex.getMessage()); jsonData.put("err", "시스템오류."); } // System.out.println("result : " + jsonData.toString()); return jsonData.toString(); }
/** * Test checks that a GET on the resource "/form/colours" with mime-type "application/json" shows * the appropriate colours based on the query param "match". */ @Test public void testGetColoursAsJson() { Response response = target().path("form").path("colours").request(MediaType.APPLICATION_JSON).get(); assertEquals( "GET on path '/form/colours' with mime type 'application/json' doesn't give expected response", Response.Status.OK, response.getStatusInfo()); JSONArray jsonArray = target() .path("form") .path("colours") .request(MediaType.APPLICATION_JSON) .get(JSONArray.class); assertEquals( "Returned JSONArray doesn't have expected number of entries", 7, jsonArray.length()); // with the query param "match" value "re" jsonArray = target("form/colours") .queryParam("match", "re") .request(MediaType.APPLICATION_JSON) .get(JSONArray.class); assertEquals( "Returned JSONArray doesn't have expected number of entries with the query param 'match=re'", 2, jsonArray.length()); }
@Test public void testNodeAppsState() throws JSONException, Exception { WebResource r = resource(); Application app = new MockApp(1); nmContext.getApplications().put(app.getAppId(), app); addAppContainers(app); MockApp app2 = new MockApp("foo", 1234, 2); nmContext.getApplications().put(app2.getAppId(), app2); HashMap<String, String> hash2 = addAppContainers(app2); app2.setState(ApplicationState.RUNNING); ClientResponse response = r.path("ws") .path("v1") .path("node") .path("apps") .queryParam("state", ApplicationState.RUNNING.toString()) .accept(MediaType.APPLICATION_JSON) .get(ClientResponse.class); assertEquals(MediaType.APPLICATION_JSON_TYPE, response.getType()); JSONObject json = response.getEntity(JSONObject.class); JSONObject info = json.getJSONObject("apps"); assertEquals("incorrect number of elements", 1, info.length()); JSONArray appInfo = info.getJSONArray("app"); assertEquals("incorrect number of elements", 1, appInfo.length()); verifyNodeAppInfo(appInfo.getJSONObject(0), app2, hash2); }
@Test public void shouldRetrieveDataFromXPathQuery() throws Exception { final String NODE_PATH = "/nodeForQuery"; URL postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items" + NODE_PATH); HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON); String payload = "{ \"properties\": {\"jcr:primaryType\": \"nt:unstructured\" }}"; connection.getOutputStream().write(payload.getBytes()); assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_CREATED)); connection.disconnect(); URL queryUrl = new URL(SERVER_URL + "/mode%3arepository/default/query"); connection = (HttpURLConnection) queryUrl.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/jcr+xpath"); payload = "//nodeForQuery"; connection.getOutputStream().write(payload.getBytes()); JSONObject queryResult = new JSONObject(getResponseFor(connection)); JSONArray results = (JSONArray) queryResult.get("rows"); assertThat(results.length(), is(1)); JSONObject result = (JSONObject) results.get(0); assertThat(result, is(notNullValue())); assertThat((String) result.get("jcr:path"), is(NODE_PATH)); assertThat((String) result.get("jcr:primaryType"), is("nt:unstructured")); }
@Nullable private <T> Collection<T> parseOptionalArray( boolean shouldUseNestedValueJson, JSONObject json, JsonWeakParser<T> jsonParser, String... path) throws JSONException { if (shouldUseNestedValueJson) { final JSONObject js = JsonParseUtil.getNestedOptionalObject(json, path); if (js == null) { return null; } return parseArray(js, jsonParser, VALUE_ATTR); } else { final JSONArray jsonArray = JsonParseUtil.getNestedOptionalArray(json, path); if (jsonArray == null) { return null; } final Collection<T> res = new ArrayList<T>(jsonArray.length()); for (int i = 0; i < jsonArray.length(); i++) { res.add(jsonParser.parse(jsonArray.get(i))); } return res; } }
@Test public void shouldRespectQueryOffsetAndLimit() throws Exception { final String NODE_PATH = "nodeForOffsetAndLimitTest"; createNode("/" + NODE_PATH, 1); createNode("/" + NODE_PATH, 2); createNode("/" + NODE_PATH, 3); createNode("/" + NODE_PATH, 4); URL queryUrl = new URL(SERVER_URL + "/mode%3arepository/default/query?offset=1&limit=2"); HttpURLConnection connection = (HttpURLConnection) queryUrl.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/jcr+xpath"); String payload = "//element(" + NODE_PATH + ") order by @foo"; connection.getOutputStream().write(payload.getBytes()); JSONObject queryResult = new JSONObject(getResponseFor(connection)); JSONArray results = (JSONArray) queryResult.get("rows"); assertThat(results.length(), is(2)); JSONObject result = (JSONObject) results.get(0); assertThat(result, is(notNullValue())); assertThat((String) result.get("jcr:path"), is("/" + NODE_PATH + "[2]")); result = (JSONObject) results.get(1); assertThat(result, is(notNullValue())); assertThat((String) result.get("jcr:path"), is("/" + NODE_PATH + "[3]")); }
public Object getAttribute(String userAttribute, boolean optional) throws InvalidClaimException { Object attribute = null; for (org.xdi.ldap.model.CustomAttribute customAttribute : customAttributes) { if (customAttribute.getName().equals(userAttribute)) { List<String> values = customAttribute.getValues(); if (values != null) { if (values.size() == 1) { attribute = values.get(0); } else { JSONArray array = new JSONArray(); for (String v : values) { array.put(v); } attribute = array; } } break; } } if (attribute != null) { return attribute; } else if (optional) { return attribute; } else { throw new InvalidClaimException("The claim " + userAttribute + " was not found."); } }
// @FixFor( "MODE-886" ) @Test public void shouldAllowJcrSql2Query() throws Exception { final String NODE_PATH = "nodeForJcrSql2QueryTest"; createNode("/" + NODE_PATH, 1); createNode("/" + NODE_PATH + "/child", 1); createNode("/" + NODE_PATH + "/child", 2); createNode("/" + NODE_PATH + "/child", 3); createNode("/" + NODE_PATH + "/child", 4); URL queryUrl = new URL(SERVER_URL + "/mode%3arepository/default/query"); HttpURLConnection connection = (HttpURLConnection) queryUrl.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/jcr+sql2"); String payload = "SELECT * FROM [nt:unstructured] WHERE ISCHILDNODE('/" + NODE_PATH + "')"; connection.getOutputStream().write(payload.getBytes()); JSONObject queryResult = new JSONObject(getResponseFor(connection)); JSONArray results = (JSONArray) queryResult.get("rows"); assertThat(results.length(), is(4)); }
@Test public void testSubmit() throws Exception { for (HierarchicalTypeDefinition typeDefinition : typeDefinitions) { String typesAsJSON = TypesSerialization.toJson(typeDefinition); System.out.println("typesAsJSON = " + typesAsJSON); WebResource resource = service.path("api/atlas/types"); ClientResponse clientResponse = resource .accept(Servlets.JSON_MEDIA_TYPE) .type(Servlets.JSON_MEDIA_TYPE) .method(HttpMethod.POST, ClientResponse.class, typesAsJSON); assertEquals(clientResponse.getStatus(), Response.Status.CREATED.getStatusCode()); String responseAsString = clientResponse.getEntity(String.class); Assert.assertNotNull(responseAsString); JSONObject response = new JSONObject(responseAsString); JSONArray typesAdded = response.getJSONArray(AtlasClient.TYPES); assertEquals(typesAdded.length(), 1); assertEquals(typesAdded.getJSONObject(0).getString("name"), typeDefinition.typeName); Assert.assertNotNull(response.get(AtlasClient.REQUEST_ID)); } }
@Test public void shouldRetrieveRootNodeForValidRepository() throws Exception { URL postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/"); HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON); JSONObject body = new JSONObject(getResponseFor(connection)); assertThat(body.length(), is(2)); JSONObject properties = body.getJSONObject("properties"); assertThat(properties, is(notNullValue())); assertThat(properties.length(), is(2)); assertThat(properties.getString("jcr:primaryType"), is("mode:root")); assertThat(properties.get("jcr:uuid"), is(notNullValue())); JSONArray children = body.getJSONArray("children"); assertThat(children.length(), is(1)); assertThat(children.getString(0), is("jcr:system")); assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_OK)); connection.disconnect(); }
public void guardarCambiosGrupo() { JSONArray lista = new JSONArray(); for (int i = 0; i < listaTecnicosGrupo.size(); i++) { lista.put(listaTecnicosGrupo.get(i).getMail()); } JSONObject respuesta = new IGrupo() .modificiarGrupo( sesion.getTokenId(), grupoSeleccionado, nuevoNombreGrupo, lista, parsearMail(nuevoAdministrador)); try { FacesMessage msg; if (respuesta.getInt("status") == 2) { msg = new FacesMessage("Grupo modificado con exito", ""); listarGrupos(); } else msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error al modificar grupo.", ""); FacesContext.getCurrentInstance().addMessage(null, msg); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@Test public void shouldPostNodeToValidPathWithPrimaryType() throws Exception { URL postUrl = new URL(SERVER_URL + "/mode%3arepository/default/items/nodeA"); HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", MediaType.APPLICATION_JSON); String payload = "{ \"properties\": {\"jcr:primaryType\": \"nt:unstructured\", \"testProperty\": \"testValue\", \"multiValuedProperty\": [\"value1\", \"value2\"]}}"; connection.getOutputStream().write(payload.getBytes()); JSONObject body = new JSONObject(getResponseFor(connection)); assertThat(body.length(), is(1)); JSONObject properties = body.getJSONObject("properties"); assertThat(properties, is(notNullValue())); assertThat(properties.length(), is(3)); assertThat(properties.getString("jcr:primaryType"), is("nt:unstructured")); assertThat(properties.getString("testProperty"), is("testValue")); assertThat(properties.get("multiValuedProperty"), instanceOf(JSONArray.class)); JSONArray values = properties.getJSONArray("multiValuedProperty"); assertThat(values, is(notNullValue())); assertThat(values.length(), is(2)); assertThat(values.getString(0), is("value1")); assertThat(values.getString(1), is("value2")); assertThat(connection.getResponseCode(), is(HttpURLConnection.HTTP_CREATED)); connection.disconnect(); }
public List<NombreMail> listarAdministradores() { JSONObject respuesta = new IGrupo().listarAdministradores(sesion.getTokenId()); JSONArray admins = null; listaAdministradores.clear(); try { admins = respuesta.getJSONArray("lista"); if (admins != null) { for (int i = 0; i < admins.length(); i++) { JSONObject ob = admins.getJSONObject(i); NombreMail b = new NombreMail(); b.setMail(ob.getString("correo")); b.setNombre(ob.getString("nombre") + " " + ob.getString("apellido")); listaAdministradores.add(b); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } return listaAdministradores; }
@Test public void step3_getUsers2() { JSONArray users = target().path("resources/users/").request("application/json").get(JSONArray.class); assertTrue(users != null); assertTrue(users.length() == 1); }