Search in sources :

Example 1 with Content

use of org.springframework.extensions.surf.util.Content in project alfresco-remote-api by Alfresco.

the class ParamsExtractorTests method testPostExtractor.

@SuppressWarnings("unchecked")
@Test
public void testPostExtractor() throws IOException {
    // Put together the stubs
    ResourceWebScriptPost extractor = new ResourceWebScriptPost();
    extractor.setAssistant(assistant);
    Map<String, String> templateVars = new HashMap<String, String>();
    Content content = mock(Content.class);
    when(content.getReader()).thenReturn(new StringReader(JsonJacksonTests.FARMER_JSON));
    WebScriptRequest request = mock(WebScriptRequest.class);
    when(request.getServiceMatch()).thenReturn(new Match(null, templateVars, null));
    when(request.getContent()).thenReturn(content);
    Params params = extractor.extractParams(mockEntity(), request);
    assertNotNull(params);
    assertNotNull(params.getFilter());
    assertTrue("Default filter is BeanPropertiesFilter.AllProperties", BeanPropertiesFilter.AllProperties.class.equals(params.getFilter().getClass()));
    Object passed = params.getPassedIn();
    assertNotNull(passed);
    assertTrue(List.class.isAssignableFrom(passed.getClass()));
    List<Object> passedObjs = (List<Object>) passed;
    assertTrue(passedObjs.size() == 1);
    assertTrue("A Farmer was passed in.", Farmer.class.equals(passedObjs.get(0).getClass()));
    // No entity id for POST
    templateVars.put(ResourceLocator.ENTITY_ID, "1234");
    try {
        params = extractor.extractParams(mockEntity(), request);
        fail("Should not get here. No entity id for POST");
    } catch (UnsupportedResourceOperationException uoe) {
        // Must throw this exception
        assertNotNull(uoe);
    }
    // reset the reader
    when(content.getReader()).thenReturn(new StringReader(JsonJacksonTests.FARMER_JSON));
    params = extractor.extractParams(mockRelationship(), request);
    assertNotNull(params);
    assertEquals("1234", params.getEntityId());
    passed = params.getPassedIn();
    assertNotNull(passed);
    passedObjs = (List<Object>) passed;
    assertTrue(passedObjs.size() == 1);
    assertTrue("A Farmer was passed in.", Farmer.class.equals(passedObjs.get(0).getClass()));
    try {
        // reset the reader
        when(content.getReader()).thenReturn(new StringReader(JsonJacksonTests.FARMER_JSON));
        templateVars.put(ResourceLocator.RELATIONSHIP_ID, "45678");
        params = extractor.extractParams(mockRelationship(), request);
        fail("Should not get here.");
    } catch (UnsupportedResourceOperationException iae) {
        // Must throw this exception
        assertNotNull("POSTING to a relationship collection by id is not correct.", iae);
    }
    templateVars.clear();
    // reset the reader
    when(content.getReader()).thenReturn(new StringReader(JsonJacksonTests.FARMER_JSON));
    templateVars.put(ResourceLocator.ENTITY_ID, "1234");
    templateVars.put(ResourceLocator.RELATIONSHIP_ID, "codfish");
    try {
        // POST does not support addressed parameters.
        params = extractor.extractParams(mockEntity(), request);
        fail("Should not get here.");
    } catch (UnsupportedResourceOperationException uoe) {
        // Must throw this exception
        assertNotNull(uoe);
    }
    testExtractOperationParams(templateVars, request, extractor);
    templateVars.clear();
    Method aMethod = ResourceInspector.findMethod(EntityResourceAction.Create.class, GrassEntityResource.class);
    ResourceOperation op = ResourceInspector.inspectOperation(GrassEntityResource.class, aMethod, HttpMethod.POST);
    List<ResourceMetadata> metainfo = ResourceInspector.inspect(GrassEntityResource.class);
    assertNotNull(op);
    assertTrue("Create method should have two params", op.getParameters().size() == 2);
    ResourceParameter singleParam = op.getParameters().get(0);
    assertTrue(ResourceParameter.KIND.HTTP_BODY_OBJECT.equals(singleParam.getParamType()));
    assertFalse("Create grass does not support multiple grass creations", singleParam.isAllowMultiple());
    assertFalse(singleParam.isRequired());
    // Test context when the request body is null and 'required' webApiParam is false
    when(request.getHeader("content-length")).thenReturn("0");
    params = extractor.extractParams(metainfo.get(0), request);
    assertNotNull(params);
    // Test context when the request body is provided and 'required' property is false
    when(content.getReader()).thenReturn(new StringReader(JsonJacksonTests.GRASS_JSON));
    params = extractor.extractParams(metainfo.get(0), request);
    assertNotNull(params);
}
Also used : WebScriptRequest(org.springframework.extensions.webscripts.WebScriptRequest) EntityResourceAction(org.alfresco.rest.framework.resource.actions.interfaces.EntityResourceAction) HashMap(java.util.HashMap) UnsupportedResourceOperationException(org.alfresco.rest.framework.core.exceptions.UnsupportedResourceOperationException) Params(org.alfresco.rest.framework.resource.parameters.Params) Method(java.lang.reflect.Method) HttpMethod(org.springframework.http.HttpMethod) ResourceMetadata(org.alfresco.rest.framework.core.ResourceMetadata) Match(org.springframework.extensions.webscripts.Match) ResourceWebScriptPost(org.alfresco.rest.framework.webscripts.ResourceWebScriptPost) ResourceParameter(org.alfresco.rest.framework.core.ResourceParameter) Content(org.springframework.extensions.surf.util.Content) StringReader(java.io.StringReader) List(java.util.List) Farmer(org.alfresco.rest.framework.tests.api.mocks.Farmer) ResourceOperation(org.alfresco.rest.framework.core.ResourceOperation) Test(org.junit.Test)

Example 2 with Content

use of org.springframework.extensions.surf.util.Content in project alfresco-remote-api by Alfresco.

the class ParamsExtractorTests method testSpecialChars.

@Test
public void testSpecialChars() throws IOException {
    String specialChars = new String(new char[] { (char) '香' }) + " 香蕉";
    ResourceWebScriptPost extractor = new ResourceWebScriptPost();
    extractor.setAssistant(assistant);
    Map<String, String> templateVars = new HashMap<String, String>();
    String mockMe = "{\"name\":\"" + specialChars + "\",\"created\":\"2012-03-23T15:56:18.552+0000\",\"age\":54,\"id\":\"1234A3\",\"farm\":\"LARGE\"}";
    Content content = mock(Content.class);
    when(content.getReader()).thenReturn(new StringReader(mockMe));
    WebScriptRequest request = mock(WebScriptRequest.class);
    when(request.getServiceMatch()).thenReturn(new Match(null, templateVars, null));
    when(request.getContent()).thenReturn(content);
    Params params = extractor.extractParams(mockEntity(), request);
    assertNotNull(params);
    Object passed = params.getPassedIn();
    assertTrue(List.class.isAssignableFrom(passed.getClass()));
    @SuppressWarnings("unchecked") List<Object> passedObjs = (List<Object>) passed;
    assertTrue(passedObjs.size() == 1);
    assertTrue("A Farmer was passed in.", Farmer.class.equals(passedObjs.get(0).getClass()));
    Farmer f = (Farmer) passedObjs.get(0);
    assertTrue(f.getName().equals("香 香蕉"));
    // Test passing in special characters as a param.
    ResourceWebScriptGet getExtractor = new ResourceWebScriptGet();
    getExtractor.setAssistant(assistant);
    Map<String, String> getTemplateVars = new HashMap<String, String>();
    WebScriptRequest getRequest = mock(WebScriptRequest.class);
    when(getRequest.getServiceMatch()).thenReturn(new Match(null, getTemplateVars, null));
    when(getRequest.getParameterNames()).thenReturn(new String[] { "aParam" });
    when(getRequest.getParameterValues("aParam")).thenReturn(new String[] { specialChars });
    Params pGet = getExtractor.extractParams(mockEntity(), getRequest);
    assertNotNull(pGet);
    String pVal = pGet.getParameter("aParam");
    assertTrue(pVal.equals("香 香蕉"));
}
Also used : WebScriptRequest(org.springframework.extensions.webscripts.WebScriptRequest) ResourceWebScriptGet(org.alfresco.rest.framework.webscripts.ResourceWebScriptGet) HashMap(java.util.HashMap) Params(org.alfresco.rest.framework.resource.parameters.Params) Match(org.springframework.extensions.webscripts.Match) ResourceWebScriptPost(org.alfresco.rest.framework.webscripts.ResourceWebScriptPost) Content(org.springframework.extensions.surf.util.Content) StringReader(java.io.StringReader) List(java.util.List) Farmer(org.alfresco.rest.framework.tests.api.mocks.Farmer) Test(org.junit.Test)

Example 3 with Content

use of org.springframework.extensions.surf.util.Content in project alfresco-remote-api by Alfresco.

the class AclsReadersGet method buildModel.

private Map<String, Object> buildModel(WebScriptRequest req) throws JSONException, IOException {
    List<Long> aclIds = null;
    Content content = req.getContent();
    if (content == null) {
        throw new WebScriptException("Request content is empty");
    }
    JSONObject o = new JSONObject(content.getContent());
    JSONArray aclIdsJSON = o.has("aclIds") ? o.getJSONArray("aclIds") : null;
    if (aclIdsJSON == null) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter 'aclIds' not provided in request content.");
    } else if (aclIdsJSON.length() == 0) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Parameter 'aclIds' must hold from 1 or more IDs.");
    }
    aclIds = new ArrayList<Long>(aclIdsJSON.length());
    for (int i = 0; i < aclIdsJSON.length(); i++) {
        aclIds.add(aclIdsJSON.getLong(i));
    }
    // Request according to the paging query style required
    List<AclReaders> aclsReaders = solrTrackingComponent.getAclsReaders(aclIds);
    Map<String, Object> model = new HashMap<String, Object>(1, 1.0f);
    model.put("aclsReaders", aclsReaders);
    if (logger.isDebugEnabled()) {
        logger.debug("Result: \n\tRequest: " + req + "\n\tModel: " + model);
    }
    return model;
}
Also used : HashMap(java.util.HashMap) JSONArray(org.json.JSONArray) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) JSONObject(org.json.JSONObject) Content(org.springframework.extensions.surf.util.Content) JSONObject(org.json.JSONObject) AclReaders(org.alfresco.repo.solr.AclReaders)

Example 4 with Content

use of org.springframework.extensions.surf.util.Content in project records-management by Alfresco.

the class WebScriptUtils method getRequestContentAsJSONObject.

/**
 * Gets the request content as JSON object
 *
 * @param req The webscript request
 * @return The request content as JSON object
 */
public static JSONObject getRequestContentAsJSONObject(WebScriptRequest req) {
    mandatory("req", req);
    Content reqContent = req.getContent();
    if (reqContent == null) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Missing request body.");
    }
    String content;
    try {
        content = reqContent.getContent();
    } catch (IOException error) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Could not get content from the request.", error);
    }
    if (isBlank(content)) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Content does not exist.");
    }
    JSONTokener jsonTokener = new JSONTokener(content);
    JSONObject json;
    try {
        json = new JSONObject(jsonTokener);
    } catch (JSONException error) {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Unable to parse request body.", error);
    }
    return json;
}
Also used : JSONTokener(org.json.JSONTokener) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) JSONObject(org.json.JSONObject) Content(org.springframework.extensions.surf.util.Content) JSONException(org.json.JSONException) ParameterCheck.mandatoryString(org.alfresco.util.ParameterCheck.mandatoryString) IOException(java.io.IOException)

Example 5 with Content

use of org.springframework.extensions.surf.util.Content in project records-management by Alfresco.

the class BaseWebScriptUnitTest method getMockedWebScriptRequest.

/**
 * Helper method to get the mocked web script request.
 *
 * @param webScript                 declarative web script
 * @param parameters                web script parameter values
 * @return {@link WebScriptRequest} mocked web script request
 */
@SuppressWarnings("rawtypes")
protected WebScriptRequest getMockedWebScriptRequest(AbstractWebScript webScript, final Map<String, String> parameters, String content) throws Exception {
    Match match = new Match(null, parameters, null, webScript);
    org.springframework.extensions.webscripts.Runtime mockedRuntime = mock(org.springframework.extensions.webscripts.Runtime.class);
    WebScriptRequest mockedRequest = mock(WebScriptRequest.class);
    doReturn(match).when(mockedRequest).getServiceMatch();
    doReturn(mockedRuntime).when(mockedRequest).getRuntime();
    if (content != null && !content.isEmpty()) {
        Content mockedContent = mock(Content.class);
        doReturn(content).when(mockedContent).getContent();
        doReturn(mockedContent).when(mockedRequest).getContent();
    }
    String[] paramNames = (String[]) parameters.keySet().toArray(new String[parameters.size()]);
    doReturn(paramNames).when(mockedRequest).getParameterNames();
    doAnswer(new Answer() {

        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            String paramName = (String) invocation.getArguments()[0];
            return parameters.get(paramName);
        }
    }).when(mockedRequest).getParameter(anyString());
    doReturn(new String[0]).when(mockedRequest).getHeaderNames();
    doReturn("json").when(mockedRequest).getFormat();
    return mockedRequest;
}
Also used : WebScriptRequest(org.springframework.extensions.webscripts.WebScriptRequest) Matchers.anyString(org.mockito.Matchers.anyString) Match(org.springframework.extensions.webscripts.Match) Answer(org.mockito.stubbing.Answer) Mockito.doAnswer(org.mockito.Mockito.doAnswer) Content(org.springframework.extensions.surf.util.Content) InvocationOnMock(org.mockito.invocation.InvocationOnMock) JSONObject(org.json.JSONObject)

Aggregations

Content (org.springframework.extensions.surf.util.Content)17 HashMap (java.util.HashMap)10 JSONObject (org.json.JSONObject)10 WebScriptException (org.springframework.extensions.webscripts.WebScriptException)9 IOException (java.io.IOException)7 JSONArray (org.json.JSONArray)6 JSONException (org.json.JSONException)6 WebScriptRequest (org.springframework.extensions.webscripts.WebScriptRequest)6 StringReader (java.io.StringReader)5 QName (org.alfresco.service.namespace.QName)4 Match (org.springframework.extensions.webscripts.Match)3 List (java.util.List)2 Params (org.alfresco.rest.framework.resource.parameters.Params)2 Farmer (org.alfresco.rest.framework.tests.api.mocks.Farmer)2 ResourceWebScriptPost (org.alfresco.rest.framework.webscripts.ResourceWebScriptPost)2 NodeRef (org.alfresco.service.cmr.repository.NodeRef)2 Test (org.junit.Test)2 BufferedReader (java.io.BufferedReader)1 InputStream (java.io.InputStream)1 InputStreamReader (java.io.InputStreamReader)1