Example usage for org.apache.commons.httpclient HttpStatus SC_BAD_REQUEST

List of usage examples for org.apache.commons.httpclient HttpStatus SC_BAD_REQUEST

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus SC_BAD_REQUEST.

Prototype

int SC_BAD_REQUEST

To view the source code for org.apache.commons.httpclient HttpStatus SC_BAD_REQUEST.

Click Source Link

Document

<tt>400 Bad Request</tt> (HTTP/1.1 - RFC 2616)

Usage

From source file:org.alfresco.rest.api.tests.TestNodeComments.java

@Test
// TODO test embedded entity createdBy full visibility e.g. view comment by another user who's full details the caller can't see
// TODO test update comment and modifiedBy in result is a person object
public void testNodeComments() throws Exception {
    Comments commentsProxy = publicApiClient.comments();
    Nodes nodesProxy = publicApiClient.nodes();
    People peopleProxy = publicApiClient.people();

    // Test Case cloud-1518
    // Create comments

    // invalid node id
    try {/*from w w w.  j a v a2  s . co m*/
        Comment comment = new Comment("Test Comment 4", "Test Comment 4");
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        commentsProxy.createNodeComment(GUID.generate(), comment);
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // person from the same network - no permission
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person12.getId()));
        Comment comment = new Comment("Test Comment 4", "Test Comment 4");
        commentsProxy.createNodeComment(nodeRef1.getId(), comment);
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_FORBIDDEN, e.getHttpResponse().getStatusCode());
    }

    // Test Case cloud-2196
    // multi-byte characters, create and update comments
    {
        Comment[] multiByteComments = new Comment[] { new Comment("", ""),
                new Comment("\u67e5\u770b\u5168\u90e8", "\u67e5\u770b\u5168\u90e8") };

        Map<String, Comment> createdComments = new HashMap<String, Comment>();
        for (Comment comment : multiByteComments) {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
            Comment ret = commentsProxy.createNodeComment(nodeRef2.getId(), comment);
            createdComments.put(ret.getId(), ret);
        }

        // test that it is possible to add comment to custom type node
        commentsProxy.createNodeComment(customTypeObject.getId(),
                new Comment("Custom type node comment", "The Comment"));

        try {
            // test that it is not possible to add comment to cm:object node
            commentsProxy.createNodeComment(cmObjectNodeRef.getId(),
                    new Comment("CM Object node comment", "The Comment"));
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        // get comments of the non-folder/non-document nodeRef
        try {
            int skipCount = 0;
            int maxItems = 2;
            Paging paging = getPaging(skipCount, maxItems);
            commentsProxy.getNodeComments(cmObjectNodeRef.getId(), createParams(paging, null));
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }

        int skipCount = 0;
        int maxItems = 2;
        Paging paging = getPaging(skipCount, maxItems);
        ListResponse<Comment> resp = commentsProxy.getNodeComments(nodeRef2.getId(),
                createParams(paging, null));
        List<Comment> retComments = resp.getList();
        assertEquals(2, retComments.size());
        for (Comment comment : retComments) {
            String commentId = comment.getId();
            Comment expectedComment = createdComments.get(commentId);
            expectedComment.expected(comment);
        }

        Comment[] multiByteCommentUpdates = new Comment[] { new Comment("?", "?"),
                new Comment("\u4e00\u4e01\u4e02\u4e03", "\u4e00\u4e01\u4e02\u4e03") };

        Map<String, Comment> updatedComments = new HashMap<String, Comment>();
        for (Comment comment : multiByteCommentUpdates) {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
            Comment ret = commentsProxy.createNodeComment(nodeRef2.getId(), comment);
            updatedComments.put(ret.getId(), ret);
        }

        skipCount = 0;
        maxItems = 2;
        paging = getPaging(skipCount, maxItems);
        resp = commentsProxy.getNodeComments(nodeRef2.getId(), createParams(paging, null));
        retComments = resp.getList();
        assertEquals(2, retComments.size());
        for (Comment comment : retComments) {
            String commentId = comment.getId();
            Comment expectedComment = updatedComments.get(commentId);
            expectedComment.expected(comment);
        }
    }

    {
        // special characters
        Comment comment = new Comment("", "?*^&*(,");
        List<Comment> expectedComments = new ArrayList<Comment>(1);
        expectedComments.add(comment);

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        commentsProxy.createNodeComment(nodeRef3.getId(), comment);

        int skipCount = 0;
        int maxItems = 2;
        Paging paging = getPaging(skipCount, maxItems, expectedComments.size(), expectedComments.size());
        ListResponse<Comment> resp = commentsProxy.getNodeComments(nodeRef3.getId(),
                createParams(paging, null));
        checkList(expectedComments.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                paging.getExpectedPaging(), resp);
    }

    try {
        Comment comment = new Comment("", "");
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        commentsProxy.createNodeComment(nodeRef2.getId(), comment);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
    }

    DateFormat format = PublicApiDateFormat.getDateFormat();
    final List<Comment> expectedComments = new ArrayList<Comment>(10);
    final List<Comment> comments = new ArrayList<Comment>(10);
    comments.add(new Comment("Test Comment 4", "Test Comment 4"));
    comments.add(new Comment("Test Comment 1", "Test Comment 1"));
    comments.add(new Comment("Test Comment 3", "Test Comment 3"));
    comments.add(new Comment("Test Comment 2", "Test Comment 2"));

    {
        Date time = new Date();
        for (Comment comment : comments) {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
            Comment resp = commentsProxy.createNodeComment(nodeRef1.getId(), comment);
            // check response
            assertEquals(comment.getContent(), resp.getContent());
            assertTrue(format.parse(resp.getCreatedAt()).after(time));
            person11.expected(resp.getCreatedBy());
            assertNotNull(resp.getId());

            expectedComments.add(resp);
        }

        // check activities have been raised
        repoService.generateFeed();

        {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));

            Paging paging = getPaging(0, Integer.MAX_VALUE);
            ListResponse<Activity> activities = peopleProxy.getActivities(person11.getId(),
                    createParams(paging, null));

            boolean found = false;
            for (Activity activity : activities.getList()) {
                String activityType = activity.getActivityType();
                if (activityType.equals(ActivityType.COMMENT_CREATED)) {
                    Map<String, Object> summary = activity.getSummary();
                    assertNotNull(summary);
                    String objectId = (String) summary.get("objectId");
                    assertNotNull(objectId);
                    if (nodeRef1.getId().equals(objectId)) {
                        found = true;
                        break;
                    }
                }
            }

            assertTrue(found);
        }
    }

    // try to add a comment to a comment
    try {
        Comment comment = comments.get(0);
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        Comment newComment = commentsProxy.createNodeComment(nodeRef1.getId(), comment);
        expectedComments.add(newComment);

        commentsProxy.createNodeComment(newComment.getId(), comment);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    // try to add a comment to a tag
    try {
        Comment comment = comments.get(0);
        Tag tag = new Tag("taggification");
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        Tag addedTag = nodesProxy.createNodeTag(nodeRef1.getId(), tag);
        commentsProxy.createNodeComment(addedTag.getId(), comment);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    // add a comment to a folder
    {
        Date time = new Date();

        Comment comment = comments.get(0);
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        Comment resp = commentsProxy.createNodeComment(folderNodeRef1.getId(), comment);

        // check response
        assertEquals(comment.getContent(), resp.getContent());
        assertTrue(format.parse(resp.getCreatedAt()).after(time));
        person11.expected(resp.getCreatedBy());
        assertNotNull(resp.getId());
    }

    Collections.sort(expectedComments);

    // Test Case cloud-2205
    // Test Case cloud-2217
    // Test Case cloud-1517
    // pagination
    {
        int skipCount = 0;
        int maxItems = 2;
        Paging paging = getPaging(skipCount, maxItems, expectedComments.size(), expectedComments.size());
        ListResponse<Comment> resp = commentsProxy.getNodeComments(nodeRef1.getId(),
                createParams(paging, null));
        checkList(expectedComments.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                paging.getExpectedPaging(), resp);
    }

    {
        int skipCount = 2;
        int maxItems = 10;
        Paging paging = getPaging(skipCount, maxItems, expectedComments.size(), expectedComments.size());
        ListResponse<Comment> resp = commentsProxy.getNodeComments(nodeRef1.getId(),
                createParams(paging, null));
        checkList(expectedComments.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                paging.getExpectedPaging(), resp);
    }

    // invalid node id - 404
    try {
        int skipCount = 0;
        int maxItems = 2;
        Paging expectedPaging = getPaging(skipCount, maxItems, expectedComments.size(),
                expectedComments.size());
        commentsProxy.getNodeComments("invalid", createParams(expectedPaging, null));
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    try {
        int skipCount = 0;
        int maxItems = 2;
        Paging paging = getPaging(skipCount, maxItems, expectedComments.size(), expectedComments.size());
        commentsProxy.getNodeComments(nodeRef1.getId() + ";pwc", createParams(paging, null));
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // suffix the node id with a version number
    {
        int skipCount = 0;
        int maxItems = 2;
        Paging paging = getPaging(skipCount, maxItems, expectedComments.size(), expectedComments.size());
        ListResponse<Comment> resp = commentsProxy.getNodeComments(nodeRef1.getId() + ";3.0",
                createParams(paging, null));
        checkList(expectedComments.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                paging.getExpectedPaging(), resp);
    }

    // view comments of a document created by another person in the same network, who is not a member of the site
    // in which the comment resides
    try {
        int skipCount = 0;
        int maxItems = 2;
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person12.getId()));
        Paging expectedPaging = getPaging(skipCount, maxItems, expectedComments.size(),
                expectedComments.size());
        commentsProxy.getNodeComments(nodeRef1.getId(), createParams(expectedPaging, null));
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_FORBIDDEN, e.getHttpResponse().getStatusCode());
    }

    // document owned by another person in another network, the user is not a member of that network
    try {
        int skipCount = 0;
        int maxItems = 2;
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person21.getId()));
        Paging expectedPaging = getPaging(skipCount, maxItems, expectedComments.size(),
                expectedComments.size());
        commentsProxy.getNodeComments(nodeRef1.getId(), createParams(expectedPaging, null));
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
    }

    // Test Case cloud-1971
    // invalid methods
    {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));

        int skipCount = 0;
        int maxItems = 2;
        Paging expectedPaging = getPaging(skipCount, maxItems, expectedComments.size(),
                expectedComments.size());
        ListResponse<Comment> resp = commentsProxy.getNodeComments(nodeRef1.getId(),
                createParams(expectedPaging, null));
        List<Comment> nodeComments = resp.getList();
        assertTrue(nodeComments.size() > 0);
        Comment comment = nodeComments.get(0);

        try {
            commentsProxy.create("nodes", nodeRef1.getId(), "comments", comment.getId(), null,
                    "Unable to POST to a node comment");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        try {
            commentsProxy.update("nodes", nodeRef1.getId(), "comments", null, null,
                    "Unable to PUT node comments");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        try {
            commentsProxy.getSingle("nodes", nodeRef1.getId(), "comments", comment.getId(),
                    "Unable to GET a node comment");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        try {
            commentsProxy.remove("nodes", nodeRef1.getId(), "comments", null, "Unable to DELETE node comments");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }
    }

    // Test Case cloud-2184
    // update comments
    {
        Comment[] testComments = new Comment[] { new Comment("?", "?"),
                new Comment("\u4e00\u4e01\u4e02\u4e03", "\u4e00\u4e01\u4e02\u4e03") };

        List<Comment> mlComments = new ArrayList<Comment>();
        mlComments.add(new Comment("?", "?"));
        mlComments.add(new Comment("\u4e00\u4e01\u4e02\u4e03", "\u4e00\u4e01\u4e02\u4e03"));

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));

        // create some comments
        Map<String, Comment> createdComments = new HashMap<String, Comment>();
        for (Comment comment : testComments) {

            Comment ret = commentsProxy.createNodeComment(nodeRef4.getId(), comment);
            createdComments.put(ret.getId(), ret);
        }

        // update them with multi-byte content
        int i = 0;
        List<Comment> updatedComments = new ArrayList<Comment>();
        for (Comment comment : createdComments.values()) {
            Comment updateComment = mlComments.get(i);
            Comment ret = commentsProxy.updateNodeComment(nodeRef4.getId(), comment.getId(), updateComment);
            updatedComments.add(ret);
            i++;
        }
        Collections.sort(updatedComments);

        int skipCount = 0;
        int maxItems = 2;
        Paging paging = getPaging(skipCount, maxItems, mlComments.size(), mlComments.size());
        ListResponse<Comment> resp = commentsProxy.getNodeComments(nodeRef4.getId(),
                createParams(paging, null));
        checkList(updatedComments, paging.getExpectedPaging(), resp);
    }

    // invalid node id
    try {
        Comment comment = expectedComments.get(1);
        Comment update = new Comment("Test Comment 4", "Test Comment 4");
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        commentsProxy.updateNodeComment(GUID.generate(), comment.getId(), update);
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // invalid comment id
    try {
        Comment update = new Comment("Test Comment 4", "Test Comment 4");
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        commentsProxy.updateNodeComment(nodeRef1.getId(), GUID.generate(), update);
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // person from the same network, not comment creator
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person12.getId()));
        Comment comment = expectedComments.get(1);
        Comment update = new Comment("Test Comment 4", "Test Comment 4");
        commentsProxy.updateNodeComment(nodeRef1.getId(), comment.getId(), update);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_FORBIDDEN, e.getHttpResponse().getStatusCode());
    }

    // person from a different network
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person22.getId()));
        Comment comment = expectedComments.get(1);
        Comment update = new Comment("Test Comment 4", "Test Comment 4");
        commentsProxy.updateNodeComment(nodeRef1.getId(), comment.getId(), update);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
    }

    // successful update
    {
        Date time = new Date();

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        Comment comment = expectedComments.get(1);
        Comment update = new Comment("Updated comment", "Updated comment");
        Comment resp = commentsProxy.updateNodeComment(nodeRef1.getId(), comment.getId(), update);

        Thread.sleep(100); // simulate a user edit to a comment

        Comment expected = new Comment(comment);
        expected.setTitle("Updated comment");
        expected.setEdited(true);
        expected.setContent("Updated comment");
        expected.setModifiedBy(repoService.getPerson(person11.getId()));
        expected.setModifiedAt(PublicApiDateFormat.getDateFormat().format(time));
        expected.expected(resp);
    }

    // delete comments

    // invalid node ref
    try {
        Comment comment = expectedComments.get(1);
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        commentsProxy.removeNodeComment(GUID.generate(), comment.getId());
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // invalid comment id
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        commentsProxy.removeNodeComment(nodeRef1.getId(), GUID.generate());
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // successful delete
    {
        Comment toDelete = expectedComments.get(1);
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        commentsProxy.removeNodeComment(nodeRef1.getId(), toDelete.getId());

        // check it's been removed
        int skipCount = 0;
        int maxItems = Integer.MAX_VALUE;
        Paging expectedPaging = getPaging(skipCount, maxItems, expectedComments.size(),
                expectedComments.size());
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        ListResponse<Comment> resp = commentsProxy.getNodeComments(nodeRef1.getId(),
                createParams(expectedPaging, null));
        List<Comment> actualComments = resp.getList();
        assertFalse(actualComments.contains(toDelete));
    }

    // PUT: test update with null/empty comment
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));

        Comment comment = new Comment();
        comment.setContent("my comment");
        Comment createdComment = commentsProxy.createNodeComment(nodeRef1.getId(), comment);

        Comment updatedComment = new Comment();
        updatedComment.setContent(null);
        commentsProxy.updateNodeComment(nodeRef1.getId(), createdComment.getId(), updatedComment);

        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
    }
}

From source file:org.alfresco.rest.api.tests.TestNodeRatings.java

@Test
public void testNodeRatings() throws Exception {
    Iterator<TestNetwork> networksIt = getTestFixture().getNetworksIt();
    assertTrue(networksIt.hasNext());//from w  w w. j  a  v a2 s  .  co  m
    final TestNetwork network1 = networksIt.next();
    assertTrue(networksIt.hasNext());
    final TestNetwork network2 = networksIt.next();

    final List<TestPerson> people = new ArrayList<TestPerson>(3);

    // create users
    TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>() {
        @Override
        public Void doWork() throws Exception {
            TestPerson person = network1.createUser();
            people.add(person);
            person = network1.createUser();
            people.add(person);
            return null;
        }
    }, network1.getId());

    TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>() {
        @Override
        public Void doWork() throws Exception {
            TestPerson person = network2.createUser();
            people.add(person);
            return null;
        }
    }, network2.getId());

    final TestPerson person11 = people.get(0);
    final TestPerson person12 = people.get(1);
    final TestPerson person21 = people.get(2);

    final List<NodeRef> nodes = new ArrayList<NodeRef>();
    final List<TestSite> sites = new ArrayList<TestSite>();

    // Create site
    TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {
        @Override
        public Void doWork() throws Exception {
            TestSite site = network1.createSite(SiteVisibility.PRIVATE);
            sites.add(site);

            NodeRef nodeRef = repoService.createDocument(site.getContainerNodeRef("documentLibrary"),
                    "Test Doc 1", "Test Content");
            nodes.add(nodeRef);

            nodeRef = repoService.createDocument(site.getContainerNodeRef("documentLibrary"), "Test Doc 2",
                    "Test Content");
            nodes.add(nodeRef);

            return null;
        }
    }, person11.getId(), network1.getId());

    final NodeRef nodeRef1 = nodes.get(0);

    Comments commentsProxy = publicApiClient.comments();
    People peopleProxy = publicApiClient.people();
    Nodes nodesProxy = publicApiClient.nodes();
    DateFormat format = PublicApiDateFormat.getDateFormat();

    // Test Case cloud-1976
    // Create node ratings
    // try to add a rating to a comment
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));

        Comment comment = new Comment("Test Comment", "Test Comment");
        Comment newComment = commentsProxy.createNodeComment(nodeRef1.getId(), comment);
        NodeRating rating = new NodeRating("likes", true);
        nodesProxy.createNodeRating(newComment.getId(), rating);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    // invalid node id
    try {
        NodeRating rating = new NodeRating("likes", true);
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        nodesProxy.createNodeRating(GUID.generate(), rating);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // try to add a rating to a tag
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));

        Tag tag = new Tag("testTag");
        Tag newTag = nodesProxy.createNodeTag(nodeRef1.getId(), tag);
        NodeRating rating = new NodeRating("likes", true);
        nodesProxy.createNodeRating(newTag.getId(), rating);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    // invalid rating scheme
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        nodesProxy.createNodeRating(nodeRef1.getId(),
                new NodeRating("missingRatingScheme", Double.valueOf(1.0f)));
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
    }

    // invalid rating
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        nodesProxy.createNodeRating(nodeRef1.getId(), new NodeRating("likes", Double.valueOf(2.0f)));
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
    }

    // invalid rating
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        nodesProxy.createNodeRating(nodeRef1.getId(), new NodeRating("fiveStar", true));
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
    }

    // invalid rating - can't rate own content for fiveStar
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        nodesProxy.createNodeRating(nodeRef1.getId(), new NodeRating("fiveStar", 5));
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
    }

    // valid ratings
    {
        NodeRating rating = new NodeRating("likes", true);

        Date time = new Date();

        // rate by multiple users in more than 1 network
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        NodeRating ret = nodesProxy.createNodeRating(nodeRef1.getId(), rating);
        assertEquals(rating.getMyRating(), ret.getMyRating());
        assertTrue(format.parse(ret.getRatedAt()).after(time));
        assertEquals(rating.getId(), ret.getId());
        assertEquals(new NodeRating.Aggregate(1, null), ret.getAggregate());

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person12.getId()));
        ret = nodesProxy.createNodeRating(nodeRef1.getId(), rating);
        assertEquals(rating.getMyRating(), ret.getMyRating());
        assertTrue(format.parse(ret.getRatedAt()).after(time));
        assertEquals(rating.getId(), ret.getId());
        assertEquals(new NodeRating.Aggregate(2, null), ret.getAggregate());

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person12.getId()));
        ret = nodesProxy.createNodeRating(nodeRef1.getId(), rating);
        assertEquals(rating.getMyRating(), ret.getMyRating());
        assertTrue(format.parse(ret.getRatedAt()).after(time));
        assertEquals(rating.getId(), ret.getId());
        assertEquals(new NodeRating.Aggregate(2, null), ret.getAggregate());

        // different network - unauthorized
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person21.getId()));
            nodesProxy.createNodeRating(nodeRef1.getId(), rating);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
        }

        // Test Case cloud-2209
        // Test Case cloud-2220
        // Test Case cloud-1520
        // check that the node ratings are there, test paging

        {
            // person11

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));

            List<NodeRating> expectedRatings = repoService.getNodeRatings(person11.getId(), network1.getId(),
                    nodeRef1);

            {
                int skipCount = 0;
                int maxItems = 1;
                Paging paging = getPaging(skipCount, maxItems, expectedRatings.size(), expectedRatings.size());
                ListResponse<NodeRating> resp = nodesProxy.getNodeRatings(nodeRef1.getId(),
                        createParams(paging, null));
                checkList(expectedRatings.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                        paging.getExpectedPaging(), resp);
            }

            {
                int skipCount = 1;
                int maxItems = Integer.MAX_VALUE;
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
                Paging paging = getPaging(skipCount, maxItems, expectedRatings.size(), expectedRatings.size());
                ListResponse<NodeRating> resp = nodesProxy.getNodeRatings(nodeRef1.getId(),
                        createParams(paging, null));
                checkList(expectedRatings.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                        paging.getExpectedPaging(), resp);
            }

            {
                int skipCount = 1;
                int maxItems = expectedRatings.size();
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
                Paging paging = getPaging(skipCount, maxItems, expectedRatings.size(), expectedRatings.size());
                ListResponse<NodeRating> resp = nodesProxy.getNodeRatings(nodeRef1.getId(),
                        createParams(paging, null));
                checkList(expectedRatings.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                        paging.getExpectedPaging(), resp);
            }
        }

        {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person12.getId()));

            // person12
            List<NodeRating> expectedRatings = repoService.getNodeRatings(person12.getId(), network1.getId(),
                    nodeRef1);

            {
                int skipCount = 0;
                int maxItems = 1;
                Paging paging = getPaging(skipCount, maxItems, expectedRatings.size(), expectedRatings.size());
                ListResponse<NodeRating> resp = nodesProxy.getNodeRatings(nodeRef1.getId(),
                        createParams(paging, null));
                checkList(expectedRatings.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                        paging.getExpectedPaging(), resp);
            }

            {
                int skipCount = 1;
                int maxItems = Integer.MAX_VALUE;
                Paging paging = getPaging(skipCount, maxItems, expectedRatings.size(), expectedRatings.size());
                ListResponse<NodeRating> resp = nodesProxy.getNodeRatings(nodeRef1.getId(),
                        createParams(paging, null));
                checkList(expectedRatings.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                        paging.getExpectedPaging(), resp);
            }
        }

        {
            // person21

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person21.getId()));

            List<NodeRating> expectedRatings = Collections.emptyList();

            try {
                int skipCount = 0;
                int maxItems = 1;

                Paging paging = getPaging(skipCount, maxItems, expectedRatings.size(), expectedRatings.size());
                nodesProxy.getNodeRatings(nodeRef1.getId(), createParams(paging, null));
                fail();
            } catch (PublicApiException e) {
                assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
            }
        }

        // invalid node id
        try {
            int skipCount = 1;
            int maxItems = Integer.MAX_VALUE;
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
            Paging paging = getPaging(skipCount, maxItems);
            nodesProxy.getNodeRatings(GUID.generate(), createParams(paging, null));
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // check activities have been raised for the created ratings
        repoService.generateFeed();

        {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));

            Paging paging = getPaging(0, Integer.MAX_VALUE);
            ListResponse<Activity> activities = peopleProxy.getActivities(person11.getId(),
                    createParams(paging, null));

            boolean found = false;
            for (Activity activity : activities.getList()) {
                String activityType = activity.getActivityType();
                if (activityType.equals(ActivityType.FILE_LIKED)) {
                    Map<String, Object> summary = activity.getSummary();
                    assertNotNull(summary);
                    String objectId = (String) summary.get("objectId");
                    assertNotNull(objectId);
                    if (nodeRef1.getId().equals(objectId)) {
                        found = true;
                        break;
                    }
                }
            }

            assertTrue(found);
        }
    }

    {
        // remove node rating

        NodeRating rating = new NodeRating("likes", null);

        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person21.getId()));
            nodesProxy.removeNodeRating(nodeRef1.getId(), rating);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
        }

        {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person12.getId()));
            nodesProxy.removeNodeRating(nodeRef1.getId(), rating);
        }

        // check list
        {
            List<NodeRating> ratings = repoService.getNodeRatings(person11.getId(), network1.getId(), nodeRef1);

            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
            Paging paging = getPaging(skipCount, maxItems, ratings.size(), ratings.size());
            ListResponse<NodeRating> resp = nodesProxy.getNodeRatings(nodeRef1.getId(),
                    createParams(paging, null));
            checkList(ratings.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), resp);
        }
    }

    // get a node rating
    // 1977
    {
        NodeRating rating = new NodeRating("likes", true);
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));

        NodeRating expected = nodesProxy.createNodeRating(nodeRef1.getId(), rating);
        NodeRating actual = nodesProxy.getNodeRating(nodeRef1.getId(), "likes");
        expected.expected(actual);
    }

    {
        // update node rating
        NodeRating rating = new NodeRating("fiveStar", 2);

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person12.getId()));

        // create initial rating
        NodeRating createdRating = nodesProxy.createNodeRating(nodeRef1.getId(), rating);
        NodeRating updateRating = new NodeRating(createdRating.getId(), 5);

        // update - not supported
        try {
            nodesProxy.updateNodeRating(nodeRef1.getId(), updateRating);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }
    }

    // Test Case cloud-1977
    // invalid methods
    {
        try {
            // -ve test - cannot create multiple ratings in single POST call (unsupported)
            List<NodeRating> ratings = new ArrayList<>(2);
            ratings.add(new NodeRating("likes", true));
            ratings.add(new NodeRating("likes", false));

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
            nodesProxy.create("nodes", nodeRef1.getId(), "ratings", null, JSONArray.toJSONString(ratings),
                    "Unable to POST to multiple ratings");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        // get an arbitrary rating
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        ListResponse<NodeRating> resp = nodesProxy.getNodeRatings(nodeRef1.getId(),
                createParams(getPaging(0, Integer.MAX_VALUE), null));
        List<NodeRating> nodeRatings = resp.getList();
        assertTrue(nodeRatings.size() > 0);

        try {
            NodeRating rating = new NodeRating("likes", true);

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
            nodesProxy.create("nodes", nodeRef1.getId(), "ratings", "likes", rating.toJSON().toString(),
                    "Unable to POST to a node rating");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
            nodesProxy.update("nodes", nodeRef1.getId(), "ratings", null, null, "Unable to PUT node ratings");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
            nodesProxy.remove("nodes", nodeRef1.getId(), "ratings", null, "Unable to DELETE node ratings");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        try {
            NodeRating rating = nodeRatings.get(0);

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
            nodesProxy.update("nodes", nodeRef1.getId(), "ratings", rating.getId(), null,
                    "Unable to PUT a node rating");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }
    }
}

From source file:org.alfresco.rest.api.tests.TestSiteMembers.java

@Test
public void testSiteMembers() throws Exception {
    Iterator<TestNetwork> networksIt = getTestFixture().getNetworksIt();
    final TestNetwork testNetwork = networksIt.next();
    final List<String> networkPeople = testNetwork.getPersonIds();
    String personId = networkPeople.get(0);

    Sites sitesProxy = publicApiClient.sites();

    {//from w w  w .  j a  v  a2  s.  c  o  m
        final List<SiteMember> expectedSiteMembers = new ArrayList<SiteMember>();

        // Create a private site and invite some users
        // TODO create site members using public api rather than directly using the services
        TestSite testSite = TenantUtil.runAsUserTenant(new TenantRunAsWork<TestSite>() {
            @Override
            public TestSite doWork() throws Exception {
                TestSite testSite = testNetwork.createSite(SiteVisibility.PRIVATE);
                for (int i = 1; i <= 5; i++) {
                    String inviteeId = networkPeople.get(i);
                    testSite.inviteToSite(inviteeId, SiteRole.SiteConsumer);
                    SiteMember sm = new SiteMember(inviteeId, repoService.getPerson(inviteeId),
                            testSite.getSiteId(), SiteRole.SiteConsumer.toString());
                    expectedSiteMembers.add(sm);
                }

                return testSite;
            }
        }, personId, testNetwork.getId());

        {
            SiteMember sm = new SiteMember(personId, repoService.getPerson(personId), testSite.getSiteId(),
                    SiteRole.SiteManager.toString());
            expectedSiteMembers.add(sm);
            Collections.sort(expectedSiteMembers);
        }

        // Test Case cloud-1482
        {
            int skipCount = 0;
            int maxItems = 2;
            Paging paging = getPaging(skipCount, maxItems, expectedSiteMembers.size(), null);
            publicApiClient.setRequestContext(new RequestContext(testNetwork.getId(), personId));
            ListResponse<SiteMember> siteMembers = sitesProxy.getSiteMembers(testSite.getSiteId(),
                    createParams(paging, null));
            checkList(expectedSiteMembers.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), siteMembers);
        }

        {
            int skipCount = 2;
            int maxItems = 10;
            Paging paging = getPaging(skipCount, maxItems, expectedSiteMembers.size(), null);
            publicApiClient.setRequestContext(new RequestContext(testNetwork.getId(), personId));
            ListResponse<SiteMember> siteMembers = sitesProxy.getSiteMembers(testSite.getSiteId(),
                    createParams(paging, null));
            checkList(expectedSiteMembers.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), siteMembers);

            HttpResponse response = sitesProxy.getAll("sites", testSite.getSiteId(), "members", null,
                    createParams(paging, Collections.singletonMap("includeSource", "true")),
                    "Failed to get all site members");
            checkList(expectedSiteMembers.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(),
                    SiteMember.parseSiteMembers(testSite.getSiteId(), response.getJsonResponse()));
            JSONObject source = sitesProxy.parseListSource(response.getJsonResponse());
            Site sourceSite = SiteImpl.parseSite(source);
            assertNotNull(sourceSite);
            testSite.expected(sourceSite);
        }

        // invalid site id
        try {
            int skipCount = 2;
            int maxItems = 10;
            Paging paging = getPaging(skipCount, maxItems, expectedSiteMembers.size(), null);
            publicApiClient.setRequestContext(new RequestContext(testNetwork.getId(), personId));
            sitesProxy.getSiteMembers(GUID.generate(), createParams(paging, null));
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // invalid methods
        try {
            SiteMember siteMember = expectedSiteMembers.get(0);

            publicApiClient.setRequestContext(new RequestContext(testNetwork.getId(), personId));
            sitesProxy.update("sites", testSite.getSiteId(), "members", null, siteMember.toJSON().toString(),
                    "Unable to PUT site members");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        // Test Case cloud-1965
        try {
            SiteMember siteMember1 = expectedSiteMembers.get(0);
            publicApiClient.setRequestContext(new RequestContext(testNetwork.getId(), personId));
            sitesProxy.create("sites", testSite.getSiteId(), "members", siteMember1.getMemberId(),
                    siteMember1.toJSON().toString(), "Unable to POST to a site member");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        try {
            SiteMember siteMember1 = expectedSiteMembers.get(0);
            publicApiClient.setRequestContext(new RequestContext(testNetwork.getId(), personId));
            sitesProxy.update("sites", testSite.getSiteId(), "members", null, siteMember1.toJSON().toString(),
                    "Unable to PUT site members");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        try {
            publicApiClient.setRequestContext(new RequestContext(testNetwork.getId(), personId));
            sitesProxy.remove("sites", testSite.getSiteId(), "members", null, "Unable to DELETE site members");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        // update site member
        {
            SiteMember siteMember1 = expectedSiteMembers.get(0);
            publicApiClient.setRequestContext(new RequestContext(testNetwork.getId(), personId));
            SiteMember ret = sitesProxy.updateSiteMember(testSite.getSiteId(), siteMember1);
            assertEquals(siteMember1.getRole(), ret.getRole());
            Person expectedSiteMember = repoService.getPerson(siteMember1.getMemberId());
            expectedSiteMember.expected(ret.getMember());
        }

        // GET single site member
        {
            SiteMember siteMember1 = expectedSiteMembers.get(0);
            publicApiClient.setRequestContext(new RequestContext(testNetwork.getId(), personId));
            SiteMember ret = sitesProxy.getSingleSiteMember(testSite.getSiteId(), siteMember1.getMemberId());
            siteMember1.expected(ret);
        }
    }

    // test: user is member of different tenant, but has site membership(s) in common with the http request user
    {
        Iterator<TestNetwork> accountsIt = getTestFixture().getNetworksIt();

        assertTrue(accountsIt.hasNext());
        final TestNetwork network1 = accountsIt.next();

        assertTrue(accountsIt.hasNext());
        final TestNetwork network2 = accountsIt.next();

        final List<TestPerson> people = new ArrayList<TestPerson>();

        // Create users
        TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>() {
            @Override
            public Void doWork() throws Exception {
                TestPerson person = network1.createUser();
                people.add(person);
                person = network1.createUser();
                people.add(person);
                person = network1.createUser();
                people.add(person);

                return null;
            }
        }, network1.getId());

        TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>() {
            @Override
            public Void doWork() throws Exception {
                TestPerson person = network2.createUser();
                people.add(person);

                return null;
            }
        }, network2.getId());

        final TestPerson person1 = people.get(0);
        final TestPerson person2 = people.get(1);
        final TestPerson person3 = people.get(2);
        final TestPerson person4 = people.get(3);

        // Create site
        final TestSite site = TenantUtil.runAsUserTenant(new TenantRunAsWork<TestSite>() {
            @Override
            public TestSite doWork() throws Exception {
                TestSite site = network1.createSite(SiteVisibility.PUBLIC);
                return site;
            }
        }, person2.getId(), network1.getId());

        // invalid role - 400
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
            sitesProxy.createSiteMember(site.getSiteId(), new SiteMember(person1.getId(), "dodgyRole"));
            fail("");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }

        // user in network but not site member, try to create site member
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            sitesProxy.createSiteMember(site.getSiteId(),
                    new SiteMember(person3.getId(), SiteRole.SiteContributor.toString()));
            fail("");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_FORBIDDEN, e.getHttpResponse().getStatusCode());
        }

        // unknown invitee - 404
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
            sitesProxy.createSiteMember(site.getSiteId(),
                    new SiteMember("dodgyUser", SiteRole.SiteContributor.toString()));
            fail("");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // unknown site - 404
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
            sitesProxy.createSiteMember("dodgySite",
                    new SiteMember(person1.getId(), SiteRole.SiteContributor.toString()));
            fail("");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // inviter is not a member of the site
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            sitesProxy.createSiteMember(site.getSiteId(),
                    new SiteMember(person1.getId(), SiteRole.SiteContributor.toString()));
            fail("");
        } catch (PublicApiException e) {
            assertEquals(e.getMessage(), HttpStatus.SC_FORBIDDEN, e.getHttpResponse().getStatusCode());
        }

        // inviter is not a member of the site nor a member of the tenant
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person4.getId()));
            sitesProxy.createSiteMember(site.getSiteId(),
                    new SiteMember(person1.getId(), SiteRole.SiteContributor.toString()));
            fail("");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode()); // TODO check that 404 is correct here - external user of network can't see public site??
        }

        {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
            SiteMember sm = new SiteMember(person1.getId(), SiteRole.SiteConsumer.toString());
            SiteMember siteMember = sitesProxy.createSiteMember(site.getSiteId(), sm);
            assertEquals(person1.getId(), siteMember.getMemberId());
            assertEquals(SiteRole.SiteConsumer.toString(), siteMember.getRole());
        }

        // already invited
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
            sitesProxy.createSiteMember(site.getSiteId(),
                    new SiteMember(person1.getId(), SiteRole.SiteContributor.toString()));
            fail("");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_CONFLICT, e.getHttpResponse().getStatusCode());
        }

        // inviter is consumer member of the site, should not be able to add site member
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            sitesProxy.createSiteMember(site.getSiteId(),
                    new SiteMember(person4.getId(), SiteRole.SiteContributor.toString()));
            fail("");
        } catch (PublicApiException e) {
            assertEquals(e.getMessage(), HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // invitee from another network
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            sitesProxy.createSiteMember(site.getSiteId(),
                    new SiteMember(person4.getId(), SiteRole.SiteContributor.toString()));
            fail("");
        } catch (PublicApiException e) {
            assertEquals(e.getMessage(), HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // check site membership in GET
        List<SiteMember> expectedSiteMembers = site.getMembers();

        {
            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expectedSiteMembers.size(), null);
            ListResponse<SiteMember> siteMembers = sitesProxy.getSiteMembers(site.getSiteId(),
                    createParams(paging, null));
            checkList(expectedSiteMembers.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), siteMembers);
        }
    }

    // test: create site membership, remove it, get list of site memberships
    {
        Iterator<TestNetwork> accountsIt = getTestFixture().getNetworksIt();

        assertTrue(accountsIt.hasNext());
        final TestNetwork network1 = accountsIt.next();

        assertTrue(accountsIt.hasNext());

        final List<TestPerson> people = new ArrayList<TestPerson>();

        // Create user
        TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>() {
            @Override
            public Void doWork() throws Exception {
                TestPerson person = network1.createUser();
                people.add(person);
                person = network1.createUser();
                people.add(person);

                return null;
            }
        }, network1.getId());

        TestPerson person1 = people.get(0);
        TestPerson person2 = people.get(1);

        // Create site
        TestSite site = TenantUtil.runAsUserTenant(new TenantRunAsWork<TestSite>() {
            @Override
            public TestSite doWork() throws Exception {
                TestSite site = network1.createSite(SiteVisibility.PRIVATE);
                return site;
            }
        }, person2.getId(), network1.getId());

        // remove site membership

        // for -me- user (PUBLICAPI-90)
        {
            // create a site member
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
            SiteMember siteMember = sitesProxy.createSiteMember(site.getSiteId(),
                    new SiteMember(person1.getId(), SiteRole.SiteContributor.toString()));
            assertEquals(person1.getId(), siteMember.getMemberId());
            assertEquals(SiteRole.SiteContributor.toString(), siteMember.getRole());

            SiteMember toRemove = new SiteMember("-me-");
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            sitesProxy.removeSiteMember(site.getSiteId(), toRemove);
        }

        {
            // create a site member
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
            SiteMember siteMember = sitesProxy.createSiteMember(site.getSiteId(),
                    new SiteMember(person1.getId(), SiteRole.SiteContributor.toString()));
            assertEquals(person1.getId(), siteMember.getMemberId());
            assertEquals(SiteRole.SiteContributor.toString(), siteMember.getRole());

            // unknown site
            try {
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
                sitesProxy.removeSiteMember(GUID.generate(), siteMember);
                fail();
            } catch (PublicApiException e) {
                assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
            }

            // unknown user
            try {
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
                sitesProxy.removeSiteMember(site.getSiteId(), new SiteMember(GUID.generate()));
                fail();
            } catch (PublicApiException e) {
                assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
            }

            {
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
                sitesProxy.removeSiteMember(site.getSiteId(), siteMember);
            }

            // check site membership in GET
            List<SiteMember> expectedSiteMembers = site.getMembers();
            assertFalse(expectedSiteMembers.contains(siteMember));

            {
                int skipCount = 0;
                int maxItems = Integer.MAX_VALUE;
                Paging paging = getPaging(skipCount, maxItems, expectedSiteMembers.size(), null);
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
                ListResponse<SiteMember> siteMembers = sitesProxy.getSiteMembers(site.getSiteId(),
                        createParams(paging, null));
                checkList(
                        expectedSiteMembers.subList(skipCount,
                                skipCount + paging.getExpectedPaging().getCount()),
                        paging.getExpectedPaging(), siteMembers);
            }

            // update site membership

            // unknown site
            try {
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
                sitesProxy.updateSiteMember(GUID.generate(), siteMember);
                fail();
            } catch (PublicApiException e) {
                assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
            }

            // unknown user
            try {
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
                sitesProxy.updateSiteMember(site.getSiteId(), new SiteMember(GUID.generate()));
                fail();
            } catch (PublicApiException e) {
                assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
            }

            // invalid role
            try {
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
                sitesProxy.updateSiteMember(site.getSiteId(), new SiteMember(person1.getId(), "invalidRole"));
                fail();
            } catch (PublicApiException e) {
                assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
            }

            // user is not a member of the site - 400
            try {
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
                sitesProxy.updateSiteMember(site.getSiteId(),
                        new SiteMember(person1.getId(), SiteRole.SiteContributor.toString()));
                fail();
            } catch (PublicApiException e) {
                assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
            }

            // successful update
            {
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));

                SiteMember sm = new SiteMember(person1.getId(), SiteRole.SiteContributor.toString());
                SiteMember ret = sitesProxy.createSiteMember(site.getSiteId(), sm);
                assertEquals(SiteRole.SiteContributor.toString(), ret.getRole());
                person1.expected(ret.getMember());

                sm = new SiteMember(person1.getId(), SiteRole.SiteCollaborator.toString());
                ret = sitesProxy.updateSiteMember(site.getSiteId(), sm);
                assertEquals(SiteRole.SiteCollaborator.toString(), ret.getRole());
                person1.expected(ret.getMember());

                // check site membership in GET
                expectedSiteMembers = site.getMembers();
                SiteMember toCheck = null;
                for (SiteMember sm1 : expectedSiteMembers) {
                    if (sm1.getMemberId().equals(person1.getId())) {
                        toCheck = sm1;
                    }
                }
                assertNotNull(toCheck); // check that the update site membership is present
                assertEquals(sm.getRole(), toCheck.getRole()); // check that the role is correct

                int skipCount = 0;
                int maxItems = Integer.MAX_VALUE;
                Paging paging = getPaging(skipCount, maxItems, expectedSiteMembers.size(), null);
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
                ListResponse<SiteMember> siteMembers = sitesProxy.getSiteMembers(site.getSiteId(),
                        createParams(paging, null));
                checkList(
                        expectedSiteMembers.subList(skipCount,
                                skipCount + paging.getExpectedPaging().getCount()),
                        paging.getExpectedPaging(), siteMembers);
            }
        }
    }
}

From source file:org.alfresco.rest.api.tests.TestSiteMembershipRequests.java

@Test
public void testValidRequests() throws Exception {
    final List<SiteMembershipRequest> expectedSiteMembershipRequests = new ArrayList<SiteMembershipRequest>();

    {//  w  w w  . j ava 2 s. c om
        // GET
        // cloud-2531
        // user has no site membership requests
        {
            log("cloud-2531");

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));

            int skipCount = 0;
            int maxItems = 2;
            Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(),
                    expectedSiteMembershipRequests.size());
            ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy
                    .getSiteMembershipRequests(person11Id, createParams(paging, null));
            checkList(
                    expectedSiteMembershipRequests.subList(skipCount,
                            skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), resp);
        }

        {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));

            int skipCount = 0;
            Paging paging = getPaging(skipCount, null, expectedSiteMembershipRequests.size(),
                    expectedSiteMembershipRequests.size());
            ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy
                    .getSiteMembershipRequests(person11Id, createParams(paging, null));
            checkList(
                    expectedSiteMembershipRequests.subList(skipCount,
                            skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), resp);
        }

        // POSTs
        // cloud-2502
        // cloud-2510
        {
            log("cloud-2502");
            log("cloud-2510");

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));

            // moderated site
            SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
            siteMembershipRequest.setId(person1ModeratedSites.get(0).getSiteId());
            siteMembershipRequest.setMessage("Please can I join your site?");
            final SiteMembershipRequest moderatedSiteResponse = siteMembershipRequestsProxy
                    .createSiteMembershipRequest("-me-", siteMembershipRequest);
            expectedSiteMembershipRequests.add(moderatedSiteResponse);
            siteMembershipRequest.expected(moderatedSiteResponse);

            // public site
            siteMembershipRequest = new SiteMembershipRequest();
            siteMembershipRequest.setId(person1PublicSites.get(0).getSiteId());
            siteMembershipRequest.setMessage("Please can I join your site?");
            SiteMembershipRequest ret = siteMembershipRequestsProxy.createSiteMembershipRequest(person11Id,
                    siteMembershipRequest);
            siteMembershipRequest.expected(ret);

            // test we have a moderated site request only
            // cloud-2532
            {
                log("cloud-2532");

                int skipCount = 0;
                int maxItems = 4;
                Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(),
                        expectedSiteMembershipRequests.size());
                ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy
                        .getSiteMembershipRequests(person11Id, createParams(paging, null));
                checkList(expectedSiteMembershipRequests, paging.getExpectedPaging(), resp);
            }

            // test against the underlying invitation service
            List<Invitation> invitations = repoService.getModeratedSiteInvitations(network1.getId(), person11Id,
                    person11Id, null);
            assertEquals(1, invitations.size());
            Invitation invitation = invitations.get(0);
            assertTrue(invitation instanceof ModeratedInvitation);
            ModeratedInvitation moderatedInvitation = (ModeratedInvitation) invitation;
            String siteId = moderatedInvitation.getResourceName();
            Invitation.InvitationType invitationType = moderatedInvitation.getInvitationType();
            Invitation.ResourceType resourceType = moderatedInvitation.getResourceType();
            String inviteeId = moderatedInvitation.getInviteeUserName();
            assertEquals(person11Id, inviteeId);
            assertEquals(Invitation.ResourceType.WEB_SITE, resourceType);
            assertEquals(Invitation.InvitationType.MODERATED, invitationType);
            assertEquals(person1ModeratedSites.get(0).getSiteId(), siteId);

            // test that personId is a member of the public site
            assertTrue(person1PublicSites.get(0).isMember(person11Id));

            // cloud-2534
            // approve the moderated site invitation and check that it is gone from the list
            {
                log("cloud-2534");

                TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {
                    @Override
                    public Void doWork() throws Exception {
                        repoService.approveSiteInvitation(person11Id, moderatedSiteResponse.getId());
                        expectedSiteMembershipRequests.remove(0);
                        return null;
                    }
                }, person12Id, network1.getId());

                // make sure the outstanding request has gone
                int skipCount = 0;
                int maxItems = 4;
                Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(),
                        expectedSiteMembershipRequests.size());
                ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy
                        .getSiteMembershipRequests(person11Id, createParams(paging, null));
                checkList(expectedSiteMembershipRequests, paging.getExpectedPaging(), resp);
            }
        }

        // user from another network - un-authorised
        try {
            log("cloud-2511");

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person24Id));

            // moderated site
            SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
            siteMembershipRequest.setId(person1ModeratedSites.get(0).getSiteId());
            siteMembershipRequest.setMessage("Please can I join your site?");
            siteMembershipRequestsProxy.createSiteMembershipRequest(person24Id, siteMembershipRequest);

            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
        }

        // cloud-2512
        // cloud-2535
        // invitee from another network
        {
            log("cloud-2512");
            log("cloud-2535");
            log("cloud-2536");

            final List<SiteMembershipRequest> person4ExpectedSiteMembershipRequests = new ArrayList<SiteMembershipRequest>();

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person24Id));

            {
                // public site
                try {
                    SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
                    siteMembershipRequest.setId(person1PublicSites.get(0).getSiteId());
                    siteMembershipRequest.setMessage("Please can I join your site?");
                    siteMembershipRequestsProxy.createSiteMembershipRequest(person24Id, siteMembershipRequest);

                    fail();
                } catch (PublicApiException e) {
                    assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
                }
            }

            {
                // moderated site
                try {
                    SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
                    siteMembershipRequest.setId(person1ModeratedSites.get(0).getSiteId());
                    siteMembershipRequest.setMessage("Please can I join your site?");
                    siteMembershipRequestsProxy.createSiteMembershipRequest(person24Id, siteMembershipRequest);

                    fail();
                } catch (PublicApiException e) {
                    assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
                }

                try {
                    int skipCount = 0;
                    int maxItems = 2;
                    Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(),
                            expectedSiteMembershipRequests.size());
                    siteMembershipRequestsProxy.getSiteMembershipRequests(person24Id,
                            createParams(paging, null));
                    fail();
                } catch (PublicApiException e) {
                    assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
                }
            }

            {
                // private site
                try {
                    SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
                    siteMembershipRequest.setId(person1PrivateSites.get(0).getSiteId());
                    siteMembershipRequest.setMessage("Please can I join your site?");
                    siteMembershipRequestsProxy.createSiteMembershipRequest(person24Id, siteMembershipRequest);

                    fail();
                } catch (PublicApiException e) {
                    assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
                }

                try {
                    int skipCount = 0;
                    int maxItems = 2;
                    Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(),
                            expectedSiteMembershipRequests.size());
                    siteMembershipRequestsProxy.getSiteMembershipRequests(person24Id,
                            createParams(paging, null));
                    fail();
                } catch (PublicApiException e) {
                    assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
                }
            }
        }

        // cloud-2513
        try {
            log("cloud-2513");

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));

            // unknown site
            SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
            siteMembershipRequest.setId(GUID.generate());
            siteMembershipRequest.setMessage("Please can I join your site?");
            siteMembershipRequestsProxy.createSiteMembershipRequest(person11Id, siteMembershipRequest);

            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));

            // private site
            SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
            siteMembershipRequest.setId(person1PrivateSites.get(0).getSiteId());
            siteMembershipRequest.setMessage("Please can I join your site?");
            siteMembershipRequestsProxy.createSiteMembershipRequest(person11Id, siteMembershipRequest);

            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));

            // moderated site in another network
            SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
            siteMembershipRequest.setId(person4ModeratedSites.get(0).getSiteId());
            siteMembershipRequest.setMessage("Please can I join your site?");
            siteMembershipRequestsProxy.createSiteMembershipRequest(person11Id, siteMembershipRequest);

            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // cloud-2514
        try {
            log("cloud-2514");

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));

            // already joined the site
            SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
            siteMembershipRequest.setId(person1ModeratedSites.get(0).getSiteId());
            siteMembershipRequest.setMessage("Please can I join your site?");
            siteMembershipRequestsProxy.createSiteMembershipRequest(person11Id, siteMembershipRequest);

            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }

        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));

            // already requested to join the site but not yet joined
            SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
            siteMembershipRequest.setId(person1ModeratedSites.get(0).getSiteId());
            siteMembershipRequest.setMessage("Please can I join your site?");
            siteMembershipRequestsProxy.createSiteMembershipRequest(person11Id, siteMembershipRequest);

            siteMembershipRequest = new SiteMembershipRequest();
            siteMembershipRequest.setId(person1ModeratedSites.get(0).getSiteId());
            siteMembershipRequest.setMessage("Please can I join your site?");
            siteMembershipRequestsProxy.createSiteMembershipRequest(person11Id, siteMembershipRequest);

            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }

        // cloud-2538
        // blank message
        {
            log("cloud-2538");

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));

            SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
            siteMembershipRequest.setId(person1ModeratedSites.get(1).getSiteId());
            siteMembershipRequest.setMessage("");
            SiteMembershipRequest ret = siteMembershipRequestsProxy.createSiteMembershipRequest(person11Id,
                    siteMembershipRequest);
            expectedSiteMembershipRequests.add(ret);
        }

        // GETs

        // cloud-2501
        // cloud-2509
        // test paging
        {
            log("cloud-2501");
            log("cloud-2509");

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));

            // add some more site membership requests to moderated sites
            for (int i = 1; i < person1ModeratedSites.size(); i++) {
                SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
                siteMembershipRequest.setId(person1ModeratedSites.get(i).getSiteId());
                siteMembershipRequest.setMessage("Please can I join your site?");
                try {
                    SiteMembershipRequest ret = siteMembershipRequestsProxy
                            .createSiteMembershipRequest(person11Id, siteMembershipRequest);
                    expectedSiteMembershipRequests.add(ret);
                    siteMembershipRequest.expected(ret);
                } catch (PublicApiException e) {
                    // this is ok, already created
                }

            }

            Collections.sort(expectedSiteMembershipRequests);

            {
                int skipCount = 0;
                int maxItems = 2;
                Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(),
                        expectedSiteMembershipRequests.size());
                ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy
                        .getSiteMembershipRequests(person11Id, createParams(paging, null));
                checkList(
                        expectedSiteMembershipRequests.subList(skipCount,
                                skipCount + paging.getExpectedPaging().getCount()),
                        paging.getExpectedPaging(), resp);

                skipCount = 2;
                maxItems = 5;
                paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(),
                        expectedSiteMembershipRequests.size());
                resp = siteMembershipRequestsProxy.getSiteMembershipRequests(person11Id,
                        createParams(paging, null));
                checkList(
                        expectedSiteMembershipRequests.subList(skipCount,
                                skipCount + paging.getExpectedPaging().getCount()),
                        paging.getExpectedPaging(), resp);

                skipCount = 5;
                maxItems = 10;
                paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(),
                        expectedSiteMembershipRequests.size());
                resp = siteMembershipRequestsProxy.getSiteMembershipRequests(person11Id,
                        createParams(paging, null));
                checkList(
                        expectedSiteMembershipRequests.subList(skipCount,
                                skipCount + paging.getExpectedPaging().getCount()),
                        paging.getExpectedPaging(), resp);

                skipCount = 0;
                maxItems = expectedSiteMembershipRequests.size();
                paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(),
                        expectedSiteMembershipRequests.size());
                resp = siteMembershipRequestsProxy.getSiteMembershipRequests(person11Id,
                        createParams(paging, null));
                checkList(
                        expectedSiteMembershipRequests.subList(skipCount,
                                skipCount + paging.getExpectedPaging().getCount()),
                        paging.getExpectedPaging(), resp);
            }

            // skipCount is greater than the number of site membership requests in the list
            {
                int skipCount = 1000;
                int maxItems = 2;
                Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(),
                        expectedSiteMembershipRequests.size());
                ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy
                        .getSiteMembershipRequests(person11Id, createParams(paging, null));
                checkList(
                        sublist(expectedSiteMembershipRequests, skipCount,
                                skipCount + paging.getExpectedPaging().getCount()),
                        paging.getExpectedPaging(), resp);
            }

            // cloud-2537
            // -me- user
            {
                log("cloud-2537");

                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));

                int skipCount = 0;
                int maxItems = 2;
                Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(),
                        expectedSiteMembershipRequests.size());
                ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy
                        .getSiteMembershipRequests("-me-", createParams(paging, null));
                checkList(
                        expectedSiteMembershipRequests.subList(skipCount,
                                skipCount + paging.getExpectedPaging().getCount()),
                        paging.getExpectedPaging(), resp);
            }
        }

        // DELETEs
        // cloud-2504
        {
            log("cloud-2504");

            SiteMembershipRequest request = getSiteMembershipRequest(network1.getId(), person11Id, person11Id);

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));

            siteMembershipRequestsProxy.cancelSiteMembershipRequest(person11Id, request.getId());
            expectedSiteMembershipRequests.remove(request);
            Collections.sort(expectedSiteMembershipRequests);

            // cloud-2533
            // check that the site membership request has gone
            log("cloud-2533");

            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(),
                    expectedSiteMembershipRequests.size());
            ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy
                    .getSiteMembershipRequests(person11Id, createParams(paging, null));
            checkList(expectedSiteMembershipRequests, paging.getExpectedPaging(), resp);

            // cloud-2528
            // try to cancel the same request
            try {
                log("cloud-2528");

                siteMembershipRequestsProxy.cancelSiteMembershipRequest(person11Id, request.getId());

                fail("");
            } catch (PublicApiException e) {
                assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
            }
        }

        // cloud-2529
        // cancel a site membership request that has been rejected
        {
            log("cloud-2529");

            final String siteId = person1ModeratedSites.get(1).getSiteId();

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person14Id));

            SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
            siteMembershipRequest.setId(siteId);
            siteMembershipRequest.setMessage("Please can I join your site?");
            SiteMembershipRequest moderatedSiteResponse = siteMembershipRequestsProxy
                    .createSiteMembershipRequest(person14Id, siteMembershipRequest);
            expectedSiteMembershipRequests.add(moderatedSiteResponse);
            Collections.sort(expectedSiteMembershipRequests);
            siteMembershipRequest.expected(moderatedSiteResponse);

            TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {
                @Override
                public Void doWork() throws Exception {
                    Invitation invitation = repoService.rejectSiteInvitation(person14Id, siteId);
                    assertNotNull(invitation);

                    return null;
                }
            }, person12Id, network1.getId());

            // try to cancel the request
            try {
                siteMembershipRequestsProxy.cancelSiteMembershipRequest(person14Id, siteId);

                fail("");
            } catch (PublicApiException e) {
                assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
            }
        }

        // cloud-2530
        // cancel a site membership request that has been approved
        {
            log("cloud-2530");

            final String siteId = person1ModeratedSites.get(2).getSiteId();

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person14Id));

            SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
            siteMembershipRequest.setId(siteId);
            siteMembershipRequest.setMessage("Please can I join your site?");
            SiteMembershipRequest moderatedSiteResponse = siteMembershipRequestsProxy
                    .createSiteMembershipRequest(person14Id, siteMembershipRequest);
            expectedSiteMembershipRequests.add(moderatedSiteResponse);
            Collections.sort(expectedSiteMembershipRequests);
            siteMembershipRequest.expected(moderatedSiteResponse);

            TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {
                @Override
                public Void doWork() throws Exception {
                    Invitation invitation = repoService.approveSiteInvitation(person14Id, siteId);
                    assertNotNull(invitation);

                    return null;
                }
            }, person12Id, network1.getId());

            // try to cancel the request
            try {
                siteMembershipRequestsProxy.cancelSiteMembershipRequest(person14Id, siteId);

                fail("");
            } catch (PublicApiException e) {
                assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
            }
        }

        // PUTs

        // cloud-2503
        // cloud-2517
        // cloud-2518
        {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person14Id));

            // merged these tests
            // cloud-2503: use -me- pseudo user
            // cloud-2517: initially no message
            log("cloud-2503");
            log("cloud-2517");

            // create a request without a message
            String siteId = person1ModeratedSites.get(7).getSiteId();

            SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
            siteMembershipRequest.setId(siteId);
            SiteMembershipRequest request = siteMembershipRequestsProxy.createSiteMembershipRequest(person14Id,
                    siteMembershipRequest);
            assertNotNull(request);

            // update it, with a message
            request.setMessage("Please can I join your site?");
            SiteMembershipRequest updated = siteMembershipRequestsProxy.updateSiteMembershipRequest(person14Id,
                    request);
            request.expected(updated);

            // check it's updated
            int skipCount = 0;
            int maxItems = 2;
            Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(),
                    expectedSiteMembershipRequests.size());
            ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy
                    .getSiteMembershipRequests(person14Id, createParams(paging, null));
            List<SiteMembershipRequest> requests = resp.getList();
            assertTrue(requests.size() > 0);
            int idx = requests.indexOf(request);
            SiteMembershipRequest toCheck = requests.get(idx);
            updated.expected(toCheck);

            // cloud-2518
            // update it again, with ammended message

            log("cloud-2518");

            request.setMessage("Please can I join your site, pretty please?");
            updated = siteMembershipRequestsProxy.updateSiteMembershipRequest(person14Id, request);
            request.expected(updated);

            // check it's updated
            skipCount = 0;
            maxItems = 2;
            paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(),
                    expectedSiteMembershipRequests.size());
            resp = siteMembershipRequestsProxy.getSiteMembershipRequests(person14Id,
                    createParams(paging, null));
            requests = resp.getList();
            assertTrue(requests.size() > 0);
            idx = requests.indexOf(request);
            toCheck = requests.get(idx);
            updated.expected(toCheck);
        }

        // cloud-2515 - no changes
        {
            log("cloud-2515");

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person14Id));

            // create a request
            String siteId = person1ModeratedSites.get(8).getSiteId();

            SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
            siteMembershipRequest.setId(siteId);
            siteMembershipRequest.setMessage("Please can I join your site?");
            SiteMembershipRequest request = siteMembershipRequestsProxy.createSiteMembershipRequest(person14Id,
                    siteMembershipRequest);
            assertNotNull(request);

            // update it, with no changes
            SiteMembershipRequest updated = siteMembershipRequestsProxy.updateSiteMembershipRequest(person14Id,
                    request);
            request.expected(updated); // should not have changed
        }

        // cloud-2516 - unknown person id
        try {
            log("cloud-2516");

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));

            // get an outstanding request
            int skipCount = 0;
            int maxItems = 2;
            Paging paging = getPaging(skipCount, maxItems, expectedSiteMembershipRequests.size(),
                    expectedSiteMembershipRequests.size());
            ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy
                    .getSiteMembershipRequests(person11Id, createParams(paging, null));
            List<SiteMembershipRequest> requests = resp.getList();
            assertTrue(requests.size() > 0);
            SiteMembershipRequest request = requests.get(0);
            siteMembershipRequestsProxy.updateSiteMembershipRequest(GUID.generate(), request);

            fail("");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // cloud-2521 - unknown site membership request
        try {
            log("cloud-2521");

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));

            SiteMembershipRequest request = new SiteMembershipRequest();
            request.setId(GUID.generate());
            siteMembershipRequestsProxy.updateSiteMembershipRequest(person11Id, request);

            fail("");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // cloud-2522
        // update a site membership request that has been rejected
        {
            log("cloud-2522");

            String siteId = person1ModeratedSites.get(5).getSiteId();

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person14Id));

            SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
            siteMembershipRequest.setId(siteId);
            siteMembershipRequest.setMessage("Please can I join your site?");
            SiteMembershipRequest moderatedSiteResponse = siteMembershipRequestsProxy
                    .createSiteMembershipRequest(person14Id, siteMembershipRequest);
            expectedSiteMembershipRequests.add(moderatedSiteResponse);
            Collections.sort(expectedSiteMembershipRequests);
            siteMembershipRequest.expected(moderatedSiteResponse);

            repoService.rejectSiteInvitation(person14Id, siteId);

            // try to update the request
            try {
                siteMembershipRequestsProxy.updateSiteMembershipRequest(siteId, moderatedSiteResponse);

                fail("");
            } catch (PublicApiException e) {
                assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
            }
        }

        // cloud-2523
        // update a site membership request that has been approved
        {
            log("cloud-2523");

            String siteId = person1ModeratedSites.get(6).getSiteId();

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person14Id));

            SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
            siteMembershipRequest.setId(siteId);
            siteMembershipRequest.setMessage("Please can I join your site?");
            SiteMembershipRequest moderatedSiteResponse = siteMembershipRequestsProxy
                    .createSiteMembershipRequest(person14Id, siteMembershipRequest);
            expectedSiteMembershipRequests.add(moderatedSiteResponse);
            Collections.sort(expectedSiteMembershipRequests);
            siteMembershipRequest.expected(moderatedSiteResponse);

            repoService.approveSiteInvitation(person14Id, siteId);

            // try to update the request
            try {
                siteMembershipRequestsProxy.updateSiteMembershipRequest(siteId, moderatedSiteResponse);

                fail("");
            } catch (PublicApiException e) {
                assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
            }
        }

        {
            // cloud-2539 - probing attack tests

            log("cloud-2539");

            // i) create site membership request to a moderated site
            // ii) site owner changes the site to a private site
            // iii) re-issue create site membership request should be a 404
            {
                final List<SiteMembershipRequest> person2ExpectedSiteMembershipRequests = new ArrayList<SiteMembershipRequest>();

                final TestSite site = person1ModeratedSites.get(0);

                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person13Id));

                SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
                siteMembershipRequest.setId(site.getSiteId());
                siteMembershipRequest.setMessage("Please can I join your site?");
                siteMembershipRequestsProxy.createSiteMembershipRequest(person13Id, siteMembershipRequest);

                TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {
                    @Override
                    public Void doWork() throws Exception {
                        site.setSiteVisibility(SiteVisibility.PRIVATE);
                        return null;
                    }
                }, person12Id, network1.getId());

                // Can we still GET it? Should be a 404 (private site)
                try {
                    siteMembershipRequestsProxy.getSiteMembershipRequest(person13Id,
                            siteMembershipRequest.getId());
                } catch (PublicApiException e) {
                    assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
                }

                // GET should not contain the site
                {
                    int skipCount = 0;
                    int maxItems = 10;
                    assertEquals(0, person2ExpectedSiteMembershipRequests.size());
                    Paging paging = getPaging(skipCount, maxItems, person2ExpectedSiteMembershipRequests.size(),
                            person2ExpectedSiteMembershipRequests.size());
                    ListResponse<SiteMembershipRequest> resp = siteMembershipRequestsProxy
                            .getSiteMembershipRequests(person13Id, createParams(paging, null));
                    checkList(
                            sublist(person2ExpectedSiteMembershipRequests, skipCount,
                                    skipCount + paging.getExpectedPaging().getCount()),
                            paging.getExpectedPaging(), resp);
                }

                try {
                    siteMembershipRequestsProxy.createSiteMembershipRequest(person13Id, siteMembershipRequest);

                    fail("");
                } catch (PublicApiException e) {
                    assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
                }
            }

            // i) create site membership request to a public site
            // ii) site owner changes the site to a private site
            // iii) re-issue create site membership request should be a 404
            {
                final TestSite site = person1PublicSites.get(0);

                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person13Id));

                SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
                siteMembershipRequest.setId(site.getSiteId());
                siteMembershipRequest.setMessage("Please can I join your site?");
                siteMembershipRequestsProxy.createSiteMembershipRequest(person13Id, siteMembershipRequest);

                TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {
                    @Override
                    public Void doWork() throws Exception {
                        site.setSiteVisibility(SiteVisibility.PRIVATE);
                        return null;
                    }
                }, person12Id, network1.getId());

                try {
                    siteMembershipRequestsProxy.createSiteMembershipRequest(person13Id, siteMembershipRequest);

                    fail("");
                } catch (PublicApiException e) {
                    assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
                }

                try {
                    siteMembershipRequestsProxy.updateSiteMembershipRequest(person13Id, siteMembershipRequest);

                    fail("");
                } catch (PublicApiException e) {
                    assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
                }

                try {
                    siteMembershipRequestsProxy.cancelSiteMembershipRequest(person13Id,
                            siteMembershipRequest.getId());

                    fail("");
                } catch (PublicApiException e) {
                    assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
                }
            }
        }

        // i) create site membership request to a moderated site
        // ii) site owner accepts the request -> user is now a member of the site
        // iii) site owner changes the site to a private site
        // iv) re-issue create site membership request should be a 404
        {
            final TestSite site = person1ModeratedSites.get(1);

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person13Id));

            SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
            siteMembershipRequest.setId(site.getSiteId());
            siteMembershipRequest.setMessage("Please can I join your site?");
            siteMembershipRequestsProxy.createSiteMembershipRequest(person13Id, siteMembershipRequest);

            // approve the site invitation request and convert the site to a private site
            TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {
                @Override
                public Void doWork() throws Exception {
                    repoService.approveSiteInvitation(person13Id, site.getSiteId());

                    site.setSiteVisibility(SiteVisibility.PRIVATE);
                    return null;
                }
            }, person12Id, network1.getId());

            try {
                siteMembershipRequestsProxy.createSiteMembershipRequest(person13Id, siteMembershipRequest);

                fail("");
            } catch (PublicApiException e) {
                assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
            }
        }

        // blank message in POST and PUT
        {
            final TestSite site = person1ModeratedSites.get(2);

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person13Id));

            SiteMembershipRequest siteMembershipRequest = new SiteMembershipRequest();
            siteMembershipRequest.setId(site.getSiteId());
            siteMembershipRequest.setMessage("");
            SiteMembershipRequest created = siteMembershipRequestsProxy.createSiteMembershipRequest(person13Id,
                    siteMembershipRequest);
            SiteMembershipRequest updated = siteMembershipRequestsProxy.updateSiteMembershipRequest(person13Id,
                    siteMembershipRequest);

            assertTrue(updated.getModifiedAt().after(created.getCreatedAt()));
        }
    }
}

From source file:org.alfresco.rest.api.tests.TestSites.java

@Test
public void testSites() throws Exception {
    Sites sitesProxy = publicApiClient.sites();

    // create & get sites (as person 2)
    {/* ww  w .  j  a v a2 s.  c  o m*/
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2Id));

        String siteTitle = "site 1 " + System.currentTimeMillis();
        Site site = new SiteImpl(siteTitle, SiteVisibility.PRIVATE.toString());
        site1 = sitesProxy.createSite(site);

        Site ret = sitesProxy.getSite(site1.getSiteId());
        site1.expected(ret);

        siteTitle = "site 2 " + System.currentTimeMillis();
        site = new SiteImpl(siteTitle, SiteVisibility.PUBLIC.toString());
        site2 = sitesProxy.createSite(site);

        ret = sitesProxy.getSite(site2.getSiteId());
        site2.expected(ret);

        siteTitle = "site 3 " + System.currentTimeMillis();
        site = new SiteImpl(siteTitle, SiteVisibility.MODERATED.toString());
        site3 = sitesProxy.createSite(site);

        ret = sitesProxy.getSite(site3.getSiteId());
        site3.expected(ret);
    }

    List<TestSite> expectedSites = TenantUtil.runAsUserTenant(new TenantRunAsWork<List<TestSite>>() {
        @Override
        public List<TestSite> doWork() throws Exception {
            List<TestSite> sites = network1.getSites(person1Id);
            return sites;
        }
    }, person1Id, network1.getId());

    {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1Id));

        int skipCount = 0;
        int maxItems = 2;
        Paging paging = getPaging(skipCount, maxItems, expectedSites.size(), expectedSites.size());
        ListResponse<Site> resp = sitesProxy.getSites(createParams(paging, null));
        checkList(expectedSites.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                paging.getExpectedPaging(), resp);
    }

    {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1Id));

        int skipCount = 2;
        int maxItems = Integer.MAX_VALUE;
        Paging paging = getPaging(skipCount, maxItems, expectedSites.size(), expectedSites.size());
        ListResponse<Site> resp = sitesProxy.getSites(createParams(paging, null));
        checkList(expectedSites.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                paging.getExpectedPaging(), resp);
    }

    // test create and delete site
    {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1Id));

        String siteTitle = "my site !*#$ 123";
        String siteDescription = "my site description";

        SiteImpl site = new SiteImpl(siteTitle, SiteVisibility.PRIVATE.toString());
        site.setDescription(siteDescription);

        Site ret = sitesProxy.createSite(site);
        String siteId = ret.getSiteId();

        String expectedSiteId = "my-site-123";
        Site siteExp = new SiteImpl(null, expectedSiteId, ret.getGuid(), siteTitle, siteDescription,
                SiteVisibility.PRIVATE.toString(), null, SiteRole.SiteManager);
        siteExp.expected(ret);

        ret = sitesProxy.getSite(siteId);
        siteExp.expected(ret);

        sitesProxy.removeSite(siteId);

        // -ve test - ie. cannot get site after it has been deleted
        sitesProxy.getSite(siteId, 404);
    }

    // test create + permanent delete + create
    {

        String siteId = "bbb";
        String siteTitle = "BBB site";

        Site site = new SiteImpl(null, siteId, null, siteTitle, null, SiteVisibility.PUBLIC.toString(), null,
                null);

        sitesProxy.createSite(site);

        // permanent site delete (bypass trashcan/archive)
        sitesProxy.removeSite(siteId, true, 204);

        sitesProxy.createSite(site);
    }

    // test create using site id = "true" (RA-1101)
    {

        String siteId = "true";
        String siteTitle = "string";
        String siteDescription = "string";

        Site site = new SiteImpl(null, siteId, null, siteTitle, siteDescription,
                SiteVisibility.PUBLIC.toString(), null, null);

        sitesProxy.createSite(site);
    }

    // -ve tests
    {
        // invalid auth
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), GUID.generate(), "password"));
        sitesProxy.getSite(site1.getSiteId(), 401);

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1Id));

        // -ve - cannot view or delete a private site
        sitesProxy.getSite(site1.getSiteId(), 404);
        sitesProxy.removeSite(site1.getSiteId(), false, 404);

        // -ve - test cannot delete a public site (but can view it)
        sitesProxy.getSite(site2.getSiteId(), 200);
        sitesProxy.removeSite(site2.getSiteId(), false, 403);

        // -ve - try to get unknown site
        sitesProxy.getSite(GUID.generate(), 404);

        SiteImpl site = new SiteImpl("my site 123", "invalidsitevisibility");
        sitesProxy.createSite(site, 400);

        site = new SiteImpl(null, "invalid site id", null, "my site 123", null,
                SiteVisibility.PRIVATE.toString(), null, null);
        sitesProxy.createSite(site, 400);

        site = new SiteImpl(null, "invalidsiteid*", null, "my site 123", null,
                SiteVisibility.PRIVATE.toString(), null, null);
        sitesProxy.createSite(site, 400);

        site = new SiteImpl();
        site.setSiteId(new String(new char[72]).replace('\0', 'a'));
        site.setTitle(new String(new char[256]).replace('\0', 'a'));
        site.setDescription(new String(new char[512]).replace('\0', 'a'));
        site.setVisibility(SiteVisibility.PUBLIC.toString());
        sitesProxy.createSite(site, 201);

        // -ve - site id too long
        site = new SiteImpl();
        site.setSiteId(new String(new char[73]).replace('\0', 'a'));
        site.setTitle("ok");
        site.setDescription("ok");
        site.setVisibility(SiteVisibility.PUBLIC.toString());
        sitesProxy.createSite(site, 400);

        // -ve - site title too long
        site = new SiteImpl();
        site.setSiteId("ok");
        site.setTitle(new String(new char[257]).replace('\0', 'a'));
        site.setDescription("ok");
        site.setVisibility(SiteVisibility.PUBLIC.toString());
        sitesProxy.createSite(site, 400);

        // -ve - site description too long
        site = new SiteImpl();
        site.setSiteId("ok");
        site.setTitle("ok");
        site.setDescription(new String(new char[513]).replace('\0', 'a'));
        site.setVisibility(SiteVisibility.PUBLIC.toString());
        sitesProxy.createSite(site, 400);

        // site already exists (409)
        String siteTitle = "my site 456";
        site = new SiteImpl(siteTitle, SiteVisibility.PRIVATE.toString());
        String siteId = sitesProxy.createSite(site, 201).getSiteId();
        sitesProxy.createSite(site, 409);
        sitesProxy.removeSite(siteId); // cleanup

        sitesProxy.removeSite(GUID.generate(), false, 404);
    }

    // -ve - cannot create site with same site id as an existing site (even if it is in the trashcan/archive)
    {
        String siteId = "aaa";
        String siteTitle = "AAA site";

        Site site = new SiteImpl(null, siteId, null, siteTitle, null, SiteVisibility.PUBLIC.toString(), null,
                null);

        String siteNodeId = sitesProxy.createSite(site).getGuid();

        // -ve - duplicate site id
        sitesProxy.createSite(site, 409);

        sitesProxy.removeSite(siteId);

        // -ve - duplicate site id (even if site is in trashcan)
        sitesProxy.createSite(site, 409);

        // now purge the site
        sitesProxy.remove("deleted-nodes", siteNodeId, null, null, "Cannot purge site");

        sitesProxy.createSite(site);
    }

    // -ve - minor: error code if updating via nodes api (REPO-512)
    {
        String siteId = "zzz";
        String siteTitle = "ZZZ site";

        Site site = new SiteImpl(null, siteId, null, siteTitle, null, SiteVisibility.PRIVATE.toString(), null,
                null);
        String siteNodeId = sitesProxy.createSite(site).getGuid();

        // try to update to invalid site visibility
        JSONObject prop = new JSONObject();
        prop.put("st:siteVisibility", "INVALID");
        JSONObject properties = new JSONObject();
        properties.put("properties", new JSONObject(prop));
        try {
            sitesProxy.update("nodes", siteNodeId, null, null, properties.toJSONString(), null);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }

        sitesProxy.removeSite(siteId); // cleanup
    }

    // -ve test - cannot create multiple sites in single POST call (unsupported)
    {
        List<Site> sites = new ArrayList<>(2);
        sites.add(new SiteImpl(null, "siteA1", null, "siteA1", null, SiteVisibility.PRIVATE.toString(), null,
                null));
        sites.add(new SiteImpl(null, "siteB1", null, "siteB1", null, SiteVisibility.PRIVATE.toString(), null,
                null));

        sitesProxy.create("sites", null, null, null, JSONArray.toJSONString(sites), null, 405);
    }

    // -ve tests - belts-and-braces for unsupported methods
    {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1Id));

        // -ve - cannot call POST method on /sites/siteId
        try {
            sitesProxy.create("sites", "site", null, null, null, "Unable to POST to a site");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        // -ve - cannot call DELETE method on /sites
        try {
            sitesProxy.remove("sites", null, null, null, "Unable to DELETE sites");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }
    }

    // Test Case cloud-1478
    // Test Case cloud-1479
    // user invited to network and user invited to site
    // user invited to network and user not invited to site
}

From source file:org.alfresco.rest.api.tests.TestTags.java

@Test
public void testTags() throws Exception {
    Iterator<TestNetwork> networksIt = getTestFixture().getNetworksIt();
    assertTrue(networksIt.hasNext());//from   www .ja v  a  2  s. c om
    final TestNetwork network1 = networksIt.next();
    assertTrue(networksIt.hasNext());
    final TestNetwork network2 = networksIt.next();

    final List<TestPerson> people = new ArrayList<TestPerson>(3);

    // create users and some preferences
    TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>() {
        @Override
        public Void doWork() throws Exception {
            TestPerson person = network1.createUser();
            people.add(person);
            person = network1.createUser();
            people.add(person);
            return null;
        }
    }, network1.getId());

    TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>() {
        @Override
        public Void doWork() throws Exception {
            TestPerson person = network2.createUser();
            people.add(person);
            return null;
        }
    }, network2.getId());

    final TestPerson person1 = people.get(0);
    final TestPerson person2 = people.get(1);
    final TestPerson person3 = people.get(2);

    final List<NodeRef> nodes = new ArrayList<NodeRef>();
    final List<TestSite> sites = new ArrayList<TestSite>();

    // Create site
    TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {
        @Override
        public Void doWork() throws Exception {
            TestSite site = network1.createSite(SiteVisibility.PRIVATE);
            sites.add(site);

            NodeRef nodeRef = repoService.createDocument(site.getContainerNodeRef("documentLibrary"),
                    "Test Doc", "Test Content");
            nodes.add(nodeRef);

            nodeRef = repoService.createDocument(site.getContainerNodeRef("documentLibrary"), "Test Doc 1",
                    "Test Content 1");
            nodes.add(nodeRef);

            return null;
        }
    }, person1.getId(), network1.getId());

    final NodeRef nodeRef1 = nodes.get(0);
    final NodeRef nodeRef2 = nodes.get(1);

    Nodes nodesProxy = publicApiClient.nodes();
    Comments commentsProxy = publicApiClient.comments();
    Tags tagsProxy = publicApiClient.tags();

    final List<Tag> tags = new ArrayList<Tag>();
    tags.add(new Tag("tag 1"));
    tags.add(new Tag("tag 9"));
    tags.add(new Tag("other tag 3"));
    tags.add(new Tag("my tag 1"));
    tags.add(new Tag("tag 5"));

    // try to add a tag to a comment
    try {
        Comment comment = new Comment("Test Comment", "Test Comment");
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        Comment newComment = commentsProxy.createNodeComment(nodeRef1.getId(), comment);
        Tag tag = new Tag("testTag");
        nodesProxy.createNodeTag(newComment.getId(), tag);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    // try to add a tag to a tag
    try {
        Tag tag = new Tag("testTag");
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        Tag newTag = nodesProxy.createNodeTag(nodeRef1.getId(), tag);
        nodesProxy.createNodeTag(newTag.getId(), tag);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    // Test Case cloud-2221
    // Test Case cloud-2222
    // multi-byte characters, special characters, create and update tags
    {
        Tag[] multiByteTags = new Tag[] { new Tag("\u67e5\u770b\u5168\u90e8"),
                new Tag("\u67e5\u770b\u5168\u91e8"), new Tag("%^&%&$^@") };

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));

        // first, create tags
        Map<String, Tag> createdTags = new HashMap<String, Tag>();
        for (Tag tag : multiByteTags) {
            Tag ret = nodesProxy.createNodeTag(nodeRef2.getId(), tag);
            createdTags.put(ret.getId(), ret);
        }

        int skipCount = 0;
        int maxItems = Integer.MAX_VALUE;
        Paging paging = getPaging(skipCount, maxItems);
        ListResponse<Tag> resp = nodesProxy.getNodeTags(nodeRef2.getId(), createParams(paging, null));
        List<Tag> retTags = resp.getList();
        assertEquals(createdTags.size(), retTags.size());
        for (Tag tag : retTags) {
            String tagId = tag.getId();
            Tag expectedTag = createdTags.get(tagId);
            expectedTag.expected(tag);
        }

        // special characters and update tags
        //         {
        //            Tag[] specialCharacterTags = new Tag[]
        //            {
        //                  new Tag("\u67e5\u770b\u5168\u90e8"),
        //                  new Tag("\u67e5\u770b\u5168\u91e8")
        //            };
        //            
        //            createdTags = new HashMap<String, Tag>();
        //            for(Tag tag : specialCharacterTags)
        //            {
        //               Tag ret = nodesProxy.createNodeTag(nodeRef2.getId(), tag);
        //               createdTags.put(ret.getId(), ret);
        //            }
        //            
        //            
        //            Tag tag = new Tag("%^&%&$^@");
        //            Tag ret = nodesProxy.createNodeTag(nodeRef2.getId(), tag);
        //            createdTags.put(ret.getId(), ret);
        //         }

        // update tags

        try {
            // update with an empty tag i.e. "" -> bad request
            Tag tag = new Tag("");
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            nodesProxy.createNodeTag(nodeRef2.getId(), tag);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }

        List<Tag> tagUpdates = new ArrayList<Tag>(createdTags.values());
        tagUpdates.get(0).setTag("\u4e00\u4e01\u4e02\u4e10");
        tagUpdates.get(1).setTag("\u4e00\u4e01\u4e12\u4e11");
        tagUpdates.get(2).setTag("\u4e00\u4e01\u4e12\u4e12");
        Map<String, Tag> updatedTags = new HashMap<String, Tag>();
        for (Tag tag : tagUpdates) {
            Tag ret = tagsProxy.update(tag);
            assertNotNull(ret.getId());
            assertNotNull(ret.getTag());
            //            tag.expected(ret); disabled because tag id changes
            updatedTags.put(ret.getId(), ret);
        }

        // get updated tags
        List<Tag> expectedNodeTags = TenantUtil.runAsUserTenant(new TenantRunAsWork<List<Tag>>() {
            @Override
            public List<Tag> doWork() throws Exception {
                List<Tag> tags = repoService.getTags(nodeRef2);
                return tags;
            }
        }, person1.getId(), network1.getId());

        skipCount = 0;
        maxItems = tagUpdates.size();
        paging = getPaging(skipCount, maxItems, tagUpdates.size(), tagUpdates.size());
        resp = nodesProxy.getNodeTags(nodeRef2.getId(), createParams(paging, null));
        checkList(expectedNodeTags.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                paging.getExpectedPaging(), resp);
    }

    {
        List<Tag> createdTags = new ArrayList<Tag>();

        // Test Case cloud-1975
        for (Tag tag : tags) {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            Tag ret = nodesProxy.createNodeTag(nodeRef1.getId(), tag);
            assertEquals(tag.getTag(), ret.getTag());
            assertNotNull(ret.getId());
            createdTags.add(ret);
        }

        // update tag, empty string
        try {
            Tag tag = new Tag(createdTags.get(0).getId(), "");
            tagsProxy.update(tag);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }

        // invalid node id
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            nodesProxy.createNodeTag(GUID.generate(), tags.get(0));
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // Test Case cloud-1973
        // Test Case cloud-2208
        // Test Case cloud-2219
        // check that the tags are there in the node tags, test paging
        List<Tag> expectedNodeTags = TenantUtil.runAsUserTenant(new TenantRunAsWork<List<Tag>>() {
            @Override
            public List<Tag> doWork() throws Exception {
                List<Tag> tags = repoService.getTags(nodeRef1);
                return tags;
            }
        }, person1.getId(), network1.getId());

        {
            int skipCount = 0;
            int maxItems = 2;
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            Paging paging = getPaging(skipCount, maxItems, expectedNodeTags.size(), expectedNodeTags.size());
            ListResponse<Tag> resp = nodesProxy.getNodeTags(nodeRef1.getId(), createParams(paging, null));
            checkList(expectedNodeTags.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), resp);
        }

        {
            int skipCount = 2;
            int maxItems = Integer.MAX_VALUE;
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            Paging paging = getPaging(skipCount, maxItems, expectedNodeTags.size(), expectedNodeTags.size());
            ListResponse<Tag> resp = nodesProxy.getNodeTags(nodeRef1.getId(), createParams(paging, null));
            checkList(expectedNodeTags.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), resp);
        }

        // invalid node
        try {
            int skipCount = 0;
            int maxItems = 2;
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            Paging paging = getPaging(skipCount, maxItems, expectedNodeTags.size(), expectedNodeTags.size());
            ListResponse<Tag> allTags = nodesProxy.getNodeTags("invalidNode", createParams(paging, null));
            checkList(expectedNodeTags.subList(skipCount, paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), allTags);
            fail("");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // user from another account - 403
        try {
            int skipCount = 0;
            int maxItems = 2;
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person3.getId()));
            Paging expectedPaging = getPaging(skipCount, maxItems, expectedNodeTags.size(),
                    expectedNodeTags.size());
            nodesProxy.getNodeTags(nodeRef1.getId(), createParams(expectedPaging, null));
            fail("");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
        }

        // another user from the same account
        try {
            int skipCount = 0;
            int maxItems = 2;
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
            Paging paging = getPaging(skipCount, maxItems, expectedNodeTags.size(), expectedNodeTags.size());
            ListResponse<Tag> resp = nodesProxy.getNodeTags(nodeRef1.getId(), createParams(paging, null));
            checkList(expectedNodeTags.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), resp);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_FORBIDDEN, e.getHttpResponse().getStatusCode());
        }

        // Test Case cloud-1519
        // Test Case cloud-2206
        // Test Case cloud-2218
        // check that the tags are there in the network tags, test paging
        // TODO for user from another network who is invited to this network
        List<Tag> expectedNetworkTags = TenantUtil.runAsUserTenant(new TenantRunAsWork<List<Tag>>() {
            @Override
            public List<Tag> doWork() throws Exception {
                List<Tag> tags = repoService.getTags();
                return tags;
            }
        }, person1.getId(), network1.getId());

        {
            int skipCount = 0;
            int maxItems = 2;
            Paging paging = getPaging(skipCount, maxItems, expectedNetworkTags.size(), null);
            ListResponse<Tag> allTags = tagsProxy.getTags(createParams(paging, null));
            checkList(expectedNetworkTags.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), allTags);
        }

        {
            int skipCount = 2;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expectedNetworkTags.size(), null);
            ListResponse<Tag> allTags = tagsProxy.getTags(createParams(paging, null));
            checkList(expectedNetworkTags.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), allTags);
        }
    }

    {
        // Try a create with the same tag value
        Tag tag = tags.get(0);
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        nodesProxy.createNodeTag(nodeRef1.getId(), tag);
    }

    try {
        // Invalid node id
        Tag tag = tags.get(0);
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        nodesProxy.createNodeTag(GUID.generate(), tag);
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // Test Case cloud-2183
    // update tags
    {
        // get a network tag
        int skipCount = 0;
        int maxItems = 2;
        Paging paging = getPaging(skipCount, maxItems);
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        ListResponse<Tag> allTags = tagsProxy.getTags(createParams(paging, null));
        assertTrue(allTags.getList().size() > 0);

        // and update it
        Tag tag = allTags.getList().get(0);
        String newTagValue = GUID.generate();
        Tag newTag = new Tag(tag.getId(), newTagValue);
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        Tag ret = tagsProxy.update(newTag);
        assertEquals(newTagValue, ret.getTag());
        //         assertNotEquals(tag.getId, ret.getId()); // disabled due to CLOUD-628
    }

    // update invalid/unknown tag id
    try {
        Tag unknownTag = new Tag(GUID.generate(), GUID.generate());
        tagsProxy.update(unknownTag);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // Test Case cloud-1972
    // Test Case cloud-1974
    // not allowed methods
    {
        List<Tag> networkTags = TenantUtil.runAsUserTenant(new TenantRunAsWork<List<Tag>>() {
            @Override
            public List<Tag> doWork() throws Exception {
                List<Tag> tags = repoService.getTags();
                return tags;
            }
        }, person1.getId(), network1.getId());
        assertTrue(networkTags.size() > 0);

        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            nodesProxy.update("nodes", nodeRef1.getId(), "tags", null, null, "Unable to PUT node tags");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            nodesProxy.remove("nodes", nodeRef1.getId(), "tags", null, "Unable to DELETE node tags");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        try {
            Tag tag = networkTags.get(0);

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            nodesProxy.update("nodes", nodeRef1.getId(), "tags", tag.getId(), null, "Unable to PUT node tag");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        try {
            Tag tag = networkTags.get(0);

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            nodesProxy.create("tags", null, null, null, tag.toJSON().toString(), "Unable to POST to tags");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        try {
            Tag tag = networkTags.get(0);

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            nodesProxy.update("tags", null, null, null, tag.toJSON().toString(), "Unable to PUT tags");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            nodesProxy.remove("tags", null, null, null, "Unable to DELETE tags");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        try {
            Tag tag = networkTags.get(0);

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            nodesProxy.create("tags", tag.getId(), null, null, tag.toJSON().toString(),
                    "Unable to POST to a tag");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        try {
            Tag tag = networkTags.get(0);

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            nodesProxy.remove("tags", tag.getId(), null, null, "Unable to DELETE a tag");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

        // delete node tag
        {
            Tag tag = networkTags.get(0);

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            nodesProxy.removeNodeTag(nodeRef1.getId(), tag.getId());

            // check that the tag is gone
            ListResponse<Tag> resp = nodesProxy.getNodeTags(nodeRef1.getId(),
                    createParams(getPaging(0, Integer.MAX_VALUE), null));
            List<Tag> nodeTags = resp.getList();
            assertTrue(!nodeTags.contains(tag));
        }

        try {
            Tag tag = networkTags.get(0);

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            nodesProxy.getSingle("nodes", nodeRef1.getId(), "tags", tag.getId(), "Unable to GET node tag");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }
    }
}

From source file:org.alfresco.rest.api.tests.TestUserPreferences.java

@Test
public void testUserPreferences() throws Exception {
    Iterator<TestNetwork> networksIt = getTestFixture().getNetworksIt();
    assertTrue(networksIt.hasNext());//w  w w. jav  a2 s.c o m
    final TestNetwork network1 = networksIt.next();
    assertTrue(networksIt.hasNext());
    final TestNetwork network2 = networksIt.next();

    final List<TestPerson> people = new ArrayList<TestPerson>(3);

    // create users and some preferences
    TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>() {
        @Override
        public Void doWork() throws Exception {
            TestPerson person = network1.createUser();
            people.add(person);
            person = network1.createUser();
            people.add(person);
            return null;
        }
    }, network1.getId());

    TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>() {
        @Override
        public Void doWork() throws Exception {
            TestPerson person = network2.createUser();
            people.add(person);
            return null;
        }
    }, network2.getId());

    final TestPerson person1 = people.get(0);
    final TestPerson person2 = people.get(1);
    final TestPerson person3 = people.get(2);

    final List<Preference> expectedPreferences = new ArrayList<Preference>();
    expectedPreferences
            .add(new Preference("org.alfresco.share.documentList.testPreference2", String.valueOf(true)));
    expectedPreferences
            .add(new Preference("org.alfresco.share.documentList.testPreference1", String.valueOf(true)));
    expectedPreferences
            .add(new Preference("org.alfresco.share.documentList.sortAscending", String.valueOf(true)));
    expectedPreferences
            .add(new Preference("org.alfresco.share.documentList.testPreference3", String.valueOf(true)));
    // new preference name for issue REPO-855
    expectedPreferences.add(new Preference(
            "org.alfresco.ext.folders.favourites.workspace://SpacesStore/4e3d0779-388a-4b94-91e1-eab588a7da3d.createdAt",
            String.valueOf(true)));

    TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {
        @Override
        public Void doWork() throws Exception {
            for (Preference pref : expectedPreferences) {
                // TODO add preferences thru api
                repoService.addPreference(person1.getId(), pref.getId(), pref.getValue());
            }

            return null;
        }
    }, person1.getId(), network1.getId());

    Collections.sort(expectedPreferences);

    People peopleProxy = publicApiClient.people();

    // GET preferences
    // Test case: cloud-1492

    // unknown user
    try {
        int skipCount = 0;
        int maxItems = 2;
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        Paging paging = getPaging(skipCount, maxItems, expectedPreferences.size(), expectedPreferences.size());
        peopleProxy.getPreferences(GUID.generate(), createParams(paging, null));

        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // test paging
    {
        int skipCount = 0;
        int maxItems = 2;
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        Paging paging = getPaging(skipCount, maxItems, expectedPreferences.size(), expectedPreferences.size());
        ListResponse<Preference> resp = peopleProxy.getPreferences(person1.getId(), createParams(paging, null));
        checkList(expectedPreferences.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                paging.getExpectedPaging(), resp);
    }

    {
        int skipCount = 2;
        int maxItems = 10;
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        Paging paging = getPaging(skipCount, maxItems, expectedPreferences.size(), expectedPreferences.size());
        ListResponse<Preference> resp = peopleProxy.getPreferences(person1.getId(), createParams(paging, null));
        checkList(expectedPreferences.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                paging.getExpectedPaging(), resp);
    }

    // "-me-" user
    {
        int skipCount = 0;
        int maxItems = 2;
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        Paging paging = getPaging(skipCount, maxItems, expectedPreferences.size(), expectedPreferences.size());
        ListResponse<Preference> resp = peopleProxy.getPreferences(org.alfresco.rest.api.People.DEFAULT_USER,
                createParams(paging, null));
        checkList(expectedPreferences.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                paging.getExpectedPaging(), resp);
    }

    // invalid user - 404
    try {
        int skipCount = 2;
        int maxItems = 10;
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        Paging paging = getPaging(skipCount, maxItems, expectedPreferences.size(), expectedPreferences.size());
        peopleProxy.getPreferences("invalid.user", createParams(paging, null));
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // user from another account - 401
    try {
        int skipCount = 0;
        int maxItems = 2;
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person3.getId()));
        Paging paging = getPaging(skipCount, maxItems, expectedPreferences.size(), expectedPreferences.size());
        //           ListResponse<Preference> resp = peopleProxy.getPreferences(person1.getId(), createParams(paging, null));
        //           checkList(expectedPreferences.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()), paging.getExpectedPaging(), resp);
        peopleProxy.getPreferences(person1.getId(), createParams(paging, null));
        fail();
    } catch (PublicApiException e) {
        assertEquals(e.getHttpResponse().getStatusCode(), HttpStatus.SC_UNAUTHORIZED);
    }

    // another user from the same account - 403
    try {
        int skipCount = 0;
        int maxItems = 2;
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
        Paging paging = getPaging(skipCount, maxItems, expectedPreferences.size(), expectedPreferences.size());
        peopleProxy.getPreferences(person1.getId(), createParams(paging, null));
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_FORBIDDEN, e.getHttpResponse().getStatusCode());
    }

    // get a single preference
    // Test Case: cloud-1493

    {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        Preference pref = expectedPreferences.get(0);
        Preference ret = peopleProxy.getPreference(person1.getId(), pref.getId());
        pref.expected(ret);
    }

    // unknown person id
    try {
        Preference pref = expectedPreferences.get(0);
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
        peopleProxy.getPreference(GUID.generate(), pref.getId());
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // unknown preference id
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        peopleProxy.getPreference(person1.getId(), GUID.generate());
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // Invalid methods
    // Test case: cloud-1968
    try {
        Preference pref = expectedPreferences.get(0);

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        peopleProxy.create("people", person1.getId(), "preferences", pref.getId(), pref.toJSON().toString(),
                "Unable to POST to a preference");
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    try {
        Preference pref = expectedPreferences.get(0);

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        peopleProxy.update("people", person1.getId(), "preferences", pref.getId(), pref.toJSON().toString(),
                "Unable to PUT a preference");
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    try {
        Preference pref = expectedPreferences.get(0);

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        peopleProxy.remove("people", person1.getId(), "preferences", pref.getId(),
                "Unable to DELETE a preference");
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    try {
        Preference pref = expectedPreferences.get(0);

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        peopleProxy.create("people", person1.getId(), "preferences", null, pref.toJSON().toString(),
                "Unable to POST to preferences");
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    try {
        Preference pref = expectedPreferences.get(0);

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        peopleProxy.update("people", person1.getId(), "preferences", null, pref.toJSON().toString(),
                "Unable to PUT preferences");
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        peopleProxy.remove("people", person1.getId(), "preferences", null, "Unable to DELETE preferences");
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    {
        // REPO-1061, REPO-890
        try {
            String skipCount = "a";
            String maxItems = "hi";
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("skipCount", skipCount);
            params.put("maxItems", maxItems);
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            peopleProxy.getPreferences(person1.getId(), params);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }

        try {
            String skipCount = "a";
            String maxItems = "null";
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("skipCount", skipCount);
            params.put("maxItems", maxItems);
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            peopleProxy.getPreferences(person1.getId(), params);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }

        try {
            String maxItems = "Red";
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("maxItems", maxItems);
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            peopleProxy.getPreferences(person1.getId(), params);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }

        try {
            String skipCount = "yuck";
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("skipCount", skipCount);
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            peopleProxy.getPreferences(person1.getId(), params);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }

        try {
            String skipCount = "-1";
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("skipCount", skipCount);
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            peopleProxy.getPreferences(person1.getId(), params);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }

        try {
            String maxItems = "0";
            HashMap<String, String> params = new HashMap<String, String>();
            params.put("maxItems", maxItems);
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            peopleProxy.getPreferences(person1.getId(), params);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
        }
    }
}

From source file:org.apache.ambari.server.controller.metrics.timeline.MetricsRequestHelper.java

private boolean checkConnectionForPrecisionException(HttpURLConnection connection)
        throws IOException, URISyntaxException {

    if (connection != null && connection.getResponseCode() == HttpStatus.SC_BAD_REQUEST) {
        InputStream errorStream = connection.getErrorStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream));
        String errorMessage = reader.readLine();
        if (errorMessage != null && errorMessage.contains("PrecisionLimitExceededException")) {
            LOG.debug("Encountered Precision exception while requesting metrics : " + errorMessage);
            return false;
        } else {/* w w  w. jav  a 2  s  .  c om*/
            throw new IOException(errorMessage);
        }
    }
    return true;
}

From source file:org.apache.ambari.server.controller.metrics.timeline.MetricsRequestHelperTest.java

@Test
public void testFetchTimelineMetrics() throws Exception {

    EasyMockSupport easyMockSupport = new EasyMockSupport();
    final long now = System.currentTimeMillis();
    TimelineMetrics metrics = new TimelineMetrics();
    TimelineMetric timelineMetric = new TimelineMetric();
    timelineMetric.setMetricName("cpu_user");
    timelineMetric.setAppId("app1");
    TreeMap<Long, Double> metricValues = new TreeMap<Long, Double>();
    metricValues.put(now + 100, 1.0);//from ww  w.ja  v a2  s.c  om
    metricValues.put(now + 200, 2.0);
    metricValues.put(now + 300, 3.0);
    timelineMetric.setMetricValues(metricValues);
    metrics.getMetrics().add(timelineMetric);

    ObjectMapper mapper = new ObjectMapper();
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
    mapper.setAnnotationIntrospector(introspector);
    ObjectWriter writer = mapper.writerWithDefaultPrettyPrinter();
    String metricsResponse = writer.writeValueAsString(metrics);

    InputStream inputStream = IOUtils.toInputStream(metricsResponse);
    HttpURLConnection httpURLConnectionMock = createMock(HttpURLConnection.class);
    expect(httpURLConnectionMock.getInputStream()).andReturn(inputStream).once();
    expect(httpURLConnectionMock.getResponseCode()).andReturn(HttpStatus.SC_OK).once();

    URLStreamProvider urlStreamProviderMock = createMock(URLStreamProvider.class);
    expect(urlStreamProviderMock.processURL(EasyMock.isA(String.class), EasyMock.isA(String.class),
            isNull(String.class), EasyMock.isA(Map.class))).andReturn(httpURLConnectionMock).once();

    replay(httpURLConnectionMock, urlStreamProviderMock);

    //Case 1 : No error.
    String randomSpec = "http://localhost:6188/ws/v1/timeline/metrics?metricNames=cpu_wio&hostname=host1&appId=HOST"
            + "&startTime=1447912834&endTime=1447990034&precision=SECONDS";
    MetricsRequestHelper metricsRequestHelper = new MetricsRequestHelper(urlStreamProviderMock);
    metricsRequestHelper.fetchTimelineMetrics(new URIBuilder(randomSpec), now, now + 300);

    easyMockSupport.verifyAll();

    //Case 2 : Precision Error returned first time.
    String metricsPrecisionErrorResponse = "{\"exception\": \"PrecisionLimitExceededException\",\n"
            + "\"message\": \"Requested precision (SECONDS) for given time range causes result set size of 169840, "
            + "which exceeds the limit - 15840. Please request higher precision.\",\n"
            + "\"javaClassName\": \"org.apache.hadoop.metrics2.sink.timeline.PrecisionLimitExceededException\"\n"
            + "}";

    InputStream errorStream = IOUtils.toInputStream(metricsPrecisionErrorResponse);
    inputStream = IOUtils.toInputStream(metricsResponse); //Reloading stream.

    httpURLConnectionMock = createMock(HttpURLConnection.class);
    expect(httpURLConnectionMock.getErrorStream()).andReturn(errorStream).once();
    expect(httpURLConnectionMock.getInputStream()).andReturn(inputStream).once();
    expect(httpURLConnectionMock.getResponseCode()).andReturn(HttpStatus.SC_BAD_REQUEST).once()
            .andReturn(HttpStatus.SC_OK).once();

    urlStreamProviderMock = createMock(URLStreamProvider.class);
    expect(urlStreamProviderMock.processURL(EasyMock.isA(String.class), EasyMock.isA(String.class),
            isNull(String.class), EasyMock.isA(Map.class))).andReturn(httpURLConnectionMock).times(2);

    replay(httpURLConnectionMock, urlStreamProviderMock);

    metricsRequestHelper = new MetricsRequestHelper(urlStreamProviderMock);
    metricsRequestHelper.fetchTimelineMetrics(new URIBuilder(randomSpec), now, now + 300);

    easyMockSupport.verifyAll();

}

From source file:org.apache.axis2.transport.http.HTTPSender.java

/**
 * Used to handle the HTTP Response/*from  ww  w .j a  v  a 2  s  . c  om*/
 *
 * @param msgContext - The MessageContext of the message
 * @param method     - The HTTP method used
 * @throws IOException - Thrown in case an exception occurs
 */
private void handleResponse(MessageContext msgContext, HttpMethodBase method) throws IOException {
    int statusCode = method.getStatusCode();
    HTTPStatusCodeFamily family = getHTTPStatusCodeFamily(statusCode);
    log.trace("Handling response - " + statusCode);
    Set<Integer> nonErrorCodes = (Set<Integer>) msgContext
            .getProperty(HTTPConstants.NON_ERROR_HTTP_STATUS_CODES);
    Set<Integer> errorCodes = new HashSet<Integer>();
    String strRetryErrorCodes = (String) msgContext.getProperty(HTTPConstants.ERROR_HTTP_STATUS_CODES); // Fixing
    // ESBJAVA-3178
    if (strRetryErrorCodes != null && !strRetryErrorCodes.trim().equals("")) {
        for (String strRetryErrorCode : strRetryErrorCodes.split(",")) {
            try {
                errorCodes.add(Integer.valueOf(strRetryErrorCode));
            } catch (NumberFormatException e) {
                log.warn(strRetryErrorCode + " is not a valid status code");
            }
        }
    }
    if (statusCode == HttpStatus.SC_ACCEPTED) {
        /* When an HTTP 202 Accepted code has been received, this will be the case of an execution 
         * of an in-only operation. In such a scenario, the HTTP response headers should be returned,
         * i.e. session cookies. */
        obtainHTTPHeaderInformation(method, msgContext);
        // Since we don't expect any content with a 202 response, we must release the connection
        method.releaseConnection();
    } else if (HTTPStatusCodeFamily.SUCCESSFUL.equals(family)) {
        // Save the HttpMethod so that we can release the connection when cleaning up
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        processResponse(method, msgContext);
    } else if (!errorCodes.contains(statusCode) && (statusCode == HttpStatus.SC_INTERNAL_SERVER_ERROR
            || statusCode == HttpStatus.SC_BAD_REQUEST || statusCode == HttpStatus.SC_CONFLICT)) {
        // Save the HttpMethod so that we can release the connection when cleaning up
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        Header contenttypeHeader = method.getResponseHeader(HTTPConstants.HEADER_CONTENT_TYPE);
        String value = null;
        if (contenttypeHeader != null) {
            value = contenttypeHeader.getValue();
        }
        OperationContext opContext = msgContext.getOperationContext();
        if (opContext != null) {
            MessageContext inMessageContext = opContext.getMessageContext(WSDLConstants.MESSAGE_LABEL_IN_VALUE);
            if (inMessageContext != null) {
                inMessageContext.setProcessingFault(true);
            }
        }
        if (value != null) {

            processResponse(method, msgContext);
        }

        if (org.apache.axis2.util.Utils.isClientThreadNonBlockingPropertySet(msgContext)) {
            throw new AxisFault(
                    Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText()));
        }
    } else if (nonErrorCodes != null && nonErrorCodes.contains(statusCode)) {
        msgContext.setProperty(HTTPConstants.HTTP_METHOD, method);
        processResponse(method, msgContext);
        return;
    } else {
        // Since we don't process the response, we must release the connection immediately
        method.releaseConnection();
        throw new AxisFault(
                Messages.getMessage("transportError", String.valueOf(statusCode), method.getStatusText()));
    }
}