Search in sources :

Example 21 with TestPerson

use of org.alfresco.rest.api.tests.RepoService.TestPerson in project alfresco-remote-api by Alfresco.

the class TestTags method testTags.

@Test
@Category({ LuceneTests.class, RedundantTests.class })
public void testTags() throws Exception {
    Iterator<TestNetwork> networksIt = getTestFixture().getNetworksIt();
    assertTrue(networksIt.hasNext());
    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);
        }
        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());
        }
    }
}
Also used : ListResponse(org.alfresco.rest.api.tests.client.PublicApiClient.ListResponse) ArrayList(java.util.ArrayList) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ArrayList(java.util.ArrayList) List(java.util.List) RequestContext(org.alfresco.rest.api.tests.client.RequestContext) Tags(org.alfresco.rest.api.tests.client.PublicApiClient.Tags) Comment(org.alfresco.rest.api.tests.client.data.Comment) TestSite(org.alfresco.rest.api.tests.RepoService.TestSite) Comments(org.alfresco.rest.api.tests.client.PublicApiClient.Comments) Paging(org.alfresco.rest.api.tests.client.PublicApiClient.Paging) PublicApiException(org.alfresco.rest.api.tests.client.PublicApiException) Nodes(org.alfresco.rest.api.tests.client.PublicApiClient.Nodes) PublicApiException(org.alfresco.rest.api.tests.client.PublicApiException) TenantRunAsWork(org.alfresco.repo.tenant.TenantUtil.TenantRunAsWork) TestNetwork(org.alfresco.rest.api.tests.RepoService.TestNetwork) Tag(org.alfresco.rest.api.tests.client.data.Tag) TestPerson(org.alfresco.rest.api.tests.RepoService.TestPerson) HashMap(java.util.HashMap) Map(java.util.Map) Category(org.junit.experimental.categories.Category) Test(org.junit.Test)

Example 22 with TestPerson

use of org.alfresco.rest.api.tests.RepoService.TestPerson in project alfresco-remote-api by Alfresco.

the class AbstractTestApi method setupTests.

@Before
public void setupTests() throws Exception {
    TestFixture testFixture = getTestFixture(false);
    this.applicationContext = testFixture.getApplicationContext();
    this.repoService = testFixture.getRepoService();
    this.transactionHelper = (RetryingTransactionHelper) applicationContext.getBean("retryingTransactionHelper");
    HttpClientProvider httpClientProvider = (HttpClientProvider) applicationContext.getBean("httpClientProvider");
    UserDataService userDataService = new UserDataService() {

        @Override
        public UserData findUserByUserName(String userName) {
            UserData userData = new UserData();
            TestPerson person = getRepoService().getPerson(userName.toLowerCase());
            userData.setUserName(person.getId());
            userData.setPassword(person.getPassword());
            userData.setId(person.getId());
            return userData;
        }
    };
    AuthenticationDetailsProvider authenticationDetailsProvider = new UserAuthenticationDetailsProviderImpl(userDataService, "admin", "admin");
    AuthenticatedHttp authenticatedHttp = new AuthenticatedHttp(httpClientProvider, authenticationDetailsProvider);
    this.httpClient = new PublicApiHttpClient(TestFixture.HOST, TestFixture.PORT, TestFixture.CONTEXT_PATH, TestFixture.PUBLIC_API_SERVLET_NAME, authenticatedHttp);
    this.publicApiClient = new PublicApiClient(httpClient, userDataService);
}
Also used : AuthenticationDetailsProvider(org.alfresco.rest.api.tests.client.AuthenticationDetailsProvider) HttpClientProvider(org.alfresco.rest.api.tests.client.HttpClientProvider) UserData(org.alfresco.rest.api.tests.client.UserData) AuthenticatedHttp(org.alfresco.rest.api.tests.client.AuthenticatedHttp) PublicApiHttpClient(org.alfresco.rest.api.tests.client.PublicApiHttpClient) PublicApiClient(org.alfresco.rest.api.tests.client.PublicApiClient) UserAuthenticationDetailsProviderImpl(org.alfresco.rest.api.tests.client.UserAuthenticationDetailsProviderImpl) TestPerson(org.alfresco.rest.api.tests.RepoService.TestPerson) UserDataService(org.alfresco.rest.api.tests.client.UserDataService) Before(org.junit.Before)

Example 23 with TestPerson

use of org.alfresco.rest.api.tests.RepoService.TestPerson in project alfresco-remote-api by Alfresco.

the class TestActivities method setup.

@Before
public void setup() throws Exception {
    // note: we don't call super.setup() since we create our own test data here !
    this.network1 = repoService.createNetworkWithAlias("activitiesNetwork1", true);
    this.network2 = repoService.createNetworkWithAlias("activitiesNetwork2", true);
    this.defaultNetwork = repoService.createNetwork(TenantService.DEFAULT_DOMAIN, true);
    siteService = (SiteService) applicationContext.getBean("SiteService");
    try {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setFullyAuthenticatedUser(AuthenticationUtil.getAdminUserName());
        network1.create();
        network2.create();
        defaultNetwork.create();
    } finally {
        AuthenticationUtil.popAuthentication();
    }
    // Create some users and sites
    final List<TestPerson> people = new ArrayList<TestPerson>(5);
    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());
    TenantUtil.runAsSystemTenant(new TenantRunAsWork<Void>() {

        @Override
        public Void doWork() throws Exception {
            TestPerson person = defaultNetwork.createUser();
            people.add(person);
            person = defaultNetwork.createUser();
            people.add(person);
            return null;
        }
    }, defaultNetwork.getId());
    this.person1 = people.get(0);
    this.person2 = people.get(1);
    this.person3 = people.get(2);
    this.person4 = people.get(3);
    this.person5 = people.get(4);
    this.testSite = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<TestSite>() {

        @SuppressWarnings("synthetic-access")
        public TestSite execute() throws Throwable {
            return TenantUtil.runAsUserTenant(new TenantRunAsWork<TestSite>() {

                public TestSite doWork() throws Exception {
                    SiteInformation siteInfo = new SiteInformation(GUID.generate(), "", "", SiteVisibility.PUBLIC);
                    TestSite site = network1.createSite(siteInfo);
                    site.inviteToSite(person2.getId(), SiteRole.SiteCollaborator);
                    return site;
                }
            }, person1.getId(), network1.getId());
        }
    }, false, true);
    this.testSite1 = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<TestSite>() {

        @SuppressWarnings("synthetic-access")
        public TestSite execute() throws Throwable {
            return TenantUtil.runAsUserTenant(new TenantRunAsWork<TestSite>() {

                public TestSite doWork() throws Exception {
                    SiteInformation siteInfo = new SiteInformation(GUID.generate(), "", "", SiteVisibility.PUBLIC);
                    return network1.createSite(siteInfo);
                }
            }, person1.getId(), network1.getId());
        }
    }, false, true);
    // create some activities against those sites
    TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {

        @SuppressWarnings("unchecked")
        @Override
        public Void doWork() throws Exception {
            // ensure at least 3 activities
            JSONObject activityData = new JSONObject();
            activityData.put("title", GUID.generate());
            activityData.put("nodeRef", testSite.getContainerNodeRef("documentLibrary").toString());
            repoService.postActivity("org.alfresco.documentlibrary.file-added", testSite.getSiteId(), activityData);
            activityData = new JSONObject();
            activityData.put("title", GUID.generate());
            activityData.put("nodeRef", testSite.getContainerNodeRef("documentLibrary").toString());
            repoService.postActivity("org.alfresco.documentlibrary.file-added", testSite.getSiteId(), activityData);
            activityData = new JSONObject();
            activityData.put("title", GUID.generate());
            activityData.put("nodeRef", testSite.getContainerNodeRef("documentLibrary").toString());
            repoService.postActivity("org.alfresco.documentlibrary.file-added", testSite.getSiteId(), activityData);
            activityData = new JSONObject();
            activityData.put("title", GUID.generate());
            activityData.put("nodeRef", testSite1.getContainerNodeRef("documentLibrary").toString());
            repoService.postActivity("org.alfresco.documentlibrary.file-added", testSite1.getSiteId(), activityData);
            return null;
        }
    }, person1.getId(), network1.getId());
    TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {

        @SuppressWarnings("unchecked")
        @Override
        public Void doWork() throws Exception {
            // ensure at least 3 activities
            JSONObject activityData = new JSONObject();
            activityData.put("title", GUID.generate());
            activityData.put("nodeRef", testSite.getContainerNodeRef("documentLibrary").toString());
            repoService.postActivity("org.alfresco.documentlibrary.file-added", testSite.getSiteId(), activityData);
            activityData = new JSONObject();
            activityData.put("title", GUID.generate());
            activityData.put("nodeRef", testSite.getContainerNodeRef("documentLibrary").toString());
            repoService.postActivity("org.alfresco.documentlibrary.file-added", testSite.getSiteId(), activityData);
            activityData = new JSONObject();
            activityData.put("title", GUID.generate());
            activityData.put("nodeRef", testSite.getContainerNodeRef("documentLibrary").toString());
            repoService.postActivity("org.alfresco.documentlibrary.file-added", testSite.getSiteId(), activityData);
            return null;
        }
    }, person2.getId(), network1.getId());
    // user generates activities in 2 networks
    this.testSite2 = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<TestSite>() {

        @SuppressWarnings("synthetic-access")
        public TestSite execute() throws Throwable {
            return TenantUtil.runAsUserTenant(new TenantRunAsWork<TestSite>() {

                public TestSite doWork() throws Exception {
                    SiteInformation siteInfo = new SiteInformation(GUID.generate(), "", "", SiteVisibility.PUBLIC);
                    return network2.createSite(siteInfo);
                }
            }, person3.getId(), network2.getId());
        }
    }, false, true);
    TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {

        @SuppressWarnings("unchecked")
        @Override
        public Void doWork() throws Exception {
            // ensure at least 3 activities
            JSONObject activityData = new JSONObject();
            activityData.put("title", GUID.generate());
            activityData.put("nodeRef", testSite.getContainerNodeRef("documentLibrary").toString());
            repoService.postActivity("org.alfresco.documentlibrary.file-added", testSite.getSiteId(), activityData);
            activityData = new JSONObject();
            activityData.put("title", GUID.generate());
            activityData.put("nodeRef", testSite.getContainerNodeRef("documentLibrary").toString());
            repoService.postActivity("org.alfresco.documentlibrary.file-added", testSite.getSiteId(), activityData);
            activityData = new JSONObject();
            activityData.put("title", GUID.generate());
            activityData.put("nodeRef", testSite.getContainerNodeRef("documentLibrary").toString());
            repoService.postActivity("org.alfresco.documentlibrary.file-added", testSite.getSiteId(), activityData);
            return null;
        }
    }, person3.getId(), network1.getId());
    TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {

        @SuppressWarnings("unchecked")
        @Override
        public Void doWork() throws Exception {
            // ensure at least 3 activities
            JSONObject activityData = new JSONObject();
            activityData.put("title", GUID.generate());
            activityData.put("nodeRef", testSite2.getContainerNodeRef("documentLibrary").toString());
            repoService.postActivity("org.alfresco.documentlibrary.file-added", testSite2.getSiteId(), activityData);
            activityData = new JSONObject();
            activityData.put("title", GUID.generate());
            activityData.put("nodeRef", testSite2.getContainerNodeRef("documentLibrary").toString());
            repoService.postActivity("org.alfresco.documentlibrary.file-added", testSite2.getSiteId(), activityData);
            activityData = new JSONObject();
            activityData.put("title", GUID.generate());
            activityData.put("nodeRef", testSite2.getContainerNodeRef("documentLibrary").toString());
            repoService.postActivity("org.alfresco.documentlibrary.file-added", testSite2.getSiteId(), activityData);
            return null;
        }
    }, person3.getId(), network2.getId());
    this.testSite3 = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<TestSite>() {

        @SuppressWarnings("synthetic-access")
        public TestSite execute() throws Throwable {
            return TenantUtil.runAsUserTenant(new TenantRunAsWork<TestSite>() {

                public TestSite doWork() throws Exception {
                    SiteInformation siteInfo = new SiteInformation(GUID.generate(), "", "", SiteVisibility.PUBLIC);
                    return defaultNetwork.createSite(siteInfo);
                }
            }, person4.getId(), defaultNetwork.getId());
        }
    }, false, true);
    TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {

        @SuppressWarnings("unchecked")
        @Override
        public Void doWork() throws Exception {
            siteService.setMembership(testSite3.getSiteId(), person5.getId(), SiteModel.SITE_CONSUMER);
            return null;
        }
    }, person4.getId(), defaultNetwork.getId());
    repoService.generateFeed();
}
Also used : TestSite(org.alfresco.rest.api.tests.RepoService.TestSite) ArrayList(java.util.ArrayList) PublicApiException(org.alfresco.rest.api.tests.client.PublicApiException) JSONObject(org.json.simple.JSONObject) SiteInformation(org.alfresco.rest.api.tests.RepoService.SiteInformation) TestPerson(org.alfresco.rest.api.tests.RepoService.TestPerson) Before(org.junit.Before)

Example 24 with TestPerson

use of org.alfresco.rest.api.tests.RepoService.TestPerson in project alfresco-remote-api by Alfresco.

the class TaskWorkflowApiTest method testUpdateTaskMnt13276.

@Test
@SuppressWarnings("unchecked")
public void testUpdateTaskMnt13276() throws Exception {
    RequestContext requestContext = initApiClientWithTestUser();
    String initiatorId = requestContext.getRunAsUser();
    ProcessInfo processInfo = startReviewPooledProcess(requestContext);
    // create test users
    final List<TestPerson> persons = transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<List<TestPerson>>() {

        @SuppressWarnings("synthetic-access")
        public List<TestPerson> execute() throws Throwable {
            ArrayList<TestPerson> persons = new ArrayList<TestPerson>();
            String temp = "_" + System.currentTimeMillis();
            persons.add(currentNetwork.createUser(new PersonInfo("user0", "user0", "user0" + temp, "password", null, "skype", "location", "telephone", "mob", "instant", "google")));
            persons.add(currentNetwork.createUser(new PersonInfo("user1", "user1", "user1" + temp, "password", null, "skype", "location", "telephone", "mob", "instant", "google")));
            persons.add(currentNetwork.createUser(new PersonInfo("user2", "user2", "user2" + temp, "password", null, "skype", "location", "telephone", "mob", "instant", "google")));
            return persons;
        }
    }, false, true);
    final MemberOfSite memberOfSite = currentNetwork.getSiteMemberships(initiatorId).get(0);
    // startReviewPooledProcess() uses initiator's site id and role name for construct bpm_groupAssignee, thus we need appropriate things for created users
    transactionHelper.doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<Void>() {

        public Void execute() throws Throwable {
            TenantUtil.runAsUserTenant(new TenantRunAsWork<Void>() {

                @Override
                public Void doWork() throws Exception {
                    TestSite initiatorSite = (TestSite) memberOfSite.getSite();
                    initiatorSite.inviteToSite(persons.get(0).getId(), memberOfSite.getRole());
                    initiatorSite.inviteToSite(persons.get(1).getId(), memberOfSite.getRole());
                    // this user wouldn't be in group
                    initiatorSite.inviteToSite(persons.get(2).getId(), SiteRole.SiteConsumer == memberOfSite.getRole() ? SiteRole.SiteCollaborator : SiteRole.SiteConsumer);
                    return null;
                }
            }, AuthenticationUtil.getAdminUserName(), currentNetwork.getId());
            return null;
        }
    }, false, true);
    try {
        Task task = activitiProcessEngine.getTaskService().createTaskQuery().processInstanceId(processInfo.getId()).singleResult();
        TasksClient tasksClient = publicApiClient.tasksClient();
        // Updating the task by user in group
        JSONObject taskBody = new JSONObject();
        taskBody.put("name", "Updated name by user in group");
        List<String> selectedFields = new ArrayList<String>();
        selectedFields.addAll(Arrays.asList(new String[] { "name" }));
        requestContext.setRunAsUser(persons.get(0).getId());
        JSONObject result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
        assertEquals("Updated name by user in group", result.get("name"));
        task = activitiProcessEngine.getTaskService().createTaskQuery().processInstanceId(processInfo.getId()).singleResult();
        assertNotNull(task);
        assertEquals("Updated name by user in group", task.getName());
        // Updating the task by user not in group
        try {
            taskBody.put("name", "Updated name by user not in group");
            requestContext.setRunAsUser(persons.get(2).getId());
            tasksClient.updateTask(task.getId(), taskBody, selectedFields);
            fail("User not from group should not see items.");
        } catch (PublicApiException expected) {
            assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode());
            assertErrorSummary("Permission was denied", expected.getHttpResponse());
        }
        // claim task
        TaskService taskService = activitiProcessEngine.getTaskService();
        task = taskService.createTaskQuery().processInstanceId(processInfo.getId()).singleResult();
        taskService.setAssignee(task.getId(), persons.get(1).getId());
        // Updating by user in group for claimed task by another user
        try {
            taskBody = new JSONObject();
            taskBody.put("name", "Updated name by user in group for claimed task");
            selectedFields.addAll(Arrays.asList(new String[] { "name" }));
            requestContext.setRunAsUser(persons.get(0).getId());
            result = tasksClient.updateTask(task.getId(), taskBody, selectedFields);
            fail("User from group should not see items for claimed task by another user.");
        } catch (PublicApiException expected) {
            assertEquals(HttpStatus.FORBIDDEN.value(), expected.getHttpResponse().getStatusCode());
            assertErrorSummary("Permission was denied", expected.getHttpResponse());
        }
    } finally {
        cleanupProcessInstance(processInfo.getId());
    }
}
Also used : Task(org.activiti.engine.task.Task) PersonInfo(org.alfresco.rest.api.tests.PersonInfo) RetryingTransactionHelper(org.alfresco.repo.transaction.RetryingTransactionHelper) TestSite(org.alfresco.rest.api.tests.RepoService.TestSite) TaskService(org.activiti.engine.TaskService) TasksClient(org.alfresco.rest.workflow.api.tests.WorkflowApiClient.TasksClient) ArrayList(java.util.ArrayList) MemberOfSite(org.alfresco.rest.api.tests.client.data.MemberOfSite) ProcessInfo(org.alfresco.rest.workflow.api.model.ProcessInfo) PublicApiException(org.alfresco.rest.api.tests.client.PublicApiException) JSONObject(org.json.simple.JSONObject) TenantRunAsWork(org.alfresco.repo.tenant.TenantUtil.TenantRunAsWork) List(java.util.List) ArrayList(java.util.ArrayList) RequestContext(org.alfresco.rest.api.tests.client.RequestContext) TestPerson(org.alfresco.rest.api.tests.RepoService.TestPerson) Test(org.junit.Test)

Example 25 with TestPerson

use of org.alfresco.rest.api.tests.RepoService.TestPerson in project alfresco-remote-api by Alfresco.

the class TestCMIS method testVersioning.

/**
 * Test that updating properties does not automatically create a new version.
 * Test that updating content creates a new version automatically.
 */
@Test
public void testVersioning() throws Exception {
    final TestNetwork network1 = getTestFixture().getRandomNetwork();
    String username = "user" + System.currentTimeMillis();
    PersonInfo personInfo = new PersonInfo(username, username, username, TEST_PASSWORD, null, null, null, null, null, null, null);
    TestPerson person1 = network1.createUser(personInfo);
    String person1Id = person1.getId();
    final String siteName = "site" + System.currentTimeMillis();
    TenantUtil.runAsUserTenant(new TenantRunAsWork<NodeRef>() {

        @Override
        public NodeRef doWork() throws Exception {
            SiteInformation siteInfo = new SiteInformation(siteName, siteName, siteName, SiteVisibility.PRIVATE);
            TestSite site = repoService.createSite(null, siteInfo);
            String name = GUID.generate();
            NodeRef folderNodeRef = repoService.createFolder(site.getContainerNodeRef(DOCUMENT_LIBRARY_CONTAINER_NAME), name);
            return folderNodeRef;
        }
    }, person1Id, network1.getId());
    // Create a document...
    publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1Id));
    CmisSession cmisSession = publicApiClient.createPublicApiCMISSession(Binding.atom, CMIS_VERSION_10, AlfrescoObjectFactoryImpl.class.getName());
    AlfrescoFolder docLibrary = (AlfrescoFolder) cmisSession.getObjectByPath("/Sites/" + siteName + "/documentLibrary");
    Map<String, String> properties = new HashMap<String, String>();
    {
        properties.put(PropertyIds.OBJECT_TYPE_ID, TYPE_CMIS_DOCUMENT);
        properties.put(PropertyIds.NAME, "mydoc-" + GUID.generate() + ".txt");
    }
    ContentStreamImpl fileContent = new ContentStreamImpl();
    {
        ContentWriter writer = new FileContentWriter(TempFileProvider.createTempFile(GUID.generate(), ".txt"));
        writer.putContent("Ipsum and so on");
        ContentReader reader = writer.getReader();
        fileContent.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
        fileContent.setStream(reader.getContentInputStream());
    }
    AlfrescoDocument doc = (AlfrescoDocument) docLibrary.createDocument(properties, fileContent, VersioningState.MAJOR);
    String versionLabel = doc.getVersionLabel();
    // ...and check that updating its properties does not create a new version
    properties = new HashMap<String, String>();
    {
        properties.put(PropertyIds.DESCRIPTION, GUID.generate());
    }
    AlfrescoDocument doc1 = (AlfrescoDocument) doc.updateProperties(properties);
    doc1 = (AlfrescoDocument) doc1.getObjectOfLatestVersion(false);
    String versionLabel1 = doc1.getVersionLabel();
    assertTrue(Float.parseFloat(versionLabel) < Float.parseFloat(versionLabel1));
    // ...and check that updating its content creates a new version
    fileContent = new ContentStreamImpl();
    {
        ContentWriter writer = new FileContentWriter(TempFileProvider.createTempFile(GUID.generate(), ".txt"));
        writer.putContent("Ipsum and so on and so on");
        ContentReader reader = writer.getReader();
        fileContent.setMimeType(MimetypeMap.MIMETYPE_TEXT_PLAIN);
        fileContent.setStream(reader.getContentInputStream());
    }
    doc1.setContentStream(fileContent, true);
    AlfrescoDocument doc2 = (AlfrescoDocument) doc1.getObjectOfLatestVersion(false);
    @SuppressWarnings("unused") String versionLabel2 = doc2.getVersionLabel();
    assertTrue("Set content stream should create a new version automatically", Float.parseFloat(versionLabel1) < Float.parseFloat(versionLabel2));
}
Also used : ContentStreamImpl(org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl) AlfrescoObjectFactoryImpl(org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl) AlfrescoDocument(org.alfresco.cmis.client.AlfrescoDocument) CmisSession(org.alfresco.rest.api.tests.client.PublicApiClient.CmisSession) HashMap(java.util.HashMap) TestSite(org.alfresco.rest.api.tests.RepoService.TestSite) AlfrescoFolder(org.alfresco.cmis.client.AlfrescoFolder) FileContentWriter(org.alfresco.repo.content.filestore.FileContentWriter) ContentReader(org.alfresco.service.cmr.repository.ContentReader) CmisUpdateConflictException(org.apache.chemistry.opencmis.commons.exceptions.CmisUpdateConflictException) CmisConstraintException(org.apache.chemistry.opencmis.commons.exceptions.CmisConstraintException) CmisPermissionDeniedException(org.apache.chemistry.opencmis.commons.exceptions.CmisPermissionDeniedException) CmisInvalidArgumentException(org.apache.chemistry.opencmis.commons.exceptions.CmisInvalidArgumentException) PublicApiException(org.alfresco.rest.api.tests.client.PublicApiException) CmisObjectNotFoundException(org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ContentWriter(org.alfresco.service.cmr.repository.ContentWriter) FileContentWriter(org.alfresco.repo.content.filestore.FileContentWriter) SiteInformation(org.alfresco.rest.api.tests.RepoService.SiteInformation) TestNetwork(org.alfresco.rest.api.tests.RepoService.TestNetwork) RequestContext(org.alfresco.rest.api.tests.client.RequestContext) TestPerson(org.alfresco.rest.api.tests.RepoService.TestPerson) VersionableAspectTest(org.alfresco.repo.version.VersionableAspectTest) Test(org.junit.Test)

Aggregations

TestPerson (org.alfresco.rest.api.tests.RepoService.TestPerson)43 TestNetwork (org.alfresco.rest.api.tests.RepoService.TestNetwork)36 PublicApiException (org.alfresco.rest.api.tests.client.PublicApiException)34 Test (org.junit.Test)34 RequestContext (org.alfresco.rest.api.tests.client.RequestContext)33 TestSite (org.alfresco.rest.api.tests.RepoService.TestSite)30 NodeRef (org.alfresco.service.cmr.repository.NodeRef)22 VersionableAspectTest (org.alfresco.repo.version.VersionableAspectTest)20 SiteInformation (org.alfresco.rest.api.tests.RepoService.SiteInformation)19 CmisSession (org.alfresco.rest.api.tests.client.PublicApiClient.CmisSession)19 HashMap (java.util.HashMap)18 CmisObjectNotFoundException (org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException)18 ArrayList (java.util.ArrayList)17 CmisConstraintException (org.apache.chemistry.opencmis.commons.exceptions.CmisConstraintException)17 CmisInvalidArgumentException (org.apache.chemistry.opencmis.commons.exceptions.CmisInvalidArgumentException)17 CmisPermissionDeniedException (org.apache.chemistry.opencmis.commons.exceptions.CmisPermissionDeniedException)17 CmisUpdateConflictException (org.apache.chemistry.opencmis.commons.exceptions.CmisUpdateConflictException)17 AlfrescoDocument (org.alfresco.cmis.client.AlfrescoDocument)15 List (java.util.List)12 AlfrescoFolder (org.alfresco.cmis.client.AlfrescoFolder)12