diff --git a/packaging/tests/tas-restapi/src/main/java/org/alfresco/rest/requests/People.java b/packaging/tests/tas-restapi/src/main/java/org/alfresco/rest/requests/People.java index 83207435af..008c203bd4 100644 --- a/packaging/tests/tas-restapi/src/main/java/org/alfresco/rest/requests/People.java +++ b/packaging/tests/tas-restapi/src/main/java/org/alfresco/rest/requests/People.java @@ -2,7 +2,7 @@ * #%L * alfresco-tas-restapi * %% - * Copyright (C) 2005 - 2022 Alfresco Software Limited + * Copyright (C) 2005 - 2024 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of @@ -29,6 +29,12 @@ import static io.restassured.RestAssured.given; import java.io.File; +import io.restassured.RestAssured; +import io.restassured.http.ContentType; +import io.restassured.response.ValidatableResponse; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; + import org.alfresco.rest.core.JsonBodyGenerator; import org.alfresco.rest.core.RestRequest; import org.alfresco.rest.core.RestResponse; @@ -56,12 +62,6 @@ import org.alfresco.utility.model.FileModel; import org.alfresco.utility.model.FolderModel; import org.alfresco.utility.model.SiteModel; import org.alfresco.utility.model.UserModel; -import org.springframework.http.HttpMethod; -import org.springframework.http.HttpStatus; - -import io.restassured.RestAssured; -import io.restassured.http.ContentType; -import io.restassured.response.ValidatableResponse; /** * Declares all Rest API under the /people path @@ -97,9 +97,7 @@ public class People extends ModelRequest } /** - * Retrieve list of activities for a specific person using GET call on "people/{personId}/activities" - * Please note that it retries to get the list of activities several times before returning the empty list. The list of activities are not displayed as - * they are created. + * Retrieve list of activities for a specific person using GET call on "people/{personId}/activities" Please note that it retries to get the list of activities several times before returning the empty list. The list of activities are not displayed as they are created. */ public RestActivityModelsCollection getPersonActivitiesUntilEntriesCountIs(int expectedNoOfEntries) { @@ -173,6 +171,15 @@ public class People extends ModelRequest return restWrapper.processModel(RestPreferenceModel.class, request); } + /** + * Updates a specific preference of a specific person using PUT call on "people/{personId}/preferences/{preferenceName}" + */ + public RestPreferenceModel updatePersonPreferenceInformation(String preferenceName, RestPreferenceModel preferenceModel) + { + RestRequest request = RestRequest.requestWithBody(HttpMethod.PUT, preferenceModel.toJson(), "people/{personId}/preferences/{preferenceName}", this.person.getUsername(), preferenceName); + return restWrapper.processModel(RestPreferenceModel.class, request); + } + /** * Remove a specific site from favorite sites list of a person using DELETE call on "people/{personId}/favorite-sites/{siteId}" */ @@ -334,7 +341,7 @@ public class People extends ModelRequest */ public RestWrapper deleteSiteFromFavorites(SiteModel site) { - RestRequest request = RestRequest.simpleRequest(HttpMethod.DELETE, "people/{personId}/favorites/{favoriteId}", this.person.getUsername(), site.getGuid()); + RestRequest request = RestRequest.simpleRequest(HttpMethod.DELETE, "people/{personId}/favorites/{favoriteId}", this.person.getUsername(), site.getGuid()); restWrapper.processEmptyModel(request); return restWrapper; } @@ -379,7 +386,7 @@ public class People extends ModelRequest public RestNetworkModel getNetwork(UserModel tenant) { Utility.checkObjectIsInitialized(tenant.getDomain(), "tenant.getDomain()"); - String personId = tenant.getUsername().contains("-me-@")? "-me-" : tenant.getUsername(); + String personId = tenant.getUsername().contains("-me-@") ? "-me-" : tenant.getUsername(); RestRequest request = RestRequest.simpleRequest(HttpMethod.GET, "people/{personId}/networks/{networkId}?{parameters}", personId, tenant.getDomain(), restWrapper.getParameters()); return restWrapper.processModel(RestNetworkModel.class, request); } @@ -410,10 +417,9 @@ public class People extends ModelRequest RestRequest request = RestRequest.requestWithBody(HttpMethod.POST, newPerson.toJson(), "people"); return restWrapper.processModel(RestPersonModel.class, request); } - + /** - * Get people avatar image using GET call on '/people/{personId}/avatar Please note that it retries to get the - * renditions response several times because on the alfresco server the rendition can take a while to be created. + * Get people avatar image using GET call on '/people/{personId}/avatar Please note that it retries to get the renditions response several times because on the alfresco server the rendition can take a while to be created. */ public RestResponse downloadAvatarContent() { @@ -456,17 +462,8 @@ public class People extends ModelRequest return new WhereClause(this); } -/** - * Construct the Where clause of getFavorites - * You can use the where parameter to restrict the list in the response to entries of a specific kind. The where parameter takes a value. The value is a - * single predicate that can include one or more EXISTS conditions. The EXISTS condition uses a single operand to limit the list to include entries that - * include that one property. The property values are:- - * target/file - * target/folder - * target/site - * Usage: - * where.. targetFileExist().or().targetSiteExist().filterAnd().getFavorites(...) - * At this point this method is working only with @link {@link RestFavoritesApi#getFavorites(UserModel) method. + /** + * Construct the Where clause of getFavorites You can use the where parameter to restrict the list in the response to entries of a specific kind. The where parameter takes a value. The value is a single predicate that can include one or more EXISTS conditions. The EXISTS condition uses a single operand to limit the list to include entries that include that one property. The property values are:- target/file target/folder target/site Usage: where.. targetFileExist().or().targetSiteExist().filterAnd().getFavorites(...) At this point this method is working only with @link {@link RestFavoritesApi#getFavorites(UserModel) method. * * @author paul.brodner */ diff --git a/packaging/tests/tas-restapi/src/test/java/org/alfresco/rest/people/preferences/GetPeoplePreferenceFullTests.java b/packaging/tests/tas-restapi/src/test/java/org/alfresco/rest/people/preferences/GetPeoplePreferenceFullTests.java index f0d7172220..927f06e943 100644 --- a/packaging/tests/tas-restapi/src/test/java/org/alfresco/rest/people/preferences/GetPeoplePreferenceFullTests.java +++ b/packaging/tests/tas-restapi/src/test/java/org/alfresco/rest/people/preferences/GetPeoplePreferenceFullTests.java @@ -1,5 +1,11 @@ package org.alfresco.rest.people.preferences; +import java.nio.file.Paths; + +import org.springframework.http.HttpStatus; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + import org.alfresco.rest.RestTest; import org.alfresco.rest.model.RestErrorModel; import org.alfresco.rest.model.RestPreferenceModel; @@ -9,11 +15,6 @@ import org.alfresco.utility.model.*; import org.alfresco.utility.report.Bug; import org.alfresco.utility.testrail.ExecutionType; import org.alfresco.utility.testrail.annotation.TestRail; -import org.springframework.http.HttpStatus; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; - -import java.nio.file.Paths; public class GetPeoplePreferenceFullTests extends RestTest { @@ -29,53 +30,53 @@ public class GetPeoplePreferenceFullTests extends RestTest dataSite.usingUser(userModel).usingSite(siteModel).addSiteToFavorites(); } - @Test(groups = { TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.REGRESSION }) - @TestRail(section = { TestGroup.REST_API, TestGroup.PEOPLE,TestGroup.PREFERENCES }, executionType = ExecutionType.REGRESSION, - description = "Check that properties parameter is applied") + @Test(groups = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.REGRESSION}) + @TestRail(section = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES}, executionType = ExecutionType.REGRESSION, + description = "Check that properties parameter is applied") public void propertiesParameterIsAppliedWhenRetrievingPreference() throws Exception { restPreferenceModel = restClient.authenticateUser(userModel).withParams("properties=id").withCoreAPI().usingUser(userModel) .getPersonPreferenceInformation(String.format(PreferenceName.SITES_FAVORITES_PREFIX.toString(), siteModel.getId())); restClient.assertStatusCodeIs(HttpStatus.OK); restPreferenceModel.assertThat().field("id").is(String.format(PreferenceName.SITES_FAVORITES_PREFIX.toString(), siteModel.getId())) - .and().field("value").isNull(); - + .and().field("value").isNull(); + restPreferenceModel = restClient.authenticateUser(userModel).withParams("properties=id,value").withCoreAPI().usingUser(userModel) .getPersonPreferenceInformation(String.format(PreferenceName.SITES_FAVORITES_PREFIX.toString(), siteModel.getId())); restClient.assertStatusCodeIs(HttpStatus.OK); restPreferenceModel.assertThat().field("id").is(String.format(PreferenceName.SITES_FAVORITES_PREFIX.toString(), siteModel.getId())) - .and().field("value").is("true"); - } - - @Test(groups = { TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.REGRESSION }) - @TestRail(section = { TestGroup.REST_API, TestGroup.PEOPLE,TestGroup.PREFERENCES }, executionType = ExecutionType.REGRESSION, - description = "Validate ID element in get site preference response") + .and().field("value").is("true"); + } + + @Test(groups = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.REGRESSION}) + @TestRail(section = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES}, executionType = ExecutionType.REGRESSION, + description = "Validate ID element in get site preference response") public void validateIdElementInGetSitePreferenceResponse() throws Exception { restPreferenceModel = restClient.authenticateUser(userModel).withCoreAPI().usingAuthUser() .getPersonPreferenceInformation(String.format(PreferenceName.SITES_FAVORITES_PREFIX.toString(), siteModel.getId())); restPreferenceModel.assertThat().field("id").is(String.format(PreferenceName.SITES_FAVORITES_PREFIX.toString(), siteModel.getId())) - .and().field("value").is("true"); - } - - @Test(groups = { TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.REGRESSION }) - @TestRail(section = { TestGroup.REST_API,TestGroup.PEOPLE, TestGroup.PREFERENCES }, executionType = ExecutionType.REGRESSION, - description = "Validate ID element in get folder preference response") + .and().field("value").is("true"); + } + + @Test(groups = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.REGRESSION}) + @TestRail(section = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES}, executionType = ExecutionType.REGRESSION, + description = "Validate ID element in get folder preference response") public void validateIdElementInGetFolderPreferenceResponse() throws Exception { FolderModel folderFavorite = new FolderModel("favoriteFolder"); folderFavorite = dataContent.usingSite(siteModel).createFolder(folderFavorite); dataContent.getContentActions().setFolderAsFavorite(userModel.getUsername(), userModel.getPassword(), siteModel.getId(), folderFavorite.getName()); - + restPreferenceModel = restClient.authenticateUser(userModel).withCoreAPI().usingAuthUser() .getPersonPreferenceInformation(PreferenceName.FOLDERS_FAVORITES_PREFIX.toString()); restPreferenceModel.assertThat().field("id").is(PreferenceName.FOLDERS_FAVORITES_PREFIX) - .and().field("value").is(Utility.removeLastSlash(Utility.buildPath("workspace://SpacesStore", folderFavorite.getNodeRef()))); - } - - @Test(groups = { TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.REGRESSION }) - @TestRail(section = { TestGroup.REST_API,TestGroup.PEOPLE, TestGroup.PREFERENCES }, executionType = ExecutionType.REGRESSION, - description = "Validate ID element in get file preference response") + .and().field("value").is(Utility.removeLastSlash(Utility.buildPath("workspace://SpacesStore", folderFavorite.getNodeRef()))); + } + + @Test(groups = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.REGRESSION}) + @TestRail(section = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES}, executionType = ExecutionType.REGRESSION, + description = "Validate ID element in get file preference response") public void validateIdElementInGetFilePreferenceResponse() throws Exception { FileModel fileFavorite = new FileModel("favoriteFile", FileType.TEXT_PLAIN); @@ -85,86 +86,86 @@ public class GetPeoplePreferenceFullTests extends RestTest restPreferenceModel = restClient.authenticateUser(userModel).withCoreAPI().usingAuthUser() .getPersonPreferenceInformation(PreferenceName.DOCUMENTS_FAVORITES_PREFIX.toString()); restPreferenceModel.assertThat().field("id").is(PreferenceName.DOCUMENTS_FAVORITES_PREFIX) - .and().field("value").is(Utility.removeLastSlash(Utility.buildPath("workspace://SpacesStore", fileFavorite.getNodeRefWithoutVersion()))); - } - - @Test(groups = { TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.REGRESSION }) - @TestRail(section = { TestGroup.REST_API, TestGroup.PEOPLE,TestGroup.PREFERENCES }, executionType = ExecutionType.REGRESSION, - description = "Get preference of an user that has no preferences") + .and().field("value").is(Utility.removeLastSlash(Utility.buildPath("workspace://SpacesStore", fileFavorite.getNodeRefWithoutVersion()))); + } + + @Test(groups = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.REGRESSION}) + @TestRail(section = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES}, executionType = ExecutionType.REGRESSION, + description = "Get preference of an user that has no preferences") public void getPreferenceForUserWithoutPreferences() throws Exception { UserModel newUser = dataUser.createRandomTestUser(); - + restPreferenceModel = restClient.authenticateUser(newUser).withCoreAPI().usingAuthUser() .getPersonPreferenceInformation(PreferenceName.DOCUMENTS_FAVORITES_PREFIX.toString()); restClient.assertLastError().containsSummary( String.format("The relationship resource was not found for the" + " entity with id: %s and a relationship id of %s", newUser.getUsername(), PreferenceName.DOCUMENTS_FAVORITES_PREFIX.toString())); - + restPreferenceModel = restClient.authenticateUser(newUser).withCoreAPI().usingAuthUser() .getPersonPreferenceInformation(PreferenceName.FOLDERS_FAVORITES_PREFIX.toString()); restClient.assertLastError().containsSummary( String.format("The relationship resource was not found for the" + " entity with id: %s and a relationship id of %s", newUser.getUsername(), PreferenceName.FOLDERS_FAVORITES_PREFIX.toString())); - + restPreferenceModel = restClient.authenticateUser(newUser).withCoreAPI().usingAuthUser() .getPersonPreferenceInformation(PreferenceName.SITES_FAVORITES_PREFIX.toString()); restClient.assertLastError().containsSummary( String.format("The relationship resource was not found for the" + " entity with id: %s and a relationship id of %s", newUser.getUsername(), PreferenceName.SITES_FAVORITES_PREFIX.toString())); - } - - @Test(groups = { TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.REGRESSION }) - @TestRail(section = { TestGroup.REST_API, TestGroup.PEOPLE,TestGroup.PREFERENCES }, executionType = ExecutionType.REGRESSION, - description = "Change one preference for an user then perform get call") + } + + @Test(groups = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.REGRESSION}) + @TestRail(section = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES}, executionType = ExecutionType.REGRESSION, + description = "Change one preference for an user then perform get call") @Bug(id = "REPO-1922") public void changePreferenceThenPerformGetPreferenceCall() throws Exception { UserModel newUser = dataUser.createRandomTestUser(); SiteModel site = dataSite.usingUser(newUser).createPublicRandomSite(); - + dataSite.usingUser(newUser).usingSite(site).addSiteToFavorites(); - + FileModel fileFavorite = new FileModel("favoriteFile", FileType.TEXT_PLAIN); fileFavorite = dataContent.usingSite(site).createContent(fileFavorite); dataContent.getContentActions().setFileAsFavorite(newUser.getUsername(), newUser.getPassword(), site.getId(), String.format("%s.%s", fileFavorite.getName(), fileFavorite.getFileType().extension)); - + FolderModel folderFavorite = new FolderModel("favoriteFolder"); folderFavorite = dataContent.usingSite(site).createFolder(folderFavorite); dataContent.getContentActions().setFolderAsFavorite(newUser.getUsername(), newUser.getPassword(), site.getId(), folderFavorite.getName()); - + dataSite.usingUser(newUser).usingSite(site).removeSiteFromFavorites(); dataContent.getContentActions().removeFavorite(newUser.getUsername(), newUser.getPassword(), site.getId(), folderFavorite.getName()); dataContent.getContentActions().removeFavorite(newUser.getUsername(), newUser.getPassword(), site.getId(), Paths.get(fileFavorite.getCmisLocation()).getFileName().toString()); - + restPreferenceModel = restClient.authenticateUser(newUser).withCoreAPI().usingAuthUser() .getPersonPreferenceInformation(PreferenceName.FOLDERS_FAVORITES_PREFIX.toString()); restClient.assertLastError().containsSummary( String.format("The relationship resource was not found for the" + " entity with id: %s and a relationship id of %s", newUser.getUsername(), PreferenceName.FOLDERS_FAVORITES_PREFIX.toString())); - + restPreferenceModel = restClient.authenticateUser(newUser).withCoreAPI().usingAuthUser() .getPersonPreferenceInformation(PreferenceName.SITES_FAVORITES_PREFIX.toString()); restClient.assertLastError().containsSummary( String.format("The relationship resource was not found for the" + " entity with id: %s and a relationship id of %s", newUser.getUsername(), PreferenceName.SITES_FAVORITES_PREFIX.toString())); - + restPreferenceModel = restClient.authenticateUser(newUser).withCoreAPI().usingAuthUser() .getPersonPreferenceInformation(PreferenceName.DOCUMENTS_FAVORITES_PREFIX.toString()); restClient.assertLastError().containsSummary( String.format("The relationship resource was not found for the" + " entity with id: %s and a relationship id of %s", newUser.getUsername(), PreferenceName.DOCUMENTS_FAVORITES_PREFIX.toString())); - + restPreferenceModel = restClient.authenticateUser(newUser).withCoreAPI().usingAuthUser() .getPersonPreferenceInformation(PreferenceName.FOLDERS_FAVORITES_PREFIX.toString()); restClient.assertLastError().containsSummary( String.format("The relationship resource was not found for the" + " entity with id: %s and a relationship id of %s", newUser.getUsername(), PreferenceName.FOLDERS_FAVORITES_PREFIX.toString())); - } - - @Test(groups = { TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES, TestGroup.REGRESSION }) - @TestRail(section = { TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES }, executionType = ExecutionType.REGRESSION, - description = "Verify admin is able to get preference of another user") + } + + @Test(groups = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES, TestGroup.REGRESSION}) + @TestRail(section = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES}, executionType = ExecutionType.REGRESSION, + description = "Verify admin is able to get preference of another user") public void adminIsAbleToGetOtherUserPreference() throws Exception { restPreferenceModel = restClient.authenticateUser(dataUser.getAdminUser()).withCoreAPI().usingUser(userModel) @@ -172,18 +173,62 @@ public class GetPeoplePreferenceFullTests extends RestTest restClient.assertStatusCodeIs(HttpStatus.OK); restPreferenceModel.assertThat().field("id").is(String.format(PreferenceName.SITES_FAVORITES_PREFIX.toString(), siteModel.getId())).and().field("value").is("true"); } - - @Test(groups = { TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES, TestGroup.REGRESSION }) - @TestRail(section = { TestGroup.REST_API, TestGroup.PEOPLE,TestGroup.PREFERENCES }, executionType = ExecutionType.REGRESSION, - description = "Verify regular user is not able to get preference of admin user") + + @Test(groups = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES, TestGroup.REGRESSION}) + @TestRail(section = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES}, executionType = ExecutionType.REGRESSION, + description = "Verify regular user is not able to get preference of admin user") public void regularUserIsNotAbleToGetAdminPreference() throws Exception { SiteModel newSite = dataSite.usingUser(dataUser.getAdminUser()).createPublicRandomSite(); dataSite.usingUser(dataUser.getAdminUser()).usingSite(newSite).addSiteToFavorites(); - + restClient.authenticateUser(userModel).withCoreAPI().usingUser(dataUser.getAdminUser()) .getPersonPreferenceInformation(PreferenceName.SITES_FAVORITES_PREFIX + newSite.getId()); restClient.assertStatusCodeIs(HttpStatus.FORBIDDEN); restClient.assertLastError().containsSummary(RestErrorModel.PERMISSION_WAS_DENIED); } -} \ No newline at end of file + + @Test(groups = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES, TestGroup.REGRESSION}) + @TestRail(section = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES}, executionType = ExecutionType.REGRESSION, + description = "Verify regular user is able to change own preferences") + public void regularUserIsAbleToChangeOwnPreference() throws Exception + { + var newUser = dataUser.createRandomTestUser(); + var newSite = dataSite.usingUser(newUser).createPublicRandomSite(); + var preferenceId = String.format(PreferenceName.SITES_FAVORITES_PREFIX.toString(), newSite.getId()); + var updatedPreferenceModel = new RestPreferenceModel(); + updatedPreferenceModel.setId(preferenceId); + updatedPreferenceModel.setValue(""); + + dataSite.usingUser(newUser).usingSite(newSite).addSiteToFavorites(); + restClient.authenticateUser(newUser).withCoreAPI().usingAuthUser() + .getPersonPreferenceInformation(preferenceId); + restClient.assertStatusCodeIs(HttpStatus.OK); + + restClient.authenticateUser(newUser).withCoreAPI().usingAuthUser().updatePersonPreferenceInformation(preferenceId, updatedPreferenceModel); + restClient.assertStatusCodeIs(HttpStatus.OK); + var personPreferences = restClient.authenticateUser(newUser).withCoreAPI().usingAuthUser().getPersonPreferences(); + personPreferences.assertThat().entriesListDoesNotContain("id", preferenceId); + } + + @Test(groups = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES, TestGroup.REGRESSION}) + @TestRail(section = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES}, executionType = ExecutionType.REGRESSION, + description = "Verify admin is not able to change regular user preferences") + public void adminIsNotAbleToChangeRegularUserPreference() throws Exception + { + var newUser = dataUser.createRandomTestUser(); + var newSite = dataSite.usingUser(newUser).createPublicRandomSite(); + var preferenceId = String.format(PreferenceName.SITES_FAVORITES_PREFIX.toString(), newSite.getId()); + var updatedPreferenceModel = new RestPreferenceModel(); + updatedPreferenceModel.setId(preferenceId); + updatedPreferenceModel.setValue(""); + + dataSite.usingUser(newUser).usingSite(newSite).addSiteToFavorites(); + restClient.authenticateUser(newUser).withCoreAPI().usingAuthUser() + .getPersonPreferenceInformation(preferenceId); + restClient.assertStatusCodeIs(HttpStatus.OK); + + restClient.authenticateUser(dataUser.getAdminUser()).withCoreAPI().usingUser(newUser).updatePersonPreferenceInformation(preferenceId, updatedPreferenceModel); + restClient.assertStatusCodeIs(HttpStatus.NOT_FOUND); + } +} diff --git a/packaging/tests/tas-restapi/src/test/java/org/alfresco/rest/people/preferences/GetPeoplePreferenceSanityTests.java b/packaging/tests/tas-restapi/src/test/java/org/alfresco/rest/people/preferences/GetPeoplePreferenceSanityTests.java index ccfd5f1cee..9c3dddf616 100644 --- a/packaging/tests/tas-restapi/src/test/java/org/alfresco/rest/people/preferences/GetPeoplePreferenceSanityTests.java +++ b/packaging/tests/tas-restapi/src/test/java/org/alfresco/rest/people/preferences/GetPeoplePreferenceSanityTests.java @@ -1,7 +1,10 @@ package org.alfresco.rest.people.preferences; +import org.springframework.http.HttpStatus; +import org.testng.annotations.BeforeClass; +import org.testng.annotations.Test; + import org.alfresco.rest.RestTest; -import org.alfresco.rest.model.RestErrorModel; import org.alfresco.rest.model.RestPreferenceModel; import org.alfresco.utility.constants.PreferenceName; import org.alfresco.utility.constants.UserRole; @@ -10,9 +13,6 @@ import org.alfresco.utility.model.TestGroup; import org.alfresco.utility.model.UserModel; import org.alfresco.utility.testrail.ExecutionType; import org.alfresco.utility.testrail.annotation.TestRail; -import org.springframework.http.HttpStatus; -import org.testng.annotations.BeforeClass; -import org.testng.annotations.Test; /** * Tests for Get a Peference (/people/{personId}/preferences/{preferenceName}) RestAPI call @@ -33,8 +33,8 @@ public class GetPeoplePreferenceSanityTests extends RestTest siteModel = dataSite.usingUser(userModel).createPublicRandomSite(); } - @Test(groups = { TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES, TestGroup.SANITY }) - @TestRail(section = { TestGroup.REST_API, TestGroup.PEOPLE,TestGroup.PREFERENCES }, executionType = ExecutionType.SANITY, description = "Verify manager user gets a specific preference with Rest API and response is successful (200)") + @Test(groups = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES, TestGroup.SANITY}) + @TestRail(section = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES}, executionType = ExecutionType.SANITY, description = "Verify manager user gets a specific preference with Rest API and response is successful (200)") public void managerUserGetsAPreferenceWithSuccess() throws Exception { UserModel managerUser = dataUser.usingAdmin().createRandomTestUser(); @@ -47,8 +47,8 @@ public class GetPeoplePreferenceSanityTests extends RestTest restPreferenceModel.assertThat().field("id").is(String.format(PreferenceName.SITES_FAVORITES_PREFIX.toString(), siteModel.getId())).and().field("value").is("true"); } - @Test(groups = { TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES, TestGroup.SANITY }) - @TestRail(section = { TestGroup.REST_API, TestGroup.PEOPLE,TestGroup.PREFERENCES }, executionType = ExecutionType.SANITY, description = "Verify collaborator user gets a specific preference with Rest API and response is successful (200)") + @Test(groups = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES, TestGroup.SANITY}) + @TestRail(section = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES}, executionType = ExecutionType.SANITY, description = "Verify collaborator user gets a specific preference with Rest API and response is successful (200)") public void collaboratorUserGetsAPreferenceWithSuccess() throws Exception { UserModel collaboratorUser = dataUser.usingAdmin().createRandomTestUser(); @@ -61,8 +61,24 @@ public class GetPeoplePreferenceSanityTests extends RestTest restPreferenceModel.assertThat().field("id").is(String.format(PreferenceName.SITES_FAVORITES_PREFIX.toString(), siteModel.getId())).and().field("value").is("true"); } - @Test(groups = { TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES, TestGroup.SANITY }) - @TestRail(section = { TestGroup.REST_API, TestGroup.PEOPLE,TestGroup.PREFERENCES }, executionType = ExecutionType.SANITY, description = "Verify contributor user gets a specific preference with Rest API and response is successful (200)") + @Test(groups = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES, TestGroup.SANITY}) + @TestRail(section = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES}, executionType = ExecutionType.SANITY, description = "Verify collaborator user gets a specific preference with Rest API and response is successful (200)") + public void collaboratorUserUpdatesAPreferenceWithSuccess() throws Exception + { + UserModel collaboratorUser = dataUser.usingAdmin().createRandomTestUser(); + + var updatedRestPreferenceModel = new RestPreferenceModel(); + updatedRestPreferenceModel.setId("user.preference"); + updatedRestPreferenceModel.setValue("user.value"); + + restPreferenceModel = restClient.authenticateUser(collaboratorUser).withCoreAPI().usingAuthUser() + .updatePersonPreferenceInformation(updatedRestPreferenceModel.getId(), updatedRestPreferenceModel); + restClient.assertStatusCodeIs(HttpStatus.OK); + restPreferenceModel.assertThat().field("id").is("user.preference").and().field("value").is("user.value"); + } + + @Test(groups = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES, TestGroup.SANITY}) + @TestRail(section = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES}, executionType = ExecutionType.SANITY, description = "Verify contributor user gets a specific preference with Rest API and response is successful (200)") public void contributorUserGetsAPreferenceWithSuccess() throws Exception { UserModel contributorUser = dataUser.usingAdmin().createRandomTestUser(); @@ -75,8 +91,8 @@ public class GetPeoplePreferenceSanityTests extends RestTest restPreferenceModel.assertThat().field("id").is(String.format(PreferenceName.SITES_FAVORITES_PREFIX.toString(), siteModel.getId())).and().field("value").is("true"); } - @Test(groups = { TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES, TestGroup.SANITY }) - @TestRail(section = { TestGroup.REST_API,TestGroup.PEOPLE, TestGroup.PREFERENCES }, executionType = ExecutionType.SANITY, description = "Verify consumer user gets a specific preference with Rest API and response is successful (200)") + @Test(groups = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES, TestGroup.SANITY}) + @TestRail(section = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES}, executionType = ExecutionType.SANITY, description = "Verify consumer user gets a specific preference with Rest API and response is successful (200)") public void consumerUserGetsAPreferenceWithSuccess() throws Exception { UserModel consumerUser = dataUser.usingAdmin().createRandomTestUser(); @@ -84,13 +100,13 @@ public class GetPeoplePreferenceSanityTests extends RestTest dataSite.usingUser(consumerUser).usingSite(siteModel).addSiteToFavorites(); restPreferenceModel = restClient.authenticateUser(consumerUser).withCoreAPI().usingAuthUser() - .getPersonPreferenceInformation(String.format(PreferenceName.SITES_FAVORITES_PREFIX.toString(),siteModel.getId())); + .getPersonPreferenceInformation(String.format(PreferenceName.SITES_FAVORITES_PREFIX.toString(), siteModel.getId())); restClient.assertStatusCodeIs(HttpStatus.OK); - restPreferenceModel.assertThat().field("id").is(String.format(PreferenceName.SITES_FAVORITES_PREFIX.toString(),siteModel.getId())).and().field("value").is("true"); + restPreferenceModel.assertThat().field("id").is(String.format(PreferenceName.SITES_FAVORITES_PREFIX.toString(), siteModel.getId())).and().field("value").is("true"); } - @Test(groups = { TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES, TestGroup.SANITY }) - @TestRail(section = { TestGroup.REST_API, TestGroup.PEOPLE,TestGroup.PREFERENCES }, executionType = ExecutionType.SANITY, description = "Verify admin user gets a specific preference with Rest API and response is successful (200)") + @Test(groups = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES, TestGroup.SANITY}) + @TestRail(section = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES}, executionType = ExecutionType.SANITY, description = "Verify admin user gets a specific preference with Rest API and response is successful (200)") public void adminUserGetsAPreferenceWithSuccess() throws Exception { UserModel adminUser = dataUser.getAdminUser(); @@ -102,9 +118,9 @@ public class GetPeoplePreferenceSanityTests extends RestTest restPreferenceModel.assertThat().field("id").is(String.format(PreferenceName.SITES_FAVORITES_PREFIX.toString(), siteModel.getId())).and().field("value").is("true"); } - @Test(groups = { TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES, TestGroup.SANITY }) - @TestRail(section = { TestGroup.REST_API, TestGroup.PEOPLE,TestGroup.PREFERENCES }, executionType = ExecutionType.SANITY, description = "Verify manager user is NOT Authorized to get a specific preference with Rest API when authentication fails (401)") -// @Bug(id = "MNT-16904", description = "fails only on environment with tenants") + @Test(groups = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES, TestGroup.SANITY}) + @TestRail(section = {TestGroup.REST_API, TestGroup.PEOPLE, TestGroup.PREFERENCES}, executionType = ExecutionType.SANITY, description = "Verify manager user is NOT Authorized to get a specific preference with Rest API when authentication fails (401)") + // @Bug(id = "MNT-16904", description = "fails only on environment with tenants") public void managerUserNotAuthorizedFailsToGetsAPreference() throws Exception { UserModel managerUser = dataUser.usingAdmin().createRandomTestUser(); diff --git a/remote-api/src/main/java/org/alfresco/rest/api/Preferences.java b/remote-api/src/main/java/org/alfresco/rest/api/Preferences.java index c8faeb99fc..fad0a18a59 100644 --- a/remote-api/src/main/java/org/alfresco/rest/api/Preferences.java +++ b/remote-api/src/main/java/org/alfresco/rest/api/Preferences.java @@ -2,7 +2,7 @@ * #%L * Alfresco Remote API * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited + * Copyright (C) 2005 - 2024 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of @@ -23,14 +23,17 @@ * along with Alfresco. If not, see . * #L% */ -package org.alfresco.rest.api; - -import org.alfresco.rest.api.model.Preference; -import org.alfresco.rest.framework.resource.parameters.CollectionWithPagingInfo; -import org.alfresco.rest.framework.resource.parameters.Paging; - -public interface Preferences -{ - public Preference getPreference(String personId, String preferenceName); - public CollectionWithPagingInfo getPreferences(String personId, Paging paging); -} +package org.alfresco.rest.api; + +import org.alfresco.rest.api.model.Preference; +import org.alfresco.rest.framework.resource.parameters.CollectionWithPagingInfo; +import org.alfresco.rest.framework.resource.parameters.Paging; + +public interface Preferences +{ + Preference getPreference(String personId, String preferenceName); + + CollectionWithPagingInfo getPreferences(String personId, Paging paging); + + Preference updatePreference(String personId, Preference preference); +} diff --git a/remote-api/src/main/java/org/alfresco/rest/api/impl/PreferencesImpl.java b/remote-api/src/main/java/org/alfresco/rest/api/impl/PreferencesImpl.java index abdf9ee8c6..b0d422ecb8 100644 --- a/remote-api/src/main/java/org/alfresco/rest/api/impl/PreferencesImpl.java +++ b/remote-api/src/main/java/org/alfresco/rest/api/impl/PreferencesImpl.java @@ -2,7 +2,7 @@ * #%L * Alfresco Remote API * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited + * Copyright (C) 2005 - 2024 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of @@ -23,69 +23,92 @@ * along with Alfresco. If not, see . * #L% */ -package org.alfresco.rest.api.impl; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.List; - -import org.alfresco.query.PagingResults; -import org.alfresco.rest.api.People; -import org.alfresco.rest.api.Preferences; -import org.alfresco.rest.api.model.Preference; -import org.alfresco.rest.framework.core.exceptions.RelationshipResourceNotFoundException; -import org.alfresco.rest.framework.resource.parameters.CollectionWithPagingInfo; -import org.alfresco.rest.framework.resource.parameters.Paging; -import org.alfresco.service.cmr.preference.PreferenceService; -import org.alfresco.util.Pair; - -/** - * Centralises access to preference services and maps between representations. - * - * @author steveglover - * @since publicapi1.0 - */ -public class PreferencesImpl implements Preferences -{ - private People people; - private PreferenceService preferenceService; - - public void setPeople(People people) - { - this.people = people; - } - - public void setPreferenceService(PreferenceService preferenceService) - { - this.preferenceService = preferenceService; - } - - public Preference getPreference(String personId, String preferenceName) - { - personId = people.validatePerson(personId); - Serializable preferenceValue = preferenceService.getPreference(personId, preferenceName); - if(preferenceValue != null) - { - return new Preference(preferenceName, preferenceValue); - } - else - { - throw new RelationshipResourceNotFoundException(personId, preferenceName); - } - } - - public CollectionWithPagingInfo getPreferences(String personId, Paging paging) - { - personId = people.validatePerson(personId); - - PagingResults> preferences = preferenceService.getPagedPreferences(personId, null, Util.getPagingRequest(paging)); - List ret = new ArrayList(preferences.getPage().size()); - for(Pair prefEntity : preferences.getPage()) - { - Preference pref = new Preference(prefEntity.getFirst(), prefEntity.getSecond()); - ret.add(pref); - } - - return CollectionWithPagingInfo.asPaged(paging, ret, preferences.hasMoreItems(), preferences.getTotalResultCount().getFirst()); - } -} +package org.alfresco.rest.api.impl; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.alfresco.query.PagingResults; +import org.alfresco.rest.api.People; +import org.alfresco.rest.api.Preferences; +import org.alfresco.rest.api.model.Preference; +import org.alfresco.rest.framework.core.exceptions.RelationshipResourceNotFoundException; +import org.alfresco.rest.framework.resource.parameters.CollectionWithPagingInfo; +import org.alfresco.rest.framework.resource.parameters.Paging; +import org.alfresco.service.cmr.preference.PreferenceService; +import org.alfresco.util.Pair; + +/** + * Centralises access to preference services and maps between representations. + * + * @author steveglover + * @since publicapi1.0 + */ +public class PreferencesImpl implements Preferences +{ + private People people; + private PreferenceService preferenceService; + + public void setPeople(People people) + { + this.people = people; + } + + public void setPreferenceService(PreferenceService preferenceService) + { + this.preferenceService = preferenceService; + } + + @Override + public Preference getPreference(String personId, String preferenceName) + { + personId = people.validatePerson(personId); + Serializable preferenceValue = preferenceService.getPreference(personId, preferenceName); + if (preferenceValue != null) + { + return new Preference(preferenceName, preferenceValue); + } + else + { + throw new RelationshipResourceNotFoundException(personId, preferenceName); + } + } + + @Override + public CollectionWithPagingInfo getPreferences(String personId, Paging paging) + { + personId = people.validatePerson(personId); + + PagingResults> preferences = preferenceService.getPagedPreferences(personId, null, Util.getPagingRequest(paging)); + List ret = new ArrayList<>(preferences.getPage().size()); + for (Pair prefEntity : preferences.getPage()) + { + Preference pref = new Preference(prefEntity.getFirst(), prefEntity.getSecond()); + ret.add(pref); + } + + return CollectionWithPagingInfo.asPaged(paging, ret, preferences.hasMoreItems(), preferences.getTotalResultCount().getFirst()); + } + + @Override + public Preference updatePreference(String personId, Preference preference) + { + personId = people.validatePerson(personId, true); + final Map preferencesToSet; + if (preference.getValue() == null || "".equals(preference.getValue())) + { + preferencesToSet = new HashMap<>(1); + preferencesToSet.put(preference.getName(), null); + } + else + { + preferencesToSet = Map.of(preference.getName(), preference.getValue()); + } + + preferenceService.setPreferences(personId, preferencesToSet); + return new Preference(preference.getName(), preferenceService.getPreference(personId, preference.getName())); + } +} diff --git a/remote-api/src/main/java/org/alfresco/rest/api/people/PersonPreferencesRelation.java b/remote-api/src/main/java/org/alfresco/rest/api/people/PersonPreferencesRelation.java index b5ca948cf2..ab9335e136 100644 --- a/remote-api/src/main/java/org/alfresco/rest/api/people/PersonPreferencesRelation.java +++ b/remote-api/src/main/java/org/alfresco/rest/api/people/PersonPreferencesRelation.java @@ -1,93 +1,105 @@ -/* - * #%L - * Alfresco Remote API - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.rest.api.people; - -import org.alfresco.rest.api.Preferences; -import org.alfresco.rest.api.model.Preference; -import org.alfresco.rest.framework.WebApiDescription; -import org.alfresco.rest.framework.resource.RelationshipResource; -import org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction; -import org.alfresco.rest.framework.resource.parameters.CollectionWithPagingInfo; -import org.alfresco.rest.framework.resource.parameters.Parameters; -import org.alfresco.util.ParameterCheck; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.beans.factory.InitializingBean; - -@RelationshipResource(name = "preferences", entityResource = PeopleEntityResource.class, title = "Person Preferences") -public class PersonPreferencesRelation implements RelationshipResourceAction.Read, RelationshipResourceAction.ReadById, InitializingBean -{ - private static final Log logger = LogFactory.getLog(PersonPreferencesRelation.class); - - private Preferences preferences; - - public void setPreferences(Preferences preferences) - { - this.preferences = preferences; - } - - @Override - public void afterPropertiesSet() - { - ParameterCheck.mandatory("preferences", this.preferences); - } - - /** - * Returns a paged list of preferences for the user personId. - * - * If personId does not exist, NotFoundException (status 404). - * - * @see org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction.Read#readAll(java.lang.String, org.alfresco.rest.framework.resource.parameters.Parameters) - */ - @Override - @WebApiDescription(title = "A paged list of the persons preferences.") - public CollectionWithPagingInfo readAll(String personId, Parameters parameters) - { - return preferences.getPreferences(personId, parameters.getPaging()); - } - - /** - * Returns information regarding the preference 'preferenceName' for user personId. - * - * If personId does not exist, NotFoundException (status 404). - * - * @see org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction.ReadById#readById(String, String, org.alfresco.rest.framework.resource.parameters.Parameters) - */ - @Override - @WebApiDescription(title = "Preference value for preference 'preferenceName' for person 'personId'.") - public Preference readById(String personId, String preferenceName, Parameters parameters) - { - // fix for REPO-855 - String url = parameters.getRequest().getURL(); - if(url.matches(".*workspace://SpacesStore/.*")){ - preferenceName += url.substring(url.indexOf("//SpacesStore/")); - } - // - - return preferences.getPreference(personId, preferenceName); - } - -} +/* + * #%L + * Alfresco Remote API + * %% + * Copyright (C) 2005 - 2024 Alfresco Software Limited + * %% + * This file is part of the Alfresco software. + * If the software was purchased under a paid Alfresco license, the terms of + * the paid license agreement will prevail. Otherwise, the software is + * provided under the following open source license terms: + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see . + * #L% + */ +package org.alfresco.rest.api.people; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.beans.factory.InitializingBean; + +import org.alfresco.rest.api.Preferences; +import org.alfresco.rest.api.model.Preference; +import org.alfresco.rest.framework.WebApiDescription; +import org.alfresco.rest.framework.core.exceptions.InvalidArgumentException; +import org.alfresco.rest.framework.resource.RelationshipResource; +import org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction; +import org.alfresco.rest.framework.resource.parameters.CollectionWithPagingInfo; +import org.alfresco.rest.framework.resource.parameters.Parameters; +import org.alfresco.util.ParameterCheck; + +@RelationshipResource(name = "preferences", entityResource = PeopleEntityResource.class, title = "Person Preferences") +public class PersonPreferencesRelation implements RelationshipResourceAction.Read, RelationshipResourceAction.ReadById, RelationshipResourceAction.Update, InitializingBean +{ + private static final Log logger = LogFactory.getLog(PersonPreferencesRelation.class); + + private Preferences preferences; + + public void setPreferences(Preferences preferences) + { + this.preferences = preferences; + } + + @Override + public void afterPropertiesSet() + { + ParameterCheck.mandatory("preferences", this.preferences); + } + + /** + * Returns a paged list of preferences for the user personId. + * + * If personId does not exist, NotFoundException (status 404). + * + * @see org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction.Read#readAll(java.lang.String, org.alfresco.rest.framework.resource.parameters.Parameters) + */ + @Override + @WebApiDescription(title = "A paged list of the persons preferences.") + public CollectionWithPagingInfo readAll(String personId, Parameters parameters) + { + return preferences.getPreferences(personId, parameters.getPaging()); + } + + /** + * Returns information regarding the preference 'preferenceName' for user personId. + * + * If personId does not exist, NotFoundException (status 404). + * + * @see org.alfresco.rest.framework.resource.actions.interfaces.RelationshipResourceAction.ReadById#readById(String, String, org.alfresco.rest.framework.resource.parameters.Parameters) + */ + @Override + @WebApiDescription(title = "Preference value for preference 'preferenceName' for person 'personId'.") + public Preference readById(String personId, String preferenceName, Parameters parameters) + { + // fix for REPO-855 + String url = parameters.getRequest().getURL(); + if (url.matches(".*workspace://SpacesStore/.*")) + { + preferenceName += url.substring(url.indexOf("//SpacesStore/")); + } + // + + return preferences.getPreference(personId, preferenceName); + } + + @Override + public Preference update(String personId, Preference preference, Parameters parameters) + { + if (preference.getName() == null || preference.getName().isBlank()) + { + throw new InvalidArgumentException(); + } + return preferences.updatePreference(personId, preference); + } +} diff --git a/remote-api/src/main/java/org/alfresco/rest/framework/webscripts/ResourceWebScriptPut.java b/remote-api/src/main/java/org/alfresco/rest/framework/webscripts/ResourceWebScriptPut.java index 9a63cef648..240f786d15 100644 --- a/remote-api/src/main/java/org/alfresco/rest/framework/webscripts/ResourceWebScriptPut.java +++ b/remote-api/src/main/java/org/alfresco/rest/framework/webscripts/ResourceWebScriptPut.java @@ -2,7 +2,7 @@ * #%L * Alfresco Remote API * %% - * Copyright (C) 2005 - 2020 Alfresco Software Limited + * Copyright (C) 2005 - 2024 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of @@ -30,6 +30,15 @@ import java.io.InputStream; import java.util.Locale; import java.util.Map; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.extensions.webscripts.WebScriptRequest; +import org.springframework.extensions.webscripts.WrappingWebScriptRequest; +import org.springframework.extensions.webscripts.servlet.WebScriptServletRequest; +import org.springframework.http.HttpMethod; +import org.springframework.http.MediaType; + import org.alfresco.repo.content.MimetypeMap; import org.alfresco.rest.framework.core.ResourceLocator; import org.alfresco.rest.framework.core.ResourceMetadata; @@ -47,14 +56,7 @@ import org.alfresco.rest.framework.resource.parameters.Params; import org.alfresco.rest.framework.resource.parameters.Params.RecognizedParams; import org.alfresco.rest.framework.tools.RecognizedParamsExtractor; import org.alfresco.rest.framework.tools.RequestReader; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.springframework.extensions.webscripts.WebScriptRequest; -import org.springframework.extensions.webscripts.WrappingWebScriptRequest; -import org.springframework.extensions.webscripts.servlet.WebScriptServletRequest; -import org.springframework.http.HttpMethod; -import org.springframework.http.MediaType; + /** * Handles the HTTP PUT for a Resource, equivalent to CRUD Update * @@ -64,15 +66,15 @@ public class ResourceWebScriptPut extends AbstractResourceWebScript implements P RecognizedParamsExtractor, RequestReader { - private static Log logger = LogFactory.getLog(ResourceWebScriptPut.class); - + private static final Log logger = LogFactory.getLog(ResourceWebScriptPut.class); + public ResourceWebScriptPut() { - super(); - setHttpMethod(HttpMethod.PUT); - setParamsExtractor(this); + super(); + setHttpMethod(HttpMethod.PUT); + setParamsExtractor(this); } - + @Override public Params extractParams(ResourceMetadata resourceMeta, WebScriptRequest req) { @@ -86,81 +88,87 @@ public class ResourceWebScriptPut extends AbstractResourceWebScript implements P switch (resourceMeta.getType()) { - case ENTITY: - if (StringUtils.isBlank(entityId)) - { - throw new UnsupportedResourceOperationException("PUT is executed against the instance URL"); - } else - { + case ENTITY: + if (StringUtils.isBlank(entityId)) + { + throw new UnsupportedResourceOperationException("PUT is executed against the instance URL"); + } + else + { - Object putEnt = extractJsonContent(req, assistant.getJsonHelper(), resourceMeta.getObjectType(operation)); - return Params.valueOf(entityId,params,putEnt, req); - } - case RELATIONSHIP: - if (StringUtils.isBlank(relationshipId)) + Object putEnt = extractJsonContent(req, assistant.getJsonHelper(), resourceMeta.getObjectType(operation)); + return Params.valueOf(entityId, params, putEnt, req); + } + case RELATIONSHIP: + if (StringUtils.isBlank(relationshipId)) + { + throw new UnsupportedResourceOperationException("PUT is executed against the instance URL"); + } + Object putRel = extractJsonContent(req, assistant.getJsonHelper(), resourceMeta.getObjectType(operation)); + if (StringUtils.isNotBlank(relationship2Id)) + { + ResourceWebScriptHelper.setUniqueId(putRel, relationship2Id); + return Params.valueOf(false, entityId, relationshipId, relationship2Id, + putRel, null, null, params, null, req); + } + else + { + ResourceWebScriptHelper.setUniqueId(putRel, relationshipId); + return Params.valueOf(entityId, relationshipId, params, putRel, req); + } + case PROPERTY: + final String resourceName = resourceVars.get(ResourceLocator.RELATIONSHIP_RESOURCE); + final String propertyName = resourceVars.get(ResourceLocator.PROPERTY); + + if (StringUtils.isNotBlank(entityId) && StringUtils.isNotBlank(resourceName)) + { + if (StringUtils.isNotBlank(propertyName)) { - throw new UnsupportedResourceOperationException("PUT is executed against the instance URL"); - } - Object putRel = extractJsonContent(req, assistant.getJsonHelper(), resourceMeta.getObjectType(operation)); - if (StringUtils.isNotBlank(relationship2Id)) - { - ResourceWebScriptHelper.setUniqueId(putRel, relationship2Id); - return Params.valueOf(false, entityId, relationshipId, relationship2Id, - putRel, null, null, params, null, req); + return Params.valueOf(entityId, relationshipId, null, getStream(req), propertyName, params, getContentInfo(req), req); } else { - ResourceWebScriptHelper.setUniqueId(putRel,relationshipId); - return Params.valueOf(entityId, params, putRel, req); + return Params.valueOf(entityId, null, null, getStream(req), resourceName, params, getContentInfo(req), req); } - case PROPERTY: - final String resourceName = resourceVars.get(ResourceLocator.RELATIONSHIP_RESOURCE); - final String propertyName = resourceVars.get(ResourceLocator.PROPERTY); - if (StringUtils.isNotBlank(entityId) && StringUtils.isNotBlank(resourceName)) - { - if (StringUtils.isNotBlank(propertyName)) - { - return Params.valueOf(entityId, relationshipId, null, getStream(req), propertyName, params, getContentInfo(req), req); - } - else - { - return Params.valueOf(entityId, null, null, getStream(req), resourceName, params, getContentInfo(req), req); - } - - } - //Fall through to unsupported. - default: - throw new UnsupportedResourceOperationException("PUT not supported for this request."); + } + // Fall through to unsupported. + default: + throw new UnsupportedResourceOperationException("PUT not supported for this request."); } } - /** + /** * Returns the basic content info from the request. - * @param req WebScriptRequest + * + * @param req + * WebScriptRequest * @return BasicContentInfo */ - private BasicContentInfo getContentInfo(WebScriptRequest req) { - - String encoding = "UTF-8"; - String contentType = MimetypeMap.MIMETYPE_BINARY; - - if (StringUtils.isNotEmpty(req.getContentType())) - { - MediaType media = MediaType.parseMediaType(req.getContentType()); - contentType = media.getType()+'/'+media.getSubtype(); - if (media.getCharset() != null) - { - encoding = media.getCharset().toString(); - } - } + private BasicContentInfo getContentInfo(WebScriptRequest req) + { + + String encoding = "UTF-8"; + String contentType = MimetypeMap.MIMETYPE_BINARY; + + if (StringUtils.isNotEmpty(req.getContentType())) + { + MediaType media = MediaType.parseMediaType(req.getContentType()); + contentType = media.getType() + '/' + media.getSubtype(); + if (media.getCharset() != null) + { + encoding = media.getCharset().toString(); + } + } return new ContentInfoImpl(contentType, encoding, -1, Locale.getDefault()); - } + } - /** + /** * Returns the input stream for the request - * @param req WebScriptRequest + * + * @param req + * WebScriptRequest * @return InputStream */ private InputStream getStream(WebScriptRequest req) @@ -186,11 +194,14 @@ public class ResourceWebScriptPut extends AbstractResourceWebScript implements P return null; } - + /** * Executes the action on the resource - * @param resource ResourceWithMetadata - * @param params parameters to use + * + * @param resource + * ResourceWithMetadata + * @param params + * parameters to use * @return anObject the result of the execute */ @Override @@ -198,87 +209,87 @@ public class ResourceWebScriptPut extends AbstractResourceWebScript implements P { switch (resource.getMetaData().getType()) { - case ENTITY: - if (EntityResourceAction.Update.class.isAssignableFrom(resource.getResource().getClass())) + case ENTITY: + if (EntityResourceAction.Update.class.isAssignableFrom(resource.getResource().getClass())) + { + if (resource.getMetaData().isDeleted(EntityResourceAction.Update.class)) { - if (resource.getMetaData().isDeleted(EntityResourceAction.Update.class)) - { - throw new DeletedResourceException("(UPDATE) "+resource.getMetaData().getUniqueId()); - } - EntityResourceAction.Update updateEnt = (EntityResourceAction.Update) resource.getResource(); - Object result = updateEnt.update(params.getEntityId(), params.getPassedIn(), params); - return result; + throw new DeletedResourceException("(UPDATE) " + resource.getMetaData().getUniqueId()); } - else + EntityResourceAction.Update updateEnt = (EntityResourceAction.Update) resource.getResource(); + Object result = updateEnt.update(params.getEntityId(), params.getPassedIn(), params); + return result; + } + else + { + if (resource.getMetaData().isDeleted(EntityResourceAction.UpdateWithResponse.class)) { - if (resource.getMetaData().isDeleted(EntityResourceAction.UpdateWithResponse.class)) - { - throw new DeletedResourceException("(UPDATE) "+resource.getMetaData().getUniqueId()); - } - EntityResourceAction.UpdateWithResponse updateEnt = (EntityResourceAction.UpdateWithResponse) resource.getResource(); - Object result = updateEnt.update(params.getEntityId(), params.getPassedIn(), params, withResponse); - return result; + throw new DeletedResourceException("(UPDATE) " + resource.getMetaData().getUniqueId()); } - case RELATIONSHIP: - if (RelationshipResourceAction.UpdateWithResponse.class.isAssignableFrom(resource.getResource().getClass())) + EntityResourceAction.UpdateWithResponse updateEnt = (EntityResourceAction.UpdateWithResponse) resource.getResource(); + Object result = updateEnt.update(params.getEntityId(), params.getPassedIn(), params, withResponse); + return result; + } + case RELATIONSHIP: + if (RelationshipResourceAction.UpdateWithResponse.class.isAssignableFrom(resource.getResource().getClass())) + { + if (resource.getMetaData().isDeleted(RelationshipResourceAction.UpdateWithResponse.class)) { - if (resource.getMetaData().isDeleted(RelationshipResourceAction.UpdateWithResponse.class)) - { - throw new DeletedResourceException("(UPDATE) "+resource.getMetaData().getUniqueId()); - } - RelationshipResourceAction.UpdateWithResponse relationUpdater = (RelationshipResourceAction.UpdateWithResponse) resource.getResource(); - Object relResult = relationUpdater.update(params.getEntityId(), params.getPassedIn(), params, withResponse); - return relResult; + throw new DeletedResourceException("(UPDATE) " + resource.getMetaData().getUniqueId()); } - else + RelationshipResourceAction.UpdateWithResponse relationUpdater = (RelationshipResourceAction.UpdateWithResponse) resource.getResource(); + Object relResult = relationUpdater.update(params.getEntityId(), params.getPassedIn(), params, withResponse); + return relResult; + } + else + { + if (resource.getMetaData().isDeleted(RelationshipResourceAction.Update.class)) { - if (resource.getMetaData().isDeleted(RelationshipResourceAction.Update.class)) - { - throw new DeletedResourceException("(UPDATE) "+resource.getMetaData().getUniqueId()); - } - RelationshipResourceAction.Update relationUpdater = (RelationshipResourceAction.Update) resource.getResource(); - Object relResult = relationUpdater.update(params.getEntityId(), params.getPassedIn(), params); - return relResult; + throw new DeletedResourceException("(UPDATE) " + resource.getMetaData().getUniqueId()); } - case PROPERTY: - if (BinaryResourceAction.Update.class.isAssignableFrom(resource.getResource().getClass())) + RelationshipResourceAction.Update relationUpdater = (RelationshipResourceAction.Update) resource.getResource(); + Object relResult = relationUpdater.update(params.getEntityId(), params.getPassedIn(), params); + return relResult; + } + case PROPERTY: + if (BinaryResourceAction.Update.class.isAssignableFrom(resource.getResource().getClass())) + { + if (resource.getMetaData().isDeleted(BinaryResourceAction.Update.class)) { - if (resource.getMetaData().isDeleted(BinaryResourceAction.Update.class)) - { - throw new DeletedResourceException("(UPDATE) "+resource.getMetaData().getUniqueId()); - } - BinaryResourceAction.Update binUpdater = (BinaryResourceAction.Update) resource.getResource(); - return binUpdater.updateProperty(params.getEntityId(), params.getContentInfo(), params.getStream(), params); + throw new DeletedResourceException("(UPDATE) " + resource.getMetaData().getUniqueId()); } - if (BinaryResourceAction.UpdateWithResponse.class.isAssignableFrom(resource.getResource().getClass())) + BinaryResourceAction.Update binUpdater = (BinaryResourceAction.Update) resource.getResource(); + return binUpdater.updateProperty(params.getEntityId(), params.getContentInfo(), params.getStream(), params); + } + if (BinaryResourceAction.UpdateWithResponse.class.isAssignableFrom(resource.getResource().getClass())) + { + if (resource.getMetaData().isDeleted(BinaryResourceAction.UpdateWithResponse.class)) { - if (resource.getMetaData().isDeleted(BinaryResourceAction.UpdateWithResponse.class)) - { - throw new DeletedResourceException("(UPDATE) "+resource.getMetaData().getUniqueId()); - } - BinaryResourceAction.UpdateWithResponse binUpdater = (BinaryResourceAction.UpdateWithResponse) resource.getResource(); - return binUpdater.updateProperty(params.getEntityId(), params.getContentInfo(), params.getStream(), params, withResponse); + throw new DeletedResourceException("(UPDATE) " + resource.getMetaData().getUniqueId()); } - if (RelationshipResourceBinaryAction.Update.class.isAssignableFrom(resource.getResource().getClass())) + BinaryResourceAction.UpdateWithResponse binUpdater = (BinaryResourceAction.UpdateWithResponse) resource.getResource(); + return binUpdater.updateProperty(params.getEntityId(), params.getContentInfo(), params.getStream(), params, withResponse); + } + if (RelationshipResourceBinaryAction.Update.class.isAssignableFrom(resource.getResource().getClass())) + { + if (resource.getMetaData().isDeleted(RelationshipResourceBinaryAction.Update.class)) { - if (resource.getMetaData().isDeleted(RelationshipResourceBinaryAction.Update.class)) - { - throw new DeletedResourceException("(UPDATE) "+resource.getMetaData().getUniqueId()); - } - RelationshipResourceBinaryAction.Update binUpdater = (RelationshipResourceBinaryAction.Update) resource.getResource(); - return binUpdater.updateProperty(params.getEntityId(), params.getRelationshipId(), params.getContentInfo(), params.getStream(), params); + throw new DeletedResourceException("(UPDATE) " + resource.getMetaData().getUniqueId()); } - if (RelationshipResourceBinaryAction.UpdateWithResponse.class.isAssignableFrom(resource.getResource().getClass())) + RelationshipResourceBinaryAction.Update binUpdater = (RelationshipResourceBinaryAction.Update) resource.getResource(); + return binUpdater.updateProperty(params.getEntityId(), params.getRelationshipId(), params.getContentInfo(), params.getStream(), params); + } + if (RelationshipResourceBinaryAction.UpdateWithResponse.class.isAssignableFrom(resource.getResource().getClass())) + { + if (resource.getMetaData().isDeleted(RelationshipResourceBinaryAction.UpdateWithResponse.class)) { - if (resource.getMetaData().isDeleted(RelationshipResourceBinaryAction.UpdateWithResponse.class)) - { - throw new DeletedResourceException("(UPDATE) "+resource.getMetaData().getUniqueId()); - } - RelationshipResourceBinaryAction.UpdateWithResponse binUpdater = (RelationshipResourceBinaryAction.UpdateWithResponse) resource.getResource(); - return binUpdater.updateProperty(params.getEntityId(), params.getRelationshipId(), params.getContentInfo(), params.getStream(), params, withResponse); + throw new DeletedResourceException("(UPDATE) " + resource.getMetaData().getUniqueId()); } - default: - throw new UnsupportedResourceOperationException("PUT not supported for Actions"); + RelationshipResourceBinaryAction.UpdateWithResponse binUpdater = (RelationshipResourceBinaryAction.UpdateWithResponse) resource.getResource(); + return binUpdater.updateProperty(params.getEntityId(), params.getRelationshipId(), params.getContentInfo(), params.getStream(), params, withResponse); + } + default: + throw new UnsupportedResourceOperationException("PUT not supported for Actions"); } } diff --git a/remote-api/src/test/java/org/alfresco/rest/api/tests/TestUserPreferences.java b/remote-api/src/test/java/org/alfresco/rest/api/tests/TestUserPreferences.java index 94d19555e0..dbdc6e00b8 100644 --- a/remote-api/src/test/java/org/alfresco/rest/api/tests/TestUserPreferences.java +++ b/remote-api/src/test/java/org/alfresco/rest/api/tests/TestUserPreferences.java @@ -1,416 +1,411 @@ -/* - * #%L - * Alfresco Remote API - * %% - * Copyright (C) 2005 - 2016 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.rest.api.tests; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.util.*; - -import org.alfresco.repo.tenant.TenantUtil; -import org.alfresco.repo.tenant.TenantUtil.TenantRunAsWork; -import org.alfresco.rest.api.tests.RepoService.TestNetwork; -import org.alfresco.rest.api.tests.RepoService.TestPerson; -import org.alfresco.rest.api.tests.client.PublicApiClient.ListResponse; -import org.alfresco.rest.api.tests.client.PublicApiClient.Paging; -import org.alfresco.rest.api.tests.client.PublicApiClient.People; -import org.alfresco.rest.api.tests.client.PublicApiException; -import org.alfresco.rest.api.tests.client.RequestContext; -import org.alfresco.rest.api.tests.client.data.Preference; -import org.alfresco.util.GUID; -import org.apache.commons.httpclient.HttpStatus; -import org.junit.Test; - -public class TestUserPreferences extends EnterpriseTestApi -{ - @Test - public void testUserPreferences() throws Exception - { - Iterator networksIt = getTestFixture().getNetworksIt(); - assertTrue(networksIt.hasNext()); - final TestNetwork network1 = networksIt.next(); - assertTrue(networksIt.hasNext()); - final TestNetwork network2 = networksIt.next(); - - final List people = new ArrayList(3); - - // create users and some preferences - TenantUtil.runAsSystemTenant(new TenantRunAsWork() - { - @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() - { - @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 expectedPreferences = new ArrayList(); - 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() - { - @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 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 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 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 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 params = new HashMap(); - 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 params = new HashMap(); - 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 params = new HashMap(); - 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 params = new HashMap(); - 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 params = new HashMap(); - 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 params = new HashMap(); - 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()); - } - } - } -} +/* + * #%L + * Alfresco Remote API + * %% + * Copyright (C) 2005 - 2024 Alfresco Software Limited + * %% + * This file is part of the Alfresco software. + * If the software was purchased under a paid Alfresco license, the terms of + * the paid license agreement will prevail. Otherwise, the software is + * provided under the following open source license terms: + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see . + * #L% + */ +package org.alfresco.rest.api.tests; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.*; + +import org.apache.commons.httpclient.HttpStatus; +import org.junit.Test; + +import org.alfresco.repo.tenant.TenantUtil; +import org.alfresco.repo.tenant.TenantUtil.TenantRunAsWork; +import org.alfresco.rest.api.tests.RepoService.TestNetwork; +import org.alfresco.rest.api.tests.RepoService.TestPerson; +import org.alfresco.rest.api.tests.client.PublicApiClient.ListResponse; +import org.alfresco.rest.api.tests.client.PublicApiClient.Paging; +import org.alfresco.rest.api.tests.client.PublicApiClient.People; +import org.alfresco.rest.api.tests.client.PublicApiException; +import org.alfresco.rest.api.tests.client.RequestContext; +import org.alfresco.rest.api.tests.client.data.Preference; +import org.alfresco.util.GUID; + +public class TestUserPreferences extends EnterpriseTestApi +{ + @Test + public void testUserPreferences() throws Exception + { + Iterator networksIt = getTestFixture().getNetworksIt(); + assertTrue(networksIt.hasNext()); + final TestNetwork network1 = networksIt.next(); + assertTrue(networksIt.hasNext()); + final TestNetwork network2 = networksIt.next(); + + final List people = new ArrayList(3); + + // create users and some preferences + TenantUtil.runAsSystemTenant(new TenantRunAsWork() { + @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() { + @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 expectedPreferences = new ArrayList(); + 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() { + @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 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 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 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 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()); + } + + { + Preference updatedPref = new Preference("preference.to.update", "updated.value"); + + publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId())); + Preference response = peopleProxy.updatePreference(person1.getId(), updatedPref); + + assertEquals(updatedPref.getId(), response.getId()); + assertEquals(updatedPref.getValue(), response.getValue()); + } + + 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 params = new HashMap(); + 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 params = new HashMap(); + 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 params = new HashMap(); + 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 params = new HashMap(); + 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 params = new HashMap(); + 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 params = new HashMap(); + 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()); + } + } + } +} diff --git a/remote-api/src/test/java/org/alfresco/rest/api/tests/client/PublicApiClient.java b/remote-api/src/test/java/org/alfresco/rest/api/tests/client/PublicApiClient.java index 5341867246..eb30b60310 100644 --- a/remote-api/src/test/java/org/alfresco/rest/api/tests/client/PublicApiClient.java +++ b/remote-api/src/test/java/org/alfresco/rest/api/tests/client/PublicApiClient.java @@ -1,2928 +1,2934 @@ -/* - * #%L - * Alfresco Remote API - * %% - * Copyright (C) 2005 - 2023 Alfresco Software Limited - * %% - * This file is part of the Alfresco software. - * If the software was purchased under a paid Alfresco license, the terms of - * the paid license agreement will prevail. Otherwise, the software is - * provided under the following open source license terms: - * - * Alfresco is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * Alfresco is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public License - * along with Alfresco. If not, see . - * #L% - */ -package org.alfresco.rest.api.tests.client; - -import static org.junit.Assert.assertNotNull; - -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.Serializable; -import java.math.BigInteger; -import java.text.ParseException; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; - -import jakarta.servlet.http.HttpServletResponse; - -import org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl; -import org.alfresco.opencmis.CMISDispatcherRegistry.Binding; -import org.alfresco.rest.api.model.ActionDefinition; -import org.alfresco.rest.api.model.SiteUpdate; -import org.alfresco.rest.api.tests.TestPeople; -import org.alfresco.rest.api.tests.TestSites; -import org.alfresco.rest.api.tests.client.PublicApiHttpClient.BinaryPayload; -import org.alfresco.rest.api.tests.client.PublicApiHttpClient.RequestBuilder; -import org.alfresco.rest.api.tests.client.data.Action; -import org.alfresco.rest.api.tests.client.data.Aspect; -import org.alfresco.rest.api.tests.client.data.Activities; -import org.alfresco.rest.api.tests.client.data.Activity; -import org.alfresco.rest.api.tests.client.data.AuditApp; -import org.alfresco.rest.api.tests.client.data.AuditEntry; -import org.alfresco.rest.api.tests.client.data.CMISNode; -import org.alfresco.rest.api.tests.client.data.Comment; -import org.alfresco.rest.api.tests.client.data.ContentData; -import org.alfresco.rest.api.tests.client.data.Favourite; -import org.alfresco.rest.api.tests.client.data.FavouriteSite; -import org.alfresco.rest.api.tests.client.data.FolderNode; -import org.alfresco.rest.api.tests.client.data.Group; -import org.alfresco.rest.api.tests.client.data.GroupMember; -import org.alfresco.rest.api.tests.client.data.JSONAble; -import org.alfresco.rest.api.tests.client.data.MemberOfSite; -import org.alfresco.rest.api.tests.client.data.NodeRating; -import org.alfresco.rest.api.tests.client.data.Person; -import org.alfresco.rest.api.tests.client.data.PersonNetwork; -import org.alfresco.rest.api.tests.client.data.Preference; -import org.alfresco.rest.api.tests.client.data.Site; -import org.alfresco.rest.api.tests.client.data.SiteContainer; -import org.alfresco.rest.api.tests.client.data.SiteImpl; -import org.alfresco.rest.api.tests.client.data.SiteMember; -import org.alfresco.rest.api.tests.client.data.SiteGroup; -import org.alfresco.rest.api.tests.client.data.SiteMembershipRequest; -import org.alfresco.rest.api.tests.client.data.Tag; -import org.alfresco.rest.api.tests.client.data.Type; -import org.alfresco.rest.api.tests.util.RestApiUtil; -import org.apache.chemistry.opencmis.client.api.CmisObject; -import org.apache.chemistry.opencmis.client.api.Document; -import org.apache.chemistry.opencmis.client.api.FileableCmisObject; -import org.apache.chemistry.opencmis.client.api.Folder; -import org.apache.chemistry.opencmis.client.api.ItemIterable; -import org.apache.chemistry.opencmis.client.api.ObjectId; -import org.apache.chemistry.opencmis.client.api.ObjectType; -import org.apache.chemistry.opencmis.client.api.OperationContext; -import org.apache.chemistry.opencmis.client.api.QueryResult; -import org.apache.chemistry.opencmis.client.api.Repository; -import org.apache.chemistry.opencmis.client.api.Session; -import org.apache.chemistry.opencmis.client.api.SessionFactory; -import org.apache.chemistry.opencmis.client.api.Tree; -import org.apache.chemistry.opencmis.client.runtime.OperationContextImpl; -import org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl; -import org.apache.chemistry.opencmis.commons.PropertyIds; -import org.apache.chemistry.opencmis.commons.SessionParameter; -import org.apache.chemistry.opencmis.commons.data.AllowableActions; -import org.apache.chemistry.opencmis.commons.data.ContentStream; -import org.apache.chemistry.opencmis.commons.definitions.FolderTypeDefinition; -import org.apache.chemistry.opencmis.commons.enums.BindingType; -import org.apache.chemistry.opencmis.commons.enums.UnfileObject; -import org.apache.chemistry.opencmis.commons.enums.VersioningState; -import org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.json.simple.JSONArray; -import org.json.simple.JSONObject; - -import com.fasterxml.jackson.databind.ObjectMapper; - -/** - * A client for interacting with the public api and returning Java objects. - * - * @author steveglover - * - */ -public class PublicApiClient -{ - private static final Log logger = LogFactory.getLog(PublicApiClient.class); - - private UserDataService userDataService; - private PublicApiHttpClient client; - - private Sites sites; - private Tags tags; - private Comments comments; - private Nodes nodes; - private People people; - private Favourites favourites; - private SiteMembershipRequests siteMembershipRequests; - private Groups groups; - private RawProxy rawProxy; - private AuditApps auditApps; - private Actions actions; - private Aspects aspects; - private Types types; - - private ThreadLocal rc = new ThreadLocal(); - private ObjectMapper objectMapper = new ObjectMapper(); - - public PublicApiClient(PublicApiHttpClient client, UserDataService userDataService) - { - this.client = client; - this.userDataService = userDataService; - - init(); - } - - public void init() - { - sites = new Sites(); - tags = new Tags(); - comments = new Comments(); - nodes = new Nodes(); - people = new People(); - favourites = new Favourites(); - siteMembershipRequests = new SiteMembershipRequests(); - groups = new Groups(); - rawProxy = new RawProxy(); - auditApps = new AuditApps(); - actions = new Actions(); - aspects = new Aspects(); - types = new Types(); - } - - public void setRequestContext(RequestContext rc) - { - this.rc.set(rc); - } - - public RequestContext getRequestContext() - { - RequestContext context = rc.get(); - if(context == null) - { - throw new RuntimeException("Must set a request context"); - } - return context; - } - - protected UserData findUser(String userName) - { - return userDataService.findUserByUserName(userName); - } - - public RawProxy rawProxy() - { - return rawProxy; - } - - public People people() - { - return people; - } - - public Nodes nodes() - { - return nodes; - } - - public Sites sites() - { - return sites; - } - - public Favourites favourites() - { - return favourites; - } - - public SiteMembershipRequests siteMembershipRequests() - { - return siteMembershipRequests; - } - - public Tags tags() - { - return tags; - } - - public Comments comments() - { - return comments; - } - - public Groups groups() - { - return groups; - } - - public AuditApps auditApps(){ - return auditApps; - } - - public Actions actions() - { - return actions; - } - - public Aspects aspects() - { - return aspects; - } - - public Types types() - { - return types; - } - - public CmisSession createPublicApiCMISSession(Binding binding, String version) - { - return createPublicApiCMISSession(binding, version, null); - } - - public CmisSession createPublicApiCMISSession(Binding binding, String version, String objectFactoryName) - { - CmisSession cmisSession = null; - - RequestContext rc = getRequestContext(); - if(rc == null) - { - throw new RuntimeException("Must set a request context"); - } - - String networkId = rc.getNetworkId(); - String username = rc.getRunAsUser(); - UserData userData = findUser(rc.getRunAsUser()); - if(userData != null) - { - String password = userData.getPassword(); - - // default factory implementation - SessionFactory factory = SessionFactoryImpl.newInstance(); - Map parameters = new HashMap(); - - // user credentials - parameters.put(SessionParameter.USER, username); - parameters.put(SessionParameter.PASSWORD, password); - - // connection settings - if(binding == Binding.atom) - { - parameters.put(SessionParameter.ATOMPUB_URL, client.getPublicApiCmisUrl(networkId, binding, version, null)); - parameters.put(SessionParameter.BINDING_TYPE, binding.getOpenCmisBinding().value()); - } - else if(binding == Binding.browser) - { - parameters.put(SessionParameter.BROWSER_URL, client.getPublicApiCmisUrl(networkId, binding, version, null)); - parameters.put(SessionParameter.BINDING_TYPE, binding.getOpenCmisBinding().value()); - } - if(networkId != null) - { - parameters.put(SessionParameter.REPOSITORY_ID, networkId); - } - if(objectFactoryName != null) - { - parameters.put(SessionParameter.OBJECT_FACTORY_CLASS, objectFactoryName); - } - - // create session - Session session = factory.createSession(parameters); - - cmisSession = new CmisSession(session); - } - - return cmisSession; - } - - public CmisSession createCMISSession(String repositoryId, RequestContext rc) - { - CmisSession session = null; - - UserData userData = findUser(rc.getRunAsUser()); - if(userData != null) - { - session = createCMISSession(repositoryId, rc.getRunAsUser(), userData.getPassword()); - } - - return session; - } - - /** - * Get CMIS repositories (Enterprise AtomPub CMIS binding) - * - * @return List - */ - public List getCMISRepositories() - { - List repositories = null; - - RequestContext rc = getRequestContext(); - if(rc == null) - { - throw new RuntimeException("Must set a request context"); - } - - UserData userData = findUser(rc.getRunAsUser()); - if(userData != null) - { - // default factory implementation - SessionFactory factory = SessionFactoryImpl.newInstance(); - Map parameters = new HashMap(); - - // user credentials - parameters.put(SessionParameter.USER, rc.getRunAsUser()); - parameters.put(SessionParameter.PASSWORD, userData.getPassword()); - - // connection settings - parameters.put(SessionParameter.ATOMPUB_URL, client.getCmisUrl(null, null)); - parameters.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value()); - - repositories = factory.getRepositories(parameters); - } - - return repositories; - } - - /** - * Create a CMIS session using Enterprise AtomPub binding. - * - * @param repositoryId String - * @param username String - * @param password String - * @return CmisSession - */ - public CmisSession createCMISSession(String repositoryId, String username, String password) - { - // default factory implementation - SessionFactory factory = SessionFactoryImpl.newInstance(); - Map parameters = new HashMap(); - - // user credentials - parameters.put(SessionParameter.USER, username); - parameters.put(SessionParameter.PASSWORD, password); - - // connection settings - parameters.put(SessionParameter.ATOMPUB_URL, client.getCmisUrl(repositoryId, null)); - parameters.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value()); - if(repositoryId != null) - { - parameters.put(SessionParameter.REPOSITORY_ID, repositoryId); - } - parameters.put(SessionParameter.OBJECT_FACTORY_CLASS, AlfrescoObjectFactoryImpl.class.getName()); - - // create session - Session session = factory.createSession(parameters); - - CmisSession cmisSession = new CmisSession(session); - return cmisSession; - } - - public CmisSession getCMISSession(Repository respository) - { - RequestContext rc = getRequestContext(); - if(rc == null) - { - throw new RuntimeException("Must set a request context"); - } - - CmisSession session = createCMISSession(respository.getId(), rc); - return session; - } - - public HttpResponse post(Binding cmisBinding, String version, String cmisOperation, String body) throws PublicApiException - { - try - { - HttpResponse response = client.post(getRequestContext(), cmisBinding, version, cmisOperation, body); - - logger.debug(response.toString()); - - return response; - } - catch(IOException e) - { - throw new PublicApiException(e); - } - } - - public HttpResponse put(Binding cmisBinding, String version, String cmisOperation, String body) throws PublicApiException - { - try - { - HttpResponse response = client.put(getRequestContext(), cmisBinding, version, cmisOperation, body); - - logger.debug(response.toString()); - - return response; - } - catch(IOException e) - { - throw new PublicApiException(e); - } - } - - public HttpResponse get(Binding cmisBinding, String version, String cmisOperation, Map parameters) throws PublicApiException - { - try - { - HttpResponse response = client.get(getRequestContext(), cmisBinding, version, cmisOperation, parameters); - - logger.debug(response.toString()); - - return response; - } - catch(IOException e) - { - throw new PublicApiException(e); - } - } - - public HttpResponse patch(Binding cmisBinding, String version, String cmisOperation, Map parameters) throws PublicApiException - { - try - { - HttpResponse response = client.patch(getRequestContext(), cmisBinding, version, cmisOperation); - - logger.debug(response.toString()); - - return response; - } - catch(IOException e) - { - throw new PublicApiException(e); - } - } - - public HttpResponse trace(Binding cmisBinding, String version, String cmisOperation, Map parameters) throws PublicApiException - { - try - { - HttpResponse response = client.trace(getRequestContext(), cmisBinding, version, cmisOperation); - - logger.debug(response.toString()); - - return response; - } - catch(IOException e) - { - throw new PublicApiException(e); - } - } - - public HttpResponse options(Binding cmisBinding, String version, String cmisOperation, Map parameters) throws PublicApiException - { - try - { - HttpResponse response = client.options(getRequestContext(), cmisBinding, version, cmisOperation); - - logger.debug(response.toString()); - - return response; - } - catch(IOException e) - { - throw new PublicApiException(e); - } - } - - public HttpResponse head(Binding cmisBinding, String version, String cmisOperation, Map parameters) throws PublicApiException - { - try - { - HttpResponse response = client.head(getRequestContext(), cmisBinding, version, cmisOperation); - - logger.debug(response.toString()); - - return response; - } - catch(IOException e) - { - throw new PublicApiException(e); - } - } - - public HttpResponse post(String scope, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId, String body) throws IOException - { - HttpResponse response = client.post(getRequestContext(), scope, entityCollectionName, entityId, relationCollectionName, relationshipEntityId != null ? relationshipEntityId.toString() : null, body); - - logger.debug(response.toString()); - - return response; - } - - public HttpResponse post(String scope, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId, String body, - final Map params) throws IOException - { - HttpResponse response = client.post(getRequestContext(), scope, entityCollectionName, entityId, relationCollectionName, - relationshipEntityId != null ? relationshipEntityId.toString() : null, body, params); - - logger.debug(response.toString()); - - return response; - } - - public HttpResponse post(String scope, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId, - String body, String contentType) throws IOException - { - HttpResponse response = client.post(getRequestContext(), scope, entityCollectionName, entityId, relationCollectionName, - relationshipEntityId != null ? relationshipEntityId.toString() : null, body, contentType); - - logger.debug(response.toString()); - - return response; - } - - - public HttpResponse post(String scope, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId, - byte[] body, String contentType) throws IOException - { - HttpResponse response = client.post(getRequestContext(), scope, entityCollectionName, entityId, relationCollectionName, - relationshipEntityId != null ? relationshipEntityId.toString() : null, body, contentType); - - logger.debug(response.toString()); - - return response; - } - - public HttpResponse post(String urlSuffix, String body) throws IOException - { - HttpResponse response = client.post(getRequestContext(), urlSuffix, body); - - logger.debug(response.toString()); - - return response; - } - - public HttpResponse post(final Class c, Object entityId, Object relationshipEntityId, String body) throws IOException - { - HttpResponse response = client.post(c, getRequestContext(), entityId, relationshipEntityId, body); - - logger.debug(response.toString()); - - return response; - } - - public HttpResponse get(String scope, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId, Map params, Map headers) throws IOException - { - HttpResponse response = client.get(getRequestContext(), scope, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, params, headers); - - logger.debug(response.toString()); - - return response; - } - - public HttpResponse get(String scope, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId, Map params) throws IOException - { - return get(scope, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, params, null); - } - - public HttpResponse getWithPassword(String scope, String password, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId, Map params) throws IOException - { - HttpResponse response = client.get(getRequestContext(), scope, password, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, params); - - logger.debug(response.toString()); - - return response; - } - - public HttpResponse get(String url, Map params) throws IOException - { - RequestContext rc = getRequestContext(); - HttpResponse response = client.get(url, rc, params); - - logger.debug(response.toString()); - - return response; - } - - public HttpResponse get(final Class c, final Object entityId, final Object relationshipEntityId, Map params) throws IOException - { - HttpResponse response = client.get(c, getRequestContext(), entityId, relationshipEntityId, params); - - logger.debug(response.toString()); - - return response; - } - - public HttpResponse put(String scope, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId, String body, Map params) throws IOException - { - HttpResponse response = client.put(getRequestContext(), scope, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, body, params); - - logger.debug(response.toString()); - - return response; - } - - public HttpResponse put(final Class c, Object entityId, Object relationshipEntityId, String body) throws IOException - { - HttpResponse response = client.put(c, getRequestContext(), entityId, relationshipEntityId, body); - - logger.debug(response.toString()); - - return response; - } - - public HttpResponse putBinary(String scope, int version, String entityCollectionName, Object entityId, String relationCollectionName, - Object relationshipEntityId, BinaryPayload payload, Map params) throws IOException - { - HttpResponse response = client.putBinary(getRequestContext(), scope, version, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, - payload, params); - - logger.debug(response.toString()); - - return response; - } - - public HttpResponse delete(String scope, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId) throws IOException - { - return delete(scope, 1, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, null); - } - - public HttpResponse delete(String scope, int version, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId, Map params) throws IOException - { - HttpResponse response = client.delete(getRequestContext(), scope, version, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, params); - - logger.debug(response.toString()); - - return response; - } - - public HttpResponse put(final Class c, Object entityId, Object relationshipEntityId) throws IOException - { - HttpResponse response = client.delete(c, getRequestContext(), entityId, relationshipEntityId); - - logger.debug(response.toString()); - - return response; - } - - public HttpResponse execute(RequestBuilder requestBuilder) throws IOException - { - if (requestBuilder.getRequestContext() == null) - { - throw new RuntimeException("Must set a request context"); - } - HttpResponse response = client.execute(requestBuilder); - - logger.debug(response.toString()); - - return response; - } - - public HttpResponse index(Map params) throws IOException - { - HttpResponse response = get("", params); - return response; - } - - public List getNetworkIds(String version) - { - RequestContext rc = getRequestContext(); - - UserData userData = findUser(rc.getRunAsUser()); - if(userData == null) - { - throw new RuntimeException("Must provide a valid username"); - } - - SessionFactory factory = SessionFactoryImpl.newInstance(); - - Map parameters = new HashMap(); - - // connection settings - parameters.put(SessionParameter.ATOMPUB_URL, client.getPublicApiCmisUrl(null, Binding.atom, version, null)); - parameters.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value()); - - // user credentials - parameters.put(SessionParameter.USER, rc.getRunAsUser()); - parameters.put(SessionParameter.PASSWORD, userData.getPassword()); - List repositories = factory.getRepositories(parameters); - - List repositoryIds = new ArrayList(repositories.size()); - for(Repository repository : repositories) - { - repositoryIds.add(repository.getId()); - } - - return repositoryIds; - } - - public class AbstractProxy - { - public HttpResponse getAll(String entityCollectionName, String entityId, String relationCollectionName, String relationId, Map params, String errorMessage) - throws PublicApiException - { - return getAll(entityCollectionName, entityId, relationCollectionName, relationId, params, errorMessage, HttpServletResponse.SC_OK); - } - - public HttpResponse getAll(String entityCollectionName, String entityId, String relationCollectionName, String relationId, Map params, String errorMessage, - int expectedStatus) throws PublicApiException - { - try - { - HttpResponse response = get("public", entityCollectionName, entityId, relationCollectionName, relationId, params); - checkStatus(errorMessage, expectedStatus, response); - return response; - } - catch (IOException e) - { - throw new PublicApiException(e); - } - } - - public HttpResponse getSingle(String entityCollectionName, String entityId, String relationCollectionName, String relationId, String errorMessage) throws PublicApiException - { - return getSingle(entityCollectionName, entityId, relationCollectionName, relationId, errorMessage, HttpServletResponse.SC_OK); - } - - public HttpResponse getSingle(String entityCollectionName, String entityId, String relationCollectionName, String relationId, String errorMessage, int expectedStatus) throws PublicApiException - { - try - { - HttpResponse response = get("public", entityCollectionName, entityId, relationCollectionName, relationId, null); - checkStatus(errorMessage, expectedStatus, response); - return response; - } - catch(IOException e) - { - throw new PublicApiException(e); - } - } - - public HttpResponse getSingle(String entityCollectionName, String entityId, String relationCollectionName, String relationId, Map params, - Map headers, String errorMessage, int expectedStatus) throws PublicApiException - { - try - { - HttpResponse response = get("public", entityCollectionName, entityId, relationCollectionName, relationId, params, headers); - checkStatus(errorMessage, expectedStatus, response); - return response; - } - catch (IOException e) - { - throw new PublicApiException(e); - } - } - - public HttpResponse getSingle(String entityCollectionName, String entityId, String relationCollectionName, String relationId, Map params, - String errorMessage, int expectedStatus) throws PublicApiException - { - try - { - HttpResponse response = get("public", entityCollectionName, entityId, relationCollectionName, relationId, params); - checkStatus(errorMessage, expectedStatus, response); - return response; - } - catch (IOException e) - { - throw new PublicApiException(e); - } - } - - public HttpResponse update(String entityCollectionName, String entityId, String relationCollectionName, String relationId, String body, String errorMessage) throws PublicApiException - { - return update(entityCollectionName, entityId, relationCollectionName, relationId, body, null, errorMessage, 200); - } - - public HttpResponse update(String entityCollectionName, String entityId, String relationCollectionName, String relationId, String body, Map params, String errorMessage, int expectedStatus) throws PublicApiException - { - try - { - HttpResponse response = put("public", entityCollectionName, entityId, relationCollectionName, relationId, body, params); - checkStatus(errorMessage, expectedStatus, response); - return response; - } - catch(IOException e) - { - throw new PublicApiException(e); - } - } - - public HttpResponse create(String entityCollectionName, String entityId, String relationCollectionName, String relationId, String body, String errorMessage) throws PublicApiException - { - return create(entityCollectionName, entityId, relationCollectionName, relationId, body, errorMessage, HttpServletResponse.SC_CREATED); - } - - public HttpResponse create(String entityCollectionName, String entityId, String relationCollectionName, String relationId, String body, String errorMessage, - int expectedStatus) throws PublicApiException - { - return create(entityCollectionName, entityId, relationCollectionName, relationId, body, errorMessage, expectedStatus, null); - } - - public HttpResponse create(String entityCollectionName, String entityId, String relationCollectionName, String relationId, String body, String errorMessage, - int expectedStatus, Map params) throws PublicApiException - { - try - { - HttpResponse response = post("public", entityCollectionName, entityId, relationCollectionName, relationId, body, params); - checkStatus(errorMessage, expectedStatus, response); - return response; - } - catch (IOException e) - { - throw new PublicApiException(e); - } - } - - public HttpResponse remove(String entityCollectionName, String entityId, String relationCollectionName, String relationId, String errorMessage) throws PublicApiException - { - return remove(entityCollectionName, entityId, relationCollectionName, relationId, null, errorMessage, HttpServletResponse.SC_NO_CONTENT); - } - - public HttpResponse remove(String entityCollectionName, String entityId, String relationCollectionName, String relationId, Map params, String errorMessage, int expectedStatus) throws PublicApiException - { - try - { - HttpResponse response = delete("public", 1, entityCollectionName, entityId, relationCollectionName, relationId, params); - checkStatus(errorMessage, expectedStatus, response); - return response; - } - catch(IOException e) - { - throw new PublicApiException(e); - } - } - - public JSONObject parseListSource(JSONObject jsonResponse) - { - JSONObject jsonList = (JSONObject)jsonResponse.get("list"); - assertNotNull(jsonList); - - JSONObject source = (JSONObject)jsonList.get("source"); - assertNotNull(source); - return source; - } - - /** - * Used for validation of status code on rest response - */ - public void checkStatus(String errorMessage, int expectedStatus, HttpResponse response) throws PublicApiException - { - int actualStatus = response.getStatusCode(); - if ((expectedStatus > 0) && (expectedStatus != actualStatus)) - { - String msg = "Status code " + actualStatus + " returned, but expected " + expectedStatus + ": \n" + errorMessage + ": \n" - + " Response: " + response; - throw new PublicApiException(msg, response); - } - /// in case of Status.SC_UNAUTHORIZED no response is returned - if (expectedStatus >= 400 && expectedStatus != 401) - { - checkErrorKeyResponse(errorMessage, expectedStatus, response); - } - } - - /** - * Used for validation on field errorKey on Error rest response - */ - public void checkErrorKeyResponse(String errorMessage, int expectedStatus, HttpResponse response) throws PublicApiException - { - PublicApiClient.ExpectedErrorResponse error; - // the error response must have a valid format in conformity with - // the - // ErrorResponse model - try - { - error = RestApiUtil.parseErrorResponse(response.getJsonResponse()); - } - catch (Exception e) - { - throw new PublicApiException(e.getMessage(), response); - } - - String errorKey = error.errorKey; - // validate the errorKey which have default message exception - if (errorKey != null && errorKey.contains("exception")) - { - boolean validErrorKey = false; - - List httpErrorsFilteredByStatusCode = Arrays.asList(RestErrorResponseDefault.values()).stream() - .filter(t -> t.getStatusCode() == expectedStatus && t.getDefaultMessage() != null).collect(Collectors.toList()); - - httpErrorsFilteredByStatusCode.add(RestErrorResponseDefault.DEFAULT_API_EXCEPTION); - - for (RestErrorResponseDefault errorResponseDefault : httpErrorsFilteredByStatusCode) - { - if (errorResponseDefault.getDefaultMessage().equals(errorKey)) - { - validErrorKey = true; - } - } - - if (validErrorKey == false) - { - String msg = "Error key " + errorKey + " returned is not valid " + "\n" + errorMessage + ": \n" + " Response: " + response; - throw new PublicApiException(msg, response); - } - - } - } - - } - - public static class ListResponse - { - private ExpectedPaging paging; - private List list; - - public ListResponse(ExpectedPaging paging, List list) - { - super(); - this.paging = paging; - this.list = list; - } - - public ExpectedPaging getPaging() - { - return paging; - } - - public List getList() - { - return list; - } - } - - public class Sites extends AbstractProxy - { - public ListResponse getSites(Map params) throws PublicApiException - { - HttpResponse response = getAll("sites", null, null, null, params, "Failed to get sites"); - return SiteImpl.parseSites(response.getJsonResponse()); - } - - public Site getSite(String siteId) throws PublicApiException - { - return getSite(siteId, 200); - } - - public Site getSite(String siteId, int expectedStatus) throws PublicApiException - { - HttpResponse response = getSingle("sites", siteId, null, null, "Failed to get site " + siteId, expectedStatus); - if ((response != null) && (response.getJsonResponse() != null)) - { - return SiteImpl.parseSite((JSONObject)response.getJsonResponse().get("entry")); - } - else - { - return null; - } - } - - public Site createSite(Site site) throws PublicApiException - { - return createSite(site, 201); - } - - public Site createSite(Site site, int expectedStatus) throws PublicApiException - { - HttpResponse response = create("sites", null, null, null, site.toJSON().toString(), "Failed to create site "+site.getTitle(), expectedStatus); - return SiteImpl.parseSite((JSONObject)response.getJsonResponse().get("entry")); - } - - public void removeSite(String siteId) throws PublicApiException - { - removeSite(siteId, false, 204); - } - - public void removeSite(String siteId, boolean permanent, int expectedStatus) throws PublicApiException - { - Map params = null; - if (permanent) - { - params = Collections.singletonMap("permanent", "true"); - } - remove("sites", siteId, null, null, params, "Failed to remove site", expectedStatus); - } - - public Site updateSite(String siteId, SiteUpdate update, int expectedStatus) throws PublicApiException - { - JSONAble jsonizer = new TestSites.SiteUpdateJSONSerializer(update); - HttpResponse response = update("sites", siteId, null, null, jsonizer.toJSON().toString(), null, "Failed to update site " + update.getTitle(), expectedStatus); - if (response.getJsonResponse() != null) - { - return SiteImpl.parseSite((JSONObject) response.getJsonResponse().get("entry")); - } - // No JSON response to parse. - return null; - } - - public ListResponse getSiteContainers(String siteId, Map params) throws PublicApiException - { - HttpResponse response = getAll("sites", siteId, "containers", null, params, "Failed to get site containers"); - return SiteContainer.parseSiteContainers(response.getJsonResponse()); - } - - public SiteContainer getSingleSiteContainer(String siteId, String containerId) throws PublicApiException - { - HttpResponse response = getSingle("sites", siteId, "containers", containerId, "Failed to get site container"); - SiteContainer siteContainer = SiteContainer.parseSiteContainer(siteId, (JSONObject)response.getJsonResponse().get("entry")); - return siteContainer; - } - - public SiteContainer updateSiteContainer(SiteContainer siteContainer) throws PublicApiException - { - HttpResponse response = update("sites", siteContainer.getSiteId(), "containers", siteContainer.getId(), siteContainer.toJSON().toString(), "Failed to update site container"); - SiteContainer retSiteContainer = SiteContainer.parseSiteContainer(siteContainer.getSiteId(), (JSONObject)response.getJsonResponse().get("entry")); - return retSiteContainer; - } - - public SiteContainer createSiteContainer(SiteContainer siteContainer) throws PublicApiException - { - HttpResponse response = create("sites", siteContainer.getSiteId(), "containers", null, siteContainer.toJSON().toString(), "Failed to create site container"); - SiteContainer retSiteContainer = SiteContainer.parseSiteContainer(siteContainer.getSiteId(), (JSONObject)response.getJsonResponse().get("entry")); - return retSiteContainer; - } - - public void removeSiteContainer(SiteContainer siteContainer) throws PublicApiException - { - remove("sites", siteContainer.getSiteId(), "containers", siteContainer.getId(), "Failed to remove site container"); - } - - public ListResponse getSiteMembers(String siteId, Map params) throws PublicApiException - { - HttpResponse response = getAll("sites", siteId, "members", null, params, "Failed to get all site members"); - return SiteMember.parseSiteMembers(siteId, response.getJsonResponse()); - } - - public SiteMember getSingleSiteMember(String siteId, String personId) throws PublicApiException - { - HttpResponse response = getSingle("sites", siteId, "members", personId, "Failed to get site member"); - SiteMember retSiteMember = SiteMember.parseSiteMember(siteId, (JSONObject)response.getJsonResponse().get("entry")); - return retSiteMember; - } - - public SiteMember updateSiteMember(String siteId, SiteMember siteMember) throws PublicApiException - { - HttpResponse response = update("sites", siteId, "members", siteMember.getMemberId(), siteMember.toJSON().toString(), "Failed to update site member"); - SiteMember retSiteMember = SiteMember.parseSiteMember(siteMember.getSiteId(), (JSONObject)response.getJsonResponse().get("entry")); - return retSiteMember; - } - - public SiteMember createSiteMember(String siteId, SiteMember siteMember) throws PublicApiException - { - HttpResponse response = create("sites", siteId, "members", null, siteMember.toJSON().toString(), "Failed to create site member"); - SiteMember retSiteMember = SiteMember.parseSiteMember(siteMember.getSiteId(), (JSONObject)response.getJsonResponse().get("entry")); - return retSiteMember; - } - - public void removeSiteMember(String siteId, SiteMember siteMember) throws PublicApiException - { - remove("sites", siteId, "members", siteMember.getMemberId(), "Failed to remove site member"); - } - - public ListResponse getPersonSites(String personId, Map params) throws PublicApiException - { - HttpResponse response = getAll("people", personId, "sites", null, params, "Failed to get person sites"); - return MemberOfSite.parseMemberOfSites(response.getJsonResponse()); - } - - public MemberOfSite getPersonSite(String personId, String siteId) throws PublicApiException - { - HttpResponse response = getSingle("people", personId, "sites", siteId, "Failed to get person site" + siteId); - return MemberOfSite.parseMemberOfSite((JSONObject)response.getJsonResponse().get("entry")); - } - - public MemberOfSite updatePersonSite(String personId, SiteMember siteMember) throws PublicApiException - { - HttpResponse response = update("people", personId, "sites", siteMember.getSiteId(), siteMember.toJSON().toString(), "Failed to update person site"); - MemberOfSite retSiteMember = MemberOfSite.parseMemberOfSite((JSONObject)response.getJsonResponse().get("entry")); - return retSiteMember; - } - - public MemberOfSite createPersonSite(String personId, SiteMember siteMember) throws PublicApiException - { - HttpResponse response = create("people", personId, "sites", null, siteMember.toJSON().toString(), "Failed to create person site"); - MemberOfSite retSiteMember = MemberOfSite.parseMemberOfSite((JSONObject)response.getJsonResponse().get("entry")); - return retSiteMember; - } - - public void removePersonSite(String personId, SiteMember siteMember) throws PublicApiException - { - remove("people", personId, "sites", siteMember.getSiteId(), "Failed to remove person site"); - } - - public ListResponse getFavouriteSites(String personId, Map params) throws PublicApiException - { - HttpResponse response = getAll("people", personId, "favorite-sites", null, params, "Failed to get favourite sites"); - return FavouriteSite.parseFavouriteSites(response.getJsonResponse()); - } - - public FavouriteSite getSingleFavouriteSite(String personId, String siteId) throws PublicApiException - { - HttpResponse response = getSingle("people", personId, "favorite-sites", siteId, "Failed to get favourite site"); - FavouriteSite favouriteSite = FavouriteSite.parseFavouriteSite((JSONObject)response.getJsonResponse().get("entry")); - return favouriteSite; - } - - public FavouriteSite updateFavouriteSite(String personId, FavouriteSite site) throws PublicApiException - { - HttpResponse response = update("people", personId, "favorite-sites", site.getSiteId(), site.toJSON().toString(), "Failed to update favourite site"); - FavouriteSite favouriteSite = FavouriteSite.parseFavouriteSite((JSONObject)response.getJsonResponse().get("entry")); - return favouriteSite; - } - - public FavouriteSite createFavouriteSite(String personId, FavouriteSite site) throws PublicApiException - { - HttpResponse response = create("people", personId, "favorite-sites", null, site.toJSON().toString(), "Failed to create favourite site"); - FavouriteSite favouriteSite = FavouriteSite.parseFavouriteSite((JSONObject)response.getJsonResponse().get("entry")); - return favouriteSite; - } - - public void removeFavouriteSite(String personId, FavouriteSite site) throws PublicApiException - { - remove("people", personId, "favorite-sites", site.getSiteId(), "Failed to remove favourite site"); - } - - public SiteGroup addGroup(String siteId, SiteGroup group) throws PublicApiException - { - HttpResponse response = create("sites", siteId, "group-members", null, group.toJSON().toString() , "Failed to add site groups"); - return SiteGroup.parseSiteGroup(siteId, (JSONObject)response.getJsonResponse().get("entry")); - } - - public ListResponse getGroups(String siteId, Map params) throws PublicApiException - { - HttpResponse response = getAll("sites", siteId, "group-members", null, params, "Failed to fetch all site groups"); - return SiteGroup.parseGroupMemberOfSites(siteId, response.getJsonResponse()); - } - - public SiteGroup getGroup(String siteId, String groupId) throws PublicApiException - { - HttpResponse response = getSingle("sites", siteId, "group-members", groupId.toString() , "Failed to get a site group"); - return SiteGroup.parseSiteGroup(siteId, (JSONObject)response.getJsonResponse().get("entry")); - } - - public SiteGroup updateGroup(String siteId, SiteGroup group) throws PublicApiException - { - HttpResponse response = update("sites", siteId, "group-members", group.getId(), group.toJSON().toString() , "Failed to update a site group"); - return SiteGroup.parseSiteGroup(siteId, (JSONObject)response.getJsonResponse().get("entry")); - } - - public void deleteGroup(String siteId, String groupId) throws PublicApiException - { - remove("sites", siteId, "group-members", groupId , "Failed to delete site group"); - } - } - - public class SiteMembershipRequests extends AbstractProxy - { - public SiteMembershipRequest getSiteMembershipRequest(String personId, String siteId) throws PublicApiException, ParseException - { - HttpResponse response = getSingle("people", personId, "site-membership-requests", siteId, "Failed to get siteMembershipRequest"); - return SiteMembershipRequest.parseSiteMembershipRequest((JSONObject) response.getJsonResponse().get("entry")); - } - - public ListResponse getSiteMembershipRequests(String personId, Map params) throws PublicApiException, ParseException - { - HttpResponse response = getAll("people", personId, "site-membership-requests", null, params, "Failed to get siteMembershipRequests"); - return SiteMembershipRequest.parseSiteMembershipRequests(response.getJsonResponse()); - } - - public SiteMembershipRequest createSiteMembershipRequest(String personId, SiteMembershipRequest siteMembershipRequest) throws PublicApiException, ParseException - { - HttpResponse response = create("people", personId, "site-membership-requests", null, siteMembershipRequest.toJSON().toString(), "Failed to create siteMembershipRequest"); - SiteMembershipRequest ret = SiteMembershipRequest.parseSiteMembershipRequest((JSONObject) response.getJsonResponse().get("entry")); - return ret; - } - - public SiteMembershipRequest updateSiteMembershipRequest(String personId, SiteMembershipRequest siteMembershipRequest) throws PublicApiException, ParseException - { - HttpResponse response = update("people", personId, "site-membership-requests", siteMembershipRequest.getId(), siteMembershipRequest.toJSON().toString(), "Failed to update siteMembershipRequest"); - SiteMembershipRequest ret = SiteMembershipRequest.parseSiteMembershipRequest((JSONObject) response.getJsonResponse().get("entry")); - return ret; - } - - public void cancelSiteMembershipRequest(String personId, String siteMembershipRequestId) throws PublicApiException - { - remove("people", personId, "site-membership-requests", siteMembershipRequestId, "Failed to cancel siteMembershipRequest"); - } - - public ListResponse getSiteMembershipRequests(Map params, String errorMessage, int expectedStatus) throws PublicApiException, ParseException - { - HttpResponse response = getAll("site-membership-requests", null, null, null, params, errorMessage, expectedStatus); - - if (response != null && response.getJsonResponse() != null) - { - JSONObject jsonList = (JSONObject) response.getJsonResponse().get("list"); - if (jsonList != null) - { - return SiteMembershipRequest.parseSiteMembershipRequests(response.getJsonResponse()); - } - } - return null; - } - } - - public class RawProxy extends AbstractProxy - { - } - - public class Favourites extends AbstractProxy - { - public ListResponse getFavourites(String personId, Map params) throws PublicApiException, ParseException - { - HttpResponse response = getAll("people", personId, "favorites", null, params, "Failed to get favourites"); - return Favourite.parseFavourites(response.getJsonResponse()); - } - - public Favourite getFavourite(String personId, String favouriteId) throws PublicApiException, ParseException - { - HttpResponse response = getSingle("people", personId, "favorites", favouriteId, "Failed to get favourite " + favouriteId); - return Favourite.parseFavourite((JSONObject)response.getJsonResponse().get("entry")); - } - - public Favourite getFavourite(String personId, String favouriteId, Map params) throws PublicApiException, ParseException - { - HttpResponse response = getSingle("people", personId, "favorites", favouriteId, params, "Failed to get favourite " + favouriteId, 200); - return Favourite.parseFavourite((JSONObject) response.getJsonResponse().get("entry")); - } - - public Favourite createFavourite(String personId, Favourite favourite) throws PublicApiException, ParseException - { - HttpResponse response = create("people", personId, "favorites", null, favourite.toJSON().toString(), "Failed to create favourite"); - Favourite ret = Favourite.parseFavourite((JSONObject)response.getJsonResponse().get("entry")); - return ret; - } - - public Favourite createFavourite(String personId, Favourite favourite, Map params) throws PublicApiException, ParseException - { - HttpResponse response = create("people", personId, "favorites", null, favourite.toJSON().toString(), "Failed to create favourite", 201, params); - Favourite ret = Favourite.parseFavourite((JSONObject)response.getJsonResponse().get("entry")); - return ret; - } - - public void removeFavourite(String personId, String favouriteId) throws PublicApiException - { - remove("people", personId, "favorites", favouriteId, "Failed to remove favourite"); - } - } - - public class People extends AbstractProxy - { - public ListResponse getPeople(Map params) throws PublicApiException - { - HttpResponse response = getAll("people", null, null, null, params, "Failed to get people"); - return Person.parsePeople(response.getJsonResponse()); - } - - public Person getPerson(String personId) throws PublicApiException - { - return getPerson(personId, 200); - } - - public Person getPerson(String personId, int expectedStatus) throws PublicApiException - { - HttpResponse response = getSingle("people", personId, null, null, "Failed to get person", expectedStatus); - - if(logger.isDebugEnabled()) - { - logger.debug(response); - } - System.out.println(response); - - if (response != null && response.getJsonResponse() != null) - { - JSONObject entry = (JSONObject) response.getJsonResponse().get("entry"); - if (entry != null) - { - return Person.parsePerson(entry); - } - } - return null; - } - - public Person update(String personId, Person person) throws PublicApiException - { - return update(personId, person, 200); - } - - public Person update(String personId, Person person, int expectedStatus) throws PublicApiException - { - return update(personId, person.toJSON(true).toString(), expectedStatus); - } - - public Person update(String personId, String json, int expectedStatus) throws PublicApiException - { - return update(personId, json, null, expectedStatus); - } - - public Person update(String personId, String json, Map params, int expectedStatus) throws PublicApiException - { - HttpResponse response = update("people", personId, null, null, json, params, "Failed to update person", expectedStatus); - if (response != null && response.getJsonResponse() != null) - { - JSONObject entry = (JSONObject) response.getJsonResponse().get("entry"); - if (entry != null) - { - return Person.parsePerson(entry); - } - } - return null; - } - - public Person create(Person person) throws PublicApiException - { - return create(person, 201); - } - - public Person create(Person person, int expectedStatus) throws PublicApiException - { - TestPeople.PersonJSONSerializer jsonizer = new TestPeople.PersonJSONSerializer(person) ; - HttpResponse response = create("people", null, null, null, jsonizer.toJSON().toString(), "Failed to create person", expectedStatus); - if ((response != null) && (response.getJsonResponse() != null)) - { - JSONObject entry = (JSONObject) response.getJsonResponse().get("entry"); - if (entry != null) - { - return Person.parsePerson(entry); - } - } - return null; - } - - public void remove(Person person) throws PublicApiException - { - remove("people", person.getId(), null, null, "Failed to remove person"); - } - - public ListResponse getPreferences(String personId, Map params) throws PublicApiException - { - HttpResponse response = getAll("people", personId, "preferences", null, params, "Failed to get person preferences"); - return Preference.parsePreferences(response.getJsonResponse()); - } - - public Preference getPreference(String personId, String preferenceId) throws PublicApiException - { - HttpResponse response = getSingle("people", personId, "preferences", preferenceId, "Failed to get person preference"); - Preference pref = Preference.parsePreference((JSONObject)response.getJsonResponse().get("entry")); - return pref; - } - - public Person updatePreference(String personId, Preference preference) throws PublicApiException - { - HttpResponse response = update("people", personId, "preferences", preference.getId(), preference.toJSON().toString(), "Failed to update person preference"); - Person retSite = Person.parsePerson((JSONObject)response.getJsonResponse().get("entry")); - return retSite; - } - - public Person createPreference(String personId, Preference preference) throws PublicApiException - { - HttpResponse response = create("people", personId, "preferences", null, preference.toJSON().toString(), "Failed to create person preference"); - Person retSite = Person.parsePerson((JSONObject)response.getJsonResponse().get("entry")); - return retSite; - } - - public void removePreference(String personId, Preference preference) throws PublicApiException - { - remove("people", personId, "preferences", preference.getId(), "Failed to remove person preference"); - } - - public ListResponse getNetworkMemberships(String personId, Map params) throws PublicApiException - { - HttpResponse response = getAll("people", personId, "networks", null, params, "Failed to get network members"); - return PersonNetwork.parseNetworkMembers(response.getJsonResponse()); - } - - public PersonNetwork getNetworkMembership(String personId, String networkId) throws PublicApiException - { - HttpResponse response = getSingle("people", personId, "networks", networkId, "Failed to get network member"); - PersonNetwork networkMember = PersonNetwork.parseNetworkMember((JSONObject)response.getJsonResponse().get("entry")); - return networkMember; - } - - public PersonNetwork updateNetworkMembership(String personId, PersonNetwork networkMember) throws PublicApiException - { - HttpResponse response = update("people", personId, "networks", networkMember.getId(), networkMember.toJSON().toString(), "Failed to update network member"); - PersonNetwork retNetwork = PersonNetwork.parseNetworkMember((JSONObject)response.getJsonResponse().get("entry")); - return retNetwork; - } - - public PersonNetwork createNetworkMembership(String personId, PersonNetwork network) throws PublicApiException - { - HttpResponse response = create("people", personId, "networks", null, network.toJSON().toString(), "Failed to create network member"); - PersonNetwork retNetwork = PersonNetwork.parseNetworkMember((JSONObject)response.getJsonResponse().get("entry")); - return retNetwork; - } - - public void removeNetworkMembership(String personId, PersonNetwork networkMember) throws PublicApiException - { - remove("people", personId, "networks", networkMember.getId(), "Failed to remove network member"); - } - - public ListResponse getActivities(String personId, Map params) throws PublicApiException - { - HttpResponse response = getAll("people", personId, "activities", null, params, "Failed to get activities"); - return Activities.parseActivities(response.getJsonResponse()); - } - - public Activity getSingleActivity(String personId, String activityId) throws PublicApiException - { - HttpResponse response = getSingle("people", personId, "activities", activityId, "Failed to get activities"); - Activity activity = Activity.parseActivity((JSONObject)response.getJsonResponse().get("entry")); - return activity; - } - - public Activity update(String personId, Activity activity) throws PublicApiException - { - HttpResponse response = update("people", personId, "activities", String.valueOf(activity.getId()), activity.toJSON().toString(), "Failed to update activity"); - Activity retActivity = Activity.parseActivity((JSONObject)response.getJsonResponse().get("entry")); - return retActivity; - } - - public Activity create(String personId, Activity activity) throws PublicApiException - { - HttpResponse response = create("people", personId, "activities", String.valueOf(activity.getId()), activity.toJSON().toString(), "Failed to create activity"); - Activity retActivity = Activity.parseActivity((JSONObject)response.getJsonResponse().get("entry")); - return retActivity; - } - - public void remove(String personId, Activity activity) throws PublicApiException - { - remove("people", personId, "activities", String.valueOf(activity.getId()), "Failed to remove activity"); - } - - public HttpResponse getAvatar(String personId, boolean placeholder, int expectedStatus) throws PublicApiException, InterruptedException - { - return getAvatar(personId, null, placeholder, null, expectedStatus); - } - - public HttpResponse getAvatar(String personId, String ifModifiedSince, int expectedStatus) throws PublicApiException, InterruptedException - { - return getAvatar(personId, null, false, ifModifiedSince, expectedStatus); - } - - public HttpResponse getAvatar(String personId, Boolean attachment, boolean placeholder, String ifModifiedSince, int expectedStatus) throws PublicApiException, InterruptedException - { - // Binary response expected - Map params = new HashMap<>(); - params.put("placeholder", Boolean.toString(placeholder)); - // Optional attachment parameter - if (attachment != null) - { - params.put("attachment", attachment.toString()); - } - - Map headers = new HashMap<>(); - if (ifModifiedSince != null) - { - headers.put("If-Modified-Since", ifModifiedSince); - } - - // As renditions are now done async, we generally need to wait. - HttpResponse response = getSingleWithDelayRetry("people", personId, "avatar", - null, params, headers, "Failed to get avatar", 40, 2500, expectedStatus); - checkStatus("Unexpected response", expectedStatus, response); - - return response; - } - - private HttpResponse getSingleWithDelayRetry(String entityCollectionName, String entityId, String relationCollectionName, String relationId, Map params, - Map headers, String errorMessage, int repeat, long pauseInMillisecond, int expectedStatus) throws PublicApiException, InterruptedException - { - int retryCount = 0; - while (retryCount < repeat) - { - try - { - return getSingle(entityCollectionName, entityId, relationCollectionName, relationId, params, headers, errorMessage, expectedStatus); - } - catch (PublicApiException ex) - { - retryCount++; - Thread.sleep(pauseInMillisecond); - } - } - return null; - } - - public HttpResponse updateAvatar(String personId, File avatar, int expectedStatus) throws PublicApiException - { - try - { - Map params = new HashMap<>(); - BinaryPayload payload = new BinaryPayload(avatar); - HttpResponse response = client.putBinary(getRequestContext(), "public", 1, "people", personId, "avatar", null, payload, params); - checkStatus("Unexpected status", expectedStatus, response); - return response; - } - catch(IOException e) - { - throw new PublicApiException(e); - } - } - - public void deleteAvatarImage(String personId, int expectedStatus) throws PublicApiException{ - remove("people", personId, "avatar", null, null, "Failed to remove avatar image", expectedStatus); - } - } - - public class Comments extends AbstractProxy - { - public ListResponse getTenantComments(Map params) throws PublicApiException - { - HttpResponse response = getAll("comments", null, null, null, params, "Failed to get comments"); - return Comment.parseComments(null, response.getJsonResponse()); - } - - public Comment getTenantComment(String commentId) throws PublicApiException - { - HttpResponse response = getSingle("comments", commentId, null, null, "Failed to get comment"); - Comment comment = Comment.parseComment(null, (JSONObject)response.getJsonResponse().get("entry")); - return comment; - } - - public Comment updateTenantComment(Comment comment) throws PublicApiException - { - HttpResponse response = update("comments", comment.getId(), null, null, comment.toJSON(true).toString(), "Failed to update comment"); - Comment retComment = Comment.parseComment(null, (JSONObject)response.getJsonResponse().get("entry")); - return retComment; - } - - public Comment createTenantComment(Comment comment) throws PublicApiException - { - HttpResponse response = create("comments", null, null, null, comment.toJSON(true).toString(), "Failed to create comment"); - Comment retComment = Comment.parseComment(null, (JSONObject)response.getJsonResponse().get("entry")); - return retComment; - } - - public void removeTenantComment(Comment comment) throws PublicApiException - { - remove("comments", comment.getId(), null, null, "Failed to remove comment"); - } - - public ListResponse getNodeComments(String nodeId, Map params) throws PublicApiException - { - HttpResponse response = getAll("nodes", nodeId, "comments", null, params, "Failed to get comments"); - return Comment.parseComments(nodeId, response.getJsonResponse()); - } - - public Comment getNodeComment(String nodeId) throws PublicApiException - { - HttpResponse response = getSingle("nodes", nodeId, null, null, "Failed to get comment"); - Comment comment = Comment.parseComment(nodeId, (JSONObject)response.getJsonResponse().get("entry")); - return comment; - } - - public Comment updateNodeComment(String nodeId, String commentId, Comment comment) throws PublicApiException - { - HttpResponse response = update("nodes", nodeId, "comments", commentId, comment.toJSON(true).toString(), "Failed to update comment"); - Comment retComment = Comment.parseComment(nodeId, (JSONObject)response.getJsonResponse().get("entry")); - return retComment; - } - - public Comment createNodeComment(String nodeId, Comment comment) throws PublicApiException - { - HttpResponse response = create("nodes", nodeId, "comments", null, comment.toJSON(true).toString(), "Failed to create comment"); - Comment retComment = Comment.parseComment(nodeId, (JSONObject)response.getJsonResponse().get("entry")); - return retComment; - } - - public void removeNodeComment(String nodeId, String commentId) throws PublicApiException - { - remove("nodes", nodeId, "comments", commentId, "Failed to remove comment"); - } - } - - public class Tags extends AbstractProxy - { - public ListResponse getTags(Map params) throws PublicApiException - { - HttpResponse response = getAll("tags", null, null, null, params, "Failed to get tags"); - return Tag.parseTags(null, response.getJsonResponse()); - } - - public Tag getSingle(String tagId) throws PublicApiException - { - HttpResponse response = getSingle("tags", tagId, null, null, "Failed to get tag"); - Tag tag = Tag.parseTag(null, (JSONObject)response.getJsonResponse().get("entry")); - return tag; - } - - public Tag update(Tag tag) throws PublicApiException - { - HttpResponse response = update("tags", tag.getId(), null, null, tag.toJSON().toString(), "Failed to update tag"); - Tag retTag = Tag.parseTag(null, (JSONObject)response.getJsonResponse().get("entry")); - return retTag; - } - -// public Tag create(Tag tag) throws PublicApiException -// { -// HttpResponse response = create("tags", tag.getTagId(), null, null, tag.toJSON().toString(), "Failed to create tag"); -// Tag retTag = Tag.parseTag(null, (JSONObject)response.getJsonResponse().get("entry")); -// return retTag; -// } - - public void remove(Tag tag) throws PublicApiException - { - remove("tags", tag.getId(), null, null, "Failed to remove tag"); - } - } - - public class Nodes extends AbstractProxy - { - public ListResponse getNodeTags(String nodeId, Map params) throws PublicApiException - { - HttpResponse response = getAll("nodes", nodeId, "tags", null, params, "Failed to get node tags"); - return Tag.parseTags(nodeId, response.getJsonResponse()); - } - - public void removeNodeTag(String nodeId, String tagId) throws PublicApiException - { - remove("nodes", nodeId, "tags", tagId, "Failed to remove node tag"); - } - - public Tag createNodeTag(String nodeId, Tag tag) throws PublicApiException - { - HttpResponse response = create("nodes", nodeId, "tags", null, tag.toJSON().toString(), "Failed to create node tag"); - Tag tagRet = Tag.parseTag(nodeId, (JSONObject)response.getJsonResponse().get("entry")); - return tagRet; - } - - public NodeRating getNodeRating(String nodeId, String ratingId) throws PublicApiException - { - HttpResponse response = getSingle("nodes", nodeId, "ratings", ratingId, "Failed to get node ratings"); - return NodeRating.parseNodeRating(nodeId, (JSONObject)response.getJsonResponse().get("entry")); - } - - public ListResponse getNodeRatings(String nodeId, Map params) throws PublicApiException - { - HttpResponse response = getAll("nodes", nodeId, "ratings", null, params, "Failed to get node ratings"); - return NodeRating.parseNodeRatings(nodeId, response.getJsonResponse()); - } - - public NodeRating updateNodeRating(String nodeId, NodeRating nodeRating) throws PublicApiException - { - HttpResponse response = update("nodes", nodeId, "ratings", nodeRating.getId(), nodeRating.toJSON().toString(), "Failed to update node rating"); - NodeRating nodeRatingRet = NodeRating.parseNodeRating(nodeId, (JSONObject)response.getJsonResponse().get("entry")); - return nodeRatingRet; - } - - public NodeRating createNodeRating(String nodeId, NodeRating nodeRating) throws PublicApiException - { - HttpResponse response = create("nodes", nodeId, "ratings", null, nodeRating.toJSON().toString(), "Failed to create node rating"); - NodeRating nodeRatingRet = NodeRating.parseNodeRating(nodeId, (JSONObject)response.getJsonResponse().get("entry")); - return nodeRatingRet; - } - - public void removeNodeRating(String nodeId, NodeRating rating) throws PublicApiException - { - remove("nodes", nodeId, "ratings", rating.getId(), "Failed to remove node rating"); - } - } - - public class Aspects extends AbstractProxy - { - public PublicApiClient.ListResponse getAspects(Map params) throws PublicApiException - { - HttpResponse response = getAll("aspects", null, null, null, params, "Failed to get aspects"); - return Aspect.parseAspects(response.getJsonResponse()); - } - - public Aspect getAspect(String aspectId) throws PublicApiException - { - HttpResponse response = getAll("aspects", aspectId, null, null, null, "Failed to get aspect"); - return Aspect.parseAspect((JSONObject)response.getJsonResponse().get("entry")); - } - } - - public class Types extends AbstractProxy - { - public PublicApiClient.ListResponse getTypes(Map params) throws PublicApiException - { - HttpResponse response = getAll("types", null, null, null, params, "Failed to get types"); - return Type.parseTypes(response.getJsonResponse()); - } - - public Type getType(String typeId) throws PublicApiException - { - HttpResponse response = getAll("types", typeId, null, null, null, "Failed to get type"); - return Type.parseType((JSONObject)response.getJsonResponse().get("entry")); - } - } - - public static class ExpectedPaging - { - private int skipCount; - private int maxItems; - private Integer totalItems; - private boolean hasMoreItems; - private int count; - - public ExpectedPaging() - { - } - - public ExpectedPaging(int skipCount, int maxItems, Integer totalItems, boolean hasMoreItems, int count) - { - super(); - this.skipCount = skipCount; - this.maxItems = maxItems; - this.totalItems = totalItems; - this.hasMoreItems = hasMoreItems; - this.count = count; - } - - public Integer getSkipCount() - { - return skipCount; - } - - public Integer getMaxItems() - { - return maxItems; - } - - public Integer getTotalItems() - { - return totalItems; - } - - public Boolean getHasMoreItems() - { - return hasMoreItems; - } - - public Integer getCount() - { - return count; - } - - public void setCount(Integer count) - { - this.count = count; - } - - public void setHasMoreItems(Boolean hasMoreItems) - { - this.hasMoreItems = hasMoreItems; - } - - public void setTotalItems(Integer totalItems) - { - this.totalItems = totalItems; - } - - public void setSkipCount(Integer skipCount) - { - this.skipCount = skipCount; - } - - public void setMaxItems(Integer maxItems) - { - this.maxItems = maxItems; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + count; - result = prime * result + (hasMoreItems ? 1231 : 1237); - result = prime * result + maxItems; - result = prime * result + skipCount; - result = prime * result - + ((totalItems == null) ? 0 : totalItems.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) - { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - ExpectedPaging other = (ExpectedPaging) obj; - if (count != other.count) - return false; - if (hasMoreItems != other.hasMoreItems) - return false; - if (maxItems != other.maxItems) - return false; - if (skipCount != other.skipCount) - return false; - if (totalItems == null) { - if (other.totalItems != null) - return false; - } else if (!totalItems.equals(other.totalItems)) - return false; - return true; - } - - @Override - public String toString() - { - return "ExpectedPaging [skipCount=" - + skipCount - + ", maxItems=" - + maxItems - + ", " - + (totalItems != null ? "totalItems=" + totalItems + ", " - : "") + "hasMoreItems=" + hasMoreItems + ", count=" - + count + "]"; - } - - public static ExpectedPaging parsePagination(JSONObject jsonList) - { - ExpectedPaging paging = new ExpectedPaging(); - JSONObject jsonPagination = (JSONObject)jsonList.get("pagination"); - if(jsonPagination != null) - { - Long count = (Long)jsonPagination.get("count"); - paging.setCount(count.intValue()); - - Boolean hasMoreItems = (Boolean)jsonPagination.get("hasMoreItems"); - paging.setHasMoreItems(hasMoreItems); - - Long totalItems = (Long)jsonPagination.get("totalItems"); - if(totalItems != null) - { - paging.setTotalItems(totalItems.intValue()); - } - - Long maxItems = (Long)jsonPagination.get("maxItems"); - paging.setMaxItems(maxItems.intValue()); - - Long skipCount = (Long)jsonPagination.get("skipCount"); - paging.setSkipCount(skipCount.intValue()); - } - return paging; - } - - public static ExpectedPaging getExpectedPaging(Integer skipCount, Integer maxItems, int total, Integer expectedTotal) - { - int skip = skipCount != null ? skipCount : org.alfresco.rest.framework.resource.parameters.Paging.DEFAULT_SKIP_COUNT; - int max = maxItems != null ? maxItems : org.alfresco.rest.framework.resource.parameters.Paging.DEFAULT_MAX_ITEMS; - int expectedCount = -1; - int end = skip + max; - if(end < 0 || end > total) - { - // overflow or greater than the total - expectedCount = total - skip; - end = total; - } - else - { - expectedCount = max; - } - if(expectedCount < 0) - { - expectedCount = 0; - } - boolean hasMore = end < total; - ExpectedPaging expectedPaging = new ExpectedPaging(skip, max, expectedTotal, hasMore, expectedCount); - return expectedPaging; - } - } - - public class CmisSession - { - private Session session; - - public CmisSession(Session session) - { - this.session = session; - } - - public Session getCMISSession() - { - return session; - } - - public CmisObject getObject(String objectId) - { - RequestContext rc = getRequestContext(); - OperationContext ctx = rc.getCmisOperationCtxOverride(); - if(ctx == null) - { - ctx = new OperationContextImpl(); - } - - CmisObject res = session.getObject(objectId, ctx); - return res; - } - - public CmisObject getObjectByPath(String path) - { - OperationContextImpl ctx = new OperationContextImpl(); - CmisObject res = session.getObjectByPath(path, ctx); - return res; - } - - public List getObjectParents(String objectId) - { - CmisObject o = session.getObject(objectId); - if(o instanceof FileableCmisObject) - { - FileableCmisObject f = (FileableCmisObject)o; - - OperationContextImpl ctx = new OperationContextImpl(); - List res = f.getParents(ctx); - return res; - } - else - { - throw new IllegalArgumentException("Object does not exist or is not a fileable cmis object"); - } - } - - public void deleteContent(String objectId, boolean refresh) - { - CmisObject o = getObject(objectId); - - if(o instanceof Document) - { - Document d = (Document)o; - d.deleteContentStream(refresh); - } - else - { - throw new IllegalArgumentException("Object does not exists or is not a document"); - } - } - - public ContentData getContent(String objectId) throws IOException - { - CmisObject o = getObject(objectId); - if(o instanceof Document) - { - Document d = (Document)o; - ContentStream res = d.getContentStream(); - ContentData c = new ContentData(res); - return c; - } - else - { - throw new IllegalArgumentException("Object does not exist or is not a document"); - } - } - - public void putContent(String objectId, String filename, BigInteger length, String mimetype, InputStream content, boolean overwrite) - { - CmisObject o = getObject(objectId); - if(o instanceof Document) - { - Document d = (Document)o; - ContentStream contentStream = new ContentStreamImpl(filename, length, mimetype, content); - try - { - d.setContentStream(contentStream, overwrite); - } - finally - { - try - { - contentStream.getStream().close(); - } - catch (Exception e) - { - } - } - } - else - { - throw new IllegalArgumentException("Object does not exist or is not a document"); - } - } - - public void addChildren(FolderNode f, Tree t) - { - FileableCmisObject fco = t.getItem(); - CMISNode child = CMISNode.createNode(fco); - - if(child instanceof FolderNode) - { - f.addFolder((FolderNode)child); - for(Tree c : t.getChildren()) - { - addChildren((FolderNode)child, c); - } - } - else - { - f.addNode(child); - } - } - - public boolean objectExists(String objectId) - { - CmisObject o = getObject(objectId); - return(o != null); - } - - public FolderNode getRootFolder() - { - Folder rootFolder = session.getRootFolder(); - - FolderNode ret = (FolderNode)CMISNode.createNode(rootFolder); - return ret; - } - - public FolderNode getDescendants(String folderId, int depth) - { - Session session = getCMISSession(); - - CmisObject o = session.getObject(folderId); - if(o instanceof Folder) - { - Folder f = (Folder)o; - - OperationContextImpl ctx = new OperationContextImpl(); - List> res = f.getDescendants(depth, ctx); - FolderNode ret = (FolderNode)CMISNode.createNode(f); - for(Tree t : res) - { - addChildren(ret, t); - } - - return ret; - } - else - { - throw new IllegalArgumentException("Folder does not exist or is not a folder"); - } - } - - public ItemIterable getTypeChildren(String typeId, boolean includePropertyDefinitions) - { - ItemIterable res = session.getTypeChildren(typeId, includePropertyDefinitions); - return res; - } - - public List> getTypeDescendants(String typeId, int depth, boolean includePropertyDefinitions) - { - List> res = session.getTypeDescendants(typeId, depth, includePropertyDefinitions); - return res; - } - - public ObjectType getTypeDefinition(String typeId) - { - ObjectType res = session.getTypeDefinition(typeId); - return res; - } - - public void removeAllVersions(String objectId) - { - CmisObject o = getObject(objectId); - if(o instanceof Document) - { - Document d = (Document)o; - d.deleteAllVersions(); - } - else - { - throw new IllegalArgumentException("Object does not exist or is not a document"); - } - } - - public List query(String query, boolean searchAllVersions, long skipCount, int maxItems) - { - OperationContext ctx = new OperationContextImpl(); - ItemIterable res = session.query(query, searchAllVersions, ctx); - res = res.skipTo(skipCount); - res = res.getPage(maxItems); - - List results = new ArrayList((int)res.getPageNumItems()); - - for(QueryResult r : res) - { - CMISNode n = CMISNode.createNode(r); - results.add(n); - } - - return results; - } - - public void removeObject(String objectId, boolean allVersions) - { - CmisObject o = getObject(objectId); - if(o != null) - { - o.delete(allVersions); - } - else - { - throw new IllegalArgumentException("Object does not exist"); - } - } - - public List removeTree(String objectId, boolean allVersions, UnfileObject unfile, boolean continueOnFailure) - { - CmisObject o = getObject(objectId); - if(o instanceof Folder) - { - Folder f = (Folder)o; - List res = f.deleteTree(allVersions, unfile, continueOnFailure); - return res; - } - else - { - throw new IllegalArgumentException("Object does not exist or is not a folder"); - } - } - - public void updateProperties(String objectId, Map properties, boolean refresh) - { - CmisObject o = getObject(objectId); - if(o != null) - { - o.updateProperties(properties, refresh); - } - else - { - throw new IllegalArgumentException("Object does not exist"); - } - } - - public List> getFolderTree(String folderId, int depth) - { - CmisObject o = session.getObject(folderId); - if(o instanceof Folder) - { - Folder f = (Folder)o; - - OperationContextImpl ctx = new OperationContextImpl(); - List> res = f.getFolderTree(depth, ctx); - return res; - } - else - { - throw new IllegalArgumentException("Object does not exist or is not a folder"); - } - } - - public FolderNode getChildren(String folderId, int skipCount, int maxItems) - { - CmisObject o = session.getObject(folderId); - if(o instanceof Folder) - { - Folder f = (Folder)o; - FolderNode ret = (FolderNode)CMISNode.createNode(f); - - OperationContextImpl ctx = new OperationContextImpl(); - ItemIterable res = f.getChildren(ctx); - res.skipTo(skipCount); - ItemIterable l = res.getPage(maxItems); - for(CmisObject c : l) - { - CMISNode child = null; - if(c.getBaseType() instanceof FolderTypeDefinition) - { - child = (FolderNode)CMISNode.createNode(c); - ret.addFolder((FolderNode)child); - } - else - { - child = CMISNode.createNode(c); - ret.addNode(child); - } - } - - return ret; - } - else - { - throw new IllegalArgumentException("Folder does not exist or is not a folder"); - } - } - - public ItemIterable getCheckedOutDocs() - { - OperationContextImpl ctx = new OperationContextImpl(); - ItemIterable res = session.getCheckedOutDocs(ctx); - return res; - } - - public List getAllVersions(String objectId) - { - CmisObject o = getObject(objectId); - if(o instanceof Document) - { - Document d = (Document)o; - OperationContext ctx = new OperationContextImpl(); - List res = d.getAllVersions(ctx); - return res; - } - else - { - throw new IllegalArgumentException("Object does not exist or is not a document"); - } - } - - public AllowableActions getAllowableActions(String objectId) - { - CmisObject o = getObject(objectId); - AllowableActions res = o.getAllowableActions(); - return res; - } - - public Document createDocument(String parentId, String name, Map properties, ContentStream contentStream, VersioningState versioningState) - { - CmisObject o = getObject(parentId); - - if(o instanceof Folder) - { - Folder f = (Folder)o; - - if(properties == null) - { - properties = new HashMap(); - } - String objectTypeId = (String)properties.get(PropertyIds.OBJECT_TYPE_ID); - String type = "cmis:document"; - if(objectTypeId == null) - { - objectTypeId = type; - } - if(objectTypeId.indexOf(type) == -1) - { - StringBuilder sb = new StringBuilder(objectTypeId); - if(sb.length() > 0) - { - sb.append(","); - } - sb.append(type); - objectTypeId = sb.toString(); - } - - properties.put(PropertyIds.NAME, name); - properties.put(PropertyIds.OBJECT_TYPE_ID, objectTypeId); - - Document res = f.createDocument(properties, contentStream, versioningState); - return res; - } - else - { - throw new IllegalArgumentException("Parent does not exists or is not a folder"); - } - } - - public Folder createFolder(String folderId, String name, Map properties) - { - CmisObject o = getObject(folderId); - - if(o instanceof Folder) - { - Folder f = (Folder)o; - - if(properties == null) - { - properties = new HashMap(); - } - String objectTypeId = (String)properties.get(PropertyIds.OBJECT_TYPE_ID); - String type = "cmis:folder"; - if(objectTypeId == null) - { - objectTypeId = type; - } - if(objectTypeId.indexOf(type) == -1) - { - StringBuilder sb = new StringBuilder(objectTypeId); - if(sb.length() > 0) - { - sb.append(","); - } - sb.append(type); - objectTypeId = sb.toString(); - } - - properties.put(PropertyIds.NAME, name); - properties.put(PropertyIds.OBJECT_TYPE_ID, objectTypeId); - - Folder res = f.createFolder(properties); - return res; - } - else - { - throw new IllegalArgumentException("Parent does not exist or is not a folder"); - } - } - - public ObjectId createRelationship(String sourceObjectId, String targetObjectId) - { - Map relProps = new HashMap(); - relProps.put("cmis:sourceId", sourceObjectId); - relProps.put("cmis:targetId", targetObjectId); - relProps.put("cmis:objectTypeId", "cmis:relationship"); - ObjectId res = session.createRelationship(relProps); - return res; - } - - public ObjectId checkoutObject(String objectId) - { - CmisObject o = getObject(objectId); - if(o instanceof Document) - { - Document d = (Document)o; - ObjectId res = d.checkOut(); - return res; - } - else - { - throw new IllegalArgumentException("Object does not exist or is not a document"); - } - } - } - - public static class Paging - { - private Integer skipCount; - private Integer maxItems; - private ExpectedPaging expectedPaging; - - public Paging() - { - } - - public Paging(Integer skipCount, Integer maxItems, ExpectedPaging expectedPaging) - { - super(); - this.skipCount = skipCount; - this.maxItems = maxItems; - this.expectedPaging = expectedPaging; - } - - public ExpectedPaging getExpectedPaging() - { - return expectedPaging; - } - - public void setExpectedPaging(ExpectedPaging expectedPaging) - { - this.expectedPaging = expectedPaging; - } - - public Integer getSkipCount() - { - return skipCount; - } - - public Integer getMaxItems() - { - return maxItems; - } - - public void setSkipCount(Integer skipCount) - { - this.skipCount = skipCount; - } - - public void setMaxItems(Integer maxItems) - { - this.maxItems = maxItems; - } - - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result - + ((maxItems == null) ? 0 : maxItems.hashCode()); - result = prime * result - + ((skipCount == null) ? 0 : skipCount.hashCode()); - return result; - } - - @Override - public boolean equals(Object obj) - { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - Paging other = (Paging) obj; - if (maxItems == null) { - if (other.maxItems != null) - return false; - } else if (!maxItems.equals(other.maxItems)) - return false; - if (skipCount == null) { - if (other.skipCount != null) - return false; - } else if (!skipCount.equals(other.skipCount)) - return false; - return true; - } - - @Override - public String toString() - { - return "Paging [" - + (skipCount != null ? "skipCount=" + skipCount + ", " : "") - + (maxItems != null ? "maxItems=" + maxItems : "") + "]"; - } - } - - /** - * Representation of an error response. - * - * @author Jamal Kaabi-Mofrad - */ - public static class ExpectedErrorResponse - { - private String errorKey; - private int statusCode; - private String briefSummary; - private String stackTrace; - private Map additionalState; - private String descriptionURL; - private String logId; - - public ExpectedErrorResponse() - { - } - - public ExpectedErrorResponse(String errorKey, int statusCode, String briefSummary, StackTraceElement[] stackTrace, - Map additionalState, String logId) - { - super(); - this.errorKey = errorKey; - this.statusCode = statusCode; - this.briefSummary = briefSummary; - this.stackTrace = Arrays.toString(stackTrace); - this.additionalState = additionalState; - this.logId = logId; - } - - public String getErrorKey() - { - return errorKey; - } - - public ExpectedErrorResponse setErrorKey(String errorKey) - { - this.errorKey = errorKey; - return this; - } - - public int getStatusCode() - { - return statusCode; - } - - public ExpectedErrorResponse setStatusCode(int statusCode) - { - this.statusCode = statusCode; - return this; - } - - public String getBriefSummary() - { - return briefSummary; - } - - public ExpectedErrorResponse setBriefSummary(String briefSummary) - { - this.briefSummary = briefSummary; - return this; - } - - public String getLogId() { - return logId; - } - - public void setLogId(String logId) { - this.logId = logId; - } - - public String getStackTrace() - { - return stackTrace; - } - - public ExpectedErrorResponse setStackTrace(String stackTrace) - { - this.stackTrace = stackTrace; - return this; - } - - public Map getAdditionalState() - { - return additionalState; - } - - public ExpectedErrorResponse setAdditionalState(Map additionalState) - { - this.additionalState = additionalState; - return this; - } - - public String getDescriptionURL() - { - return descriptionURL; - } - - public ExpectedErrorResponse setDescriptionURL(String descriptionURL) - { - this.descriptionURL = descriptionURL; - return this; - } - - @Override - public String toString() - { - final StringBuilder sb = new StringBuilder(250); - sb.append("ExpectedErrorResponse [errorKey='").append(errorKey) - .append(", statusCode=").append(statusCode) - .append(", briefSummary='").append(briefSummary) - .append(", logId='").append(logId) - .append(", stackTrace='").append(stackTrace) - .append(", additionalState=").append(additionalState) - .append(", descriptionURL='").append(descriptionURL) - .append(']'); - return sb.toString(); - } - } - - public class Groups extends AbstractProxy - { - - public Group createGroup(Group group, Map params, int expectedStatus) throws PublicApiException - { - HttpResponse response = create("groups", null, null, null, group.toJSON().toString(), "Failed to create group " + group.getId(), expectedStatus, params); - return parseGroupEntity(response); - } - - public GroupMember createGroupMember(String groupId, GroupMember groupMember) throws PublicApiException - { - return createGroupMember(groupId, groupMember, HttpServletResponse.SC_OK); - } - - public GroupMember createGroupMember(String groupId, GroupMember groupMember, int expectedStatus) throws PublicApiException - { - HttpResponse response = create("groups", groupId, "members", null, groupMember.toJSON().toString(), "Failed to create group membership", expectedStatus); - if (response != null && response.getJsonResponse() != null) - { - JSONObject jsonEntity = (JSONObject) response.getJsonResponse().get("entry"); - if (jsonEntity != null) - { - return GroupMember.parseGroupMember(response.getJsonResponse()); - } - } - return null; - } - - public Group updateGroup(String groupId, Group group, Map params, int expectedStatus) throws PublicApiException - { - HttpResponse response = update("groups", groupId, null, null, group.toJSON().toString(), params, "Failed to update group " + group.getId(), expectedStatus); - return parseGroupEntity(response); - } - - public Group getGroup(String groupId) throws PublicApiException - { - return getGroup(groupId, HttpServletResponse.SC_OK); - } - - public Group getGroup(String groupId, int expectedStatus) throws PublicApiException - { - return getGroup(groupId, null, expectedStatus); - } - - public Group getGroup(String groupId, Map params, int expectedStatus) throws PublicApiException - { - HttpResponse response = getSingle("groups", groupId, null, null, params, "Failed to get group " + groupId, expectedStatus); - return parseGroupEntity(response); - } - - public void deleteGroup(String groupId, boolean cascade, int expectedStatus) throws PublicApiException - { - Map params = null; - if (cascade) - { - params = Collections.singletonMap("cascade", "true"); - } - remove("groups", groupId, null, null, params, "Failed to remove group", expectedStatus); - } - - public void deleteGroupMembership(String groupId, String groupMemberId, int expectedStatus) throws PublicApiException - { - remove("groups", groupId, "members", groupMemberId, null, "Failed to remove group member", expectedStatus); - } - - private Group parseGroupEntity(HttpResponse response) - { - if ((response != null) && (response.getJsonResponse() != null)) - { - JSONObject jsonEntity = (JSONObject) response.getJsonResponse().get("entry"); - if (jsonEntity != null) - { - return Group.parseGroup(jsonEntity); - } - } - - return null; - } - - public ListResponse getGroups(Map params, String errorMessage, int expectedStatus) throws PublicApiException, ParseException - { - HttpResponse response = getAll("groups", null, null, null, params, errorMessage, expectedStatus); - - if (response != null && response.getJsonResponse() != null) - { - JSONObject jsonList = (JSONObject) response.getJsonResponse().get("list"); - if (jsonList != null) - { - return Group.parseGroups(response.getJsonResponse()); - } - } - return null; - } - - public ListResponse getGroupMembers(String groupId, Map params) throws PublicApiException, ParseException - { - return getGroupMembers(groupId, params, "Failed to get groups", HttpServletResponse.SC_OK); - } - - public ListResponse getGroupMembers(String groupId, Map params, String errorMessage, int expectedStatus) - throws PublicApiException, ParseException - { - HttpResponse response = getAll("groups", groupId, "members", null, params, errorMessage, expectedStatus); - - if (response != null && response.getJsonResponse() != null) - { - JSONObject jsonList = (JSONObject) response.getJsonResponse().get("list"); - if (jsonList != null) - { - return GroupMember.parseGroupMembers(response.getJsonResponse()); - } - } - return null; - } - - public ListResponse getGroupsByPersonId(String userId, Map params, String errorMessage, int expectedStatus) - throws PublicApiException, ParseException - { - HttpResponse response = getAll("people", userId, "groups", null, params, errorMessage, expectedStatus); - - if (response != null && response.getJsonResponse() != null) - { - JSONObject jsonList = (JSONObject) response.getJsonResponse().get("list"); - if (jsonList != null) - { - return Group.parseGroups(response.getJsonResponse()); - } - } - return null; - } - - } - - public class AuditApps extends AbstractProxy - { - - public ListResponse getAuditApps(Map params, String errorMessage, int expectedStatus) throws PublicApiException - { - HttpResponse response = getAll("audit-applications", null, null, null, params, errorMessage, expectedStatus); - - if (response != null && response.getJsonResponse() != null) - { - JSONObject jsonList = (JSONObject) response.getJsonResponse().get("list"); - if (jsonList != null) - { - return AuditApp.parseAuditApps(response.getJsonResponse()); - } - } - return null; - } - - public AuditApp getAuditApp(String applicationId) throws PublicApiException - { - return getAuditApp(applicationId, HttpServletResponse.SC_OK); - } - - public AuditApp getAuditApp(String applicationId, int expectedStatus) throws PublicApiException - { - return getAuditApp(applicationId, null, expectedStatus); - } - - public AuditApp getAuditApp(String applicationId, Map params, int expectedStatus) throws PublicApiException - { - HttpResponse response = getSingle("audit-applications", applicationId, null, null, params, "Failed to get Audit Application " + applicationId, - expectedStatus); - - if (response != null && response.getJsonResponse() != null) - { - JSONObject jsonEntry = (JSONObject) response.getJsonResponse().get("entry"); - if (jsonEntry != null) - { - return AuditApp.parseAuditApp(jsonEntry); - } - } - return null; - } - - public AuditApp updateAuditApp(String applicationId, AuditApp auditApp, Map params, int expectedStatus) throws PublicApiException - { - HttpResponse response = update("audit-applications", applicationId,null,null, auditApp.toJSON().toString(), params, "Failed to update Audit Application", expectedStatus); - - if (response != null && response.getJsonResponse() != null) - { - JSONObject jsonEntry = (JSONObject) response.getJsonResponse().get("entry"); - if (jsonEntry != null) - { - return AuditApp.parseAuditApp(jsonEntry); - } - } - return null; - } - - public ListResponse getAuditAppEntries(String applicationId, Map params, int expectedStatus) - throws PublicApiException, ParseException - { - HttpResponse response = getAll("audit-applications", applicationId, "audit-entries", null, params, - "Failed to get audit entries for " + applicationId, expectedStatus); - - if (response != null && response.getJsonResponse() != null) - { - JSONObject jsonList = (JSONObject) response.getJsonResponse().get("list"); - if (jsonList != null) - { - return AuditEntry.parseAuditEntries(response.getJsonResponse()); - } - } - return null; - } - - public AuditEntry getAuditEntry(String applicationId, String entryId, Map param, int expectedStatus) - throws PublicApiException, ParseException - { - HttpResponse response = getSingle("audit-applications", applicationId, "audit-entries",entryId, - param, "Failed to get Audit Application " + applicationId, expectedStatus); - - if (response != null && response.getJsonResponse() != null) - { - JSONObject jsonList = (JSONObject) response.getJsonResponse().get("entry"); - if (jsonList != null) - { - return AuditEntry.parseAuditEntry(jsonList); - } - } - return null; - } - - public void deleteAuditEntry(String applicationId, String entryId, Map param, int expectedStatus) - throws PublicApiException - { - remove("audit-applications", applicationId, "audit-entries", entryId, param,"Failed to delete entry " + entryId, expectedStatus); - } - - public void deleteAuditEntries(String applicationId, Map param, int expectedStatus) - throws PublicApiException - { - remove("audit-applications", applicationId, "audit-entries", null, param,"Failed to delete entries for audit application " + applicationId, expectedStatus); - } - - public ListResponse getAuditAppEntriesByNodeRefId(String nodeId, Map params, int expectedStatus) - throws PublicApiException, ParseException - { - HttpResponse response = getAll("nodes", nodeId, "audit-entries", null, params, "Failed to get audit entries for " + nodeId, - expectedStatus); - - if (response != null && response.getJsonResponse() != null) - { - JSONObject jsonList = (JSONObject) response.getJsonResponse().get("list"); - if (jsonList != null) - { - return AuditEntry.parseAuditEntries(response.getJsonResponse()); - } - } - return null; - } - - } - - public class Actions extends AbstractProxy - { - public ListResponse getActionDefinitionsForNode(String nodeId, - Map params, - int expectedStatus) - throws PublicApiException - { - HttpResponse response = getAll("nodes", nodeId, "action-definitions", - null, params, "Unexpected response", expectedStatus); - - if (response != null && response.getJsonResponse() != null) - { - JSONObject jsonList = (JSONObject) response.getJsonResponse().get("list"); - if (jsonList != null) - { - return parseActionDefinitions(response.getJsonResponse()); - } - } - return null; - } - - public ListResponse getActionDefinitions(Map params, - int expectedStatus) - throws PublicApiException - { - HttpResponse response = getAll("action-definitions", null, null, - null, params, "Unexpected response", expectedStatus); - - if (response != null && response.getJsonResponse() != null) - { - JSONObject jsonList = (JSONObject) response.getJsonResponse().get("list"); - if (jsonList != null) - { - return parseActionDefinitions(response.getJsonResponse()); - } - } - return null; - } - - public Action executeAction(Action action, Map params, int expectedStatus) throws PublicApiException - { - HttpResponse response = create("action-executions", null, null, null, action.toJSON().toString(), "Failed to create action for action def " + action.getActionDefinitionId(), expectedStatus, params); - return parseActionEntity(response); - } - - private ListResponse parseActionDefinitions(JSONObject jsonResponse) - { - List actionDefinitions = new ArrayList<>(); - - - JSONObject jsonList = (JSONObject) jsonResponse.get("list"); - assertNotNull(jsonList); - - JSONArray jsonEntries = (JSONArray) jsonList.get("entries"); - assertNotNull(jsonEntries); - - for (int i = 0; i < jsonEntries.size(); i++) - { - JSONObject jsonEntry = (JSONObject) jsonEntries.get(i); - JSONObject entry = (JSONObject) jsonEntry.get("entry"); - actionDefinitions.add(parseActionDefinition(entry)); - } - - ExpectedPaging paging = ExpectedPaging.parsePagination(jsonList); - return new ListResponse<>(paging, actionDefinitions); - } - - private ActionDefinition parseActionDefinition(JSONObject entry) - { - ActionDefinition def = null; - try - { - def = objectMapper.readValue(entry.toString(), ActionDefinition.class); - } - catch (IOException e) - { - throw new RuntimeException("Unable to parse ActionDefinition JSON", e); - } - - return def; - } - - private Action parseActionEntity(HttpResponse response) - { - if ((response != null) && (response.getJsonResponse() != null)) - { - JSONObject jsonEntity = (JSONObject) response.getJsonResponse().get("entry"); - if (jsonEntity != null) - { - return Action.parseAction(jsonEntity); - } - } - - return null; - } - - public ActionDefinition getActionDefinition(String actionDefinitionId, int expectedStatus) throws PublicApiException - { - HttpResponse response = getSingle("action-definitions", actionDefinitionId, null, - null, null, "Unexpected response", expectedStatus); - - if (response != null && response.getJsonResponse() != null) - { - JSONObject jsonEntity = (JSONObject) response.getJsonResponse().get("entry"); - if (jsonEntity != null) - { - return parseActionDefinition(jsonEntity); - } - } - - return null; - } - } -} +/* + * #%L + * Alfresco Remote API + * %% + * Copyright (C) 2005 - 2024 Alfresco Software Limited + * %% + * This file is part of the Alfresco software. + * If the software was purchased under a paid Alfresco license, the terms of + * the paid license agreement will prevail. Otherwise, the software is + * provided under the following open source license terms: + * + * Alfresco is free software: you can redistribute it and/or modify + * it under the terms of the GNU Lesser General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * Alfresco is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public License + * along with Alfresco. If not, see . + * #L% + */ +package org.alfresco.rest.api.tests.client; + +import static org.junit.Assert.assertNotNull; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.Serializable; +import java.math.BigInteger; +import java.text.ParseException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import jakarta.servlet.http.HttpServletResponse; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.apache.chemistry.opencmis.client.api.CmisObject; +import org.apache.chemistry.opencmis.client.api.Document; +import org.apache.chemistry.opencmis.client.api.FileableCmisObject; +import org.apache.chemistry.opencmis.client.api.Folder; +import org.apache.chemistry.opencmis.client.api.ItemIterable; +import org.apache.chemistry.opencmis.client.api.ObjectId; +import org.apache.chemistry.opencmis.client.api.ObjectType; +import org.apache.chemistry.opencmis.client.api.OperationContext; +import org.apache.chemistry.opencmis.client.api.QueryResult; +import org.apache.chemistry.opencmis.client.api.Repository; +import org.apache.chemistry.opencmis.client.api.Session; +import org.apache.chemistry.opencmis.client.api.SessionFactory; +import org.apache.chemistry.opencmis.client.api.Tree; +import org.apache.chemistry.opencmis.client.runtime.OperationContextImpl; +import org.apache.chemistry.opencmis.client.runtime.SessionFactoryImpl; +import org.apache.chemistry.opencmis.commons.PropertyIds; +import org.apache.chemistry.opencmis.commons.SessionParameter; +import org.apache.chemistry.opencmis.commons.data.AllowableActions; +import org.apache.chemistry.opencmis.commons.data.ContentStream; +import org.apache.chemistry.opencmis.commons.definitions.FolderTypeDefinition; +import org.apache.chemistry.opencmis.commons.enums.BindingType; +import org.apache.chemistry.opencmis.commons.enums.UnfileObject; +import org.apache.chemistry.opencmis.commons.enums.VersioningState; +import org.apache.chemistry.opencmis.commons.impl.dataobjects.ContentStreamImpl; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; + +import org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl; +import org.alfresco.opencmis.CMISDispatcherRegistry.Binding; +import org.alfresco.rest.api.model.ActionDefinition; +import org.alfresco.rest.api.model.SiteUpdate; +import org.alfresco.rest.api.tests.TestPeople; +import org.alfresco.rest.api.tests.TestSites; +import org.alfresco.rest.api.tests.client.PublicApiHttpClient.BinaryPayload; +import org.alfresco.rest.api.tests.client.PublicApiHttpClient.RequestBuilder; +import org.alfresco.rest.api.tests.client.data.Action; +import org.alfresco.rest.api.tests.client.data.Activities; +import org.alfresco.rest.api.tests.client.data.Activity; +import org.alfresco.rest.api.tests.client.data.Aspect; +import org.alfresco.rest.api.tests.client.data.AuditApp; +import org.alfresco.rest.api.tests.client.data.AuditEntry; +import org.alfresco.rest.api.tests.client.data.CMISNode; +import org.alfresco.rest.api.tests.client.data.Comment; +import org.alfresco.rest.api.tests.client.data.ContentData; +import org.alfresco.rest.api.tests.client.data.Favourite; +import org.alfresco.rest.api.tests.client.data.FavouriteSite; +import org.alfresco.rest.api.tests.client.data.FolderNode; +import org.alfresco.rest.api.tests.client.data.Group; +import org.alfresco.rest.api.tests.client.data.GroupMember; +import org.alfresco.rest.api.tests.client.data.JSONAble; +import org.alfresco.rest.api.tests.client.data.MemberOfSite; +import org.alfresco.rest.api.tests.client.data.NodeRating; +import org.alfresco.rest.api.tests.client.data.Person; +import org.alfresco.rest.api.tests.client.data.PersonNetwork; +import org.alfresco.rest.api.tests.client.data.Preference; +import org.alfresco.rest.api.tests.client.data.Site; +import org.alfresco.rest.api.tests.client.data.SiteContainer; +import org.alfresco.rest.api.tests.client.data.SiteGroup; +import org.alfresco.rest.api.tests.client.data.SiteImpl; +import org.alfresco.rest.api.tests.client.data.SiteMember; +import org.alfresco.rest.api.tests.client.data.SiteMembershipRequest; +import org.alfresco.rest.api.tests.client.data.Tag; +import org.alfresco.rest.api.tests.client.data.Type; +import org.alfresco.rest.api.tests.util.RestApiUtil; + +/** + * A client for interacting with the public api and returning Java objects. + * + * @author steveglover + * + */ +public class PublicApiClient +{ + private static final Log logger = LogFactory.getLog(PublicApiClient.class); + + private UserDataService userDataService; + private PublicApiHttpClient client; + + private Sites sites; + private Tags tags; + private Comments comments; + private Nodes nodes; + private People people; + private Favourites favourites; + private SiteMembershipRequests siteMembershipRequests; + private Groups groups; + private RawProxy rawProxy; + private AuditApps auditApps; + private Actions actions; + private Aspects aspects; + private Types types; + + private ThreadLocal rc = new ThreadLocal(); + private ObjectMapper objectMapper = new ObjectMapper(); + + public PublicApiClient(PublicApiHttpClient client, UserDataService userDataService) + { + this.client = client; + this.userDataService = userDataService; + + init(); + } + + public void init() + { + sites = new Sites(); + tags = new Tags(); + comments = new Comments(); + nodes = new Nodes(); + people = new People(); + favourites = new Favourites(); + siteMembershipRequests = new SiteMembershipRequests(); + groups = new Groups(); + rawProxy = new RawProxy(); + auditApps = new AuditApps(); + actions = new Actions(); + aspects = new Aspects(); + types = new Types(); + } + + public void setRequestContext(RequestContext rc) + { + this.rc.set(rc); + } + + public RequestContext getRequestContext() + { + RequestContext context = rc.get(); + if (context == null) + { + throw new RuntimeException("Must set a request context"); + } + return context; + } + + protected UserData findUser(String userName) + { + return userDataService.findUserByUserName(userName); + } + + public RawProxy rawProxy() + { + return rawProxy; + } + + public People people() + { + return people; + } + + public Nodes nodes() + { + return nodes; + } + + public Sites sites() + { + return sites; + } + + public Favourites favourites() + { + return favourites; + } + + public SiteMembershipRequests siteMembershipRequests() + { + return siteMembershipRequests; + } + + public Tags tags() + { + return tags; + } + + public Comments comments() + { + return comments; + } + + public Groups groups() + { + return groups; + } + + public AuditApps auditApps() + { + return auditApps; + } + + public Actions actions() + { + return actions; + } + + public Aspects aspects() + { + return aspects; + } + + public Types types() + { + return types; + } + + public CmisSession createPublicApiCMISSession(Binding binding, String version) + { + return createPublicApiCMISSession(binding, version, null); + } + + public CmisSession createPublicApiCMISSession(Binding binding, String version, String objectFactoryName) + { + CmisSession cmisSession = null; + + RequestContext rc = getRequestContext(); + if (rc == null) + { + throw new RuntimeException("Must set a request context"); + } + + String networkId = rc.getNetworkId(); + String username = rc.getRunAsUser(); + UserData userData = findUser(rc.getRunAsUser()); + if (userData != null) + { + String password = userData.getPassword(); + + // default factory implementation + SessionFactory factory = SessionFactoryImpl.newInstance(); + Map parameters = new HashMap(); + + // user credentials + parameters.put(SessionParameter.USER, username); + parameters.put(SessionParameter.PASSWORD, password); + + // connection settings + if (binding == Binding.atom) + { + parameters.put(SessionParameter.ATOMPUB_URL, client.getPublicApiCmisUrl(networkId, binding, version, null)); + parameters.put(SessionParameter.BINDING_TYPE, binding.getOpenCmisBinding().value()); + } + else if (binding == Binding.browser) + { + parameters.put(SessionParameter.BROWSER_URL, client.getPublicApiCmisUrl(networkId, binding, version, null)); + parameters.put(SessionParameter.BINDING_TYPE, binding.getOpenCmisBinding().value()); + } + if (networkId != null) + { + parameters.put(SessionParameter.REPOSITORY_ID, networkId); + } + if (objectFactoryName != null) + { + parameters.put(SessionParameter.OBJECT_FACTORY_CLASS, objectFactoryName); + } + + // create session + Session session = factory.createSession(parameters); + + cmisSession = new CmisSession(session); + } + + return cmisSession; + } + + public CmisSession createCMISSession(String repositoryId, RequestContext rc) + { + CmisSession session = null; + + UserData userData = findUser(rc.getRunAsUser()); + if (userData != null) + { + session = createCMISSession(repositoryId, rc.getRunAsUser(), userData.getPassword()); + } + + return session; + } + + /** + * Get CMIS repositories (Enterprise AtomPub CMIS binding) + * + * @return List + */ + public List getCMISRepositories() + { + List repositories = null; + + RequestContext rc = getRequestContext(); + if (rc == null) + { + throw new RuntimeException("Must set a request context"); + } + + UserData userData = findUser(rc.getRunAsUser()); + if (userData != null) + { + // default factory implementation + SessionFactory factory = SessionFactoryImpl.newInstance(); + Map parameters = new HashMap(); + + // user credentials + parameters.put(SessionParameter.USER, rc.getRunAsUser()); + parameters.put(SessionParameter.PASSWORD, userData.getPassword()); + + // connection settings + parameters.put(SessionParameter.ATOMPUB_URL, client.getCmisUrl(null, null)); + parameters.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value()); + + repositories = factory.getRepositories(parameters); + } + + return repositories; + } + + /** + * Create a CMIS session using Enterprise AtomPub binding. + * + * @param repositoryId + * String + * @param username + * String + * @param password + * String + * @return CmisSession + */ + public CmisSession createCMISSession(String repositoryId, String username, String password) + { + // default factory implementation + SessionFactory factory = SessionFactoryImpl.newInstance(); + Map parameters = new HashMap(); + + // user credentials + parameters.put(SessionParameter.USER, username); + parameters.put(SessionParameter.PASSWORD, password); + + // connection settings + parameters.put(SessionParameter.ATOMPUB_URL, client.getCmisUrl(repositoryId, null)); + parameters.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value()); + if (repositoryId != null) + { + parameters.put(SessionParameter.REPOSITORY_ID, repositoryId); + } + parameters.put(SessionParameter.OBJECT_FACTORY_CLASS, AlfrescoObjectFactoryImpl.class.getName()); + + // create session + Session session = factory.createSession(parameters); + + CmisSession cmisSession = new CmisSession(session); + return cmisSession; + } + + public CmisSession getCMISSession(Repository respository) + { + RequestContext rc = getRequestContext(); + if (rc == null) + { + throw new RuntimeException("Must set a request context"); + } + + CmisSession session = createCMISSession(respository.getId(), rc); + return session; + } + + public HttpResponse post(Binding cmisBinding, String version, String cmisOperation, String body) throws PublicApiException + { + try + { + HttpResponse response = client.post(getRequestContext(), cmisBinding, version, cmisOperation, body); + + logger.debug(response.toString()); + + return response; + } + catch (IOException e) + { + throw new PublicApiException(e); + } + } + + public HttpResponse put(Binding cmisBinding, String version, String cmisOperation, String body) throws PublicApiException + { + try + { + HttpResponse response = client.put(getRequestContext(), cmisBinding, version, cmisOperation, body); + + logger.debug(response.toString()); + + return response; + } + catch (IOException e) + { + throw new PublicApiException(e); + } + } + + public HttpResponse get(Binding cmisBinding, String version, String cmisOperation, Map parameters) throws PublicApiException + { + try + { + HttpResponse response = client.get(getRequestContext(), cmisBinding, version, cmisOperation, parameters); + + logger.debug(response.toString()); + + return response; + } + catch (IOException e) + { + throw new PublicApiException(e); + } + } + + public HttpResponse patch(Binding cmisBinding, String version, String cmisOperation, Map parameters) throws PublicApiException + { + try + { + HttpResponse response = client.patch(getRequestContext(), cmisBinding, version, cmisOperation); + + logger.debug(response.toString()); + + return response; + } + catch (IOException e) + { + throw new PublicApiException(e); + } + } + + public HttpResponse trace(Binding cmisBinding, String version, String cmisOperation, Map parameters) throws PublicApiException + { + try + { + HttpResponse response = client.trace(getRequestContext(), cmisBinding, version, cmisOperation); + + logger.debug(response.toString()); + + return response; + } + catch (IOException e) + { + throw new PublicApiException(e); + } + } + + public HttpResponse options(Binding cmisBinding, String version, String cmisOperation, Map parameters) throws PublicApiException + { + try + { + HttpResponse response = client.options(getRequestContext(), cmisBinding, version, cmisOperation); + + logger.debug(response.toString()); + + return response; + } + catch (IOException e) + { + throw new PublicApiException(e); + } + } + + public HttpResponse head(Binding cmisBinding, String version, String cmisOperation, Map parameters) throws PublicApiException + { + try + { + HttpResponse response = client.head(getRequestContext(), cmisBinding, version, cmisOperation); + + logger.debug(response.toString()); + + return response; + } + catch (IOException e) + { + throw new PublicApiException(e); + } + } + + public HttpResponse post(String scope, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId, String body) throws IOException + { + HttpResponse response = client.post(getRequestContext(), scope, entityCollectionName, entityId, relationCollectionName, relationshipEntityId != null ? relationshipEntityId.toString() : null, body); + + logger.debug(response.toString()); + + return response; + } + + public HttpResponse post(String scope, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId, String body, + final Map params) throws IOException + { + HttpResponse response = client.post(getRequestContext(), scope, entityCollectionName, entityId, relationCollectionName, + relationshipEntityId != null ? relationshipEntityId.toString() : null, body, params); + + logger.debug(response.toString()); + + return response; + } + + public HttpResponse post(String scope, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId, + String body, String contentType) throws IOException + { + HttpResponse response = client.post(getRequestContext(), scope, entityCollectionName, entityId, relationCollectionName, + relationshipEntityId != null ? relationshipEntityId.toString() : null, body, contentType); + + logger.debug(response.toString()); + + return response; + } + + public HttpResponse post(String scope, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId, + byte[] body, String contentType) throws IOException + { + HttpResponse response = client.post(getRequestContext(), scope, entityCollectionName, entityId, relationCollectionName, + relationshipEntityId != null ? relationshipEntityId.toString() : null, body, contentType); + + logger.debug(response.toString()); + + return response; + } + + public HttpResponse post(String urlSuffix, String body) throws IOException + { + HttpResponse response = client.post(getRequestContext(), urlSuffix, body); + + logger.debug(response.toString()); + + return response; + } + + public HttpResponse post(final Class c, Object entityId, Object relationshipEntityId, String body) throws IOException + { + HttpResponse response = client.post(c, getRequestContext(), entityId, relationshipEntityId, body); + + logger.debug(response.toString()); + + return response; + } + + public HttpResponse get(String scope, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId, Map params, Map headers) throws IOException + { + HttpResponse response = client.get(getRequestContext(), scope, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, params, headers); + + logger.debug(response.toString()); + + return response; + } + + public HttpResponse get(String scope, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId, Map params) throws IOException + { + return get(scope, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, params, null); + } + + public HttpResponse getWithPassword(String scope, String password, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId, Map params) throws IOException + { + HttpResponse response = client.get(getRequestContext(), scope, password, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, params); + + logger.debug(response.toString()); + + return response; + } + + public HttpResponse get(String url, Map params) throws IOException + { + RequestContext rc = getRequestContext(); + HttpResponse response = client.get(url, rc, params); + + logger.debug(response.toString()); + + return response; + } + + public HttpResponse get(final Class c, final Object entityId, final Object relationshipEntityId, Map params) throws IOException + { + HttpResponse response = client.get(c, getRequestContext(), entityId, relationshipEntityId, params); + + logger.debug(response.toString()); + + return response; + } + + public HttpResponse put(String scope, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId, String body, Map params) throws IOException + { + HttpResponse response = client.put(getRequestContext(), scope, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, body, params); + + logger.debug(response.toString()); + + return response; + } + + public HttpResponse put(final Class c, Object entityId, Object relationshipEntityId, String body) throws IOException + { + HttpResponse response = client.put(c, getRequestContext(), entityId, relationshipEntityId, body); + + logger.debug(response.toString()); + + return response; + } + + public HttpResponse putBinary(String scope, int version, String entityCollectionName, Object entityId, String relationCollectionName, + Object relationshipEntityId, BinaryPayload payload, Map params) throws IOException + { + HttpResponse response = client.putBinary(getRequestContext(), scope, version, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, + payload, params); + + logger.debug(response.toString()); + + return response; + } + + public HttpResponse delete(String scope, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId) throws IOException + { + return delete(scope, 1, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, null); + } + + public HttpResponse delete(String scope, int version, String entityCollectionName, Object entityId, String relationCollectionName, Object relationshipEntityId, Map params) throws IOException + { + HttpResponse response = client.delete(getRequestContext(), scope, version, entityCollectionName, entityId, relationCollectionName, relationshipEntityId, params); + + logger.debug(response.toString()); + + return response; + } + + public HttpResponse put(final Class c, Object entityId, Object relationshipEntityId) throws IOException + { + HttpResponse response = client.delete(c, getRequestContext(), entityId, relationshipEntityId); + + logger.debug(response.toString()); + + return response; + } + + public HttpResponse execute(RequestBuilder requestBuilder) throws IOException + { + if (requestBuilder.getRequestContext() == null) + { + throw new RuntimeException("Must set a request context"); + } + HttpResponse response = client.execute(requestBuilder); + + logger.debug(response.toString()); + + return response; + } + + public HttpResponse index(Map params) throws IOException + { + HttpResponse response = get("", params); + return response; + } + + public List getNetworkIds(String version) + { + RequestContext rc = getRequestContext(); + + UserData userData = findUser(rc.getRunAsUser()); + if (userData == null) + { + throw new RuntimeException("Must provide a valid username"); + } + + SessionFactory factory = SessionFactoryImpl.newInstance(); + + Map parameters = new HashMap(); + + // connection settings + parameters.put(SessionParameter.ATOMPUB_URL, client.getPublicApiCmisUrl(null, Binding.atom, version, null)); + parameters.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value()); + + // user credentials + parameters.put(SessionParameter.USER, rc.getRunAsUser()); + parameters.put(SessionParameter.PASSWORD, userData.getPassword()); + List repositories = factory.getRepositories(parameters); + + List repositoryIds = new ArrayList(repositories.size()); + for (Repository repository : repositories) + { + repositoryIds.add(repository.getId()); + } + + return repositoryIds; + } + + public class AbstractProxy + { + public HttpResponse getAll(String entityCollectionName, String entityId, String relationCollectionName, String relationId, Map params, String errorMessage) + throws PublicApiException + { + return getAll(entityCollectionName, entityId, relationCollectionName, relationId, params, errorMessage, HttpServletResponse.SC_OK); + } + + public HttpResponse getAll(String entityCollectionName, String entityId, String relationCollectionName, String relationId, Map params, String errorMessage, + int expectedStatus) throws PublicApiException + { + try + { + HttpResponse response = get("public", entityCollectionName, entityId, relationCollectionName, relationId, params); + checkStatus(errorMessage, expectedStatus, response); + return response; + } + catch (IOException e) + { + throw new PublicApiException(e); + } + } + + public HttpResponse getSingle(String entityCollectionName, String entityId, String relationCollectionName, String relationId, String errorMessage) throws PublicApiException + { + return getSingle(entityCollectionName, entityId, relationCollectionName, relationId, errorMessage, HttpServletResponse.SC_OK); + } + + public HttpResponse getSingle(String entityCollectionName, String entityId, String relationCollectionName, String relationId, String errorMessage, int expectedStatus) throws PublicApiException + { + try + { + HttpResponse response = get("public", entityCollectionName, entityId, relationCollectionName, relationId, null); + checkStatus(errorMessage, expectedStatus, response); + return response; + } + catch (IOException e) + { + throw new PublicApiException(e); + } + } + + public HttpResponse getSingle(String entityCollectionName, String entityId, String relationCollectionName, String relationId, Map params, + Map headers, String errorMessage, int expectedStatus) throws PublicApiException + { + try + { + HttpResponse response = get("public", entityCollectionName, entityId, relationCollectionName, relationId, params, headers); + checkStatus(errorMessage, expectedStatus, response); + return response; + } + catch (IOException e) + { + throw new PublicApiException(e); + } + } + + public HttpResponse getSingle(String entityCollectionName, String entityId, String relationCollectionName, String relationId, Map params, + String errorMessage, int expectedStatus) throws PublicApiException + { + try + { + HttpResponse response = get("public", entityCollectionName, entityId, relationCollectionName, relationId, params); + checkStatus(errorMessage, expectedStatus, response); + return response; + } + catch (IOException e) + { + throw new PublicApiException(e); + } + } + + public HttpResponse update(String entityCollectionName, String entityId, String relationCollectionName, String relationId, String body, String errorMessage) throws PublicApiException + { + return update(entityCollectionName, entityId, relationCollectionName, relationId, body, null, errorMessage, 200); + } + + public HttpResponse update(String entityCollectionName, String entityId, String relationCollectionName, String relationId, String body, Map params, String errorMessage, int expectedStatus) throws PublicApiException + { + try + { + HttpResponse response = put("public", entityCollectionName, entityId, relationCollectionName, relationId, body, params); + checkStatus(errorMessage, expectedStatus, response); + return response; + } + catch (IOException e) + { + throw new PublicApiException(e); + } + } + + public HttpResponse create(String entityCollectionName, String entityId, String relationCollectionName, String relationId, String body, String errorMessage) throws PublicApiException + { + return create(entityCollectionName, entityId, relationCollectionName, relationId, body, errorMessage, HttpServletResponse.SC_CREATED); + } + + public HttpResponse create(String entityCollectionName, String entityId, String relationCollectionName, String relationId, String body, String errorMessage, + int expectedStatus) throws PublicApiException + { + return create(entityCollectionName, entityId, relationCollectionName, relationId, body, errorMessage, expectedStatus, null); + } + + public HttpResponse create(String entityCollectionName, String entityId, String relationCollectionName, String relationId, String body, String errorMessage, + int expectedStatus, Map params) throws PublicApiException + { + try + { + HttpResponse response = post("public", entityCollectionName, entityId, relationCollectionName, relationId, body, params); + checkStatus(errorMessage, expectedStatus, response); + return response; + } + catch (IOException e) + { + throw new PublicApiException(e); + } + } + + public HttpResponse remove(String entityCollectionName, String entityId, String relationCollectionName, String relationId, String errorMessage) throws PublicApiException + { + return remove(entityCollectionName, entityId, relationCollectionName, relationId, null, errorMessage, HttpServletResponse.SC_NO_CONTENT); + } + + public HttpResponse remove(String entityCollectionName, String entityId, String relationCollectionName, String relationId, Map params, String errorMessage, int expectedStatus) throws PublicApiException + { + try + { + HttpResponse response = delete("public", 1, entityCollectionName, entityId, relationCollectionName, relationId, params); + checkStatus(errorMessage, expectedStatus, response); + return response; + } + catch (IOException e) + { + throw new PublicApiException(e); + } + } + + public JSONObject parseListSource(JSONObject jsonResponse) + { + JSONObject jsonList = (JSONObject) jsonResponse.get("list"); + assertNotNull(jsonList); + + JSONObject source = (JSONObject) jsonList.get("source"); + assertNotNull(source); + return source; + } + + /** + * Used for validation of status code on rest response + */ + public void checkStatus(String errorMessage, int expectedStatus, HttpResponse response) throws PublicApiException + { + int actualStatus = response.getStatusCode(); + if ((expectedStatus > 0) && (expectedStatus != actualStatus)) + { + String msg = "Status code " + actualStatus + " returned, but expected " + expectedStatus + ": \n" + errorMessage + ": \n" + + " Response: " + response; + throw new PublicApiException(msg, response); + } + /// in case of Status.SC_UNAUTHORIZED no response is returned + if (expectedStatus >= 400 && expectedStatus != 401) + { + checkErrorKeyResponse(errorMessage, expectedStatus, response); + } + } + + /** + * Used for validation on field errorKey on Error rest response + */ + public void checkErrorKeyResponse(String errorMessage, int expectedStatus, HttpResponse response) throws PublicApiException + { + PublicApiClient.ExpectedErrorResponse error; + // the error response must have a valid format in conformity with + // the + // ErrorResponse model + try + { + error = RestApiUtil.parseErrorResponse(response.getJsonResponse()); + } + catch (Exception e) + { + throw new PublicApiException(e.getMessage(), response); + } + + String errorKey = error.errorKey; + // validate the errorKey which have default message exception + if (errorKey != null && errorKey.contains("exception")) + { + boolean validErrorKey = false; + + List httpErrorsFilteredByStatusCode = Arrays.asList(RestErrorResponseDefault.values()).stream() + .filter(t -> t.getStatusCode() == expectedStatus && t.getDefaultMessage() != null).collect(Collectors.toList()); + + httpErrorsFilteredByStatusCode.add(RestErrorResponseDefault.DEFAULT_API_EXCEPTION); + + for (RestErrorResponseDefault errorResponseDefault : httpErrorsFilteredByStatusCode) + { + if (errorResponseDefault.getDefaultMessage().equals(errorKey)) + { + validErrorKey = true; + } + } + + if (validErrorKey == false) + { + String msg = "Error key " + errorKey + " returned is not valid " + "\n" + errorMessage + ": \n" + " Response: " + response; + throw new PublicApiException(msg, response); + } + + } + } + + } + + public static class ListResponse + { + private ExpectedPaging paging; + private List list; + + public ListResponse(ExpectedPaging paging, List list) + { + super(); + this.paging = paging; + this.list = list; + } + + public ExpectedPaging getPaging() + { + return paging; + } + + public List getList() + { + return list; + } + } + + public class Sites extends AbstractProxy + { + public ListResponse getSites(Map params) throws PublicApiException + { + HttpResponse response = getAll("sites", null, null, null, params, "Failed to get sites"); + return SiteImpl.parseSites(response.getJsonResponse()); + } + + public Site getSite(String siteId) throws PublicApiException + { + return getSite(siteId, 200); + } + + public Site getSite(String siteId, int expectedStatus) throws PublicApiException + { + HttpResponse response = getSingle("sites", siteId, null, null, "Failed to get site " + siteId, expectedStatus); + if ((response != null) && (response.getJsonResponse() != null)) + { + return SiteImpl.parseSite((JSONObject) response.getJsonResponse().get("entry")); + } + else + { + return null; + } + } + + public Site createSite(Site site) throws PublicApiException + { + return createSite(site, 201); + } + + public Site createSite(Site site, int expectedStatus) throws PublicApiException + { + HttpResponse response = create("sites", null, null, null, site.toJSON().toString(), "Failed to create site " + site.getTitle(), expectedStatus); + return SiteImpl.parseSite((JSONObject) response.getJsonResponse().get("entry")); + } + + public void removeSite(String siteId) throws PublicApiException + { + removeSite(siteId, false, 204); + } + + public void removeSite(String siteId, boolean permanent, int expectedStatus) throws PublicApiException + { + Map params = null; + if (permanent) + { + params = Collections.singletonMap("permanent", "true"); + } + remove("sites", siteId, null, null, params, "Failed to remove site", expectedStatus); + } + + public Site updateSite(String siteId, SiteUpdate update, int expectedStatus) throws PublicApiException + { + JSONAble jsonizer = new TestSites.SiteUpdateJSONSerializer(update); + HttpResponse response = update("sites", siteId, null, null, jsonizer.toJSON().toString(), null, "Failed to update site " + update.getTitle(), expectedStatus); + if (response.getJsonResponse() != null) + { + return SiteImpl.parseSite((JSONObject) response.getJsonResponse().get("entry")); + } + // No JSON response to parse. + return null; + } + + public ListResponse getSiteContainers(String siteId, Map params) throws PublicApiException + { + HttpResponse response = getAll("sites", siteId, "containers", null, params, "Failed to get site containers"); + return SiteContainer.parseSiteContainers(response.getJsonResponse()); + } + + public SiteContainer getSingleSiteContainer(String siteId, String containerId) throws PublicApiException + { + HttpResponse response = getSingle("sites", siteId, "containers", containerId, "Failed to get site container"); + SiteContainer siteContainer = SiteContainer.parseSiteContainer(siteId, (JSONObject) response.getJsonResponse().get("entry")); + return siteContainer; + } + + public SiteContainer updateSiteContainer(SiteContainer siteContainer) throws PublicApiException + { + HttpResponse response = update("sites", siteContainer.getSiteId(), "containers", siteContainer.getId(), siteContainer.toJSON().toString(), "Failed to update site container"); + SiteContainer retSiteContainer = SiteContainer.parseSiteContainer(siteContainer.getSiteId(), (JSONObject) response.getJsonResponse().get("entry")); + return retSiteContainer; + } + + public SiteContainer createSiteContainer(SiteContainer siteContainer) throws PublicApiException + { + HttpResponse response = create("sites", siteContainer.getSiteId(), "containers", null, siteContainer.toJSON().toString(), "Failed to create site container"); + SiteContainer retSiteContainer = SiteContainer.parseSiteContainer(siteContainer.getSiteId(), (JSONObject) response.getJsonResponse().get("entry")); + return retSiteContainer; + } + + public void removeSiteContainer(SiteContainer siteContainer) throws PublicApiException + { + remove("sites", siteContainer.getSiteId(), "containers", siteContainer.getId(), "Failed to remove site container"); + } + + public ListResponse getSiteMembers(String siteId, Map params) throws PublicApiException + { + HttpResponse response = getAll("sites", siteId, "members", null, params, "Failed to get all site members"); + return SiteMember.parseSiteMembers(siteId, response.getJsonResponse()); + } + + public SiteMember getSingleSiteMember(String siteId, String personId) throws PublicApiException + { + HttpResponse response = getSingle("sites", siteId, "members", personId, "Failed to get site member"); + SiteMember retSiteMember = SiteMember.parseSiteMember(siteId, (JSONObject) response.getJsonResponse().get("entry")); + return retSiteMember; + } + + public SiteMember updateSiteMember(String siteId, SiteMember siteMember) throws PublicApiException + { + HttpResponse response = update("sites", siteId, "members", siteMember.getMemberId(), siteMember.toJSON().toString(), "Failed to update site member"); + SiteMember retSiteMember = SiteMember.parseSiteMember(siteMember.getSiteId(), (JSONObject) response.getJsonResponse().get("entry")); + return retSiteMember; + } + + public SiteMember createSiteMember(String siteId, SiteMember siteMember) throws PublicApiException + { + HttpResponse response = create("sites", siteId, "members", null, siteMember.toJSON().toString(), "Failed to create site member"); + SiteMember retSiteMember = SiteMember.parseSiteMember(siteMember.getSiteId(), (JSONObject) response.getJsonResponse().get("entry")); + return retSiteMember; + } + + public void removeSiteMember(String siteId, SiteMember siteMember) throws PublicApiException + { + remove("sites", siteId, "members", siteMember.getMemberId(), "Failed to remove site member"); + } + + public ListResponse getPersonSites(String personId, Map params) throws PublicApiException + { + HttpResponse response = getAll("people", personId, "sites", null, params, "Failed to get person sites"); + return MemberOfSite.parseMemberOfSites(response.getJsonResponse()); + } + + public MemberOfSite getPersonSite(String personId, String siteId) throws PublicApiException + { + HttpResponse response = getSingle("people", personId, "sites", siteId, "Failed to get person site" + siteId); + return MemberOfSite.parseMemberOfSite((JSONObject) response.getJsonResponse().get("entry")); + } + + public MemberOfSite updatePersonSite(String personId, SiteMember siteMember) throws PublicApiException + { + HttpResponse response = update("people", personId, "sites", siteMember.getSiteId(), siteMember.toJSON().toString(), "Failed to update person site"); + MemberOfSite retSiteMember = MemberOfSite.parseMemberOfSite((JSONObject) response.getJsonResponse().get("entry")); + return retSiteMember; + } + + public MemberOfSite createPersonSite(String personId, SiteMember siteMember) throws PublicApiException + { + HttpResponse response = create("people", personId, "sites", null, siteMember.toJSON().toString(), "Failed to create person site"); + MemberOfSite retSiteMember = MemberOfSite.parseMemberOfSite((JSONObject) response.getJsonResponse().get("entry")); + return retSiteMember; + } + + public void removePersonSite(String personId, SiteMember siteMember) throws PublicApiException + { + remove("people", personId, "sites", siteMember.getSiteId(), "Failed to remove person site"); + } + + public ListResponse getFavouriteSites(String personId, Map params) throws PublicApiException + { + HttpResponse response = getAll("people", personId, "favorite-sites", null, params, "Failed to get favourite sites"); + return FavouriteSite.parseFavouriteSites(response.getJsonResponse()); + } + + public FavouriteSite getSingleFavouriteSite(String personId, String siteId) throws PublicApiException + { + HttpResponse response = getSingle("people", personId, "favorite-sites", siteId, "Failed to get favourite site"); + FavouriteSite favouriteSite = FavouriteSite.parseFavouriteSite((JSONObject) response.getJsonResponse().get("entry")); + return favouriteSite; + } + + public FavouriteSite updateFavouriteSite(String personId, FavouriteSite site) throws PublicApiException + { + HttpResponse response = update("people", personId, "favorite-sites", site.getSiteId(), site.toJSON().toString(), "Failed to update favourite site"); + FavouriteSite favouriteSite = FavouriteSite.parseFavouriteSite((JSONObject) response.getJsonResponse().get("entry")); + return favouriteSite; + } + + public FavouriteSite createFavouriteSite(String personId, FavouriteSite site) throws PublicApiException + { + HttpResponse response = create("people", personId, "favorite-sites", null, site.toJSON().toString(), "Failed to create favourite site"); + FavouriteSite favouriteSite = FavouriteSite.parseFavouriteSite((JSONObject) response.getJsonResponse().get("entry")); + return favouriteSite; + } + + public void removeFavouriteSite(String personId, FavouriteSite site) throws PublicApiException + { + remove("people", personId, "favorite-sites", site.getSiteId(), "Failed to remove favourite site"); + } + + public SiteGroup addGroup(String siteId, SiteGroup group) throws PublicApiException + { + HttpResponse response = create("sites", siteId, "group-members", null, group.toJSON().toString(), "Failed to add site groups"); + return SiteGroup.parseSiteGroup(siteId, (JSONObject) response.getJsonResponse().get("entry")); + } + + public ListResponse getGroups(String siteId, Map params) throws PublicApiException + { + HttpResponse response = getAll("sites", siteId, "group-members", null, params, "Failed to fetch all site groups"); + return SiteGroup.parseGroupMemberOfSites(siteId, response.getJsonResponse()); + } + + public SiteGroup getGroup(String siteId, String groupId) throws PublicApiException + { + HttpResponse response = getSingle("sites", siteId, "group-members", groupId.toString(), "Failed to get a site group"); + return SiteGroup.parseSiteGroup(siteId, (JSONObject) response.getJsonResponse().get("entry")); + } + + public SiteGroup updateGroup(String siteId, SiteGroup group) throws PublicApiException + { + HttpResponse response = update("sites", siteId, "group-members", group.getId(), group.toJSON().toString(), "Failed to update a site group"); + return SiteGroup.parseSiteGroup(siteId, (JSONObject) response.getJsonResponse().get("entry")); + } + + public void deleteGroup(String siteId, String groupId) throws PublicApiException + { + remove("sites", siteId, "group-members", groupId, "Failed to delete site group"); + } + } + + public class SiteMembershipRequests extends AbstractProxy + { + public SiteMembershipRequest getSiteMembershipRequest(String personId, String siteId) throws PublicApiException, ParseException + { + HttpResponse response = getSingle("people", personId, "site-membership-requests", siteId, "Failed to get siteMembershipRequest"); + return SiteMembershipRequest.parseSiteMembershipRequest((JSONObject) response.getJsonResponse().get("entry")); + } + + public ListResponse getSiteMembershipRequests(String personId, Map params) throws PublicApiException, ParseException + { + HttpResponse response = getAll("people", personId, "site-membership-requests", null, params, "Failed to get siteMembershipRequests"); + return SiteMembershipRequest.parseSiteMembershipRequests(response.getJsonResponse()); + } + + public SiteMembershipRequest createSiteMembershipRequest(String personId, SiteMembershipRequest siteMembershipRequest) throws PublicApiException, ParseException + { + HttpResponse response = create("people", personId, "site-membership-requests", null, siteMembershipRequest.toJSON().toString(), "Failed to create siteMembershipRequest"); + SiteMembershipRequest ret = SiteMembershipRequest.parseSiteMembershipRequest((JSONObject) response.getJsonResponse().get("entry")); + return ret; + } + + public SiteMembershipRequest updateSiteMembershipRequest(String personId, SiteMembershipRequest siteMembershipRequest) throws PublicApiException, ParseException + { + HttpResponse response = update("people", personId, "site-membership-requests", siteMembershipRequest.getId(), siteMembershipRequest.toJSON().toString(), "Failed to update siteMembershipRequest"); + SiteMembershipRequest ret = SiteMembershipRequest.parseSiteMembershipRequest((JSONObject) response.getJsonResponse().get("entry")); + return ret; + } + + public void cancelSiteMembershipRequest(String personId, String siteMembershipRequestId) throws PublicApiException + { + remove("people", personId, "site-membership-requests", siteMembershipRequestId, "Failed to cancel siteMembershipRequest"); + } + + public ListResponse getSiteMembershipRequests(Map params, String errorMessage, int expectedStatus) throws PublicApiException, ParseException + { + HttpResponse response = getAll("site-membership-requests", null, null, null, params, errorMessage, expectedStatus); + + if (response != null && response.getJsonResponse() != null) + { + JSONObject jsonList = (JSONObject) response.getJsonResponse().get("list"); + if (jsonList != null) + { + return SiteMembershipRequest.parseSiteMembershipRequests(response.getJsonResponse()); + } + } + return null; + } + } + + public class RawProxy extends AbstractProxy + {} + + public class Favourites extends AbstractProxy + { + public ListResponse getFavourites(String personId, Map params) throws PublicApiException, ParseException + { + HttpResponse response = getAll("people", personId, "favorites", null, params, "Failed to get favourites"); + return Favourite.parseFavourites(response.getJsonResponse()); + } + + public Favourite getFavourite(String personId, String favouriteId) throws PublicApiException, ParseException + { + HttpResponse response = getSingle("people", personId, "favorites", favouriteId, "Failed to get favourite " + favouriteId); + return Favourite.parseFavourite((JSONObject) response.getJsonResponse().get("entry")); + } + + public Favourite getFavourite(String personId, String favouriteId, Map params) throws PublicApiException, ParseException + { + HttpResponse response = getSingle("people", personId, "favorites", favouriteId, params, "Failed to get favourite " + favouriteId, 200); + return Favourite.parseFavourite((JSONObject) response.getJsonResponse().get("entry")); + } + + public Favourite createFavourite(String personId, Favourite favourite) throws PublicApiException, ParseException + { + HttpResponse response = create("people", personId, "favorites", null, favourite.toJSON().toString(), "Failed to create favourite"); + Favourite ret = Favourite.parseFavourite((JSONObject) response.getJsonResponse().get("entry")); + return ret; + } + + public Favourite createFavourite(String personId, Favourite favourite, Map params) throws PublicApiException, ParseException + { + HttpResponse response = create("people", personId, "favorites", null, favourite.toJSON().toString(), "Failed to create favourite", 201, params); + Favourite ret = Favourite.parseFavourite((JSONObject) response.getJsonResponse().get("entry")); + return ret; + } + + public void removeFavourite(String personId, String favouriteId) throws PublicApiException + { + remove("people", personId, "favorites", favouriteId, "Failed to remove favourite"); + } + } + + public class People extends AbstractProxy + { + public ListResponse getPeople(Map params) throws PublicApiException + { + HttpResponse response = getAll("people", null, null, null, params, "Failed to get people"); + return Person.parsePeople(response.getJsonResponse()); + } + + public Person getPerson(String personId) throws PublicApiException + { + return getPerson(personId, 200); + } + + public Person getPerson(String personId, int expectedStatus) throws PublicApiException + { + HttpResponse response = getSingle("people", personId, null, null, "Failed to get person", expectedStatus); + + if (logger.isDebugEnabled()) + { + logger.debug(response); + } + System.out.println(response); + + if (response != null && response.getJsonResponse() != null) + { + JSONObject entry = (JSONObject) response.getJsonResponse().get("entry"); + if (entry != null) + { + return Person.parsePerson(entry); + } + } + return null; + } + + public Person update(String personId, Person person) throws PublicApiException + { + return update(personId, person, 200); + } + + public Person update(String personId, Person person, int expectedStatus) throws PublicApiException + { + return update(personId, person.toJSON(true).toString(), expectedStatus); + } + + public Person update(String personId, String json, int expectedStatus) throws PublicApiException + { + return update(personId, json, null, expectedStatus); + } + + public Person update(String personId, String json, Map params, int expectedStatus) throws PublicApiException + { + HttpResponse response = update("people", personId, null, null, json, params, "Failed to update person", expectedStatus); + if (response != null && response.getJsonResponse() != null) + { + JSONObject entry = (JSONObject) response.getJsonResponse().get("entry"); + if (entry != null) + { + return Person.parsePerson(entry); + } + } + return null; + } + + public Person create(Person person) throws PublicApiException + { + return create(person, 201); + } + + public Person create(Person person, int expectedStatus) throws PublicApiException + { + TestPeople.PersonJSONSerializer jsonizer = new TestPeople.PersonJSONSerializer(person); + HttpResponse response = create("people", null, null, null, jsonizer.toJSON().toString(), "Failed to create person", expectedStatus); + if ((response != null) && (response.getJsonResponse() != null)) + { + JSONObject entry = (JSONObject) response.getJsonResponse().get("entry"); + if (entry != null) + { + return Person.parsePerson(entry); + } + } + return null; + } + + public void remove(Person person) throws PublicApiException + { + remove("people", person.getId(), null, null, "Failed to remove person"); + } + + public ListResponse getPreferences(String personId, Map params) throws PublicApiException + { + HttpResponse response = getAll("people", personId, "preferences", null, params, "Failed to get person preferences"); + return Preference.parsePreferences(response.getJsonResponse()); + } + + public Preference getPreference(String personId, String preferenceId) throws PublicApiException + { + HttpResponse response = getSingle("people", personId, "preferences", preferenceId, "Failed to get person preference"); + Preference pref = Preference.parsePreference((JSONObject) response.getJsonResponse().get("entry")); + return pref; + } + + public Preference updatePreference(String personId, Preference preference) throws PublicApiException + { + HttpResponse response = update("people", personId, "preferences", preference.getId(), preference.toJSON().toString(), "Failed to update person preference"); + Preference pref = Preference.parsePreference((JSONObject) response.getJsonResponse().get("entry")); + return pref; + } + + public Person createPreference(String personId, Preference preference) throws PublicApiException + { + HttpResponse response = create("people", personId, "preferences", null, preference.toJSON().toString(), "Failed to create person preference"); + Person retSite = Person.parsePerson((JSONObject) response.getJsonResponse().get("entry")); + return retSite; + } + + public void removePreference(String personId, Preference preference) throws PublicApiException + { + remove("people", personId, "preferences", preference.getId(), "Failed to remove person preference"); + } + + public ListResponse getNetworkMemberships(String personId, Map params) throws PublicApiException + { + HttpResponse response = getAll("people", personId, "networks", null, params, "Failed to get network members"); + return PersonNetwork.parseNetworkMembers(response.getJsonResponse()); + } + + public PersonNetwork getNetworkMembership(String personId, String networkId) throws PublicApiException + { + HttpResponse response = getSingle("people", personId, "networks", networkId, "Failed to get network member"); + PersonNetwork networkMember = PersonNetwork.parseNetworkMember((JSONObject) response.getJsonResponse().get("entry")); + return networkMember; + } + + public PersonNetwork updateNetworkMembership(String personId, PersonNetwork networkMember) throws PublicApiException + { + HttpResponse response = update("people", personId, "networks", networkMember.getId(), networkMember.toJSON().toString(), "Failed to update network member"); + PersonNetwork retNetwork = PersonNetwork.parseNetworkMember((JSONObject) response.getJsonResponse().get("entry")); + return retNetwork; + } + + public PersonNetwork createNetworkMembership(String personId, PersonNetwork network) throws PublicApiException + { + HttpResponse response = create("people", personId, "networks", null, network.toJSON().toString(), "Failed to create network member"); + PersonNetwork retNetwork = PersonNetwork.parseNetworkMember((JSONObject) response.getJsonResponse().get("entry")); + return retNetwork; + } + + public void removeNetworkMembership(String personId, PersonNetwork networkMember) throws PublicApiException + { + remove("people", personId, "networks", networkMember.getId(), "Failed to remove network member"); + } + + public ListResponse getActivities(String personId, Map params) throws PublicApiException + { + HttpResponse response = getAll("people", personId, "activities", null, params, "Failed to get activities"); + return Activities.parseActivities(response.getJsonResponse()); + } + + public Activity getSingleActivity(String personId, String activityId) throws PublicApiException + { + HttpResponse response = getSingle("people", personId, "activities", activityId, "Failed to get activities"); + Activity activity = Activity.parseActivity((JSONObject) response.getJsonResponse().get("entry")); + return activity; + } + + public Activity update(String personId, Activity activity) throws PublicApiException + { + HttpResponse response = update("people", personId, "activities", String.valueOf(activity.getId()), activity.toJSON().toString(), "Failed to update activity"); + Activity retActivity = Activity.parseActivity((JSONObject) response.getJsonResponse().get("entry")); + return retActivity; + } + + public Activity create(String personId, Activity activity) throws PublicApiException + { + HttpResponse response = create("people", personId, "activities", String.valueOf(activity.getId()), activity.toJSON().toString(), "Failed to create activity"); + Activity retActivity = Activity.parseActivity((JSONObject) response.getJsonResponse().get("entry")); + return retActivity; + } + + public void remove(String personId, Activity activity) throws PublicApiException + { + remove("people", personId, "activities", String.valueOf(activity.getId()), "Failed to remove activity"); + } + + public HttpResponse getAvatar(String personId, boolean placeholder, int expectedStatus) throws PublicApiException, InterruptedException + { + return getAvatar(personId, null, placeholder, null, expectedStatus); + } + + public HttpResponse getAvatar(String personId, String ifModifiedSince, int expectedStatus) throws PublicApiException, InterruptedException + { + return getAvatar(personId, null, false, ifModifiedSince, expectedStatus); + } + + public HttpResponse getAvatar(String personId, Boolean attachment, boolean placeholder, String ifModifiedSince, int expectedStatus) throws PublicApiException, InterruptedException + { + // Binary response expected + Map params = new HashMap<>(); + params.put("placeholder", Boolean.toString(placeholder)); + // Optional attachment parameter + if (attachment != null) + { + params.put("attachment", attachment.toString()); + } + + Map headers = new HashMap<>(); + if (ifModifiedSince != null) + { + headers.put("If-Modified-Since", ifModifiedSince); + } + + // As renditions are now done async, we generally need to wait. + HttpResponse response = getSingleWithDelayRetry("people", personId, "avatar", + null, params, headers, "Failed to get avatar", 40, 2500, expectedStatus); + checkStatus("Unexpected response", expectedStatus, response); + + return response; + } + + private HttpResponse getSingleWithDelayRetry(String entityCollectionName, String entityId, String relationCollectionName, String relationId, Map params, + Map headers, String errorMessage, int repeat, long pauseInMillisecond, int expectedStatus) throws PublicApiException, InterruptedException + { + int retryCount = 0; + while (retryCount < repeat) + { + try + { + return getSingle(entityCollectionName, entityId, relationCollectionName, relationId, params, headers, errorMessage, expectedStatus); + } + catch (PublicApiException ex) + { + retryCount++; + Thread.sleep(pauseInMillisecond); + } + } + return null; + } + + public HttpResponse updateAvatar(String personId, File avatar, int expectedStatus) throws PublicApiException + { + try + { + Map params = new HashMap<>(); + BinaryPayload payload = new BinaryPayload(avatar); + HttpResponse response = client.putBinary(getRequestContext(), "public", 1, "people", personId, "avatar", null, payload, params); + checkStatus("Unexpected status", expectedStatus, response); + return response; + } + catch (IOException e) + { + throw new PublicApiException(e); + } + } + + public void deleteAvatarImage(String personId, int expectedStatus) throws PublicApiException + { + remove("people", personId, "avatar", null, null, "Failed to remove avatar image", expectedStatus); + } + } + + public class Comments extends AbstractProxy + { + public ListResponse getTenantComments(Map params) throws PublicApiException + { + HttpResponse response = getAll("comments", null, null, null, params, "Failed to get comments"); + return Comment.parseComments(null, response.getJsonResponse()); + } + + public Comment getTenantComment(String commentId) throws PublicApiException + { + HttpResponse response = getSingle("comments", commentId, null, null, "Failed to get comment"); + Comment comment = Comment.parseComment(null, (JSONObject) response.getJsonResponse().get("entry")); + return comment; + } + + public Comment updateTenantComment(Comment comment) throws PublicApiException + { + HttpResponse response = update("comments", comment.getId(), null, null, comment.toJSON(true).toString(), "Failed to update comment"); + Comment retComment = Comment.parseComment(null, (JSONObject) response.getJsonResponse().get("entry")); + return retComment; + } + + public Comment createTenantComment(Comment comment) throws PublicApiException + { + HttpResponse response = create("comments", null, null, null, comment.toJSON(true).toString(), "Failed to create comment"); + Comment retComment = Comment.parseComment(null, (JSONObject) response.getJsonResponse().get("entry")); + return retComment; + } + + public void removeTenantComment(Comment comment) throws PublicApiException + { + remove("comments", comment.getId(), null, null, "Failed to remove comment"); + } + + public ListResponse getNodeComments(String nodeId, Map params) throws PublicApiException + { + HttpResponse response = getAll("nodes", nodeId, "comments", null, params, "Failed to get comments"); + return Comment.parseComments(nodeId, response.getJsonResponse()); + } + + public Comment getNodeComment(String nodeId) throws PublicApiException + { + HttpResponse response = getSingle("nodes", nodeId, null, null, "Failed to get comment"); + Comment comment = Comment.parseComment(nodeId, (JSONObject) response.getJsonResponse().get("entry")); + return comment; + } + + public Comment updateNodeComment(String nodeId, String commentId, Comment comment) throws PublicApiException + { + HttpResponse response = update("nodes", nodeId, "comments", commentId, comment.toJSON(true).toString(), "Failed to update comment"); + Comment retComment = Comment.parseComment(nodeId, (JSONObject) response.getJsonResponse().get("entry")); + return retComment; + } + + public Comment createNodeComment(String nodeId, Comment comment) throws PublicApiException + { + HttpResponse response = create("nodes", nodeId, "comments", null, comment.toJSON(true).toString(), "Failed to create comment"); + Comment retComment = Comment.parseComment(nodeId, (JSONObject) response.getJsonResponse().get("entry")); + return retComment; + } + + public void removeNodeComment(String nodeId, String commentId) throws PublicApiException + { + remove("nodes", nodeId, "comments", commentId, "Failed to remove comment"); + } + } + + public class Tags extends AbstractProxy + { + public ListResponse getTags(Map params) throws PublicApiException + { + HttpResponse response = getAll("tags", null, null, null, params, "Failed to get tags"); + return Tag.parseTags(null, response.getJsonResponse()); + } + + public Tag getSingle(String tagId) throws PublicApiException + { + HttpResponse response = getSingle("tags", tagId, null, null, "Failed to get tag"); + Tag tag = Tag.parseTag(null, (JSONObject) response.getJsonResponse().get("entry")); + return tag; + } + + public Tag update(Tag tag) throws PublicApiException + { + HttpResponse response = update("tags", tag.getId(), null, null, tag.toJSON().toString(), "Failed to update tag"); + Tag retTag = Tag.parseTag(null, (JSONObject) response.getJsonResponse().get("entry")); + return retTag; + } + + // public Tag create(Tag tag) throws PublicApiException + // { + // HttpResponse response = create("tags", tag.getTagId(), null, null, tag.toJSON().toString(), "Failed to create tag"); + // Tag retTag = Tag.parseTag(null, (JSONObject)response.getJsonResponse().get("entry")); + // return retTag; + // } + + public void remove(Tag tag) throws PublicApiException + { + remove("tags", tag.getId(), null, null, "Failed to remove tag"); + } + } + + public class Nodes extends AbstractProxy + { + public ListResponse getNodeTags(String nodeId, Map params) throws PublicApiException + { + HttpResponse response = getAll("nodes", nodeId, "tags", null, params, "Failed to get node tags"); + return Tag.parseTags(nodeId, response.getJsonResponse()); + } + + public void removeNodeTag(String nodeId, String tagId) throws PublicApiException + { + remove("nodes", nodeId, "tags", tagId, "Failed to remove node tag"); + } + + public Tag createNodeTag(String nodeId, Tag tag) throws PublicApiException + { + HttpResponse response = create("nodes", nodeId, "tags", null, tag.toJSON().toString(), "Failed to create node tag"); + Tag tagRet = Tag.parseTag(nodeId, (JSONObject) response.getJsonResponse().get("entry")); + return tagRet; + } + + public NodeRating getNodeRating(String nodeId, String ratingId) throws PublicApiException + { + HttpResponse response = getSingle("nodes", nodeId, "ratings", ratingId, "Failed to get node ratings"); + return NodeRating.parseNodeRating(nodeId, (JSONObject) response.getJsonResponse().get("entry")); + } + + public ListResponse getNodeRatings(String nodeId, Map params) throws PublicApiException + { + HttpResponse response = getAll("nodes", nodeId, "ratings", null, params, "Failed to get node ratings"); + return NodeRating.parseNodeRatings(nodeId, response.getJsonResponse()); + } + + public NodeRating updateNodeRating(String nodeId, NodeRating nodeRating) throws PublicApiException + { + HttpResponse response = update("nodes", nodeId, "ratings", nodeRating.getId(), nodeRating.toJSON().toString(), "Failed to update node rating"); + NodeRating nodeRatingRet = NodeRating.parseNodeRating(nodeId, (JSONObject) response.getJsonResponse().get("entry")); + return nodeRatingRet; + } + + public NodeRating createNodeRating(String nodeId, NodeRating nodeRating) throws PublicApiException + { + HttpResponse response = create("nodes", nodeId, "ratings", null, nodeRating.toJSON().toString(), "Failed to create node rating"); + NodeRating nodeRatingRet = NodeRating.parseNodeRating(nodeId, (JSONObject) response.getJsonResponse().get("entry")); + return nodeRatingRet; + } + + public void removeNodeRating(String nodeId, NodeRating rating) throws PublicApiException + { + remove("nodes", nodeId, "ratings", rating.getId(), "Failed to remove node rating"); + } + } + + public class Aspects extends AbstractProxy + { + public PublicApiClient.ListResponse getAspects(Map params) throws PublicApiException + { + HttpResponse response = getAll("aspects", null, null, null, params, "Failed to get aspects"); + return Aspect.parseAspects(response.getJsonResponse()); + } + + public Aspect getAspect(String aspectId) throws PublicApiException + { + HttpResponse response = getAll("aspects", aspectId, null, null, null, "Failed to get aspect"); + return Aspect.parseAspect((JSONObject) response.getJsonResponse().get("entry")); + } + } + + public class Types extends AbstractProxy + { + public PublicApiClient.ListResponse getTypes(Map params) throws PublicApiException + { + HttpResponse response = getAll("types", null, null, null, params, "Failed to get types"); + return Type.parseTypes(response.getJsonResponse()); + } + + public Type getType(String typeId) throws PublicApiException + { + HttpResponse response = getAll("types", typeId, null, null, null, "Failed to get type"); + return Type.parseType((JSONObject) response.getJsonResponse().get("entry")); + } + } + + public static class ExpectedPaging + { + private int skipCount; + private int maxItems; + private Integer totalItems; + private boolean hasMoreItems; + private int count; + + public ExpectedPaging() + {} + + public ExpectedPaging(int skipCount, int maxItems, Integer totalItems, boolean hasMoreItems, int count) + { + super(); + this.skipCount = skipCount; + this.maxItems = maxItems; + this.totalItems = totalItems; + this.hasMoreItems = hasMoreItems; + this.count = count; + } + + public Integer getSkipCount() + { + return skipCount; + } + + public Integer getMaxItems() + { + return maxItems; + } + + public Integer getTotalItems() + { + return totalItems; + } + + public Boolean getHasMoreItems() + { + return hasMoreItems; + } + + public Integer getCount() + { + return count; + } + + public void setCount(Integer count) + { + this.count = count; + } + + public void setHasMoreItems(Boolean hasMoreItems) + { + this.hasMoreItems = hasMoreItems; + } + + public void setTotalItems(Integer totalItems) + { + this.totalItems = totalItems; + } + + public void setSkipCount(Integer skipCount) + { + this.skipCount = skipCount; + } + + public void setMaxItems(Integer maxItems) + { + this.maxItems = maxItems; + } + + @Override + public int hashCode() + { + final int prime = 31; + int result = 1; + result = prime * result + count; + result = prime * result + (hasMoreItems ? 1231 : 1237); + result = prime * result + maxItems; + result = prime * result + skipCount; + result = prime * result + + ((totalItems == null) ? 0 : totalItems.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) + { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ExpectedPaging other = (ExpectedPaging) obj; + if (count != other.count) + return false; + if (hasMoreItems != other.hasMoreItems) + return false; + if (maxItems != other.maxItems) + return false; + if (skipCount != other.skipCount) + return false; + if (totalItems == null) + { + if (other.totalItems != null) + return false; + } + else if (!totalItems.equals(other.totalItems)) + return false; + return true; + } + + @Override + public String toString() + { + return "ExpectedPaging [skipCount=" + + skipCount + + ", maxItems=" + + maxItems + + ", " + + (totalItems != null ? "totalItems=" + totalItems + ", " + : "") + + "hasMoreItems=" + hasMoreItems + ", count=" + + count + "]"; + } + + public static ExpectedPaging parsePagination(JSONObject jsonList) + { + ExpectedPaging paging = new ExpectedPaging(); + JSONObject jsonPagination = (JSONObject) jsonList.get("pagination"); + if (jsonPagination != null) + { + Long count = (Long) jsonPagination.get("count"); + paging.setCount(count.intValue()); + + Boolean hasMoreItems = (Boolean) jsonPagination.get("hasMoreItems"); + paging.setHasMoreItems(hasMoreItems); + + Long totalItems = (Long) jsonPagination.get("totalItems"); + if (totalItems != null) + { + paging.setTotalItems(totalItems.intValue()); + } + + Long maxItems = (Long) jsonPagination.get("maxItems"); + paging.setMaxItems(maxItems.intValue()); + + Long skipCount = (Long) jsonPagination.get("skipCount"); + paging.setSkipCount(skipCount.intValue()); + } + return paging; + } + + public static ExpectedPaging getExpectedPaging(Integer skipCount, Integer maxItems, int total, Integer expectedTotal) + { + int skip = skipCount != null ? skipCount : org.alfresco.rest.framework.resource.parameters.Paging.DEFAULT_SKIP_COUNT; + int max = maxItems != null ? maxItems : org.alfresco.rest.framework.resource.parameters.Paging.DEFAULT_MAX_ITEMS; + int expectedCount = -1; + int end = skip + max; + if (end < 0 || end > total) + { + // overflow or greater than the total + expectedCount = total - skip; + end = total; + } + else + { + expectedCount = max; + } + if (expectedCount < 0) + { + expectedCount = 0; + } + boolean hasMore = end < total; + ExpectedPaging expectedPaging = new ExpectedPaging(skip, max, expectedTotal, hasMore, expectedCount); + return expectedPaging; + } + } + + public class CmisSession + { + private Session session; + + public CmisSession(Session session) + { + this.session = session; + } + + public Session getCMISSession() + { + return session; + } + + public CmisObject getObject(String objectId) + { + RequestContext rc = getRequestContext(); + OperationContext ctx = rc.getCmisOperationCtxOverride(); + if (ctx == null) + { + ctx = new OperationContextImpl(); + } + + CmisObject res = session.getObject(objectId, ctx); + return res; + } + + public CmisObject getObjectByPath(String path) + { + OperationContextImpl ctx = new OperationContextImpl(); + CmisObject res = session.getObjectByPath(path, ctx); + return res; + } + + public List getObjectParents(String objectId) + { + CmisObject o = session.getObject(objectId); + if (o instanceof FileableCmisObject) + { + FileableCmisObject f = (FileableCmisObject) o; + + OperationContextImpl ctx = new OperationContextImpl(); + List res = f.getParents(ctx); + return res; + } + else + { + throw new IllegalArgumentException("Object does not exist or is not a fileable cmis object"); + } + } + + public void deleteContent(String objectId, boolean refresh) + { + CmisObject o = getObject(objectId); + + if (o instanceof Document) + { + Document d = (Document) o; + d.deleteContentStream(refresh); + } + else + { + throw new IllegalArgumentException("Object does not exists or is not a document"); + } + } + + public ContentData getContent(String objectId) throws IOException + { + CmisObject o = getObject(objectId); + if (o instanceof Document) + { + Document d = (Document) o; + ContentStream res = d.getContentStream(); + ContentData c = new ContentData(res); + return c; + } + else + { + throw new IllegalArgumentException("Object does not exist or is not a document"); + } + } + + public void putContent(String objectId, String filename, BigInteger length, String mimetype, InputStream content, boolean overwrite) + { + CmisObject o = getObject(objectId); + if (o instanceof Document) + { + Document d = (Document) o; + ContentStream contentStream = new ContentStreamImpl(filename, length, mimetype, content); + try + { + d.setContentStream(contentStream, overwrite); + } + finally + { + try + { + contentStream.getStream().close(); + } + catch (Exception e) + {} + } + } + else + { + throw new IllegalArgumentException("Object does not exist or is not a document"); + } + } + + public void addChildren(FolderNode f, Tree t) + { + FileableCmisObject fco = t.getItem(); + CMISNode child = CMISNode.createNode(fco); + + if (child instanceof FolderNode) + { + f.addFolder((FolderNode) child); + for (Tree c : t.getChildren()) + { + addChildren((FolderNode) child, c); + } + } + else + { + f.addNode(child); + } + } + + public boolean objectExists(String objectId) + { + CmisObject o = getObject(objectId); + return (o != null); + } + + public FolderNode getRootFolder() + { + Folder rootFolder = session.getRootFolder(); + + FolderNode ret = (FolderNode) CMISNode.createNode(rootFolder); + return ret; + } + + public FolderNode getDescendants(String folderId, int depth) + { + Session session = getCMISSession(); + + CmisObject o = session.getObject(folderId); + if (o instanceof Folder) + { + Folder f = (Folder) o; + + OperationContextImpl ctx = new OperationContextImpl(); + List> res = f.getDescendants(depth, ctx); + FolderNode ret = (FolderNode) CMISNode.createNode(f); + for (Tree t : res) + { + addChildren(ret, t); + } + + return ret; + } + else + { + throw new IllegalArgumentException("Folder does not exist or is not a folder"); + } + } + + public ItemIterable getTypeChildren(String typeId, boolean includePropertyDefinitions) + { + ItemIterable res = session.getTypeChildren(typeId, includePropertyDefinitions); + return res; + } + + public List> getTypeDescendants(String typeId, int depth, boolean includePropertyDefinitions) + { + List> res = session.getTypeDescendants(typeId, depth, includePropertyDefinitions); + return res; + } + + public ObjectType getTypeDefinition(String typeId) + { + ObjectType res = session.getTypeDefinition(typeId); + return res; + } + + public void removeAllVersions(String objectId) + { + CmisObject o = getObject(objectId); + if (o instanceof Document) + { + Document d = (Document) o; + d.deleteAllVersions(); + } + else + { + throw new IllegalArgumentException("Object does not exist or is not a document"); + } + } + + public List query(String query, boolean searchAllVersions, long skipCount, int maxItems) + { + OperationContext ctx = new OperationContextImpl(); + ItemIterable res = session.query(query, searchAllVersions, ctx); + res = res.skipTo(skipCount); + res = res.getPage(maxItems); + + List results = new ArrayList((int) res.getPageNumItems()); + + for (QueryResult r : res) + { + CMISNode n = CMISNode.createNode(r); + results.add(n); + } + + return results; + } + + public void removeObject(String objectId, boolean allVersions) + { + CmisObject o = getObject(objectId); + if (o != null) + { + o.delete(allVersions); + } + else + { + throw new IllegalArgumentException("Object does not exist"); + } + } + + public List removeTree(String objectId, boolean allVersions, UnfileObject unfile, boolean continueOnFailure) + { + CmisObject o = getObject(objectId); + if (o instanceof Folder) + { + Folder f = (Folder) o; + List res = f.deleteTree(allVersions, unfile, continueOnFailure); + return res; + } + else + { + throw new IllegalArgumentException("Object does not exist or is not a folder"); + } + } + + public void updateProperties(String objectId, Map properties, boolean refresh) + { + CmisObject o = getObject(objectId); + if (o != null) + { + o.updateProperties(properties, refresh); + } + else + { + throw new IllegalArgumentException("Object does not exist"); + } + } + + public List> getFolderTree(String folderId, int depth) + { + CmisObject o = session.getObject(folderId); + if (o instanceof Folder) + { + Folder f = (Folder) o; + + OperationContextImpl ctx = new OperationContextImpl(); + List> res = f.getFolderTree(depth, ctx); + return res; + } + else + { + throw new IllegalArgumentException("Object does not exist or is not a folder"); + } + } + + public FolderNode getChildren(String folderId, int skipCount, int maxItems) + { + CmisObject o = session.getObject(folderId); + if (o instanceof Folder) + { + Folder f = (Folder) o; + FolderNode ret = (FolderNode) CMISNode.createNode(f); + + OperationContextImpl ctx = new OperationContextImpl(); + ItemIterable res = f.getChildren(ctx); + res.skipTo(skipCount); + ItemIterable l = res.getPage(maxItems); + for (CmisObject c : l) + { + CMISNode child = null; + if (c.getBaseType() instanceof FolderTypeDefinition) + { + child = (FolderNode) CMISNode.createNode(c); + ret.addFolder((FolderNode) child); + } + else + { + child = CMISNode.createNode(c); + ret.addNode(child); + } + } + + return ret; + } + else + { + throw new IllegalArgumentException("Folder does not exist or is not a folder"); + } + } + + public ItemIterable getCheckedOutDocs() + { + OperationContextImpl ctx = new OperationContextImpl(); + ItemIterable res = session.getCheckedOutDocs(ctx); + return res; + } + + public List getAllVersions(String objectId) + { + CmisObject o = getObject(objectId); + if (o instanceof Document) + { + Document d = (Document) o; + OperationContext ctx = new OperationContextImpl(); + List res = d.getAllVersions(ctx); + return res; + } + else + { + throw new IllegalArgumentException("Object does not exist or is not a document"); + } + } + + public AllowableActions getAllowableActions(String objectId) + { + CmisObject o = getObject(objectId); + AllowableActions res = o.getAllowableActions(); + return res; + } + + public Document createDocument(String parentId, String name, Map properties, ContentStream contentStream, VersioningState versioningState) + { + CmisObject o = getObject(parentId); + + if (o instanceof Folder) + { + Folder f = (Folder) o; + + if (properties == null) + { + properties = new HashMap(); + } + String objectTypeId = (String) properties.get(PropertyIds.OBJECT_TYPE_ID); + String type = "cmis:document"; + if (objectTypeId == null) + { + objectTypeId = type; + } + if (objectTypeId.indexOf(type) == -1) + { + StringBuilder sb = new StringBuilder(objectTypeId); + if (sb.length() > 0) + { + sb.append(","); + } + sb.append(type); + objectTypeId = sb.toString(); + } + + properties.put(PropertyIds.NAME, name); + properties.put(PropertyIds.OBJECT_TYPE_ID, objectTypeId); + + Document res = f.createDocument(properties, contentStream, versioningState); + return res; + } + else + { + throw new IllegalArgumentException("Parent does not exists or is not a folder"); + } + } + + public Folder createFolder(String folderId, String name, Map properties) + { + CmisObject o = getObject(folderId); + + if (o instanceof Folder) + { + Folder f = (Folder) o; + + if (properties == null) + { + properties = new HashMap(); + } + String objectTypeId = (String) properties.get(PropertyIds.OBJECT_TYPE_ID); + String type = "cmis:folder"; + if (objectTypeId == null) + { + objectTypeId = type; + } + if (objectTypeId.indexOf(type) == -1) + { + StringBuilder sb = new StringBuilder(objectTypeId); + if (sb.length() > 0) + { + sb.append(","); + } + sb.append(type); + objectTypeId = sb.toString(); + } + + properties.put(PropertyIds.NAME, name); + properties.put(PropertyIds.OBJECT_TYPE_ID, objectTypeId); + + Folder res = f.createFolder(properties); + return res; + } + else + { + throw new IllegalArgumentException("Parent does not exist or is not a folder"); + } + } + + public ObjectId createRelationship(String sourceObjectId, String targetObjectId) + { + Map relProps = new HashMap(); + relProps.put("cmis:sourceId", sourceObjectId); + relProps.put("cmis:targetId", targetObjectId); + relProps.put("cmis:objectTypeId", "cmis:relationship"); + ObjectId res = session.createRelationship(relProps); + return res; + } + + public ObjectId checkoutObject(String objectId) + { + CmisObject o = getObject(objectId); + if (o instanceof Document) + { + Document d = (Document) o; + ObjectId res = d.checkOut(); + return res; + } + else + { + throw new IllegalArgumentException("Object does not exist or is not a document"); + } + } + } + + public static class Paging + { + private Integer skipCount; + private Integer maxItems; + private ExpectedPaging expectedPaging; + + public Paging() + {} + + public Paging(Integer skipCount, Integer maxItems, ExpectedPaging expectedPaging) + { + super(); + this.skipCount = skipCount; + this.maxItems = maxItems; + this.expectedPaging = expectedPaging; + } + + public ExpectedPaging getExpectedPaging() + { + return expectedPaging; + } + + public void setExpectedPaging(ExpectedPaging expectedPaging) + { + this.expectedPaging = expectedPaging; + } + + public Integer getSkipCount() + { + return skipCount; + } + + public Integer getMaxItems() + { + return maxItems; + } + + public void setSkipCount(Integer skipCount) + { + this.skipCount = skipCount; + } + + public void setMaxItems(Integer maxItems) + { + this.maxItems = maxItems; + } + + @Override + public int hashCode() + { + final int prime = 31; + int result = 1; + result = prime * result + + ((maxItems == null) ? 0 : maxItems.hashCode()); + result = prime * result + + ((skipCount == null) ? 0 : skipCount.hashCode()); + return result; + } + + @Override + public boolean equals(Object obj) + { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Paging other = (Paging) obj; + if (maxItems == null) + { + if (other.maxItems != null) + return false; + } + else if (!maxItems.equals(other.maxItems)) + return false; + if (skipCount == null) + { + if (other.skipCount != null) + return false; + } + else if (!skipCount.equals(other.skipCount)) + return false; + return true; + } + + @Override + public String toString() + { + return "Paging [" + + (skipCount != null ? "skipCount=" + skipCount + ", " : "") + + (maxItems != null ? "maxItems=" + maxItems : "") + "]"; + } + } + + /** + * Representation of an error response. + * + * @author Jamal Kaabi-Mofrad + */ + public static class ExpectedErrorResponse + { + private String errorKey; + private int statusCode; + private String briefSummary; + private String stackTrace; + private Map additionalState; + private String descriptionURL; + private String logId; + + public ExpectedErrorResponse() + {} + + public ExpectedErrorResponse(String errorKey, int statusCode, String briefSummary, StackTraceElement[] stackTrace, + Map additionalState, String logId) + { + super(); + this.errorKey = errorKey; + this.statusCode = statusCode; + this.briefSummary = briefSummary; + this.stackTrace = Arrays.toString(stackTrace); + this.additionalState = additionalState; + this.logId = logId; + } + + public String getErrorKey() + { + return errorKey; + } + + public ExpectedErrorResponse setErrorKey(String errorKey) + { + this.errorKey = errorKey; + return this; + } + + public int getStatusCode() + { + return statusCode; + } + + public ExpectedErrorResponse setStatusCode(int statusCode) + { + this.statusCode = statusCode; + return this; + } + + public String getBriefSummary() + { + return briefSummary; + } + + public ExpectedErrorResponse setBriefSummary(String briefSummary) + { + this.briefSummary = briefSummary; + return this; + } + + public String getLogId() + { + return logId; + } + + public void setLogId(String logId) + { + this.logId = logId; + } + + public String getStackTrace() + { + return stackTrace; + } + + public ExpectedErrorResponse setStackTrace(String stackTrace) + { + this.stackTrace = stackTrace; + return this; + } + + public Map getAdditionalState() + { + return additionalState; + } + + public ExpectedErrorResponse setAdditionalState(Map additionalState) + { + this.additionalState = additionalState; + return this; + } + + public String getDescriptionURL() + { + return descriptionURL; + } + + public ExpectedErrorResponse setDescriptionURL(String descriptionURL) + { + this.descriptionURL = descriptionURL; + return this; + } + + @Override + public String toString() + { + final StringBuilder sb = new StringBuilder(250); + sb.append("ExpectedErrorResponse [errorKey='").append(errorKey) + .append(", statusCode=").append(statusCode) + .append(", briefSummary='").append(briefSummary) + .append(", logId='").append(logId) + .append(", stackTrace='").append(stackTrace) + .append(", additionalState=").append(additionalState) + .append(", descriptionURL='").append(descriptionURL) + .append(']'); + return sb.toString(); + } + } + + public class Groups extends AbstractProxy + { + + public Group createGroup(Group group, Map params, int expectedStatus) throws PublicApiException + { + HttpResponse response = create("groups", null, null, null, group.toJSON().toString(), "Failed to create group " + group.getId(), expectedStatus, params); + return parseGroupEntity(response); + } + + public GroupMember createGroupMember(String groupId, GroupMember groupMember) throws PublicApiException + { + return createGroupMember(groupId, groupMember, HttpServletResponse.SC_OK); + } + + public GroupMember createGroupMember(String groupId, GroupMember groupMember, int expectedStatus) throws PublicApiException + { + HttpResponse response = create("groups", groupId, "members", null, groupMember.toJSON().toString(), "Failed to create group membership", expectedStatus); + if (response != null && response.getJsonResponse() != null) + { + JSONObject jsonEntity = (JSONObject) response.getJsonResponse().get("entry"); + if (jsonEntity != null) + { + return GroupMember.parseGroupMember(response.getJsonResponse()); + } + } + return null; + } + + public Group updateGroup(String groupId, Group group, Map params, int expectedStatus) throws PublicApiException + { + HttpResponse response = update("groups", groupId, null, null, group.toJSON().toString(), params, "Failed to update group " + group.getId(), expectedStatus); + return parseGroupEntity(response); + } + + public Group getGroup(String groupId) throws PublicApiException + { + return getGroup(groupId, HttpServletResponse.SC_OK); + } + + public Group getGroup(String groupId, int expectedStatus) throws PublicApiException + { + return getGroup(groupId, null, expectedStatus); + } + + public Group getGroup(String groupId, Map params, int expectedStatus) throws PublicApiException + { + HttpResponse response = getSingle("groups", groupId, null, null, params, "Failed to get group " + groupId, expectedStatus); + return parseGroupEntity(response); + } + + public void deleteGroup(String groupId, boolean cascade, int expectedStatus) throws PublicApiException + { + Map params = null; + if (cascade) + { + params = Collections.singletonMap("cascade", "true"); + } + remove("groups", groupId, null, null, params, "Failed to remove group", expectedStatus); + } + + public void deleteGroupMembership(String groupId, String groupMemberId, int expectedStatus) throws PublicApiException + { + remove("groups", groupId, "members", groupMemberId, null, "Failed to remove group member", expectedStatus); + } + + private Group parseGroupEntity(HttpResponse response) + { + if ((response != null) && (response.getJsonResponse() != null)) + { + JSONObject jsonEntity = (JSONObject) response.getJsonResponse().get("entry"); + if (jsonEntity != null) + { + return Group.parseGroup(jsonEntity); + } + } + + return null; + } + + public ListResponse getGroups(Map params, String errorMessage, int expectedStatus) throws PublicApiException, ParseException + { + HttpResponse response = getAll("groups", null, null, null, params, errorMessage, expectedStatus); + + if (response != null && response.getJsonResponse() != null) + { + JSONObject jsonList = (JSONObject) response.getJsonResponse().get("list"); + if (jsonList != null) + { + return Group.parseGroups(response.getJsonResponse()); + } + } + return null; + } + + public ListResponse getGroupMembers(String groupId, Map params) throws PublicApiException, ParseException + { + return getGroupMembers(groupId, params, "Failed to get groups", HttpServletResponse.SC_OK); + } + + public ListResponse getGroupMembers(String groupId, Map params, String errorMessage, int expectedStatus) + throws PublicApiException, ParseException + { + HttpResponse response = getAll("groups", groupId, "members", null, params, errorMessage, expectedStatus); + + if (response != null && response.getJsonResponse() != null) + { + JSONObject jsonList = (JSONObject) response.getJsonResponse().get("list"); + if (jsonList != null) + { + return GroupMember.parseGroupMembers(response.getJsonResponse()); + } + } + return null; + } + + public ListResponse getGroupsByPersonId(String userId, Map params, String errorMessage, int expectedStatus) + throws PublicApiException, ParseException + { + HttpResponse response = getAll("people", userId, "groups", null, params, errorMessage, expectedStatus); + + if (response != null && response.getJsonResponse() != null) + { + JSONObject jsonList = (JSONObject) response.getJsonResponse().get("list"); + if (jsonList != null) + { + return Group.parseGroups(response.getJsonResponse()); + } + } + return null; + } + + } + + public class AuditApps extends AbstractProxy + { + + public ListResponse getAuditApps(Map params, String errorMessage, int expectedStatus) throws PublicApiException + { + HttpResponse response = getAll("audit-applications", null, null, null, params, errorMessage, expectedStatus); + + if (response != null && response.getJsonResponse() != null) + { + JSONObject jsonList = (JSONObject) response.getJsonResponse().get("list"); + if (jsonList != null) + { + return AuditApp.parseAuditApps(response.getJsonResponse()); + } + } + return null; + } + + public AuditApp getAuditApp(String applicationId) throws PublicApiException + { + return getAuditApp(applicationId, HttpServletResponse.SC_OK); + } + + public AuditApp getAuditApp(String applicationId, int expectedStatus) throws PublicApiException + { + return getAuditApp(applicationId, null, expectedStatus); + } + + public AuditApp getAuditApp(String applicationId, Map params, int expectedStatus) throws PublicApiException + { + HttpResponse response = getSingle("audit-applications", applicationId, null, null, params, "Failed to get Audit Application " + applicationId, + expectedStatus); + + if (response != null && response.getJsonResponse() != null) + { + JSONObject jsonEntry = (JSONObject) response.getJsonResponse().get("entry"); + if (jsonEntry != null) + { + return AuditApp.parseAuditApp(jsonEntry); + } + } + return null; + } + + public AuditApp updateAuditApp(String applicationId, AuditApp auditApp, Map params, int expectedStatus) throws PublicApiException + { + HttpResponse response = update("audit-applications", applicationId, null, null, auditApp.toJSON().toString(), params, "Failed to update Audit Application", expectedStatus); + + if (response != null && response.getJsonResponse() != null) + { + JSONObject jsonEntry = (JSONObject) response.getJsonResponse().get("entry"); + if (jsonEntry != null) + { + return AuditApp.parseAuditApp(jsonEntry); + } + } + return null; + } + + public ListResponse getAuditAppEntries(String applicationId, Map params, int expectedStatus) + throws PublicApiException, ParseException + { + HttpResponse response = getAll("audit-applications", applicationId, "audit-entries", null, params, + "Failed to get audit entries for " + applicationId, expectedStatus); + + if (response != null && response.getJsonResponse() != null) + { + JSONObject jsonList = (JSONObject) response.getJsonResponse().get("list"); + if (jsonList != null) + { + return AuditEntry.parseAuditEntries(response.getJsonResponse()); + } + } + return null; + } + + public AuditEntry getAuditEntry(String applicationId, String entryId, Map param, int expectedStatus) + throws PublicApiException, ParseException + { + HttpResponse response = getSingle("audit-applications", applicationId, "audit-entries", entryId, + param, "Failed to get Audit Application " + applicationId, expectedStatus); + + if (response != null && response.getJsonResponse() != null) + { + JSONObject jsonList = (JSONObject) response.getJsonResponse().get("entry"); + if (jsonList != null) + { + return AuditEntry.parseAuditEntry(jsonList); + } + } + return null; + } + + public void deleteAuditEntry(String applicationId, String entryId, Map param, int expectedStatus) + throws PublicApiException + { + remove("audit-applications", applicationId, "audit-entries", entryId, param, "Failed to delete entry " + entryId, expectedStatus); + } + + public void deleteAuditEntries(String applicationId, Map param, int expectedStatus) + throws PublicApiException + { + remove("audit-applications", applicationId, "audit-entries", null, param, "Failed to delete entries for audit application " + applicationId, expectedStatus); + } + + public ListResponse getAuditAppEntriesByNodeRefId(String nodeId, Map params, int expectedStatus) + throws PublicApiException, ParseException + { + HttpResponse response = getAll("nodes", nodeId, "audit-entries", null, params, "Failed to get audit entries for " + nodeId, + expectedStatus); + + if (response != null && response.getJsonResponse() != null) + { + JSONObject jsonList = (JSONObject) response.getJsonResponse().get("list"); + if (jsonList != null) + { + return AuditEntry.parseAuditEntries(response.getJsonResponse()); + } + } + return null; + } + + } + + public class Actions extends AbstractProxy + { + public ListResponse getActionDefinitionsForNode(String nodeId, + Map params, + int expectedStatus) + throws PublicApiException + { + HttpResponse response = getAll("nodes", nodeId, "action-definitions", + null, params, "Unexpected response", expectedStatus); + + if (response != null && response.getJsonResponse() != null) + { + JSONObject jsonList = (JSONObject) response.getJsonResponse().get("list"); + if (jsonList != null) + { + return parseActionDefinitions(response.getJsonResponse()); + } + } + return null; + } + + public ListResponse getActionDefinitions(Map params, + int expectedStatus) + throws PublicApiException + { + HttpResponse response = getAll("action-definitions", null, null, + null, params, "Unexpected response", expectedStatus); + + if (response != null && response.getJsonResponse() != null) + { + JSONObject jsonList = (JSONObject) response.getJsonResponse().get("list"); + if (jsonList != null) + { + return parseActionDefinitions(response.getJsonResponse()); + } + } + return null; + } + + public Action executeAction(Action action, Map params, int expectedStatus) throws PublicApiException + { + HttpResponse response = create("action-executions", null, null, null, action.toJSON().toString(), "Failed to create action for action def " + action.getActionDefinitionId(), expectedStatus, params); + return parseActionEntity(response); + } + + private ListResponse parseActionDefinitions(JSONObject jsonResponse) + { + List actionDefinitions = new ArrayList<>(); + + JSONObject jsonList = (JSONObject) jsonResponse.get("list"); + assertNotNull(jsonList); + + JSONArray jsonEntries = (JSONArray) jsonList.get("entries"); + assertNotNull(jsonEntries); + + for (int i = 0; i < jsonEntries.size(); i++) + { + JSONObject jsonEntry = (JSONObject) jsonEntries.get(i); + JSONObject entry = (JSONObject) jsonEntry.get("entry"); + actionDefinitions.add(parseActionDefinition(entry)); + } + + ExpectedPaging paging = ExpectedPaging.parsePagination(jsonList); + return new ListResponse<>(paging, actionDefinitions); + } + + private ActionDefinition parseActionDefinition(JSONObject entry) + { + ActionDefinition def = null; + try + { + def = objectMapper.readValue(entry.toString(), ActionDefinition.class); + } + catch (IOException e) + { + throw new RuntimeException("Unable to parse ActionDefinition JSON", e); + } + + return def; + } + + private Action parseActionEntity(HttpResponse response) + { + if ((response != null) && (response.getJsonResponse() != null)) + { + JSONObject jsonEntity = (JSONObject) response.getJsonResponse().get("entry"); + if (jsonEntity != null) + { + return Action.parseAction(jsonEntity); + } + } + + return null; + } + + public ActionDefinition getActionDefinition(String actionDefinitionId, int expectedStatus) throws PublicApiException + { + HttpResponse response = getSingle("action-definitions", actionDefinitionId, null, + null, null, "Unexpected response", expectedStatus); + + if (response != null && response.getJsonResponse() != null) + { + JSONObject jsonEntity = (JSONObject) response.getJsonResponse().get("entry"); + if (jsonEntity != null) + { + return parseActionDefinition(jsonEntity); + } + } + + return null; + } + } +}