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

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

Introduction

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

Prototype

int SC_FORBIDDEN

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

Click Source Link

Document

<tt>403 Forbidden</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:org.alfresco.integrations.google.docs.webscripts.DiscardContent.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    getGoogleDocsServiceSubsystem();//www  .  j  ava  2  s . com

    Map<String, Object> model = new HashMap<String, Object>();

    Map<String, Serializable> map = parseContent(req);
    final NodeRef nodeRef = (NodeRef) map.get(JSON_KEY_NODEREF);

    if (nodeService.hasAspect(nodeRef, GoogleDocsModel.ASPECT_EDITING_IN_GOOGLE)) {
        try {
            boolean deleted = false;

            if (!Boolean.valueOf(map.get(JSON_KEY_OVERRIDE).toString())) {
                SiteInfo siteInfo = siteService.getSite(nodeRef);
                if (siteInfo == null
                        || siteService.isMember(siteInfo.getShortName(), AuthenticationUtil.getRunAsUser())) {

                    if (googledocsService.hasConcurrentEditors(nodeRef)) {
                        throw new WebScriptException(HttpStatus.SC_CONFLICT,
                                "Node: " + nodeRef.toString() + " has concurrent editors.");
                    }
                } else {
                    throw new AccessDeniedException(
                            "Access Denied.  You do not have the appropriate permissions to perform this operation.");
                }
            }

            deleted = delete(nodeRef);

            model.put(MODEL_SUCCESS, deleted);

        } catch (InvalidNodeRefException ine) {
            throw new WebScriptException(HttpStatus.SC_NOT_FOUND, ine.getMessage());
        } catch (IOException ioe) {
            throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ioe.getMessage());
        } catch (GoogleDocsAuthenticationException gdae) {
            throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdae.getMessage());
        } catch (GoogleDocsRefreshTokenException gdrte) {
            throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdrte.getMessage());
        } catch (GoogleDocsServiceException gdse) {
            if (gdse.getPassedStatusCode() > -1) {
                throw new WebScriptException(gdse.getPassedStatusCode(), gdse.getMessage());
            } else {
                throw new WebScriptException(gdse.getMessage());
            }
        } catch (AccessDeniedException ade) {
            // This code will make changes after the rollback has occurred to clean up the node: remove the lock and the Google
            // Docs aspect. If it has the temporary aspect it will also remove the node from Alfresco
            AlfrescoTransactionSupport.bindListener(new TransactionListenerAdapter() {
                public void afterRollback() {
                    transactionService.getRetryingTransactionHelper()
                            .doInTransaction(new RetryingTransactionCallback<Object>() {
                                public Object execute() throws Throwable {
                                    DriveFile driveFile = googledocsService.getDriveFile(nodeRef);
                                    googledocsService.unlockNode(nodeRef);
                                    boolean deleted = googledocsService.deleteContent(nodeRef, driveFile);

                                    if (deleted) {
                                        AuthenticationUtil
                                                .runAsSystem(new AuthenticationUtil.RunAsWork<Object>() {
                                                    public Object doWork() throws Exception {
                                                        if (nodeService.hasAspect(nodeRef,
                                                                ContentModel.ASPECT_TEMPORARY)) {
                                                            nodeService.deleteNode(nodeRef);
                                                        }

                                                        return null;
                                                    }
                                                });
                                    }

                                    return null;
                                }
                            }, false, true);
                }
            });

            throw new WebScriptException(HttpStatus.SC_FORBIDDEN, ade.getMessage(), ade);
        } catch (Exception e) {
            throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage(), e);
        }
    } else {
        throw new WebScriptException(HttpStatus.SC_NOT_ACCEPTABLE,
                "Missing Google Docs Aspect on " + nodeRef.toString());
    }

    return model;
}

From source file:org.alfresco.integrations.google.docs.webscripts.RemoveContent.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    getGoogleDocsServiceSubsystem();//from w  w w  .  j av a  2  s . c om

    Map<String, Object> model = new HashMap<String, Object>();

    boolean success = false;

    /* The node we are working on */
    Map<String, Serializable> map = parseContent(req);
    final NodeRef nodeRef = (NodeRef) map.get(JSON_KEY_NODEREF);

    /* Make sure the node is currently "checked out" to Google */
    if (nodeService.hasAspect(nodeRef, GoogleDocsModel.ASPECT_EDITING_IN_GOOGLE)) {
        try {
            Credential credential = googledocsService.getCredential();

            /* Get the metadata for the file we are working on */
            File file = googledocsService.getDriveFile(credential, nodeRef);
            /* remove it from users Google account and free it in the repo */
            googledocsService.removeContent(credential, nodeRef, file, (Boolean) map.get(JSON_KEY_FORCE));

            /* if we reach this point all should be completed */
            success = true;

        } catch (GoogleDocsAuthenticationException gdae) {
            throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdae.getMessage());
        } catch (GoogleDocsServiceException gdse) {
            if (gdse.getPassedStatusCode() > -1) {
                throw new WebScriptException(gdse.getPassedStatusCode(), gdse.getMessage());
            } else {
                throw new WebScriptException(gdse.getMessage());
            }
        } catch (GoogleDocsRefreshTokenException gdrte) {
            throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdrte.getMessage());
        } catch (ConstraintException ce) {
            throw new WebScriptException(GoogleDocsConstants.STATUS_INTEGIRTY_VIOLATION, ce.getMessage(), ce);
        } catch (AccessDeniedException ade) {
            // This code will make changes after the rollback has occurred to clean up the node
            // (remove the lock and the Google Docs aspect
            AlfrescoTransactionSupport.bindListener(new TransactionListenerAdapter() {
                public void afterRollback() {
                    log.debug("Rollback Save to node: " + nodeRef);
                    transactionService.getRetryingTransactionHelper()
                            .doInTransaction(new RetryingTransactionCallback<Object>() {
                                public Object execute() throws Throwable {
                                    return AuthenticationUtil
                                            .runAsSystem(new AuthenticationUtil.RunAsWork<Object>() {
                                                public Object doWork() throws Exception {
                                                    googledocsService.unlockNode(nodeRef);
                                                    googledocsService.unDecorateNode(nodeRef);

                                                    // If the node was just created ('Create Content') it will
                                                    // have the temporary aspect and should be completely removed.
                                                    if (nodeService.hasAspect(nodeRef,
                                                            ContentModel.ASPECT_TEMPORARY)) {
                                                        nodeService.deleteNode(nodeRef);
                                                    }

                                                    return null;
                                                }
                                            });
                                }
                            }, false, true);
                }
            });

            throw new WebScriptException(HttpStatus.SC_FORBIDDEN, ade.getMessage(), ade);
        } catch (Exception e) {
            throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage(), e);
        }
    }

    model.put(MODEL_SUCCESSFUL, success);

    return model;
}

From source file:org.alfresco.integrations.google.docs.webscripts.SaveContent.java

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    getGoogleDocsServiceSubsystem();/* w w w.jav a2s.  c o  m*/

    Map<String, Object> model = new HashMap<String, Object>();

    boolean success = false;

    Map<String, Serializable> map = parseContent(req);
    final NodeRef nodeRef = (NodeRef) map.get(JSON_KEY_NODEREF);
    log.debug("Saving Node to Alfresco from Google: " + nodeRef);

    try {
        SiteInfo siteInfo = siteService.getSite(nodeRef);
        if (siteInfo == null
                || siteService.isMember(siteInfo.getShortName(), AuthenticationUtil.getRunAsUser())) {

            if (!(Boolean) map.get(JSON_KEY_OVERRIDE)) {
                log.debug("Check for Concurent Users.");
                if (googledocsService.hasConcurrentEditors(nodeRef)) {
                    throw new WebScriptException(HttpStatus.SC_CONFLICT,
                            "Node: " + nodeRef.toString() + " has concurrent editors.");
                }
            }

            // Should the content be removed from the users Google Drive Account
            boolean removeFromDrive = (map.get(JSON_KEY_REMOVEFROMDRIVE) != null)
                    ? (Boolean) map.get(JSON_KEY_REMOVEFROMDRIVE)
                    : true;

            String contentType = googledocsService.getContentType(nodeRef);
            log.debug("NodeRef: " + nodeRef + "; ContentType: " + contentType);
            if (contentType.equals(GoogleDocsConstants.DOCUMENT_TYPE)) {
                if (googledocsService.isGoogleDocsLockOwner(nodeRef)) {
                    googledocsService.unlockNode(nodeRef);

                    if (removeFromDrive) {
                        googledocsService.getDocument(nodeRef);
                    } else {
                        googledocsService.getDocument(nodeRef, removeFromDrive);
                    }
                    success = true; // TODO Make getDocument return boolean
                } else {
                    throw new WebScriptException(HttpStatus.SC_FORBIDDEN,
                            "Document is locked by another user.");
                }
            } else if (contentType.equals(GoogleDocsConstants.SPREADSHEET_TYPE)) {
                if (googledocsService.isGoogleDocsLockOwner(nodeRef)) {
                    googledocsService.unlockNode(nodeRef);

                    if (removeFromDrive) {
                        googledocsService.getSpreadSheet(nodeRef);
                    } else {
                        googledocsService.getSpreadSheet(nodeRef, removeFromDrive);
                    }
                    success = true; // TODO Make getSpreadsheet return
                                    // boolean
                } else {
                    throw new WebScriptException(HttpStatus.SC_FORBIDDEN,
                            "Document is locked by another user.");
                }
            } else if (contentType.equals(GoogleDocsConstants.PRESENTATION_TYPE)) {
                if (googledocsService.isGoogleDocsLockOwner(nodeRef)) {
                    googledocsService.unlockNode(nodeRef);

                    if (removeFromDrive) {
                        googledocsService.getPresentation(nodeRef);
                    } else {
                        googledocsService.getPresentation(nodeRef, removeFromDrive);
                    }
                    success = true; // TODO Make getPresentation return
                                    // boolean
                } else {
                    throw new WebScriptException(HttpStatus.SC_FORBIDDEN,
                            "Document is locked by another user.");
                }
            } else {
                throw new WebScriptException(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE,
                        "Content Type: " + contentType + " unknown.");
            }

            // Finish this off with a version create or update
            Map<String, Serializable> versionProperties = new HashMap<String, Serializable>();
            if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE)) {
                versionProperties.put(Version2Model.PROP_VERSION_TYPE, map.get(JSON_KEY_MAJORVERSION));
                versionProperties.put(Version2Model.PROP_DESCRIPTION, map.get(JSON_KEY_DESCRIPTION));
            } else {
                versionProperties.put(Version2Model.PROP_VERSION_TYPE, VersionType.MAJOR);

                nodeService.setProperty(nodeRef, ContentModel.PROP_AUTO_VERSION, true);
                nodeService.setProperty(nodeRef, ContentModel.PROP_AUTO_VERSION_PROPS, true);
            }

            log.debug("Version Node:" + nodeRef + "; Version Properties: " + versionProperties);
            Version version = versionService.createVersion(nodeRef, versionProperties);

            model.put(MODEL_VERSION, version.getVersionLabel());

            if (!removeFromDrive) {
                googledocsService.lockNode(nodeRef);
            }

        } else {
            throw new AccessDeniedException(
                    "Access Denied.  You do not have the appropriate permissions to perform this operation.");
        }

    } catch (GoogleDocsAuthenticationException gdae) {
        throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdae.getMessage());
    } catch (GoogleDocsServiceException gdse) {
        if (gdse.getPassedStatusCode() > -1) {
            throw new WebScriptException(gdse.getPassedStatusCode(), gdse.getMessage());
        } else {
            throw new WebScriptException(gdse.getMessage());
        }
    } catch (GoogleDocsRefreshTokenException gdrte) {
        throw new WebScriptException(HttpStatus.SC_BAD_GATEWAY, gdrte.getMessage());
    } catch (ConstraintException ce) {
        throw new WebScriptException(GoogleDocsConstants.STATUS_INTEGIRTY_VIOLATION, ce.getMessage(), ce);
    } catch (AccessDeniedException ade) {
        // This code will make changes after the rollback has occurred to clean up the node (remove the lock and the Google Docs
        // aspect
        AlfrescoTransactionSupport.bindListener(new TransactionListenerAdapter() {
            public void afterRollback() {
                log.debug("Rollback Save to node: " + nodeRef);
                transactionService.getRetryingTransactionHelper()
                        .doInTransaction(new RetryingTransactionCallback<Object>() {
                            public Object execute() throws Throwable {
                                return AuthenticationUtil
                                        .runAsSystem(new AuthenticationUtil.RunAsWork<Object>() {
                                            public Object doWork() throws Exception {
                                                googledocsService.unlockNode(nodeRef);
                                                googledocsService.unDecorateNode(nodeRef);

                                                // If the node was just created ('Create Content') it will have the temporary aspect and should
                                                // be completely removed.
                                                if (nodeService.hasAspect(nodeRef,
                                                        ContentModel.ASPECT_TEMPORARY)) {
                                                    nodeService.deleteNode(nodeRef);
                                                }

                                                return null;
                                            }
                                        });
                            }
                        }, false, true);
            }
        });

        throw new WebScriptException(HttpStatus.SC_FORBIDDEN, ade.getMessage(), ade);
    } catch (Exception e) {
        throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage(), e);
    }

    model.put(MODEL_SUCCESS, success);

    return model;
}

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/*from   www . j  av 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
    {/* ww  w.  j  a  v a2  s.co m*/
        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.TestFavouriteSites.java

@Test
public void testFavouriteSites() throws Exception {
    Iterator<TestNetwork> networksIt = getTestFixture().getNetworksIt();
    assertTrue(networksIt.hasNext());//from w ww .j  a va2s.  c  om
    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.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  .  j  a v a2 s.com*/
        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.TestNodeComments.java

@Test
public void test_MNT_16446() throws Exception {
    Comments commentsProxy = publicApiClient.comments();

    // in a site/*w ww. j a  v  a  2s  .c  o  m*/

    publicApiClient.setRequestContext(new RequestContext(network1.getId(), person13.getId()));
    Comment comment = new Comment("Test Comment 1", "Test Comment 1");
    Comment resp = commentsProxy.createNodeComment(nodeRef1.getId(), comment);
    String commentId = resp.getId();

    // MNT-16446: another site collaborator should not be able to edit
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person14.getId()));
        Comment update = new Comment("Test Comment 4", "Test Comment 4");
        commentsProxy.updateNodeComment(nodeRef1.getId(), commentId, update);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_FORBIDDEN, e.getHttpResponse().getStatusCode());
    }

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

    Comment update = new Comment("Updated comment", "Updated comment");
    commentsProxy.updateNodeComment(nodeRef1.getId(), commentId, update);

    commentsProxy.removeNodeComment(nodeRef1.getId(), commentId);
}

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

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

    Sites sitesProxy = publicApiClient.sites();

    {//from w ww.  ja  va  2  s  .co  m
        final List<SiteMember> expectedSiteMembers = new ArrayList<SiteMember>();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        assertTrue(accountsIt.hasNext());

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

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

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

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

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

        // remove site membership

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

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

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

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

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

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

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

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

            // update site membership

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        // update tags

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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