Search in sources :

Example 21 with WebScriptRequest

use of org.springframework.extensions.webscripts.WebScriptRequest in project alfresco-remote-api by Alfresco.

the class ParamsExtractorTests method testMultiPartPostExtractor.

@Test
public void testMultiPartPostExtractor() throws Exception {
    ResourceWebScriptPost extractor = new ResourceWebScriptPost();
    extractor.setAssistant(assistant);
    Map<String, String> templateVars = new HashMap<String, String>();
    WebScriptRequest request = mock(WebScriptRequest.class);
    when(request.getServiceMatch()).thenReturn(new Match(null, templateVars, null));
    File file = TempFileProvider.createTempFile("ParamsExtractorTests-", ".txt");
    PrintWriter writer = new PrintWriter(file);
    writer.println("Multipart Mock test.");
    writer.close();
    MultiPartRequest reqBody = MultiPartBuilder.create().setFileData(new FileData(file.getName(), file, MimetypeMap.MIMETYPE_TEXT_PLAIN)).build();
    MockHttpServletRequest mockRequest = new MockHttpServletRequest("POST", "");
    mockRequest.setContent(reqBody.getBody());
    mockRequest.setContentType(reqBody.getContentType());
    when(request.getContentType()).thenReturn("multipart/form-data");
    when(request.parseContent()).thenReturn(new FormData(mockRequest));
    Params params = extractor.extractParams(mockEntity(), request);
    assertNotNull(params);
    Object passed = params.getPassedIn();
    assertNotNull(passed);
    assertTrue(FormData.class.isAssignableFrom(passed.getClass()));
    FormData formData = (FormData) passed;
    assertTrue(formData.getIsMultiPart());
    // 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) {
        assertNotNull(uoe);
    }
    params = extractor.extractParams(mockRelationship(), request);
    assertNotNull(params);
    assertEquals("1234", params.getEntityId());
    passed = params.getPassedIn();
    assertNotNull(passed);
    assertTrue(FormData.class.isAssignableFrom(passed.getClass()));
    formData = (FormData) passed;
    assertTrue(formData.getIsMultiPart());
}
Also used : WebScriptRequest(org.springframework.extensions.webscripts.WebScriptRequest) FormData(org.springframework.extensions.webscripts.servlet.FormData) HashMap(java.util.HashMap) UnsupportedResourceOperationException(org.alfresco.rest.framework.core.exceptions.UnsupportedResourceOperationException) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) Params(org.alfresco.rest.framework.resource.parameters.Params) MultiPartRequest(org.alfresco.rest.api.tests.util.MultiPartBuilder.MultiPartRequest) Match(org.springframework.extensions.webscripts.Match) ResourceWebScriptPost(org.alfresco.rest.framework.webscripts.ResourceWebScriptPost) File(java.io.File) FileData(org.alfresco.rest.api.tests.util.MultiPartBuilder.FileData) PrintWriter(java.io.PrintWriter) Test(org.junit.Test)

Example 22 with WebScriptRequest

use of org.springframework.extensions.webscripts.WebScriptRequest in project alfresco-remote-api by Alfresco.

the class ParamsExtractorTests method testPutExtractor.

@Test
public void testPutExtractor() throws IOException {
    // Put together the stubs
    ResourceWebScriptPut extractor = new ResourceWebScriptPut();
    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);
    when(request.getContentType()).thenReturn("application/pdf; charset=UTF-16BE");
    Params params = null;
    try {
        params = extractor.extractParams(mockEntity(), request);
        fail("Should not get here. PUT is executed against the instance URL");
    } catch (UnsupportedResourceOperationException uoe) {
        // Must throw this exception
        assertNotNull(uoe);
    }
    templateVars.put(ResourceLocator.ENTITY_ID, "1234");
    try {
        params = extractor.extractParams(mockRelationship(), request);
        fail("Should not get here. PUT is executed against the instance URL");
    } catch (UnsupportedResourceOperationException uoe) {
        // Must throw this exception
        assertNotNull(uoe);
    }
    templateVars.put(ResourceLocator.ENTITY_ID, "1234");
    // Put single entity wrapped in array
    params = extractor.extractParams(mockEntity(), request);
    assertNotNull(params);
    Object passed = params.getPassedIn();
    assertNotNull(passed);
    assertTrue("A Farmer was passed in.", Farmer.class.equals(passed.getClass()));
    assertNotNull(params.getFilter());
    assertTrue("Default filter is BeanPropertiesFilter.AllProperties", BeanPropertiesFilter.AllProperties.class.equals(params.getFilter().getClass()));
    // reset the reader
    when(content.getReader()).thenReturn(new StringReader(JsonJacksonTests.FARMER_JSON));
    params = extractor.extractParams(mockEntity(), request);
    assertNotNull(params);
    assertEquals("1234", params.getEntityId());
    passed = params.getPassedIn();
    assertNotNull(passed);
    // reset the reader
    when(content.getReader()).thenReturn(new StringReader(JsonJacksonTests.FARMER_JSON));
    templateVars.put(ResourceLocator.RELATIONSHIP_ID, "67890");
    params = extractor.extractParams(mockRelationship(), request);
    assertNotNull(params);
    assertEquals("1234", params.getEntityId());
    passed = params.getPassedIn();
    assertNotNull(passed);
    assertTrue("A Farmer was passed in.", Farmer.class.equals(passed.getClass()));
    Farmer aFarmer = (Farmer) passed;
    assertEquals("Relationship id should be automatically set on the object passed in.", aFarmer.getId(), "67890");
    // reset the reader
    when(content.getReader()).thenReturn(new StringReader(JsonJacksonTests.FARMER_JSON));
    params = testExtractAddressedParams(templateVars, request, extractor);
    assertEquals("UTF-16BE", params.getContentInfo().getEncoding());
    assertEquals(MimetypeMap.MIMETYPE_PDF, params.getContentInfo().getMimeType());
}
Also used : WebScriptRequest(org.springframework.extensions.webscripts.WebScriptRequest) HashMap(java.util.HashMap) UnsupportedResourceOperationException(org.alfresco.rest.framework.core.exceptions.UnsupportedResourceOperationException) Params(org.alfresco.rest.framework.resource.parameters.Params) Match(org.springframework.extensions.webscripts.Match) Content(org.springframework.extensions.surf.util.Content) StringReader(java.io.StringReader) ResourceWebScriptPut(org.alfresco.rest.framework.webscripts.ResourceWebScriptPut) Farmer(org.alfresco.rest.framework.tests.api.mocks.Farmer) Test(org.junit.Test)

Example 23 with WebScriptRequest

use of org.springframework.extensions.webscripts.WebScriptRequest in project records-management by Alfresco.

the class ImportPost method executeImpl.

@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
    // Unwrap to a WebScriptServletRequest if we have one
    WebScriptServletRequest webScriptServletRequest = null;
    WebScriptRequest current = req;
    do {
        if (current instanceof WebScriptServletRequest) {
            webScriptServletRequest = (WebScriptServletRequest) current;
            current = null;
        } else if (current instanceof WrappingWebScriptRequest) {
            current = ((WrappingWebScriptRequest) req).getNext();
        } else {
            current = null;
        }
    } while (current != null);
    // get the content type of request and ensure it's multipart/form-data
    String contentType = req.getContentType();
    if (MULTIPART_FORMDATA.equals(contentType) && webScriptServletRequest != null) {
        String nodeRef = req.getParameter(PARAM_DESTINATION);
        if (nodeRef == null || nodeRef.length() == 0) {
            throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Mandatory 'destination' parameter was not provided in form data");
        }
        // create and check noderef
        final NodeRef destination = new NodeRef(nodeRef);
        if (nodeService.exists(destination)) {
            // check the destination is an RM container
            if (!nodeService.hasAspect(destination, RecordsManagementModel.ASPECT_FILE_PLAN_COMPONENT) || !dictionaryService.isSubClass(nodeService.getType(destination), ContentModel.TYPE_FOLDER)) {
                throw new WebScriptException(Status.STATUS_BAD_REQUEST, "NodeRef '" + destination + "' does not represent an Records Management container node.");
            }
        } else {
            status.setCode(HttpServletResponse.SC_NOT_FOUND, "NodeRef '" + destination + "' does not exist.");
        }
        // as there is no 'import capability' and the RM admin user is different from
        // the DM admin user (meaning the webscript 'admin' authentication can't be used)
        // perform a manual check here to ensure the current user has the RM admin role.
        boolean isAdmin = filePlanRoleService.hasRMAdminRole(filePlanService.getFilePlan(destination), AuthenticationUtil.getRunAsUser());
        if (!isAdmin) {
            throw new WebScriptException(Status.STATUS_FORBIDDEN, "Access Denied");
        }
        File acpFile = null;
        try {
            // create a temporary file representing uploaded ACP file
            FormField acpContent = webScriptServletRequest.getFileField(PARAM_ARCHIVE);
            if (acpContent == null) {
                acpContent = webScriptServletRequest.getFileField(PARAM_FILEDATA);
                if (acpContent == null) {
                    throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Mandatory 'archive' file content was not provided in form data");
                }
            }
            acpFile = TempFileProvider.createTempFile(TEMP_FILE_PREFIX, "." + ACPExportPackageHandler.ACP_EXTENSION);
            // copy contents of uploaded file to temp ACP file
            FileOutputStream fos = new FileOutputStream(acpFile);
            // NOTE: this method closes both streams
            FileCopyUtils.copy(acpContent.getInputStream(), fos);
            if (logger.isDebugEnabled()) {
                logger.debug("Importing uploaded ACP (" + acpFile.getAbsolutePath() + ") into " + nodeRef);
            }
            // setup the import handler
            final ACPImportPackageHandler importHandler = new ACPImportPackageHandler(acpFile, "UTF-8");
            // import the ACP file as the system user
            AuthenticationUtil.runAs(new RunAsWork<NodeRef>() {

                public NodeRef doWork() {
                    importerService.importView(importHandler, new Location(destination), null, null);
                    return null;
                }
            }, AuthenticationUtil.getSystemUserName());
            // create and return model
            Map<String, Object> model = new HashMap<String, Object>(1);
            model.put("success", true);
            return model;
        } catch (FileNotFoundException fnfe) {
            throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, "Failed to import ACP file", fnfe);
        } catch (IOException ioe) {
            throw new WebScriptException(Status.STATUS_INTERNAL_SERVER_ERROR, "Failed to import ACP file", ioe);
        } finally {
            if (acpFile != null) {
                acpFile.delete();
            }
        }
    } else {
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Request is not " + MULTIPART_FORMDATA + " encoded");
    }
}
Also used : WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest) WebScriptRequest(org.springframework.extensions.webscripts.WebScriptRequest) HashMap(java.util.HashMap) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ACPImportPackageHandler(org.alfresco.repo.importer.ACPImportPackageHandler) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) FileOutputStream(java.io.FileOutputStream) WebScriptServletRequest(org.springframework.extensions.webscripts.servlet.WebScriptServletRequest) File(java.io.File) FormField(org.springframework.extensions.webscripts.servlet.FormData.FormField) Location(org.alfresco.service.cmr.view.Location)

Aggregations

WebScriptRequest (org.springframework.extensions.webscripts.WebScriptRequest)23 WrappingWebScriptRequest (org.springframework.extensions.webscripts.WrappingWebScriptRequest)10 WebScriptServletRequest (org.springframework.extensions.webscripts.servlet.WebScriptServletRequest)9 HashMap (java.util.HashMap)8 HttpServletRequest (javax.servlet.http.HttpServletRequest)8 Test (org.junit.Test)8 Match (org.springframework.extensions.webscripts.Match)8 Params (org.alfresco.rest.framework.resource.parameters.Params)7 TransferException (org.alfresco.service.cmr.transfer.TransferException)7 Content (org.springframework.extensions.surf.util.Content)6 StringReader (java.io.StringReader)5 Matchers.anyString (org.mockito.Matchers.anyString)4 StringWriter (java.io.StringWriter)3 List (java.util.List)3 UnsupportedResourceOperationException (org.alfresco.rest.framework.core.exceptions.UnsupportedResourceOperationException)3 Farmer (org.alfresco.rest.framework.tests.api.mocks.Farmer)3 ResourceWebScriptPost (org.alfresco.rest.framework.webscripts.ResourceWebScriptPost)3 InvocationOnMock (org.mockito.invocation.InvocationOnMock)3 JSONWriter (org.springframework.extensions.webscripts.json.JSONWriter)3 File (java.io.File)2