@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]")); }
@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 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")); }
public static JSONArray concatArray(JSONArray... arrs) throws JSONException { JSONArray result = new JSONArray(); for (JSONArray arr : arrs) { for (int i = 0; i < arr.length(); i++) { result.put(arr.get(i)); } } return result; }
/** * Test Supplier Url filter Service Query option. * * @throws IOException * @throws JSONException */ @Test public void testSupplierUrlFilter() throws IOException, JSONException { JSONObject jo; HttpResponse resp = RequestExecutionHelper.executeGetRequest( ENTITY_NAME + "?$format=json&$filter=EmailAddress%20eq%20'*****@*****.**'&$top=1", true); JSONArray ja = RequestExecutionHelper.getJSONArrayofResults(resp.getBody()); assertNotNull("Unable to parse JSON response", ja); jo = (JSONObject) ja.get(0); assertEquals("Supplier not filtered Supplier Id", "100000045", jo.getString("SupplierId")); }
/** * Test if Supplier URL Skip Service Query Option. * * @throws JSONException * @throws IOException */ @Test public void testSupplierUrlSkip() throws JSONException, IOException { JSONObject jo; HttpResponse resp = RequestExecutionHelper.executeGetRequest( ENTITY_NAME + "?$format=json&$orderby=SupplierId&$skip=1", true); JSONArray ja = RequestExecutionHelper.getJSONArrayofResults(resp.getBody()); assertNotNull("Unable to parse JSON response", ja); jo = (JSONObject) ja.get(0); assertEquals( "First Supplier in the ordered response not skipped", "100000042", jo.getString("SupplierId")); }
/** * Test Supplier Url Top and Orderby Service Query option. * * @throws IOException * @throws JSONException */ @Test public void testSupplierUrlTopOrderby() throws IOException, JSONException { JSONObject jo; HttpResponse resp = RequestExecutionHelper.executeGetRequest( ENTITY_NAME + "?$format=json&$orderby=SupplierId&$top=1", true); JSONArray ja = RequestExecutionHelper.getJSONArrayofResults(resp.getBody()); assertNotNull("Unable to parse JSON response", ja); jo = (JSONObject) ja.get(0); assertEquals( "Suppliers not orderedby Supplier Id in ascending order", "100000041", jo.getString("SupplierId")); }
private <T> Collection<T> parseArray( JSONObject jsonObject, JsonWeakParser<T> jsonParser, String arrayAttribute) throws JSONException { // String type = jsonObject.getString("type"); // final String name = jsonObject.getString("name"); final JSONArray valueObject = jsonObject.optJSONArray(arrayAttribute); if (valueObject == null) { return new ArrayList<T>(); } Collection<T> res = new ArrayList<T>(valueObject.length()); for (int i = 0; i < valueObject.length(); i++) { res.add(jsonParser.parse(valueObject.get(i))); } return res; }
@Override public String execute(HttpServletRequest request) throws Exception { CourseClient cC = new CourseClient(); ArrayList<String> names = new ArrayList<>(); JSONArray courses = cC.findAll_JSON(JSONArray.class); for (int i = 0; i < courses.length(); i++) { JSONObject course = (JSONObject) courses.get(i); names.add(course.getString("name")); } Gson json = new Gson(); String str = json.toJson(names); return str; }
/** * 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")); }
/** * 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_OK, resp.getResponseCode()); }
public CompositeValueModel(JSONObject values) { try { Iterator<String> i = values.keys(); while (i.hasNext()) { String childTypeUri = i.next(); Object value = values.get(childTypeUri); if (value instanceof JSONArray) { JSONArray valueArray = (JSONArray) value; for (int j = 0; j < valueArray.length(); j++) { add(childTypeUri, createTopicModel(childTypeUri, valueArray.get(j))); } } else { put(childTypeUri, createTopicModel(childTypeUri, value)); } } } catch (Exception e) { throw new RuntimeException( "Parsing CompositeValueModel failed (JSONObject=" + values + ")", e); } }
@GET @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Path("identificateFiles/") public Response identificateFiles(@QueryParam("uuids") JSONArray uuids) { List<java.nio.file.Path> paths = new ArrayList<>(); for (int i = 0; i < uuids.length(); i++) { try { String uuid = (String) uuids.get(i); paths.add(new File(System.getProperty("user.dir")).toPath().resolve("books").resolve(uuid)); } catch (JSONException e) { return Response.serverError().build(); } } IdentificateBooks idBooks = new IdentificateBooks(paths); IdentificationResult identificationResult = idBooks.startIdentification(); logger.info(identificationResult.getResult()); return Response.ok(identificationResult.getResult()).build(); }
private boolean parseSingleClause(JSONObject jsonCriteria) throws JSONException { String operator = jsonCriteria.getString(OPERATOR_KEY); if (operator.equals(OPERATOR_BETWEEN) || operator.equals(OPERATOR_BETWEENINCLUSIVE) || operator.equals(OPERATOR_IBETWEEN) || operator.equals(OPERATOR_IBETWEENINCLUSIVE)) { return parseBetween(jsonCriteria, operator, true); } Object value = jsonCriteria.has(VALUE_KEY) ? jsonCriteria.get(VALUE_KEY) : null; if (operator.equals(OPERATOR_EXISTS)) { // not supported return mainOperatorIsAnd; } String fieldName = jsonCriteria.getString(FIELD_NAME_KEY); // translate to a OR for each value if (value instanceof JSONArray) { final JSONArray jsonArray = (JSONArray) value; final JSONObject advancedCriteria = new JSONObject(); advancedCriteria.put(OPERATOR_KEY, OPERATOR_OR); final JSONArray subCriteria = new JSONArray(); for (int i = 0; i < jsonArray.length(); i++) { final JSONObject subCriterion = new JSONObject(); subCriterion.put(OPERATOR_KEY, operator); subCriterion.put(FIELD_NAME_KEY, fieldName); subCriterion.put(VALUE_KEY, jsonArray.get(i)); subCriteria.put(i, subCriterion); } advancedCriteria.put(CRITERIA_KEY, subCriteria); return parseAdvancedCriteria(advancedCriteria); } // Retrieves the UTC time zone offset of the client if (jsonCriteria.has("minutesTimezoneOffset")) { int clientMinutesTimezoneOffset = Integer.parseInt(jsonCriteria.get("minutesTimezoneOffset").toString()); Calendar now = Calendar.getInstance(); // Obtains the UTC time zone offset of the server int serverMinutesTimezoneOffset = (now.get(Calendar.ZONE_OFFSET) + now.get(Calendar.DST_OFFSET)) / (1000 * 60); // Obtains the time zone offset between the server and the client clientUTCMinutesTimeZoneDiff = clientMinutesTimezoneOffset; UTCServerMinutesTimeZoneDiff = serverMinutesTimezoneOffset; } if (operator.equals(OPERATOR_ISNULL) || operator.equals(OPERATOR_NOTNULL)) { value = null; } // if a comparison is done on an equal date then replace // with a between start time and end time on that date if (operator.equals(OPERATOR_EQUALS) || operator.equals(OPERATOR_EQUALSFIELD)) { Object curValue = recordMap.get(fieldName); if (curValue instanceof Date) { if (operator.equals(OPERATOR_EQUALS)) { return parseSimpleClause(fieldName, OPERATOR_GREATEROREQUAL, value) && parseSimpleClause(fieldName, OPERATOR_LESSOREQUAL, value); } else { return parseSimpleClause(fieldName, OPERATOR_GREATEROREQUALFIELD, value) && parseSimpleClause(fieldName, OPERATOR_LESSOREQUALFIElD, value); } } } return parseSimpleClause(fieldName, operator, value); }
@Parameters({"redirectUris", "sectorIdentifierUri", "logoutUri"}) @Test public void requestClientAssociate2( final String redirectUris, final String sectorIdentifierUri, final String logoutUri) throws Exception { showTitle("requestClientAssociate2"); RegisterRequest registerRequest = new RegisterRequest( ApplicationType.WEB, "oxAuth test app", StringUtils.spaceSeparatedToList(redirectUris)); registerRequest.setContacts(Arrays.asList("*****@*****.**", "*****@*****.**")); registerRequest.setScopes( Arrays.asList( "openid", "address", "profile", "email", "phone", "clientinfo", "invalid_scope")); registerRequest.setLogoUri("http://www.gluu.org/wp-content/themes/gluursn/images/logo.png"); registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_JWT); registerRequest.setPolicyUri("http://www.gluu.org/policy"); registerRequest.setJwksUri("http://www.gluu.org/jwks"); registerRequest.setSectorIdentifierUri(sectorIdentifierUri); registerRequest.setSubjectType(SubjectType.PAIRWISE); registerRequest.setRequestUris(Arrays.asList("http://www.gluu.org/request")); registerRequest.setFrontChannelLogoutUris(Lists.newArrayList(logoutUri)); registerRequest.setFrontChannelLogoutSessionRequired(true); registerRequest.setIdTokenSignedResponseAlg(SignatureAlgorithm.RS512); registerRequest.setIdTokenEncryptedResponseAlg(KeyEncryptionAlgorithm.RSA1_5); registerRequest.setIdTokenEncryptedResponseEnc(BlockEncryptionAlgorithm.A128CBC_PLUS_HS256); registerRequest.setUserInfoSignedResponseAlg(SignatureAlgorithm.RS384); registerRequest.setUserInfoEncryptedResponseAlg(KeyEncryptionAlgorithm.A128KW); registerRequest.setUserInfoEncryptedResponseEnc(BlockEncryptionAlgorithm.A128GCM); registerRequest.setRequestObjectSigningAlg(SignatureAlgorithm.RS256); registerRequest.setRequestObjectEncryptionAlg(KeyEncryptionAlgorithm.A256KW); registerRequest.setRequestObjectEncryptionEnc(BlockEncryptionAlgorithm.A256CBC_PLUS_HS512); registerRequest.setTokenEndpointAuthMethod(AuthenticationMethod.CLIENT_SECRET_JWT); registerRequest.setTokenEndpointAuthSigningAlg(SignatureAlgorithm.ES256); RegisterClient registerClient = new RegisterClient(registrationEndpoint); registerClient.setRequest(registerRequest); registerClient.setExecutor(clientExecutor(true)); RegisterResponse response = registerClient.exec(); showClient(registerClient); assertEquals(response.getStatus(), 200, "Unexpected response code: " + response.getEntity()); assertNotNull(response.getClientId()); assertNotNull(response.getClientSecret()); assertNotNull(response.getRegistrationAccessToken()); assertNotNull(response.getClientSecretExpiresAt()); assertNotNull(response.getClaims().get(SCOPES.toString())); assertNotNull(response.getClaims().get(FRONT_CHANNEL_LOGOUT_SESSION_REQUIRED.toString())); assertTrue( Boolean.parseBoolean( response.getClaims().get(FRONT_CHANNEL_LOGOUT_SESSION_REQUIRED.toString()))); assertNotNull(response.getClaims().get(FRONT_CHANNEL_LOGOUT_URI.toString())); assertTrue( new JSONArray(response.getClaims().get(FRONT_CHANNEL_LOGOUT_URI.toString())) .getString(0) .equals(logoutUri)); assertNotNull(response.getClaims().get(ID_TOKEN_SIGNED_RESPONSE_ALG.toString())); assertEquals( SignatureAlgorithm.RS512, SignatureAlgorithm.fromString( response.getClaims().get(ID_TOKEN_SIGNED_RESPONSE_ALG.toString()))); assertNotNull(response.getClaims().get(ID_TOKEN_ENCRYPTED_RESPONSE_ALG.toString())); assertEquals( KeyEncryptionAlgorithm.RSA1_5, KeyEncryptionAlgorithm.fromName( response.getClaims().get(ID_TOKEN_ENCRYPTED_RESPONSE_ALG.toString()))); assertNotNull(response.getClaims().get(ID_TOKEN_ENCRYPTED_RESPONSE_ENC.toString())); assertEquals( BlockEncryptionAlgorithm.A128CBC_PLUS_HS256, BlockEncryptionAlgorithm.fromName( response.getClaims().get(ID_TOKEN_ENCRYPTED_RESPONSE_ENC.toString()))); assertNotNull(response.getClaims().get(USERINFO_SIGNED_RESPONSE_ALG.toString())); assertEquals( SignatureAlgorithm.RS384, SignatureAlgorithm.fromString( response.getClaims().get(USERINFO_SIGNED_RESPONSE_ALG.toString()))); assertNotNull(response.getClaims().get(USERINFO_ENCRYPTED_RESPONSE_ALG.toString())); assertEquals( KeyEncryptionAlgorithm.A128KW, KeyEncryptionAlgorithm.fromName( response.getClaims().get(USERINFO_ENCRYPTED_RESPONSE_ALG.toString()))); assertNotNull(response.getClaims().get(USERINFO_ENCRYPTED_RESPONSE_ENC.toString())); assertEquals( BlockEncryptionAlgorithm.A128GCM, BlockEncryptionAlgorithm.fromName( response.getClaims().get(USERINFO_ENCRYPTED_RESPONSE_ENC.toString()))); assertNotNull(response.getClaims().get(REQUEST_OBJECT_SIGNING_ALG.toString())); assertEquals( SignatureAlgorithm.RS256, SignatureAlgorithm.fromString( response.getClaims().get(REQUEST_OBJECT_SIGNING_ALG.toString()))); assertNotNull(response.getClaims().get(REQUEST_OBJECT_ENCRYPTION_ALG.toString())); assertEquals( KeyEncryptionAlgorithm.A256KW, KeyEncryptionAlgorithm.fromName( response.getClaims().get(REQUEST_OBJECT_ENCRYPTION_ALG.toString()))); assertNotNull(response.getClaims().get(REQUEST_OBJECT_ENCRYPTION_ENC.toString())); assertEquals( BlockEncryptionAlgorithm.A256CBC_PLUS_HS512, BlockEncryptionAlgorithm.fromName( response.getClaims().get(REQUEST_OBJECT_ENCRYPTION_ENC.toString()))); assertNotNull(response.getClaims().get(TOKEN_ENDPOINT_AUTH_METHOD.toString())); assertEquals( AuthenticationMethod.CLIENT_SECRET_JWT, AuthenticationMethod.fromString( response.getClaims().get(TOKEN_ENDPOINT_AUTH_METHOD.toString()))); assertNotNull(response.getClaims().get(TOKEN_ENDPOINT_AUTH_SIGNING_ALG.toString())); assertEquals( SignatureAlgorithm.ES256, SignatureAlgorithm.fromString( response.getClaims().get(TOKEN_ENDPOINT_AUTH_SIGNING_ALG.toString()))); JSONArray scopesJsonArray = new JSONArray(response.getClaims().get(SCOPES.toString())); List<String> scopes = new ArrayList<String>(); for (int i = 0; i < scopesJsonArray.length(); i++) { scopes.add(scopesJsonArray.get(i).toString()); } assertTrue(scopes.contains("openid")); assertTrue(scopes.contains("address")); assertTrue(scopes.contains("email")); assertTrue(scopes.contains("profile")); assertTrue(scopes.contains("phone")); assertTrue(scopes.contains("clientinfo")); clientId1 = response.getClientId(); registrationAccessToken1 = response.getRegistrationAccessToken(); registrationClientUri1 = response.getRegistrationClientUri(); }
@Test public void testGetDomainsAsJSON() throws JSONException { JSONArray ja = r.path("domains").accept("application/json").get(JSONArray.class); assertEquals("No domain in " + ja, MBeanServerSetup.TESTDOMAIN, ja.get(0)); }