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

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

Introduction

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

Prototype

int SC_UNAUTHORIZED

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

Click Source Link

Document

<tt>401 Unauthorized</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:org.alfresco.integrations.google.docs.service.GoogleDocsServiceImpl.java

/**
 * Get a connection to the Google APIs. Will attempt to refresh tokens if they are invalid. If unable to refresh return a
 * GoogleDocsRefreshTokenException.//  www  .  j a v  a 2 s.  c  o  m
 * 
 * @return
 * @throws GoogleDocsAuthenticationException
 * @throws GoogleDocsRefreshTokenException
 * @throws GoogleDocsServiceException
 */
private Connection<Google> getConnection()
        throws GoogleDocsAuthenticationException, GoogleDocsRefreshTokenException, GoogleDocsServiceException {
    Connection<Google> connection = null;

    // OAuth credentials for the current user, if the exist
    OAuth2CredentialsInfo credentialInfo = oauth2CredentialsStoreService
            .getPersonalOAuth2Credentials(GoogleDocsConstants.REMOTE_SYSTEM);

    if (credentialInfo != null) {
        log.debug("OAuth Access Token Exists: " + credentialInfo.getOAuthAccessToken());
        AccessGrant accessGrant = new AccessGrant(credentialInfo.getOAuthAccessToken());

        try {
            log.debug("Attempt to create OAuth Connection");
            connection = connectionFactory.createConnection(accessGrant);
        } catch (HttpClientErrorException hcee) {
            log.debug(hcee.getResponseBodyAsString());
            if (hcee.getStatusCode().value() == HttpStatus.SC_UNAUTHORIZED) {
                try {
                    accessGrant = refreshAccessToken();
                    connection = connectionFactory.createConnection(accessGrant);
                } catch (GoogleDocsRefreshTokenException gdrte) {
                    throw gdrte;
                } catch (GoogleDocsServiceException gdse) {
                    throw gdse;
                }
            } else {
                throw new GoogleDocsServiceException(hcee.getMessage(), hcee, hcee.getStatusCode().value());
            }
        } catch (HttpServerErrorException hsee) {
            throw new GoogleDocsServiceException(hsee.getMessage(), hsee, hsee.getStatusCode().value());
        }
    }

    log.debug("Connection Created");
    return connection;
}

From source file:org.alfresco.integrations.google.docs.service.GoogleDocsServiceImpl.java

private AccessGrant refreshAccessToken()
        throws GoogleDocsAuthenticationException, GoogleDocsRefreshTokenException, GoogleDocsServiceException {
    log.debug("Refreshing Access Token for " + AuthenticationUtil.getRunAsUser());
    OAuth2CredentialsInfo credentialInfo = oauth2CredentialsStoreService
            .getPersonalOAuth2Credentials(GoogleDocsConstants.REMOTE_SYSTEM);

    if (credentialInfo.getOAuthRefreshToken() != null) {

        AccessGrant accessGrant = null;//from ww w  .j av  a2  s  .com
        try {

            accessGrant = connectionFactory.getOAuthOperations()
                    .refreshAccess(credentialInfo.getOAuthRefreshToken(), GoogleDocsConstants.SCOPE, null);
        } catch (HttpClientErrorException hcee) {
            if (hcee.getStatusCode().value() == HttpStatus.SC_BAD_REQUEST) {
                throw new GoogleDocsAuthenticationException(hcee.getMessage());
            } else if (hcee.getStatusCode().value() == HttpStatus.SC_UNAUTHORIZED) {
                throw new GoogleDocsAuthenticationException("Token Refresh Failed.");
            } else {
                throw new GoogleDocsServiceException(hcee.getMessage(), hcee.getStatusCode().value());
            }

        }

        if (accessGrant != null) {
            Date expiresIn = null;

            if (accessGrant.getExpireTime() != null) {
                if (accessGrant.getExpireTime() > 0L) {
                    expiresIn = new Date(new Date().getTime() + accessGrant.getExpireTime());
                }
            }

            try {
                oauth2CredentialsStoreService.storePersonalOAuth2Credentials(GoogleDocsConstants.REMOTE_SYSTEM,
                        accessGrant.getAccessToken(), credentialInfo.getOAuthRefreshToken(), expiresIn,
                        new Date());
            } catch (NoSuchSystemException nsse) {
                throw nsse;
            }
        } else {
            throw new GoogleDocsAuthenticationException("No Access Grant Returned.");
        }

        log.debug("Access Token Refreshed");
        return accessGrant;

    } else {
        throw new GoogleDocsRefreshTokenException(
                "No Refresh Token Provided for " + AuthenticationUtil.getRunAsUser());
    }
}

From source file:org.alfresco.rest.api.tests.client.AuthenticatedHttp.java

/**
 * Execute the given method, authenticated as the given user using ticket-based authentication.
 * @param method method to execute// w  w w.ja v a 2  s .  c o  m
 * @param userName name of user to authenticate
 * @return status-code resulting from the request
 */
private <T extends Object> T executeWithTicketAuthentication(HttpMethod method, String userName,
        String password, HttpRequestCallback<T> callback) {
    String ticket = authDetailProvider.getTicketForUser(userName);
    if (ticket == null) {
        ticket = fetchLoginTicket(userName, password);
        authDetailProvider.updateTicketForUser(userName, ticket);
    }

    try {
        HttpState state = applyTicketToMethod(method, ticket);

        // Try executing the method
        int result = httpProvider.getHttpClient().executeMethod(null, method, state);

        if (result == HttpStatus.SC_UNAUTHORIZED || result == HttpStatus.SC_FORBIDDEN) {
            method.releaseConnection();
            if (!method.validate()) {
                throw new RuntimeException(
                        "Ticket re-authentication failed for user " + userName + " (HTTPMethod not reusable)");
            }
            // Fetch new ticket, store and apply to HttpMethod
            ticket = fetchLoginTicket(userName, userName);
            authDetailProvider.updateTicketForUser(userName, ticket);

            state = applyTicketToMethod(method, ticket);

            // Run method agian with new ticket
            result = httpProvider.getHttpClient().executeMethod(null, method, state);
        }

        if (callback != null) {
            return callback.onCallSuccess(method);
        }

        return null;
    } catch (Throwable t) {
        boolean handled = false;
        // Delegate to callback to handle error. If not available, throw exception
        if (callback != null) {
            handled = callback.onError(method, t);
        }

        if (!handled) {
            throw new RuntimeException("Error while executing HTTP-call (" + method.getPath() + ")", t);
        }
        return null;

    } finally {
        method.releaseConnection();
    }

}

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

@Test
public void testPersonActivities() throws Exception {
    People peopleProxy = publicApiClient.people();

    //Test with default tenant domain. see ALF-20448
    {/*from   w  ww  .ja v  a2s.c om*/
        List<Activity> expectedActivities = TenantUtil.runAsUserTenant(new TenantRunAsWork<List<Activity>>() {
            @Override
            public List<Activity> doWork() throws Exception {
                List<Activity> activities = repoService.getActivities(person5.getId(), null, false, true);
                return activities;
            }
        }, person5.getId(), defaultNetwork.getId());

        for (Activity activity : expectedActivities) {
            if (activity.getSiteId() == null) {
                fail("SiteId should present in user-joined activity.");
            }
        }

        {
            int skipCount = 0;
            int maxItems = expectedActivities.size();
            Paging paging = getPaging(skipCount, maxItems, expectedActivities.size(), null);

            Map<String, String> params = createParams(paging, null);
            params.put("who", String.valueOf(ActivityWho.me));
            publicApiClient.setRequestContext(new RequestContext(defaultNetwork.getId(), person5.getId()));
            ListResponse<Activity> response = peopleProxy.getActivities(person5.getId(), params);
            checkList(expectedActivities.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), response);
        }

    }

    // Test Case cloud-2204
    // Test case cloud-1500
    // Test Case cloud-2216
    // paging

    // Test Case cloud-1500
    {
        List<Activity> expectedActivities = TenantUtil.runAsUserTenant(new TenantRunAsWork<List<Activity>>() {
            @Override
            public List<Activity> doWork() throws Exception {
                List<Activity> activities = repoService.getActivities(person1.getId(), null, false, true);
                return activities;
            }
        }, person1.getId(), network1.getId());

        {
            int skipCount = 0;
            int maxItems = 2;
            Paging paging = getPaging(skipCount, maxItems, expectedActivities.size(), null);

            Map<String, String> params = createParams(paging, null);
            params.put("who", String.valueOf(ActivityWho.me));
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            ListResponse<Activity> response = peopleProxy.getActivities(person1.getId(), params);
            checkList(expectedActivities.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), response);
        }

        {
            int skipCount = 2;
            int maxItems = expectedActivities.size() - 2;
            assertTrue(maxItems > 0);
            Paging paging = getPaging(skipCount, maxItems, expectedActivities.size(), null);

            Map<String, String> params = createParams(paging, null);
            params.put("who", String.valueOf(ActivityWho.me));
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            ListResponse<Activity> response = peopleProxy.getActivities(person1.getId(), params);
            checkList(expectedActivities.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), response);
        }

        // "-me-" user
        {
            int skipCount = 0;
            int maxItems = 2;
            Paging paging = getPaging(skipCount, maxItems, expectedActivities.size(), null);

            Map<String, String> params = createParams(paging, null);
            params.put("who", String.valueOf(ActivityWho.me));
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            ListResponse<Activity> response = peopleProxy
                    .getActivities(org.alfresco.rest.api.People.DEFAULT_USER, params);
            checkList(expectedActivities.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), response);
        }
    }

    // unknown user - 404
    try {
        List<Activity> expectedActivities = TenantUtil.runAsUserTenant(new TenantRunAsWork<List<Activity>>() {
            @Override
            public List<Activity> doWork() throws Exception {
                List<Activity> activities = repoService.getActivities(person1.getId(), null, false, true);
                return activities;
            }
        }, person1.getId(), network1.getId());

        int skipCount = 0;
        int maxItems = 2;
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        Paging paging = getPaging(skipCount, maxItems, expectedActivities.size(), null);
        peopleProxy.getActivities(GUID.generate(), createParams(paging, null));
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // unknown site - 404
    try {
        List<Activity> expectedActivities = TenantUtil.runAsUserTenant(new TenantRunAsWork<List<Activity>>() {
            @Override
            public List<Activity> doWork() throws Exception {
                List<Activity> activities = repoService.getActivities(person1.getId(), null, false, true);
                return activities;
            }
        }, person1.getId(), network1.getId());

        int skipCount = 0;
        int maxItems = 2;
        Paging paging = getPaging(skipCount, maxItems, expectedActivities.size(), null);
        Map<String, String> params = createParams(paging, null);
        params.put("siteId", GUID.generate());
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        peopleProxy.getActivities(GUID.generate(), params);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // user from another network - 404
    try {
        List<Activity> expectedActivities = TenantUtil.runAsUserTenant(new TenantRunAsWork<List<Activity>>() {
            @Override
            public List<Activity> doWork() throws Exception {
                List<Activity> activities = repoService.getActivities(person1.getId(), null, false, true);
                return activities;
            }
        }, person1.getId(), network1.getId());

        int skipCount = 0;
        int maxItems = 2;
        Paging paging = getPaging(skipCount, maxItems, expectedActivities.size(), null);
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person3.getId()));
        peopleProxy.getActivities(person1.getId(), createParams(paging, null));
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
    }

    // another user from the same network - 403
    try {
        List<Activity> expectedActivities = TenantUtil.runAsUserTenant(new TenantRunAsWork<List<Activity>>() {
            @Override
            public List<Activity> doWork() throws Exception {
                List<Activity> activities = repoService.getActivities(person1.getId(), null, false, true);
                return activities;
            }
        }, person1.getId(), network1.getId());

        int skipCount = 0;
        int maxItems = 2;
        Paging paging = getPaging(skipCount, maxItems, expectedActivities.size(), null);
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
        peopleProxy.getActivities(person1.getId(), createParams(paging, null));
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_FORBIDDEN, e.getHttpResponse().getStatusCode());
    }

    try {
        List<Activity> activities = TenantUtil.runAsUserTenant(new TenantRunAsWork<List<Activity>>() {
            @Override
            public List<Activity> doWork() throws Exception {
                List<Activity> activities = repoService.getActivities(person1.getId(), null, false, true);
                return activities;
            }
        }, person1.getId(), network1.getId());
        assertTrue(activities.size() > 0);
        Activity activity = activities.get(0);

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        peopleProxy.remove("people", person1.getId(), "activities", String.valueOf(activity.getId()),
                "Unable to DELETE a person activity");
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    // Test Case cloud-1500
    // other user activities
    {
        List<Activity> expectedActivities = TenantUtil.runAsUserTenant(new TenantRunAsWork<List<Activity>>() {
            @Override
            public List<Activity> doWork() throws Exception {
                List<Activity> expectedActivities = repoService.getActivities(person1.getId(), null, true,
                        false);
                return expectedActivities;
            }
        }, person1.getId(), network1.getId());

        int skipCount = 0;
        int maxItems = 2;
        Paging paging = getPaging(skipCount, maxItems, expectedActivities.size(), null);

        Map<String, String> params = createParams(paging, null);
        params.put("who", String.valueOf(ActivityWho.others));
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        ListResponse<Activity> response = peopleProxy.getActivities(person1.getId(), params);
        checkList(expectedActivities.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                paging.getExpectedPaging(), response);
    }

    // all activities with siteId exclusion
    {
        List<Activity> expectedActivities = TenantUtil.runAsUserTenant(new TenantRunAsWork<List<Activity>>() {
            @Override
            public List<Activity> doWork() throws Exception {
                List<Activity> expectedActivities = repoService.getActivities(person1.getId(),
                        testSite.getSiteId(), false, false);
                return expectedActivities;
            }
        }, person1.getId(), network1.getId());

        int skipCount = 0;
        int maxItems = 2;
        Paging paging = getPaging(skipCount, maxItems, expectedActivities.size(), null);

        Map<String, String> params = createParams(paging, null);
        params.put("siteId", testSite.getSiteId());
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        ListResponse<Activity> response = peopleProxy.getActivities(person1.getId(), params);
        checkList(expectedActivities.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                paging.getExpectedPaging(), response);
    }

    // all activities with siteId exclusion, unknown site id
    try {
        int skipCount = 0;
        int maxItems = 2;
        Paging paging = getPaging(skipCount, maxItems);

        Map<String, String> params = createParams(paging, null);
        params.put("siteId", GUID.generate());
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        peopleProxy.getActivities(person1.getId(), params);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // unknown person id
    try {
        int skipCount = 0;
        int maxItems = 2;
        Paging paging = getPaging(skipCount, maxItems);

        Map<String, String> params = createParams(paging, null);
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        peopleProxy.getActivities(GUID.generate(), params);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // invalid who parameter
    try {
        int skipCount = 0;
        int maxItems = 2;
        Paging paging = getPaging(skipCount, maxItems);

        Map<String, String> params = createParams(paging, null);
        params.put("who", GUID.generate());
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        peopleProxy.getActivities(person1.getId(), params);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_BAD_REQUEST, e.getHttpResponse().getStatusCode());
    }

    // Test Case cloud-1970
    // Not allowed methods
    //      try
    //      {
    //         publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
    //         peopleProxy.create("people", person1.getId(), "activities", null, null, "Unable to POST to person activities");
    //         fail("");
    //      }
    //      catch(PublicApiException e)
    //      {
    //         assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    //      }
    //      
    //      try
    //      {
    //         publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
    //         peopleProxy.update("people", person1.getId(), "activities", null, null, "Unable to PUT person activities");
    //         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(), "activities", null, "Unable to DELETE person activities");
    //         fail("");
    //      }
    //      catch(PublicApiException e)
    //      {
    //         assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    //      }
    //
    //      try
    //      {
    //         List<Activity> activities = TenantUtil.runAsUserTenant(new TenantRunAsWork<List<Activity>>()
    //         {
    //            @Override
    //            public List<Activity> doWork() throws Exception
    //            {
    //               List<Activity> activities = repoService.getActivities(person1.getId(), null, false, true);
    //               return activities;
    //            }
    //         }, person1.getId(), network1.getId());
    //         assertTrue(activities.size() > 0);
    //         Activity activity = activities.get(0);
    //
    //         publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
    //         peopleProxy.create("people", person1.getId(), "activities", String.valueOf(activity.getId()), null, "Unable to POST to a person activity");
    //         fail("");
    //      }
    //      catch(PublicApiException e)
    //      {
    //         assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    //      }
    //
    //      try
    //      {
    //         List<Activity> activities = TenantUtil.runAsUserTenant(new TenantRunAsWork<List<Activity>>()
    //         {
    //            @Override
    //            public List<Activity> doWork() throws Exception
    //            {
    //               List<Activity> activities = repoService.getActivities(person1.getId(), null, false, true);
    //               return activities;
    //            }
    //         }, person1.getId(), network1.getId());
    //         assertTrue(activities.size() > 0);
    //         Activity activity = activities.get(0);
    //
    //         publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
    //         peopleProxy.update("people", person1.getId(), "activities", String.valueOf(activity.getId()), null, "Unable to PUT a person activity");
    //         fail("");
    //      }
    //      catch(PublicApiException e)
    //      {
    //         assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    //      }

    // Test Case cloud-1970
    // not allowed methods
    {
        List<Activity> activities = TenantUtil.runAsUserTenant(new TenantRunAsWork<List<Activity>>() {
            @Override
            public List<Activity> doWork() throws Exception {
                List<Activity> activities = repoService.getActivities(person1.getId(), null, false, false);
                return activities;
            }
        }, person1.getId(), network1.getId());
        assertTrue(activities.size() > 0);
        Activity activity = activities.get(0);

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

        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            peopleProxy.create("people", person1.getId(), "activities", String.valueOf(activity.getId()), null,
                    "Unable to POST to an activity");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }

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

        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            peopleProxy.update("people", person1.getId(), "activities", String.valueOf(activity.getId()), null,
                    "Unable to PUT an activity");
            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(), "activities", null, "Unable to DELETE activities");
            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(), "activities", String.valueOf(activity.getId()),
                    "Unable to DELETE an activity");
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }
    }
}

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

@Test
public void testValidRequests() throws Exception {
    List<Favourite> expectedFavourites = new ArrayList<Favourite>();

    {//from   ww  w .  j av  a 2  s  .  co  m
        // add some favourites
        // 2467

        log("cloud-2467");

        Favourite siteFavourite1 = makeSiteFavourite(person1PublicSites.get(0));

        FavouriteDocument document = repoService.getDocument(network1.getId(), person1PublicDocs.get(0));
        Favourite fileFavourite1 = makeFileFavourite(document.getGuid());

        FavouriteFolder folder = repoService.getFolder(network1.getId(), person1PublicFolders.get(0));
        Favourite folderFavourite1 = makeFolderFavourite(folder.getGuid());

        Favourite siteFavourite2 = makeSiteFavourite(person1PublicSites.get(1));

        document = repoService.getDocument(network1.getId(), person1PublicDocs.get(1));
        Favourite fileFavourite2 = makeFileFavourite(document.getGuid());

        folder = repoService.getFolder(network1.getId(), person1PublicFolders.get(1));
        Favourite folderFavourite2 = makeFolderFavourite(folder.getGuid());

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

            Favourite ret = favouritesProxy.createFavourite(person10Id, siteFavourite1);
            expectedFavourites.add(ret);
            siteFavourite1.expected(ret);
        }

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

            Favourite ret = favouritesProxy.createFavourite(person10Id, fileFavourite1);
            expectedFavourites.add(ret);
            fileFavourite1.expected(ret);
        }

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

            Favourite ret = favouritesProxy.createFavourite(person10Id, folderFavourite1);
            expectedFavourites.add(ret);
            folderFavourite1.expected(ret);
        }

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

            Favourite ret = favouritesProxy.createFavourite(person10Id, siteFavourite2);
            expectedFavourites.add(ret);
            siteFavourite2.expected(ret);
        }

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

            Favourite ret = favouritesProxy.createFavourite(person10Id, fileFavourite2);
            expectedFavourites.add(ret);
            fileFavourite2.expected(ret);
        }

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

            Favourite ret = favouritesProxy.createFavourite(person10Id, folderFavourite2);
            expectedFavourites.add(ret);
            folderFavourite2.expected(ret);
        }

        // already a favourite - 201
        {
            log("cloud-2472");

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

                Favourite ret = favouritesProxy.createFavourite(person10Id, siteFavourite1);
                siteFavourite1.expected(ret);
            }

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

                Favourite ret = favouritesProxy.createFavourite(person10Id, folderFavourite1);
                folderFavourite1.expected(ret);
            }

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

                Favourite ret = favouritesProxy.createFavourite(person10Id, fileFavourite1);
                fileFavourite1.expected(ret);
            }
        }

        {
            // cloud-2498
            // cloud-2499
            // create and list favourites across networks

            List<Favourite> person21ExpectedFavourites = new ArrayList<Favourite>();

            log("cloud-2498");
            log("cloud-2499");

            {
                // favourite a site in another network

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

                Favourite favourite = makeSiteFavourite(person1PrivateSites.get(0));
                try {
                    favouritesProxy.createFavourite("-me-", favourite);
                    fail();
                } catch (PublicApiException e) {
                    assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
                }

                int skipCount = 0;
                int maxItems = 10;
                Paging paging = getPaging(skipCount, maxItems, person21ExpectedFavourites.size(),
                        person21ExpectedFavourites.size());
                try {
                    favouritesProxy.getFavourites("-me-", createParams(paging, null));
                    fail();
                } catch (PublicApiException e) {
                    assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
                }
            }

            // favourite a document in another network
            {
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person21Id));

                FavouriteDocument document1 = new FavouriteDocument(person1PrivateDocs.get(0).getId());
                Favourite favourite = makeFileFavourite(document1.getGuid());
                try {
                    favouritesProxy.createFavourite("-me-", favourite);
                    fail();
                } catch (PublicApiException e) {
                    assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
                }

                sort(person21ExpectedFavourites, FavouritesService.DEFAULT_SORT_PROPS);

                int skipCount = 0;
                int maxItems = 10;
                Paging paging = getPaging(skipCount, maxItems, person21ExpectedFavourites.size(),
                        person21ExpectedFavourites.size());
                try {
                    favouritesProxy.getFavourites("-me-", createParams(paging, null));
                    fail();
                } catch (PublicApiException e) {
                    assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
                }
            }

            // favourite a folder in another network
            {
                publicApiClient.setRequestContext(new RequestContext(network1.getId(), person21Id));

                FavouriteFolder folder1 = new FavouriteFolder(person1PrivateFolders.get(0).getId());
                Favourite favourite = makeFolderFavourite(folder1.getGuid());
                try {
                    favouritesProxy.createFavourite("-me-", favourite);
                    fail();
                } catch (PublicApiException e) {
                    assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
                }

                sort(person21ExpectedFavourites, FavouritesService.DEFAULT_SORT_PROPS);

                int skipCount = 0;
                int maxItems = 10;
                Paging paging = getPaging(skipCount, maxItems, person21ExpectedFavourites.size(),
                        person21ExpectedFavourites.size());
                try {
                    favouritesProxy.getFavourites("-me-", createParams(paging, null));
                    fail();
                } catch (PublicApiException e) {
                    assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
                }
            }
        }
    }

    // GET favourites
    // test paging and sorting
    {
        // cloud-2458
        // cloud-2462
        // cloud-2461
        {
            log("cloud-2458");
            log("cloud-2461");
            log("cloud-2462");

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

            List<Favourite> expected = new ArrayList<Favourite>(expectedFavourites);
            sort(expected, FavouritesService.DEFAULT_SORT_PROPS);

            int skipCount = 0;
            int maxItems = 2;
            Paging paging = getPaging(skipCount, maxItems, expectedFavourites.size(),
                    expectedFavourites.size());
            ListResponse<Favourite> resp = favouritesProxy.getFavourites(person10Id,
                    createParams(paging, null));
            checkList(expected.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), resp);
        }

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

            List<Favourite> expected = new ArrayList<Favourite>(expectedFavourites);
            sort(expected, FavouritesService.DEFAULT_SORT_PROPS);

            int skipCount = 2;
            int maxItems = 4;
            Paging paging = getPaging(skipCount, maxItems, expectedFavourites.size(),
                    expectedFavourites.size());
            ListResponse<Favourite> resp = favouritesProxy.getFavourites(person10Id,
                    createParams(paging, null));
            checkList(expected.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), resp);
        }

        // 2466
        // GET favourites for "-me-"
        {
            log("cloud-2466");

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

            List<Favourite> expected = new ArrayList<Favourite>(expectedFavourites);
            sort(expected, FavouritesService.DEFAULT_SORT_PROPS);

            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expectedFavourites.size(),
                    expectedFavourites.size());
            ListResponse<Favourite> resp = favouritesProxy.getFavourites("-me-", createParams(paging, null));
            checkList(expected.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), resp);
        }
    }

    // 2459
    {
        log("cloud-2459");

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

        int skipCount = 0;
        int maxItems = Integer.MAX_VALUE;
        Paging paging = getPaging(skipCount, maxItems, 0, 0);
        ListResponse<Favourite> resp = favouritesProxy.getFavourites(person11Id, createParams(paging, null));
        List<Favourite> empty = Collections.emptyList();
        checkList(empty, paging.getExpectedPaging(), resp);
    }

    // cloud-2460: filtering by target type
    {
        log("cloud-2460");

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

            Set<Type> types = new HashSet<Type>(Arrays.asList(Type.FILE));
            List<Favourite> expected = filter(expectedFavourites, types);
            sort(expected, FavouritesService.DEFAULT_SORT_PROPS);

            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expected.size(), expected.size());
            Map<String, String> params = Collections.singletonMap("where", "(EXISTS(target/file))");
            ListResponse<Favourite> resp = favouritesProxy.getFavourites(person10Id,
                    createParams(paging, params));
            checkList(expected.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), resp);
        }

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

            Set<Type> types = new HashSet<Type>(Arrays.asList(Type.FOLDER));
            List<Favourite> expected = filter(expectedFavourites, types);
            sort(expected, FavouritesService.DEFAULT_SORT_PROPS);

            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expected.size(), expected.size());
            Map<String, String> params = Collections.singletonMap("where", "(EXISTS(target/folder))");
            ListResponse<Favourite> resp = favouritesProxy.getFavourites(person10Id,
                    createParams(paging, params));
            checkList(expected.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), resp);
        }

        // target/file
        {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person10Id));

            Set<Type> types = new HashSet<Type>(Arrays.asList(Type.FILE));
            List<Favourite> expected = filter(expectedFavourites, types);
            sort(expected, FavouritesService.DEFAULT_SORT_PROPS);

            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expected.size(), expected.size());
            Map<String, String> params = Collections.singletonMap("where", "(EXISTS(target/file))");
            ListResponse<Favourite> resp = favouritesProxy.getFavourites(person10Id,
                    createParams(paging, params));
            checkList(expected.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), resp);
        }

        // target/folder
        {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person10Id));

            Set<Type> types = new HashSet<Type>(Arrays.asList(Type.FOLDER));
            List<Favourite> expected = filter(expectedFavourites, types);
            sort(expected, FavouritesService.DEFAULT_SORT_PROPS);

            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expected.size(), expected.size());
            Map<String, String> params = Collections.singletonMap("where", "(EXISTS(target/folder))");
            ListResponse<Favourite> resp = favouritesProxy.getFavourites(person10Id,
                    createParams(paging, params));
            checkList(expected.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), resp);
        }

        // target/site
        {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person10Id));

            Set<Type> types = new HashSet<Type>(Arrays.asList(Type.SITE));
            List<Favourite> expected = filter(expectedFavourites, types);
            sort(expected, FavouritesService.DEFAULT_SORT_PROPS);

            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expected.size(), expected.size());
            Map<String, String> params = Collections.singletonMap("where", "(EXISTS(target/site))");
            ListResponse<Favourite> resp = favouritesProxy.getFavourites(person10Id,
                    createParams(paging, params));
            checkList(expected.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), resp);
        }

        // target/folder OR target/file.
        {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person10Id));

            Set<Type> types = new HashSet<Type>(Arrays.asList(Type.FOLDER, Type.FILE));
            List<Favourite> expected = filter(expectedFavourites, types);
            sort(expected, FavouritesService.DEFAULT_SORT_PROPS);

            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expected.size(), expected.size());
            Map<String, String> params = Collections.singletonMap("where",
                    "(EXISTS(target/file) OR EXISTS(target/folder))");
            ListResponse<Favourite> resp = favouritesProxy.getFavourites(person10Id,
                    createParams(paging, params));
            checkList(expected.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), resp);
        }

        // target/site OR target/file.
        {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person10Id));

            Set<Type> types = new HashSet<Type>(Arrays.asList(Type.SITE, Type.FILE));
            List<Favourite> expected = filter(expectedFavourites, types);
            sort(expected, FavouritesService.DEFAULT_SORT_PROPS);

            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expected.size(), expected.size());
            Map<String, String> params = Collections.singletonMap("where",
                    "(EXISTS(target/file) OR EXISTS(target/site))");
            ListResponse<Favourite> resp = favouritesProxy.getFavourites(person10Id,
                    createParams(paging, params));
            checkList(expected.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), resp);
        }

        // target/site OR target/folder.
        {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person10Id));

            Set<Type> types = new HashSet<Type>(Arrays.asList(Type.SITE, Type.FOLDER));
            List<Favourite> expected = filter(expectedFavourites, types);
            sort(expected, FavouritesService.DEFAULT_SORT_PROPS);

            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expected.size(), expected.size());
            Map<String, String> params = Collections.singletonMap("where",
                    "(EXISTS(target/site) OR EXISTS(target/folder))");
            ListResponse<Favourite> resp = favouritesProxy.getFavourites(person10Id,
                    createParams(paging, params));
            checkList(expected.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                    paging.getExpectedPaging(), resp);
        }
    }

    // GET a favourite
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person10Id));

        favouritesProxy.getFavourite(person10Id, GUID.generate());

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

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

        Favourite favourite = expectedFavourites.get(0);

        favouritesProxy.getFavourite(GUID.generate(), favourite.getTargetGuid());

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

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

        Favourite favourite = expectedFavourites.get(0);

        Favourite resp = favouritesProxy.getFavourite(person10Id, favourite.getTargetGuid());
        favourite.expected(resp);
    }

    // cloud-2479, PUT case
    {
        log("cloud-2479.1");
        updateFavourite(network1.getId(), person10Id, person10Id, TARGET_TYPE.site);

        log("cloud-2479.2");
        updateFavourite(network1.getId(), person10Id, person10Id, TARGET_TYPE.file);

        log("cloud-2479.3");
        updateFavourite(network1.getId(), person10Id, person10Id, TARGET_TYPE.folder);
    }

    try {
        // cloud-2474
        // non-existent personId
        log("cloud-2474");

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

        favouritesProxy.removeFavourite(GUID.generate(), GUID.generate());

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

    // cloud-2475
    // try delete a non-existent favourite for a node that exists
    {
        log("cloud-2475");

        NodeRef doc = TenantUtil.runAsUserTenant(new TenantRunAsWork<NodeRef>() {
            @Override
            public NodeRef doWork() throws Exception {
                NodeRef containerNodeRef = person1PublicSites.get(0).getContainerNodeRef("documentLibrary");
                NodeRef doc = repoService.createDocument(containerNodeRef, GUID.generate(), "");
                return doc;
            }
        }, person11Id, network1.getId());

        String favouriteId = doc.getId();

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

        ListResponse<Favourite> before = getFavourites(network1.getId(), person10Id, person10Id, 0,
                Integer.MAX_VALUE, null, null, null);
        List<Favourite> beforeList = before.getList();
        assertTrue(beforeList.size() > 0);

        try {
            favouritesProxy.removeFavourite(person10Id, favouriteId);
            fail("Should be a 404");
        } catch (PublicApiException e) {
            // expected
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // check no favourites have been removed
        ListResponse<Favourite> after = getFavourites(network1.getId(), person10Id, person10Id, 0,
                Integer.MAX_VALUE, null, null, null);
        assertEquals(beforeList.size(), after.getList().size());
    }

    // cloud-2473, DELETE case
    {
        log("cloud-2473.1");
        deleteFavourite(network1.getId(), person10Id, person10Id, TARGET_TYPE.site);

        log("cloud-2473.2");
        deleteFavourite(network1.getId(), person10Id, person10Id, TARGET_TYPE.file);

        log("cloud-2473.3");
        Favourite favourite = deleteFavourite(network1.getId(), person10Id, person10Id, TARGET_TYPE.folder);

        // try to delete non-existent favourite
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person10Id));
            favouritesProxy.removeFavourite(person10Id, favourite.getTargetGuid());

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

    // cloud-2476
    // try delete another user's favourite
    {
        log("cloud-2476");

        // make sure there are favourites to delete
        //         publicApiClient.setRequestContext(new RequestContext(network1.getId(), personId));
        //         SiteFavouriteTarget target = new SiteFavouriteTarget(person1Sites.get(0));
        //         Favourite favourite = new Favourite(target);
        //         favouritesProxy.createFavourite(personId, favourite);

        ListResponse<Favourite> before = getFavourites(network1.getId(), person10Id, person10Id, 0,
                Integer.MAX_VALUE, null, null, null);
        assertTrue(before.getList().size() > 0);
        Favourite favourite = before.getList().get(0);

        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
            favouritesProxy.removeFavourite(person10Id, favourite.getTargetGuid());

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

        ListResponse<Favourite> after = getFavourites(network1.getId(), person10Id, person10Id, 0,
                Integer.MAX_VALUE, null, null, null);
        assertEquals(before.getList().size(), after.getList().size());
    }
}

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

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

    // Create some users and sites
    final List<TestPerson> people = new ArrayList<TestPerson>();

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

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

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

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

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

    TestSite testSite = transactionHelper
            .doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<TestSite>() {
                @SuppressWarnings("synthetic-access")
                public TestSite execute() throws Throwable {
                    return TenantUtil.runAsUserTenant(new TenantRunAsWork<TestSite>() {
                        public TestSite doWork() throws Exception {
                            SiteInformation siteInfo = new SiteInformation(GUID.generate(), "", "",
                                    SiteVisibility.PUBLIC);
                            return network1.createSite(siteInfo);
                        }
                    }, person1.getId(), network1.getId());
                }
            }, false, true);

    TestSite testSite1 = transactionHelper
            .doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<TestSite>() {
                @SuppressWarnings("synthetic-access")
                public TestSite execute() throws Throwable {
                    return TenantUtil.runAsUserTenant(new TenantRunAsWork<TestSite>() {
                        public TestSite doWork() throws Exception {
                            SiteInformation siteInfo = new SiteInformation(GUID.generate(), "", "",
                                    SiteVisibility.PUBLIC);
                            return network1.createSite(siteInfo);
                        }
                    }, person1.getId(), network1.getId());
                }
            }, false, true);

    TestSite testSite3 = transactionHelper
            .doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<TestSite>() {
                @SuppressWarnings("synthetic-access")
                public TestSite execute() throws Throwable {
                    return TenantUtil.runAsUserTenant(new TenantRunAsWork<TestSite>() {
                        public TestSite doWork() throws Exception {
                            SiteInformation siteInfo = new SiteInformation(GUID.generate(), "", "",
                                    SiteVisibility.PUBLIC);
                            return network1.createSite(siteInfo);
                        }
                    }, person1.getId(), network1.getId());
                }
            }, false, true);

    TestSite testSite4 = transactionHelper
            .doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<TestSite>() {
                @SuppressWarnings("synthetic-access")
                public TestSite execute() throws Throwable {
                    return TenantUtil.runAsUserTenant(new TenantRunAsWork<TestSite>() {
                        public TestSite doWork() throws Exception {
                            SiteInformation siteInfo = new SiteInformation(GUID.generate(), "", "",
                                    SiteVisibility.PUBLIC);
                            return network1.createSite(siteInfo);
                        }
                    }, person5.getId(), network2.getId());
                }
            }, false, true);

    Sites sitesProxy = publicApiClient.sites();

    // invalid methods
    try {
        FavouriteSite fs = new FavouriteSite(testSite.getSiteId());

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        sitesProxy.create("people", person1.getId(), "favorite-sites", testSite.getSiteId(),
                fs.toJSON().toString(), "Unable to POST to a favorite-site");
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    try {
        FavouriteSite fs = new FavouriteSite(testSite.getSiteId());

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

    try {
        FavouriteSite fs = new FavouriteSite(testSite.getSiteId());

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        sitesProxy.update("people", person1.getId(), "favorite-sites", testSite.getSiteId(),
                fs.toJSON().toString(), "Unable to PUT a favorite-site");
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

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

    // Create favourite site

    // unknown user - 404
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        FavouriteSite fs = new FavouriteSite(testSite.getSiteId());
        sitesProxy.createFavouriteSite("invalid.user", fs);
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // user from another network - 401 (not able to auth against tenant)
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person4.getId()));
        FavouriteSite fs = new FavouriteSite(testSite.getSiteId());
        sitesProxy.createFavouriteSite(person1.getId(), fs);
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
    }

    // another user from the same network
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        FavouriteSite fs = new FavouriteSite(testSite.getSiteId());
        sitesProxy.createFavouriteSite(person2.getId(), fs);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_FORBIDDEN, e.getHttpResponse().getStatusCode());
    }

    // a member of this site
    {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        FavouriteSite fs = new FavouriteSite(testSite.getSiteId());
        FavouriteSite resp = sitesProxy.createFavouriteSite(person1.getId(), fs);
        fs.expected(resp);
    }

    // add same favourite site
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        sitesProxy.createFavouriteSite(person1.getId(), new FavouriteSite(testSite.getSiteId()));
        fail();
    } catch (PublicApiException e) {
        assertEquals(409, e.getHttpResponse().getStatusCode());
    }

    // "-me" user
    {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
        FavouriteSite fs = new FavouriteSite(testSite.getSiteId());
        FavouriteSite resp = sitesProxy.createFavouriteSite(org.alfresco.rest.api.People.DEFAULT_USER, fs);
        fs.expected(resp);

        final List<FavouriteSite> expectedFavouriteSites = TenantUtil
                .runAsUserTenant(new TenantRunAsWork<List<FavouriteSite>>() {
                    @Override
                    public List<FavouriteSite> doWork() throws Exception {
                        return repoService.getFavouriteSites(person2);
                    }
                }, person2.getId(), network1.getId());

        // check it's there
        int skipCount = 0;
        int maxItems = Integer.MAX_VALUE;
        Paging paging = getPaging(skipCount, maxItems, expectedFavouriteSites.size(),
                expectedFavouriteSites.size());

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
        sitesProxy.getFavouriteSites(person2.getId(), createParams(paging, null));
    }

    // not a member of this site
    {
        FavouriteSite fs = new FavouriteSite(testSite1.getSiteId());

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
        FavouriteSite ret = sitesProxy.createFavouriteSite(person1.getId(), fs);
        fs.expected(ret);
    }

    // GET favourite sites
    {
        final List<FavouriteSite> expectedFavouriteSites = TenantUtil
                .runAsUserTenant(new TenantRunAsWork<List<FavouriteSite>>() {
                    @Override
                    public List<FavouriteSite> doWork() throws Exception {
                        return repoService.getFavouriteSites(person1);
                    }
                }, person1.getId(), network1.getId());

        // Test Case cloud-1490
        // unknown user
        try {
            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expectedFavouriteSites.size(),
                    expectedFavouriteSites.size());

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            sitesProxy.getFavouriteSites(GUID.generate(), createParams(paging, null));
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // authentication: unknown user
        try {
            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expectedFavouriteSites.size(),
                    expectedFavouriteSites.size());

            publicApiClient
                    .setRequestContext(new RequestContext(network1.getId(), GUID.generate(), "password"));
            sitesProxy.getFavouriteSites(person1.getId(), createParams(paging, null));
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
        }

        // another user from the same network - 403
        try {
            int skipCount = 0;
            int maxItems = 2;
            Paging paging = getPaging(skipCount, maxItems, expectedFavouriteSites.size(),
                    expectedFavouriteSites.size());

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person2.getId()));
            ListResponse<FavouriteSite> response = sitesProxy.getFavouriteSites(person1.getId(),
                    createParams(paging, null));
            checkList(expectedFavouriteSites, paging.getExpectedPaging(), response);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_FORBIDDEN, e.getHttpResponse().getStatusCode());
        }

        // another user from another network - 401
        try {
            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expectedFavouriteSites.size(),
                    expectedFavouriteSites.size());

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person4.getId()));
            sitesProxy.getFavouriteSites(person1.getId(), createParams(paging, null));
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
        }

        // successful GET
        {
            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expectedFavouriteSites.size(),
                    expectedFavouriteSites.size());

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            ListResponse<FavouriteSite> response = sitesProxy.getFavouriteSites(person1.getId(),
                    createParams(paging, null));
            checkList(expectedFavouriteSites, paging.getExpectedPaging(), response);
        }

        // skipCount is greater than the number of favourite sites
        {
            int skipCount = expectedFavouriteSites.size() + 100;
            Paging paging = getPaging(skipCount, null, expectedFavouriteSites.size(),
                    expectedFavouriteSites.size());
            List<FavouriteSite> expected = Collections.emptyList();
            ListResponse<FavouriteSite> response = sitesProxy.getFavouriteSites(person1.getId(),
                    createParams(paging, null));
            checkList(expected, paging.getExpectedPaging(), response);
        }

        // "-me-" user
        {
            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expectedFavouriteSites.size(),
                    expectedFavouriteSites.size());

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            ListResponse<FavouriteSite> response = sitesProxy
                    .getFavouriteSites(org.alfresco.rest.api.People.DEFAULT_USER, createParams(paging, null));
            checkList(expectedFavouriteSites, paging.getExpectedPaging(), response);
        }
    }

    // user is a member of the site which he has favourited
    {
        publicApiClient.setRequestContext(new RequestContext(network2.getId(), person5.getId()));

        List<FavouriteSite> expectedFavouriteSites = new ArrayList<FavouriteSite>(1);
        FavouriteSite fs = new FavouriteSite(testSite4.getSiteId());
        expectedFavouriteSites.add(fs);

        FavouriteSite ret = sitesProxy.createFavouriteSite(person5.getId(), fs);
        fs.expected(ret);

        int skipCount = 0;
        int maxItems = 2;
        Paging paging = getPaging(skipCount, maxItems, expectedFavouriteSites.size(),
                expectedFavouriteSites.size());
        ListResponse<FavouriteSite> response = sitesProxy.getFavouriteSites(person5.getId(),
                createParams(paging, null));
        checkList(expectedFavouriteSites, paging.getExpectedPaging(), response);
    }

    // remove
    {
        // create some favourite sites
        {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person3.getId()));
            FavouriteSite fs = new FavouriteSite(testSite);
            sitesProxy.createFavouriteSite(person3.getId(), fs);
            fs = new FavouriteSite(testSite1);
            sitesProxy.createFavouriteSite(person3.getId(), fs);
        }

        // known user
        {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            FavouriteSite fs = new FavouriteSite(testSite);
            sitesProxy.removeFavouriteSite(person1.getId(), fs);

            List<FavouriteSite> expectedFavouriteSites = TenantUtil
                    .runAsUserTenant(new TenantRunAsWork<List<FavouriteSite>>() {
                        @Override
                        public List<FavouriteSite> doWork() throws Exception {
                            return repoService.getFavouriteSites(person1);
                        }
                    }, person1.getId(), network1.getId());

            // check removed
            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expectedFavouriteSites.size(),
                    expectedFavouriteSites.size());

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            ListResponse<FavouriteSite> response = sitesProxy.getFavouriteSites(person1.getId(),
                    createParams(paging, null));
            assertFalse(response.getList().contains(fs));
        }

        // unknown user
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            FavouriteSite fs = new FavouriteSite(testSite);
            sitesProxy.removeFavouriteSite(GUID.generate(), fs);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // unknown site
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            FavouriteSite fs = new FavouriteSite(GUID.generate());
            sitesProxy.removeFavouriteSite(person1.getId(), fs);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // try to remove a favourite site that is not a favourite site
        try {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person1.getId()));
            FavouriteSite fs = new FavouriteSite(testSite3);
            sitesProxy.removeFavouriteSite(person1.getId(), fs);
            fail();
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // "-me-" user
        {
            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person3.getId()));
            FavouriteSite fs = new FavouriteSite(testSite1);
            sitesProxy.removeFavouriteSite(org.alfresco.rest.api.People.DEFAULT_USER, fs);

            List<FavouriteSite> expectedFavouriteSites = TenantUtil
                    .runAsUserTenant(new TenantRunAsWork<List<FavouriteSite>>() {
                        @Override
                        public List<FavouriteSite> doWork() throws Exception {
                            return repoService.getFavouriteSites(person3);
                        }
                    }, person3.getId(), network1.getId());

            // check removed
            int skipCount = 0;
            int maxItems = Integer.MAX_VALUE;
            Paging paging = getPaging(skipCount, maxItems, expectedFavouriteSites.size(),
                    expectedFavouriteSites.size());

            publicApiClient.setRequestContext(new RequestContext(network1.getId(), person3.getId()));
            ListResponse<FavouriteSite> response = sitesProxy.getFavouriteSites(person3.getId(),
                    createParams(paging, null));
            assertFalse(response.getList().contains(fs));
        }
    }
}

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

@Test
public void testPersonNetworks() throws Exception {
    People peopleProxy = publicApiClient.people();

    {//from   ww w .j  a  v  a  2  s .  c  o  m
        /**
         * Test http://<host>:<port>/alfresco/a i.e. tenant servlet root - should return user's networks
         *
         */

        final TestNetwork testAccount = getTestFixture().getRandomNetwork();
        Iterator<TestPerson> personIt = testAccount.getPeople().iterator();
        final TestPerson person = personIt.next();

        RequestContext rc = new RequestContext(null, person.getId());
        publicApiClient.setRequestContext(rc);

        HttpResponse response = publicApiClient.delete(null, null, null, null, null);
        //url /null/alfresco/versions/1 does not map to a Web Script
        assertEquals(404, response.getStatusCode());
        PublicApiClient.ExpectedErrorResponse errorResponse = RestApiUtil
                .parseErrorResponse(response.getJsonResponse());
        assertNotNull(errorResponse);
        assertNotNull(errorResponse.getErrorKey());
        assertNotNull(errorResponse.getBriefSummary());

        response = publicApiClient.put(null, null, null, null, null, null, null);
        assertEquals(404, response.getStatusCode());
        errorResponse = RestApiUtil.parseErrorResponse(response.getJsonResponse());
        assertNotNull(errorResponse);
        assertNotNull(errorResponse.getErrorKey());
        assertNotNull(errorResponse.getBriefSummary());

        response = publicApiClient.post(null, null, null, null, null, null);
        assertEquals(404, response.getStatusCode());
        errorResponse = RestApiUtil.parseErrorResponse(response.getJsonResponse());
        assertNotNull(errorResponse);
        assertNotNull(errorResponse.getErrorKey());
        assertNotNull(errorResponse.getBriefSummary());

        List<PersonNetwork> expectedNetworkMembers = person.getNetworkMemberships();

        int expectedTotal = expectedNetworkMembers.size();

        {
            // GET / - users networks
            Paging paging = getPaging(0, Integer.MAX_VALUE, expectedTotal, expectedTotal);
            publicApiClient.setRequestContext(new RequestContext("-default-", person.getId()));
            response = publicApiClient.index(createParams(paging, null));
            ListResponse<PersonNetwork> resp = PersonNetwork.parseNetworkMembers(response.getJsonResponse());
            assertEquals(200, response.getStatusCode());

            checkList(new ArrayList<PersonNetwork>(expectedNetworkMembers), paging.getExpectedPaging(), resp);
        }
    }

    // user from another network
    {
        publicApiClient.setRequestContext(new RequestContext("-default-", person21.getId()));

        List<PersonNetwork> networksMemberships = Collections.emptyList();

        try {
            int skipCount = 0;
            int maxItems = 2;
            Paging paging = getPaging(skipCount, maxItems, networksMemberships.size(),
                    networksMemberships.size());
            peopleProxy.getNetworkMemberships(person11.getId(), createParams(paging, null));

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

    // user from the same network
    try {
        List<PersonNetwork> networksMemberships = person12.getNetworkMemberships();

        publicApiClient.setRequestContext(new RequestContext("-default-", person12.getId()));

        int skipCount = 0;
        int maxItems = 2;
        Paging paging = getPaging(skipCount, maxItems, networksMemberships.size(), networksMemberships.size());
        peopleProxy.getNetworkMemberships(person11.getId(), createParams(paging, null));

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

    List<PersonNetwork> networksMemberships = person11.getNetworkMemberships();

    // Test Case cloud-2203
    // Test Case cloud-1498
    // test paging
    {
        publicApiClient.setRequestContext(new RequestContext("-default-", person11.getId()));

        int skipCount = 0;
        int maxItems = 2;
        Paging paging = getPaging(skipCount, maxItems, networksMemberships.size(), networksMemberships.size());
        ListResponse<PersonNetwork> resp = peopleProxy.getNetworkMemberships(person11.getId(),
                createParams(paging, null));
        checkList(networksMemberships.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                paging.getExpectedPaging(), resp);
    }

    // "-me-" user
    {
        publicApiClient.setRequestContext(new RequestContext("-default-", person11.getId()));

        int skipCount = 0;
        int maxItems = Integer.MAX_VALUE;
        Paging paging = getPaging(skipCount, maxItems, networksMemberships.size(), networksMemberships.size());
        ListResponse<PersonNetwork> resp = peopleProxy
                .getNetworkMemberships(org.alfresco.rest.api.People.DEFAULT_USER, createParams(paging, null));
        checkList(networksMemberships.subList(skipCount, skipCount + paging.getExpectedPaging().getCount()),
                paging.getExpectedPaging(), resp);
    }

    // unknown person id
    try {
        List<PersonNetwork> networkMemberships = person11.getNetworkMemberships();

        publicApiClient.setRequestContext(new RequestContext("-default-", person11.getId()));

        int skipCount = 0;
        int maxItems = 2;
        Paging expectedPaging = getPaging(skipCount, maxItems, networkMemberships.size(),
                networkMemberships.size());
        peopleProxy.getNetworkMemberships("invalidUser", createParams(expectedPaging, null));
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // invalid caller authentication
    try {
        List<PersonNetwork> networkMemberships = person11.getNetworkMemberships();

        publicApiClient.setRequestContext(new RequestContext("-default-", person11.getId(), GUID.generate()));

        int skipCount = 0;
        int maxItems = 2;
        Paging expectedPaging = getPaging(skipCount, maxItems, networkMemberships.size(),
                networkMemberships.size());
        peopleProxy.getNetworkMemberships(person11.getId(), createParams(expectedPaging, null));
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
    }

    // Test Case cloud-1499
    // unknown person id
    try {
        List<PersonNetwork> networkMemberships = person11.getNetworkMemberships();

        assertTrue(networkMemberships.size() > 0);
        PersonNetwork network = networkMemberships.get(0);

        publicApiClient.setRequestContext(new RequestContext("-default-", person11.getId()));
        peopleProxy.getNetworkMembership("invalidUser", network.getId());
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // invalid caller authentication
    try {
        List<PersonNetwork> networkMemberships = person11.getNetworkMemberships();

        assertTrue(networkMemberships.size() > 0);
        PersonNetwork network = networkMemberships.get(0);

        publicApiClient.setRequestContext(new RequestContext("-default-", person11.getId(), GUID.generate()));
        peopleProxy.getNetworkMembership(person11.getId(), network.getId());
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
    }

    // incorrect network id
    try {
        publicApiClient.setRequestContext(new RequestContext("-default-", person11.getId()));
        peopleProxy.getNetworkMembership(person11.getId(), GUID.generate());
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // 1969
    // not allowed methods
    // POST, POST networkId, PUT, PUT networkId, DELETE, DELETE networkId
    try {
        PersonNetwork pn = new PersonNetwork(GUID.generate());

        publicApiClient.setRequestContext(new RequestContext("-default-", person11.getId()));
        peopleProxy.create("people", person11.getId(), "networks", null, pn.toJSON().toString(),
                "Unable to POST to person networks");
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    try {
        PersonNetwork pn = networksMemberships.get(0);

        publicApiClient.setRequestContext(new RequestContext("-default-", person11.getId()));
        peopleProxy.create("people", person11.getId(), "networks", pn.getId(), pn.toJSON().toString(),
                "Unable to POST to a person network");
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    try {
        PersonNetwork pn = new PersonNetwork(GUID.generate());

        publicApiClient.setRequestContext(new RequestContext("-default-", person11.getId()));
        peopleProxy.update("people", person11.getId(), "networks", null, pn.toJSON().toString(),
                "Unable to PUT person networks");
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    try {
        PersonNetwork pn = networksMemberships.get(0);

        publicApiClient.setRequestContext(new RequestContext("-default-", person11.getId()));
        peopleProxy.update("people", person11.getId(), "networks", pn.getId(), pn.toJSON().toString(),
                "Unable to PUT a person network");
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    try {
        publicApiClient.setRequestContext(new RequestContext("-default-", person11.getId()));
        peopleProxy.remove("people", person11.getId(), "networks", null, "Unable to DELETE person networks");
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    try {
        PersonNetwork pn = networksMemberships.get(0);

        publicApiClient.setRequestContext(new RequestContext("-default-", person11.getId()));
        peopleProxy.remove("people", person11.getId(), "networks", pn.getId(),
                "Unable to DELETE a person network");
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
    }

    // user not a member of the network
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person21.getId()));

        int skipCount = 0;
        int maxItems = 2;
        Paging expectedPaging = getPaging(skipCount, maxItems);
        peopleProxy.getNetworkMemberships(person11.getId(), createParams(expectedPaging, null));
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
    }
}

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

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

    // Test Case cloud-1518
    // Create comments

    // invalid node id
    try {//w  w  w. ja  va 2  s.  c  o m
        Comment comment = new Comment("Test Comment 4", "Test Comment 4");
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11.getId()));
        commentsProxy.createNodeComment(GUID.generate(), comment);
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            expectedComments.add(resp);
        }

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

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

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

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

            assertTrue(found);
        }
    }

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

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

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

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

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

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

    Collections.sort(expectedComments);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    // delete comments

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    final NodeRef nodeRef1 = nodes.get(0);

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

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

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

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

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

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

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

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

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

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

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

        Date time = new Date();

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

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

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

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

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

        {
            // person11

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

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

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

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

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

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

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

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

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

        {
            // person21

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

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

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

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

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

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

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

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

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

            assertTrue(found);
        }
    }

    {
        // remove node rating

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@Test
public void testPeople() throws Exception {
    Iterator<TestNetwork> accountsIt = getTestFixture().getNetworksIt();
    final TestNetwork account1 = accountsIt.next();
    Iterator<String> personIt1 = account1.getPersonIds().iterator();
    final String person1 = personIt1.next();
    final String person2 = personIt1.next();

    final TestNetwork account2 = accountsIt.next();
    Iterator<String> personIt2 = account2.getPersonIds().iterator();
    final String person3 = personIt2.next();

    People peopleProxy = publicApiClient.people();

    // Test Case cloud-2192
    // should be able to see oneself
    {//from ww  w .  j  a  v a 2 s.co  m
        publicApiClient.setRequestContext(new RequestContext(account1.getId(), person1));
        Person resp = peopleProxy.getPerson(person1);
        Person person1Entity = repoService.getPerson(person1);
        check(person1Entity, resp);
    }

    // should be able to see another user in the same domain, and be able to see full profile
    {
        publicApiClient.setRequestContext(new RequestContext(account1.getId(), person2));
        Person resp = peopleProxy.getPerson(person1);
        Person person1Entity = repoService.getPerson(person1);
        check(person1Entity, resp);
    }

    // "-me-" user
    {
        publicApiClient.setRequestContext(new RequestContext(account1.getId(), person1));
        Person resp = peopleProxy.getPerson(org.alfresco.rest.api.People.DEFAULT_USER);
        Person person1Entity = repoService.getPerson(person1);
        check(person1Entity, resp);
    }

    // shouldn't be able to see another user in another domain
    publicApiClient.setRequestContext(new RequestContext(account1.getId(), person3));
    try {
        peopleProxy.getPerson(person1);
        fail("");
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_UNAUTHORIZED, e.getHttpResponse().getStatusCode());
    }

    RepoService.TestPerson testP = account1.createUser();
    String personId = testP.getId();
    String desc = "<B>Nice person</B>";
    account1.addUserDescription(personId, desc);
    publicApiClient.setRequestContext(new RequestContext(account1.getId(), personId));
    Person resp = publicApiClient.people().getPerson(personId);
    assertEquals(resp.getId(), personId);
    assertEquals(resp.getDescription(), desc);
}