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

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

Introduction

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

Prototype

int SC_BAD_REQUEST

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

Click Source Link

Document

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

Usage

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

private Map<String, Serializable> parseContent(final WebScriptRequest req) {
    final Map<String, Serializable> result = new HashMap<String, Serializable>();
    Content content = req.getContent();/*from  ww w .  java2 s  . c  o m*/
    String jsonStr = null;
    JSONObject json = null;

    try {
        if (content == null || content.getSize() == 0) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "No content sent with request.");
        }

        jsonStr = content.getContent();
        log.debug("Parsed JSON: " + jsonStr);

        if (jsonStr == null || jsonStr.trim().length() == 0) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "No content sent with request.");
        }

        json = new JSONObject(jsonStr);

        if (!json.has(JSON_KEY_NODEREF)) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST,
                    "Key " + JSON_KEY_NODEREF + " is missing from JSON: " + jsonStr);
        } else {
            NodeRef nodeRef = new NodeRef(json.getString(JSON_KEY_NODEREF));
            result.put(JSON_KEY_NODEREF, nodeRef);

            if (json.has(JSON_KEY_OVERRIDE)) {
                result.put(JSON_KEY_OVERRIDE, json.getBoolean(JSON_KEY_OVERRIDE));
            } else {
                result.put(JSON_KEY_OVERRIDE, false);
            }
        }
    } catch (final IOException ioe) {
        throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ioe.getMessage(), ioe);
    } catch (final JSONException je) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Unable to parse JSON: " + jsonStr);
    } catch (final WebScriptException wse) {
        throw wse; // Ensure WebScriptExceptions get rethrown verbatim
    } catch (final Exception e) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Unable to parse JSON '" + jsonStr + "'.", e);
    }

    return result;
}

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

private Map<String, Serializable> parseContent(final WebScriptRequest req) {
    final Map<String, Serializable> result = new HashMap<String, Serializable>();
    Content content = req.getContent();/* www .  ja v a 2s  .co m*/
    String jsonStr = null;
    JSONObject json = null;

    try {
        if (content == null || content.getSize() == 0) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "No content sent with request.");
        }

        jsonStr = content.getContent();

        if (jsonStr == null || jsonStr.trim().length() == 0) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "No content sent with request.");
        }
        log.debug("Parsed JSON: " + jsonStr);

        json = new JSONObject(jsonStr);

        if (!json.has(JSON_KEY_NODEREF)) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST,
                    "Key " + JSON_KEY_NODEREF + " is missing from JSON: " + jsonStr);
        } else {
            NodeRef nodeRef = new NodeRef(json.getString(JSON_KEY_NODEREF));
            result.put(JSON_KEY_NODEREF, nodeRef);
        }

        if (!json.has(JSON_KEY_FORCE)) {
            result.put(JSON_KEY_FORCE, false);
        } else {
            result.put(JSON_KEY_FORCE, json.getBoolean(JSON_KEY_FORCE));
        }

    } catch (final IOException ioe) {
        throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ioe.getMessage(), ioe);
    } catch (final JSONException je) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Unable to parse JSON: " + jsonStr);
    } catch (final WebScriptException wse) {
        throw wse; // Ensure WebScriptExceptions get rethrown verbatim
    } catch (final Exception e) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Unable to parse JSON '" + jsonStr + "'.", e);
    }

    return result;
}

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

private Map<String, Serializable> parseContent(final WebScriptRequest req) {
    final Map<String, Serializable> result = new HashMap<String, Serializable>();
    Content content = req.getContent();//  w  w w . j av  a  2 s .  c  om
    String jsonStr = null;
    JSONObject json = null;

    try {
        if (content == null || content.getSize() == 0) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "No content sent with request.");
        }

        jsonStr = content.getContent();

        if (jsonStr == null || jsonStr.trim().length() == 0) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "No content sent with request.");
        }
        log.debug("Parsed JSON: " + jsonStr);

        json = new JSONObject(jsonStr);

        if (!json.has(JSON_KEY_NODEREF)) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST,
                    "Key " + JSON_KEY_NODEREF + " is missing from JSON: " + jsonStr);
        } else {
            NodeRef nodeRef = new NodeRef(json.getString(JSON_KEY_NODEREF));
            result.put(JSON_KEY_NODEREF, nodeRef);

            if (json.has(JSON_KEY_OVERRIDE)) {
                result.put(JSON_KEY_OVERRIDE, json.getBoolean(JSON_KEY_OVERRIDE));
            } else {
                result.put(JSON_KEY_OVERRIDE, false);
            }

            if (nodeService.hasAspect(nodeRef, ContentModel.ASPECT_VERSIONABLE)) {
                result.put(JSON_KEY_MAJORVERSION,
                        json.getBoolean(JSON_KEY_MAJORVERSION) ? VersionType.MAJOR : VersionType.MINOR);
                result.put(JSON_KEY_DESCRIPTION, json.getString(JSON_KEY_DESCRIPTION));
            }

            if (json.has(JSON_KEY_REMOVEFROMDRIVE)) {
                result.put(JSON_KEY_REMOVEFROMDRIVE, json.getBoolean(JSON_KEY_REMOVEFROMDRIVE));
            }
        }
    } catch (final IOException ioe) {
        throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ioe.getMessage(), ioe);
    } catch (final JSONException je) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Unable to parse JSON: " + jsonStr);
    } catch (final WebScriptException wse) {
        throw wse; // Ensure WebScriptExceptions get rethrown verbatim
    } catch (final Exception e) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Unable to parse JSON '" + jsonStr + "'.", e);
    }

    return result;
}

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

private Map<String, Serializable> parseContent(final WebScriptRequest req) {
    final Map<String, Serializable> result = new HashMap<String, Serializable>();
    Content content = req.getContent();/*w  ww . j  a  v a  2  s  . c o  m*/
    String jsonStr = null;
    JSONObject json = null;

    try {
        if (content == null || content.getSize() == 0) {
            return result;
        }

        jsonStr = content.getContent();

        if (jsonStr == null || jsonStr.trim().length() == 0) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "No content sent with request.");
        }
        log.debug("Parsed JSON: " + jsonStr);

        json = new JSONObject(jsonStr);

        if (json.has(JSON_KEY_PERMISSIONS)) {
            JSONObject permissionData = json.getJSONObject(JSON_KEY_PERMISSIONS);
            boolean sendEmail = permissionData.has(JSON_KEY_PERMISSIONS_SEND_EMAIL)
                    ? permissionData.getBoolean(JSON_KEY_PERMISSIONS_SEND_EMAIL)
                    : true;
            if (!permissionData.has(JSON_KEY_PERMISSIONS_ITEMS)) {
                throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Key " + JSON_KEY_PERMISSIONS_ITEMS
                        + " is missing from JSON object: " + permissionData.toString());
            }
            JSONArray jsonPerms = permissionData.getJSONArray(JSON_KEY_PERMISSIONS_ITEMS);
            ArrayList<GooglePermission> permissions = new ArrayList<GoogleDocsService.GooglePermission>(
                    jsonPerms.length());
            for (int i = 0; i < jsonPerms.length(); i++) {
                JSONObject jsonPerm = jsonPerms.getJSONObject(i);
                String authorityId, authorityType, roleName;
                if (jsonPerm.has(JSON_KEY_AUTHORITY_ID)) {
                    authorityId = jsonPerm.getString(JSON_KEY_AUTHORITY_ID);
                } else {
                    throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Key " + JSON_KEY_AUTHORITY_ID
                            + " is missing from JSON object: " + jsonPerm.toString());
                }
                if (jsonPerm.has(JSON_KEY_AUTHORITY_TYPE)) {
                    authorityType = jsonPerm.getString(JSON_KEY_AUTHORITY_TYPE);
                } else {
                    authorityType = JSON_VAL_AUTHORITY_TYPE_DEFAULT;
                }
                if (jsonPerm.has(JSON_KEY_ROLE_NAME)) {
                    roleName = jsonPerm.getString(JSON_KEY_ROLE_NAME);
                } else {
                    throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Key " + JSON_KEY_ROLE_NAME
                            + " is missing from JSON object: " + jsonPerm.toString());
                }
                permissions.add(new GooglePermission(authorityId, authorityType, roleName));
            }
            result.put(PARAM_PERMISSIONS, permissions);
            result.put(PARAM_SEND_EMAIL, Boolean.valueOf(sendEmail));
        }
    } catch (final IOException ioe) {
        throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ioe.getMessage(), ioe);
    } catch (final JSONException je) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Unable to parse JSON: " + jsonStr);
    } catch (final WebScriptException wse) {
        throw wse; // Ensure WebScriptExceptions get rethrown verbatim
    } catch (final Exception e) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Unable to parse JSON '" + jsonStr + "'.", e);
    }

    return result;
}

From source file:org.alfresco.repo.jive.rest.GetCommunitiesWebScript.java

/**
 * @see org.springframework.extensions.webscripts.DeclarativeWebScript#executeImpl(org.springframework.extensions.webscripts.WebScriptRequest, org.springframework.extensions.webscripts.Status, org.springframework.extensions.webscripts.Cache)
 *///from  w w w  .j  a v  a  2  s .c o  m
@Override
protected Map<String, Object> executeImpl(final WebScriptRequest req, final Status status, final Cache cache) {
    if (log.isTraceEnabled())
        log.trace("GetCommunitiesWebScript.executeImpl called");

    final Map<String, Object> result = new HashMap<String, Object>();
    final String communityIdAsStr = parseCommunityId(req.getExtensionPath());
    List<JiveCommunity> subCommunities = null;

    cache.setNeverCache(true);

    if (communityIdAsStr != null && communityIdAsStr.trim().length() > 0) {
        // We got a community Id in the request, so retrieve its subcommunities
        long communityId = -1;

        try {
            communityId = Long.parseLong(communityIdAsStr);
        } catch (final NumberFormatException nfe) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST,
                    "Could not parse community Id from value '" + communityIdAsStr + "'.", nfe);
        }

        try {
            if (log.isDebugEnabled())
                log.debug("Retrieving sub-communities of Jive community " + communityId);
            result.put("root", false);
            subCommunities = jiveService.getSubCommunities(communityId);
        } catch (final InvalidCommunityException ice) {
            throw new WebScriptException(HttpStatus.SC_NOT_FOUND, ice.getMessage(), ice);
        } catch (final ServiceUnavailableException sue) {
            throw new WebScriptException(HttpStatus.SC_SERVICE_UNAVAILABLE, sue.getMessage(), sue);
        }
    } else {
        try {
            // No community id provided, so retrieve the root-level communities
            if (log.isDebugEnabled())
                log.debug("Retrieving root-level communities from Jive.");
            result.put("root", true);
            subCommunities = jiveService.getCommunities();
        } catch (final ServiceUnavailableException sue) {
            throw new WebScriptException(HttpStatus.SC_SERVICE_UNAVAILABLE, sue.getMessage(), sue);
        }
    }

    result.put("subCommunities", subCommunities);

    return (result);
}

From source file:org.alfresco.repo.jive.rest.SocializeDocumentsWebScript.java

/**
 * @see org.springframework.extensions.webscripts.DeclarativeWebScript#executeImpl(org.springframework.extensions.webscripts.WebScriptRequest, org.springframework.extensions.webscripts.Status, org.springframework.extensions.webscripts.Cache)
 */// www  . j a v  a 2  s  .co m
@Override
protected Map<String, Object> executeImpl(final WebScriptRequest req, final Status status, final Cache cache) {
    if (log.isTraceEnabled())
        log.trace("SocializeDocumentsWebScript.executeImpl called");

    Map<String, Object> result = null;
    List<NodeRef> nodeRefs = parseNodeRefs(req);
    long communityId = parseCommunityId(req);

    cache.setNeverCache(true);

    try {
        if (log.isDebugEnabled())
            log.debug("Socializing documents " + Arrays.toString(nodeRefs.toArray()) + " to Jive community "
                    + communityId);
        jiveService.socializeDocuments(nodeRefs, communityId);
    } catch (final FileNotFoundException fnfe) {
        throw new WebScriptException(HttpStatus.SC_NOT_FOUND, fnfe.getMessage(), fnfe);
    } catch (final NotAFileException nafe) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, nafe.getMessage(), nafe);
    } catch (final JiveServiceException jse) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, jse.getMessage(), jse);
    } catch (final ServiceUnavailableException sue) {
        throw new WebScriptException(HttpStatus.SC_SERVICE_UNAVAILABLE, sue.getMessage(), sue);
    } catch (final DocumentSizeException dse) {
        throw new WebScriptException(HttpStatus.SC_CONFLICT, dse.getMessage(), dse);
    }

    return (result);
}

From source file:org.alfresco.repo.jive.rest.SocializeDocumentsWebScript.java

private final List<NodeRef> parseNodeRefs(final WebScriptRequest req) {
    final List<NodeRef> result = new ArrayList<NodeRef>();
    Content content = req.getContent();//w  w  w .j  a  v a2 s  . c  o m
    String jsonStr = null;
    JSONObject json = null;

    try {
        if (content == null || content.getSize() == 0) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "No content sent with request.");
        }

        jsonStr = content.getContent();

        if (jsonStr == null || jsonStr.trim().length() == 0) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "No content sent with request.");
        }

        json = new JSONObject(jsonStr);

        if (!json.has(JSON_KEY_NODE_REFS)) {
            throw new WebScriptException(HttpStatus.SC_BAD_REQUEST,
                    "Key " + JSON_KEY_NODE_REFS + " is missing from JSON: " + jsonStr);
        }

        JSONArray nodeRefs = json.getJSONArray(JSON_KEY_NODE_REFS);

        for (int i = 0; i < nodeRefs.length(); i++) {
            NodeRef nodeRef = new NodeRef(nodeRefs.getString(i));
            result.add(nodeRef);
        }
    } catch (final IOException ioe) {
        throw new WebScriptException(HttpStatus.SC_INTERNAL_SERVER_ERROR, ioe.getMessage(), ioe);
    } catch (final JSONException je) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Unable to parse JSON: " + jsonStr);
    } catch (final WebScriptException wse) {
        throw wse; // Ensure WebScriptExceptions get rethrown verbatim
    } catch (final Exception e) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST,
                "Unable to retrieve nodeRefs from JSON '" + jsonStr + "'.", e);
    }

    return (result);
}

From source file:org.alfresco.repo.jive.rest.SocializeDocumentsWebScript.java

private final long parseCommunityId(final WebScriptRequest req) {
    long result = -1;
    String extensionPath = req.getExtensionPath();
    int indexOfFullStop = extensionPath.indexOf('.');

    if (indexOfFullStop >= 0) {
        // We have a filename extension (e.g. ".json") on the end of the URL, so strip it off
        extensionPath = extensionPath.substring(0, indexOfFullStop);
    }//from  w w  w.  ja v  a 2s  .  c o  m

    String[] extensionPathComponents = extensionPath.split("/");

    if (extensionPathComponents == null) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST,
                "Unable to parse communityId from path '" + extensionPath + "'.");
    }

    if (extensionPathComponents.length != 2) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST, "Incorrect number of path parameters - got "
                + extensionPathComponents.length + ", was expecting 2.");
    }

    try {
        result = Long.valueOf(extensionPathComponents[0]);
    } catch (final NumberFormatException nfe) {
        throw new WebScriptException(HttpStatus.SC_BAD_REQUEST,
                "Unable to parse communityId from path '" + extensionPath + "'.", nfe);
    }

    return (result);
}

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

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

    //Test with default tenant domain. see ALF-20448
    {/*from w  w  w. ja  va 2s  . c  o 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.TestFavourites.java

@Test
public void testInvalidRequests() throws Exception {
    try {//from w ww .java  2 s. com
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person10Id));

        Favourite favourite = makeSiteFavourite(person1PublicSites.get(0));
        Favourite ret = favouritesProxy.createFavourite(person11Id, favourite);
        favourite.expected(ret);
        fail();
    } catch (PublicApiException e) {
        // Note: un-authorized comes back as 404
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // cloud-2468
    // invalid type
    // NOTE: The test below has swapped to attempt to favorite a comment rather than a
    //       a wiki page as the WikiService has moved to the Share Services AMP in 5.1

    try {
        log("cloud-2468");

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

        final NodeRef document = personDocs.get(0);
        final NodeRef comment = TenantUtil.runAsUserTenant(new TenantRunAsWork<NodeRef>() {
            @Override
            public NodeRef doWork() throws Exception {
                NodeRef comment = repoService.createComment(document, new Comment("Title", "Content"));
                return comment;
            }
        }, person10Id, network1.getId());

        final String guid = comment.getId();
        JSONAble commentJSON = new JSONAble() {
            @SuppressWarnings("unchecked")
            @Override
            public JSONObject toJSON() {
                JSONObject json = new JSONObject();
                json.put("guid", guid);
                return json;
            }
        };

        FavouritesTarget target = new InvalidFavouriteTarget("comment", commentJSON, guid);
        Favourite favourite = new Favourite(target);

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

    try {
        log("cloud-2468");

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

        Site site = person1PublicSites.get(0);
        FavouritesTarget target = new InvalidFavouriteTarget(GUID.generate(), site, site.getGuid());
        Favourite favourite = new Favourite(target);

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

    // type = file, target is a site
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person10Id));

        String siteGuid = person1PublicSites.get(0).getGuid();
        FavouriteDocument document = new FavouriteDocument(siteGuid);
        Favourite favourite = makeFileFavourite(document.getGuid());
        Favourite ret = favouritesProxy.createFavourite(person10Id, favourite);
        favourite.expected(ret);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // type = folder, target is a site
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person10Id));

        String siteGuid = person1PublicSites.get(0).getGuid();
        FavouriteFolder folder = new FavouriteFolder(siteGuid);
        Favourite favourite = makeFolderFavourite(folder.getGuid());
        Favourite ret = favouritesProxy.createFavourite(person10Id, favourite);
        favourite.expected(ret);

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

    // type = folder, target is a file
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person10Id));

        FavouriteFolder folder = new FavouriteFolder(person1PublicDocs.get(0).getId());
        Favourite favourite = makeFolderFavourite(folder.getGuid());
        Favourite ret = favouritesProxy.createFavourite(person10Id, favourite);
        favourite.expected(ret);

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

    // type = file, target is a folder
    try {
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person10Id));

        FavouriteDocument document = new FavouriteDocument(person1PublicFolders.get(0).getId());
        Favourite favourite = makeFileFavourite(document.getGuid());
        Favourite ret = favouritesProxy.createFavourite(person10Id, favourite);
        favourite.expected(ret);

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

    // make sure that a user can't favourite on behalf of another user
    // 2471
    {
        log("cloud-2471");

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

            FavouriteDocument document = new FavouriteDocument(person1PublicDocs.get(0).getId());
            Favourite favourite = makeFileFavourite(document.getGuid());
            favouritesProxy.createFavourite(person11Id, favourite);

            fail();
        } catch (PublicApiException e) {
            // Note: un-authorized comes back as 404
            assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
        }

        // person1 should have no favourites
        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person11Id));
        ListResponse<Favourite> response = favouritesProxy.getFavourites(person11Id, createParams(null, null));
        assertEquals(0, response.getList().size());
    }

    // invalid/non-existent user
    // 2469
    try {
        log("cloud-2469");

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

        Favourite favourite = makeSiteFavourite(personSites.get(0));
        Favourite ret = favouritesProxy.createFavourite(GUID.generate(), favourite);
        favourite.expected(ret);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // make sure that a user can't see other user's favourites.
    // 2465
    try {
        log("cloud-2465");

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person10Id));
        favouritesProxy.getFavourites(person11Id, null);
        fail();
    } catch (PublicApiException e) {
        // Note: un-authorized comes back as 404
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // 2464, unknown user
    try {
        log("cloud-2464");

        publicApiClient.setRequestContext(new RequestContext(network1.getId(), person10Id));
        favouritesProxy.getFavourites(GUID.generate(), null);
        fail();
    } catch (PublicApiException e) {
        assertEquals(HttpStatus.SC_NOT_FOUND, e.getHttpResponse().getStatusCode());
    }

    // non-existent entity for a given type
    // 2480
    {
        log("cloud-2480");

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

            SiteImpl site = new SiteImpl();
            site.setGuid(GUID.generate());
            Favourite favourite = makeSiteFavourite((Site) site);
            favouritesProxy.createFavourite(person10Id, favourite);

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

        ListResponse<Favourite> response = favouritesProxy.getFavourites(person10Id, createParams(null, null));
        assertEquals(0, response.getList().size());
    }

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

            FavouriteDocument document = new FavouriteDocument(GUID.generate());
            Favourite favourite = makeFileFavourite(document.getGuid());
            favouritesProxy.createFavourite(person10Id, favourite);

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

        ListResponse<Favourite> response = favouritesProxy.getFavourites(person10Id, createParams(null, null));
        assertEquals(0, response.getList().size());
    }

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

            FavouriteFolder folder = new FavouriteFolder(GUID.generate());
            Favourite favourite = makeFolderFavourite(folder.getGuid());
            favouritesProxy.createFavourite(person10Id, favourite);

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

        ListResponse<Favourite> response = favouritesProxy.getFavourites(person10Id, createParams(null, null));
        assertEquals(0, response.getList().size());
    }

    // 2470
    // incorrect type for a given favourite target
    {
        log("cloud-2470");

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

            Site site = person1PublicSites.get(0);
            FavouritesTarget target = new InvalidFavouriteTarget("folder", site, site.getGuid());
            Favourite favourite = new Favourite(target);

            favouritesProxy.createFavourite(person10Id, favourite);

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

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

            Site site = person1PublicSites.get(0);
            FavouritesTarget target = new InvalidFavouriteTarget("file", site, site.getGuid());
            Favourite favourite = new Favourite(target);

            favouritesProxy.createFavourite(person10Id, favourite);

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

        FavouriteDocument document = new FavouriteDocument(person1PublicDocs.get(0).getId());

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

            FavouritesTarget target = new InvalidFavouriteTarget("site", document, document.getGuid());
            Favourite favourite = new Favourite(target);

            favouritesProxy.createFavourite(person10Id, favourite);

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

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

            FavouritesTarget target = new InvalidFavouriteTarget("folder", document, document.getGuid());
            Favourite favourite = new Favourite(target);

            favouritesProxy.createFavourite(person10Id, favourite);

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

        FavouriteFolder folder = new FavouriteFolder(person1PublicFolders.get(0).getId());

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

            FavouritesTarget target = new InvalidFavouriteTarget("site", folder, folder.getGuid());
            Favourite favourite = new Favourite(target);

            favouritesProxy.createFavourite(person10Id, favourite);

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

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

            FavouritesTarget target = new InvalidFavouriteTarget("file", folder, folder.getGuid());
            Favourite favourite = new Favourite(target);

            favouritesProxy.createFavourite(person10Id, favourite);

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

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

        // none of these POSTs should have resulted in favourites being created...
        ListResponse<Favourite> response = favouritesProxy.getFavourites(person10Id, createParams(null, null));
        assertEquals(0, response.getList().size());
    }

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

        try {
            Favourite favourite = new Favourite(null);
            favouritesProxy.update("people", "-me-", "favorites", null, favourite.toJSON().toString(),
                    "Unable to PUT favourites");
        } catch (PublicApiException e) {
            assertEquals(HttpStatus.SC_METHOD_NOT_ALLOWED, e.getHttpResponse().getStatusCode());
        }
    }
}