Search in sources :

Example 36 with JsonArray

use of javax.json.JsonArray in project sling by apache.

the class JsonSupportTest method testToJson.

@Test
public void testToJson() {
    Map<String, Object> map = ImmutableMap.<String, Object>builder().put("prop1", "value1").put("prop2", ImmutableList.of("value2", "value3")).put("prop3", ImmutableMap.of("prop4", "value4")).build();
    JsonObject obj = toJson(map);
    assertEquals("value1", obj.getString("prop1"));
    JsonArray array = obj.getJsonArray("prop2");
    assertEquals(2, array.size());
    assertEquals("value2", array.getString(0));
    assertEquals("value3", array.getString(1));
    JsonObject prop3 = obj.getJsonObject("prop3");
    assertEquals("value4", prop3.getString("prop4"));
}
Also used : JsonArray(javax.json.JsonArray) JsonObject(javax.json.JsonObject) JsonObject(javax.json.JsonObject) JsonSupport.parseObject(org.apache.sling.maven.bundlesupport.JsonSupport.parseObject) Test(org.junit.Test)

Example 37 with JsonArray

use of javax.json.JsonArray in project sling by apache.

the class JsonSupportTest method testParseArray.

@Test
public void testParseArray() {
    JsonArray array = parseArray("[{\"prop1\":123}]");
    assertEquals(1, array.size());
    assertEquals(123, array.getJsonObject(0).getInt("prop1"));
}
Also used : JsonArray(javax.json.JsonArray) Test(org.junit.Test)

Example 38 with JsonArray

use of javax.json.JsonArray in project sling by apache.

the class BasicLauncherIT method testSpecificStartLevel.

@Test
@Retry(timeoutMsec = U.LONG_TIMEOUT_MSEC, intervalMsec = U.STD_INTERVAL)
public void testSpecificStartLevel() throws Exception {
    // This bundle should only be installed, as it's set to start level 99
    final String symbolicName = "org.apache.commons.collections";
    assertEquals("Expecting bundle " + symbolicName + " to be installed", "Installed", osgiConsole.getBundleState(symbolicName));
    // Start level is in the props array, with key="Start Level"
    final JsonObject status = U.getBundleData(C, client, symbolicName);
    final JsonArray props = status.getJsonArray("data").getJsonObject(0).getJsonArray("props");
    final String KEY = "key";
    final String SL = "Start Level";
    boolean found = false;
    for (int i = 0; i < props.size(); i++) {
        final JsonObject o = props.getJsonObject(i);
        if (o.containsKey(KEY) && SL.equals(o.getString(KEY))) {
            found = true;
            assertEquals("Expecting the start level that's set in provisioning model", 99, o.getInt("value"));
        }
    }
    assertTrue("Expecting start level to be found in JSON output", found);
}
Also used : JsonArray(javax.json.JsonArray) JsonObject(javax.json.JsonObject) Test(org.junit.Test) Retry(org.apache.sling.commons.testing.junit.Retry)

Example 39 with JsonArray

use of javax.json.JsonArray in project sling by apache.

the class PlumberServletTest method testAdditionalBindingsAndWriter.

@Test
public void testAdditionalBindingsAndWriter() throws Exception {
    String testBinding = "testBinding";
    String testBindingLength = testBinding + "Length";
    String bindingValue = "testBindingValue";
    String pathLengthParam = "pathLength";
    String bindings = "{\"" + testBinding + "\":\"" + bindingValue + "\"}";
    String respObject = "{\"" + pathLengthParam + "\":\"${path.get(\\\"dummyGrandChild\\\").length}\",\"" + testBindingLength + "\":\"${" + testBinding + ".length}\"}";
    SlingHttpServletRequest request = mockPlumberServletRequest(context.resourceResolver(), dummyTreePath, null, bindings.toString(), respObject.toString(), null, null);
    servlet.execute(request, response, false);
    assertDummyTree();
    JsonObject response = Json.createReader(new StringReader(stringResponse.toString())).readObject();
    JsonArray array = response.getJsonArray(OutputWriter.KEY_ITEMS);
    for (int i = 0; i < array.size(); i++) {
        JsonObject object = array.getJsonObject(i);
        assertNotNull("there should be an object returned at each time", object);
        String path = object.getString(CustomWriter.PATH_KEY);
        assertNotNull("the string path should be returned for each item, containing the path of the resource");
        String pathLength = object.getString(pathLengthParam);
        assertNotNull("there should be a pathLength param, as specified in the writer", pathLength);
        assertEquals("Pathlength should be the string representation of the path length", path.length() + "", pathLength);
        String testBindingLengthValue = object.getString(testBindingLength);
        assertNotNull("testBindingLength should be there", testBindingLengthValue);
        assertEquals("testBindingLength should be the string representation of the additional binding length", bindingValue.length() + "", testBindingLengthValue);
    }
}
Also used : JsonArray(javax.json.JsonArray) StringReader(java.io.StringReader) JsonObject(javax.json.JsonObject) SlingHttpServletRequest(org.apache.sling.api.SlingHttpServletRequest) AbstractPipeTest(org.apache.sling.pipes.AbstractPipeTest) ContainerPipeTest(org.apache.sling.pipes.ContainerPipeTest) Test(org.junit.Test)

Example 40 with JsonArray

use of javax.json.JsonArray in project sling by apache.

the class PostServletPrivilegesUpdateTest method testUpdatePropertyPrivilegesAndEvents.

/**
     * Test for SLING-897 fix: 
     * 1. Updating a property requires jcr:modifyProperties privilege on node.
     * 2. When changing an existing property observers should receive a PROPERTY_CHANGED event instead 
     *     of a PROPERTY_REMOVED event and a PROPERTY_ADDED event
     */
@Test
// TODO fails on jackrabbit 2.6.5 and on Oak
@Ignore
public void testUpdatePropertyPrivilegesAndEvents() throws IOException, JsonException, RepositoryException, InterruptedException {
    //1. Create user as admin (OK)
    // curl -F:name=myuser -Fpwd=password -FpwdConfirm=password http://admin:admin@localhost:8080/system/userManager/user.create.html
    testUserId = H.createTestUser();
    //2. Create node as admin (OK)
    // curl -F:nameHint=node -FpropOne=propOneValue1 -FpropOne=propOneValue2 -FpropTwo=propTwoValue http://admin:admin@localhost:8080/test/
    final String createTestNodeUrl = postUrl + SlingPostConstants.DEFAULT_CREATE_SUFFIX;
    NameValuePairList clientNodeProperties = new NameValuePairList();
    clientNodeProperties.add(SlingPostConstants.RP_NODE_NAME_HINT, testName.getMethodName());
    clientNodeProperties.add("propOne", "propOneValue1");
    clientNodeProperties.add("propOne", "propOneValue2");
    clientNodeProperties.add("propTwo", "propTwoValue");
    String testNodeUrl = H.getTestClient().createNode(createTestNodeUrl, clientNodeProperties, null, false);
    String content = H.getContent(testNodeUrl + ".json", HttpTest.CONTENT_TYPE_JSON);
    JsonObject json = JsonUtil.parseObject(content);
    Object propOneObj = json.get("propOne");
    assertTrue(propOneObj instanceof JsonArray);
    assertEquals(2, ((JsonArray) propOneObj).size());
    assertEquals("propOneValue1", ((JsonArray) propOneObj).getString(0));
    assertEquals("propOneValue2", ((JsonArray) propOneObj).getString(1));
    Object propTwoObj = json.get("propTwo");
    assertTrue(propTwoObj instanceof JsonString);
    assertEquals("propTwoValue", ((JsonString) propTwoObj).getString());
    //3. Attempt to update property of node as testUser (500: javax.jcr.AccessDeniedException: /test/node/propOne: not allowed to add or modify item)
    // curl -FpropOne=propOneValueChanged -FpropTwo=propTwoValueChanged1 -FpropTwo=propTwoValueChanged2 http://myuser:password@localhost:8080/test/node
    List<NameValuePair> postParams = new ArrayList<NameValuePair>();
    postParams.add(new NameValuePair("propOne", "propOneValueChanged"));
    postParams.add(new NameValuePair("propTwo", "propTwoValueChanged1"));
    postParams.add(new NameValuePair("propTwo", "propTwoValueChanged2"));
    Credentials testUserCreds = new UsernamePasswordCredentials(testUserId, "testPwd");
    String expectedMessage = "Expected javax.jcr.AccessDeniedException";
    H.assertAuthenticatedPostStatus(testUserCreds, testNodeUrl, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, postParams, expectedMessage);
    //4. Grant jcr:modifyProperties rights to testUser as admin (OK)
    // curl -FprincipalId=myuser -Fprivilege@jcr:modifyProperties=granted http://admin:admin@localhost:8080/test/node.modifyAce.html
    Map<String, String> nodeAceProperties = new HashMap<String, String>();
    nodeAceProperties.put("principalId", testUserId);
    nodeAceProperties.put("privilege@jcr:modifyProperties", "granted");
    H.getTestClient().createNode(testNodeUrl + ".modifyAce.html", nodeAceProperties);
    //use a davex session to verify the correct JCR events are delivered
    Repository repository = JcrUtils.getRepository(HttpTest.HTTP_BASE_URL + "/server/");
    Session jcrSession = null;
    TestEventListener listener = new TestEventListener();
    ObservationManager observationManager = null;
    try {
        jcrSession = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
        observationManager = jcrSession.getWorkspace().getObservationManager();
        String testNodePath = testNodeUrl.substring(HttpTest.HTTP_BASE_URL.length());
        observationManager.addEventListener(listener, //event types
        Event.PROPERTY_ADDED | Event.PROPERTY_CHANGED | Event.PROPERTY_REMOVED, //absPath
        testNodePath, //isDeep 
        true, //uuid
        null, //nodeTypeName
        null, //noLocal
        false);
        //5. Attempt to update properties of node (OK)
        // curl -FpropOne=propOneValueChanged -FpropTwo=propTwoValueChanged1 -FpropTwo=propTwoValueChanged2 http://myuser:password@localhost:8080/test/node
        H.assertAuthenticatedPostStatus(testUserCreds, testNodeUrl, HttpServletResponse.SC_OK, postParams, expectedMessage);
        //verify the change happened
        String afterUpdateContent = H.getContent(testNodeUrl + ".json", HttpTest.CONTENT_TYPE_JSON);
        JsonObject afterUpdateJson = JsonUtil.parseObject(afterUpdateContent);
        Object afterUpdatePropOneObj = afterUpdateJson.get("propOne");
        assertTrue(afterUpdatePropOneObj instanceof JsonArray);
        assertEquals(1, ((JsonArray) afterUpdatePropOneObj).size());
        assertEquals("propOneValueChanged", ((JsonArray) afterUpdatePropOneObj).getString(0));
        Object afterUpdatePropTwoObj = afterUpdateJson.get("propTwo");
        assertTrue(afterUpdatePropTwoObj instanceof JsonArray);
        assertEquals(2, ((JsonArray) afterUpdatePropTwoObj).size());
        assertEquals("propTwoValueChanged1", ((JsonArray) afterUpdatePropTwoObj).getString(0));
        assertEquals("propTwoValueChanged2", ((JsonArray) afterUpdatePropTwoObj).getString(1));
        //wait for the expected JCR events to be delivered
        for (int second = 0; second < 15; second++) {
            if (listener.getEventBundlesProcessed() > 0) {
                break;
            }
            Thread.sleep(1000);
        }
        assertEquals("One property added event was expected: " + listener.toString(), 1, listener.addedProperties.size());
        assertEquals(testNodePath + "/propTwo", listener.addedProperties.get(0));
        assertEquals("One property removed event was expected: " + listener.toString(), 1, listener.removedProperties.size());
        assertEquals(testNodePath + "/propTwo", listener.removedProperties.get(0));
        assertEquals("One property changed event was expected: " + listener.toString(), 1, listener.changedProperties.size());
        assertEquals(testNodePath + "/propOne", listener.changedProperties.get(0));
    } finally {
        //cleanup
        if (observationManager != null) {
            observationManager.removeEventListener(listener);
        }
        jcrSession.logout();
        repository = null;
    }
}
Also used : NameValuePair(org.apache.commons.httpclient.NameValuePair) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) JsonObject(javax.json.JsonObject) ObservationManager(javax.jcr.observation.ObservationManager) JsonString(javax.json.JsonString) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) JsonArray(javax.json.JsonArray) SimpleCredentials(javax.jcr.SimpleCredentials) Repository(javax.jcr.Repository) JsonObject(javax.json.JsonObject) NameValuePairList(org.apache.sling.commons.testing.integration.NameValuePairList) JsonString(javax.json.JsonString) UsernamePasswordCredentials(org.apache.commons.httpclient.UsernamePasswordCredentials) Credentials(org.apache.commons.httpclient.Credentials) SimpleCredentials(javax.jcr.SimpleCredentials) Session(javax.jcr.Session) Ignore(org.junit.Ignore) HttpTest(org.apache.sling.commons.testing.integration.HttpTest) Test(org.junit.Test)

Aggregations

JsonArray (javax.json.JsonArray)128 JsonObject (javax.json.JsonObject)97 Test (org.junit.Test)42 ArrayList (java.util.ArrayList)32 JsonReader (javax.json.JsonReader)31 HashMap (java.util.HashMap)29 JsonString (javax.json.JsonString)28 HashSet (java.util.HashSet)21 NameValuePair (org.apache.commons.httpclient.NameValuePair)20 Credentials (org.apache.commons.httpclient.Credentials)19 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)19 StringReader (java.io.StringReader)18 HttpTest (org.apache.sling.commons.testing.integration.HttpTest)17 LinkedHashMap (java.util.LinkedHashMap)14 JsonValue (javax.json.JsonValue)11 Map (java.util.Map)10 JsonException (javax.json.JsonException)9 Response (javax.ws.rs.core.Response)9 IOException (java.io.IOException)7 JerseyTest (org.glassfish.jersey.test.JerseyTest)7