Search in sources :

Example 1 with Response

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

the class RemoteFileFolderLoaderTest method testLoad_15_16bytes.

/**
 * Load 15 files; 1K size; 1 document sample; force binary storage
 */
@SuppressWarnings("unchecked")
public void testLoad_15_16bytes() throws Exception {
    JSONObject body = new JSONObject();
    body.put(FileFolderLoaderPost.KEY_FOLDER_PATH, loadHomePath);
    body.put(FileFolderLoaderPost.KEY_MIN_FILE_SIZE, 16L);
    body.put(FileFolderLoaderPost.KEY_MAX_FILE_SIZE, 16L);
    body.put(FileFolderLoaderPost.KEY_MAX_UNIQUE_DOCUMENTS, 1L);
    body.put(FileFolderLoaderPost.KEY_FORCE_BINARY_STORAGE, Boolean.TRUE);
    Response response = null;
    try {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setFullyAuthenticatedUser("maggi");
        response = sendRequest(new PostRequest(URL, body.toString(), "application/json"), Status.STATUS_OK, "maggi");
    } finally {
        AuthenticationUtil.popAuthentication();
    }
    assertEquals("{\"count\":100}", response.getContentAsString());
    // Check file(s)
    assertEquals(100, nodeService.countChildAssocs(loadHomeNodeRef, true));
    // Consistent binary text
    String contentUrlCheck = SpoofedTextContentReader.createContentUrl(Locale.ENGLISH, 0L, 16L);
    ContentReader readerCheck = new SpoofedTextContentReader(contentUrlCheck);
    String textCheck = readerCheck.getContentString();
    // Size should be default
    List<FileInfo> fileInfos = fileFolderService.list(loadHomeNodeRef);
    for (FileInfo fileInfo : fileInfos) {
        NodeRef fileNodeRef = fileInfo.getNodeRef();
        ContentReader reader = fileFolderService.getReader(fileNodeRef);
        // Expect storage in store
        assertTrue(reader.getContentUrl().startsWith(FileContentStore.STORE_PROTOCOL));
        // Check text
        String text = reader.getContentString();
        assertEquals("Text not the same.", textCheck, text);
    }
}
Also used : Response(org.springframework.extensions.webscripts.TestWebScriptServer.Response) NodeRef(org.alfresco.service.cmr.repository.NodeRef) PostRequest(org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest) JSONObject(org.json.simple.JSONObject) FileInfo(org.alfresco.service.cmr.model.FileInfo) SpoofedTextContentReader(org.alfresco.repo.content.filestore.SpoofedTextContentReader) SpoofedTextContentReader(org.alfresco.repo.content.filestore.SpoofedTextContentReader) ContentReader(org.alfresco.service.cmr.repository.ContentReader)

Example 2 with Response

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

the class RemoteFileFolderLoaderTest method testLoad_15_default.

/**
 * Load 15 files with default sizes
 */
@SuppressWarnings("unchecked")
public void testLoad_15_default() throws Exception {
    JSONObject body = new JSONObject();
    body.put(FileFolderLoaderPost.KEY_FOLDER_PATH, loadHomePath);
    body.put(FileFolderLoaderPost.KEY_FILE_COUNT, 15);
    body.put(FileFolderLoaderPost.KEY_FILES_PER_TXN, 10);
    Response response = null;
    try {
        AuthenticationUtil.pushAuthentication();
        AuthenticationUtil.setFullyAuthenticatedUser("hhoudini");
        response = sendRequest(new PostRequest(URL, body.toString(), "application/json"), Status.STATUS_OK, "hhoudini");
    } finally {
        AuthenticationUtil.popAuthentication();
    }
    assertEquals("{\"count\":15}", response.getContentAsString());
    // Check file(s)
    assertEquals(15, nodeService.countChildAssocs(loadHomeNodeRef, true));
    // Size should be default
    List<FileInfo> fileInfos = fileFolderService.list(loadHomeNodeRef);
    for (FileInfo fileInfo : fileInfos) {
        NodeRef fileNodeRef = fileInfo.getNodeRef();
        ContentReader reader = fileFolderService.getReader(fileNodeRef);
        // Expect spoofing by default
        assertTrue(reader.getContentUrl().startsWith(FileContentStore.SPOOF_PROTOCOL));
        assertTrue("Default file size not correct: " + reader, FileFolderLoaderPost.DEFAULT_MIN_FILE_SIZE < reader.getSize() && reader.getSize() < FileFolderLoaderPost.DEFAULT_MAX_FILE_SIZE);
        // Check creator
        assertEquals("hhoudini", nodeService.getProperty(fileNodeRef, ContentModel.PROP_CREATOR));
        // We also expect the default language description to be present
        String description = (String) nodeService.getProperty(fileNodeRef, ContentModel.PROP_DESCRIPTION);
        assertNotNull("No description", description);
        assertEquals("Description length incorrect: \"" + description + "\"", 128L, description.getBytes("UTF-8").length);
    }
}
Also used : Response(org.springframework.extensions.webscripts.TestWebScriptServer.Response) NodeRef(org.alfresco.service.cmr.repository.NodeRef) PostRequest(org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest) JSONObject(org.json.simple.JSONObject) FileInfo(org.alfresco.service.cmr.model.FileInfo) SpoofedTextContentReader(org.alfresco.repo.content.filestore.SpoofedTextContentReader) ContentReader(org.alfresco.service.cmr.repository.ContentReader)

Example 3 with Response

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

the class LocalWebScriptConnectorServiceImpl method executeRequest.

/**
 * Executes the specified request, and return the response
 */
public RemoteConnectorResponse executeRequest(RemoteConnectorRequest request) throws IOException, AuthenticationException, RemoteConnectorClientException, RemoteConnectorServerException {
    // Convert the request object
    RemoteConnectorRequestImpl requestImpl = (RemoteConnectorRequestImpl) request;
    Request req = new Request(request.getMethod(), request.getURL());
    req.setType(request.getContentType());
    if (request.getRequestBody() != null) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        requestImpl.getRequestBody().writeRequest(baos);
        req.setBody(baos.toByteArray());
    }
    // Log
    if (logger.isInfoEnabled())
        logger.info("Performing local " + request.getMethod() + " request to " + request.getURL());
    // Capture the user details, as they may be changed during the request processing
    Authentication fullAuth = AuthenticationUtil.getFullAuthentication();
    String runAsUser = AuthenticationUtil.getRunAsUser();
    // If they've specified Authentication details in the request, clear our security context
    // and switch to that user, to avoid our context confusing the real request
    Header authHeader = null;
    Map<String, String> headers = new HashMap<String, String>();
    for (Header header : request.getRequestHeaders()) {
        if (header.getName().equals("Authorization")) {
            authHeader = header;
        }
        headers.put(header.getName(), header.getValue());
    }
    if (authHeader != null) {
        AuthenticationUtil.clearCurrentSecurityContext();
        if (logger.isDebugEnabled())
            logger.debug("HTTP Authorization found for the request, clearing security context, Auth is " + authHeader);
    }
    req.setHeaders(headers);
    // Execute the request against the WebScript Test Framework
    Response resp;
    try {
        resp = helper.sendRequest(req, -1);
    } catch (Exception e) {
        throw new AlfrescoRuntimeException("Problem requesting", e);
    }
    // Reset the user details, now we're done performing the request
    AuthenticationUtil.setFullAuthentication(fullAuth);
    if (runAsUser != null && !runAsUser.equals(fullAuth.getName())) {
        AuthenticationUtil.setRunAsUser(runAsUser);
    }
    // Log
    if (logger.isInfoEnabled())
        logger.info("Response to request was " + resp.getStatus() + " - " + resp);
    // Check the status for specific typed exceptions
    if (resp.getStatus() == Status.STATUS_UNAUTHORIZED) {
        throw new AuthenticationException("Not Authorized to access this resource");
    }
    if (resp.getStatus() == Status.STATUS_FORBIDDEN) {
        throw new AuthenticationException("Forbidden to access this resource");
    }
    // Check for failures where we don't care about the response body
    if (resp.getStatus() >= 500 && resp.getStatus() <= 599) {
        throw new RemoteConnectorServerException(resp.getStatus(), "(not available)");
    }
    // Convert the response into our required format
    String charset = null;
    String contentType = resp.getContentType();
    if (contentType != null && contentType.contains("charset=")) {
        int splitAt = contentType.indexOf("charset=") + "charset=".length();
        charset = contentType.substring(splitAt);
    }
    InputStream body = new ByteArrayInputStream(resp.getContentAsByteArray());
    // TODO Can't easily get the list...
    Header[] respHeaders = new Header[0];
    RemoteConnectorResponse response = new RemoteConnectorResponseImpl(request, contentType, charset, resp.getStatus(), respHeaders, body);
    // If it's a client error, let them know what went wrong
    if (resp.getStatus() >= 400 && resp.getStatus() <= 499) {
        throw new RemoteConnectorClientException(resp.getStatus(), "(not available)", response);
    }
    // Otherwise return the response for processing
    return response;
}
Also used : HashMap(java.util.HashMap) AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) WebScriptServletRequest(org.springframework.extensions.webscripts.servlet.WebScriptServletRequest) RemoteConnectorRequest(org.alfresco.service.cmr.remoteconnector.RemoteConnectorRequest) Request(org.springframework.extensions.webscripts.TestWebScriptServer.Request) ByteArrayOutputStream(java.io.ByteArrayOutputStream) RemoteConnectorResponse(org.alfresco.service.cmr.remoteconnector.RemoteConnectorResponse) ParseException(org.json.simple.parser.ParseException) AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) IOException(java.io.IOException) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) RemoteConnectorClientException(org.alfresco.service.cmr.remoteconnector.RemoteConnectorClientException) RemoteConnectorServerException(org.alfresco.service.cmr.remoteconnector.RemoteConnectorServerException) Response(org.springframework.extensions.webscripts.TestWebScriptServer.Response) WebScriptServletResponse(org.springframework.extensions.webscripts.servlet.WebScriptServletResponse) RemoteConnectorResponse(org.alfresco.service.cmr.remoteconnector.RemoteConnectorResponse) RemoteConnectorClientException(org.alfresco.service.cmr.remoteconnector.RemoteConnectorClientException) Header(org.apache.commons.httpclient.Header) ByteArrayInputStream(java.io.ByteArrayInputStream) Authentication(net.sf.acegisecurity.Authentication) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException) RemoteConnectorServerException(org.alfresco.service.cmr.remoteconnector.RemoteConnectorServerException)

Example 4 with Response

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

the class DeclarativeSpreadsheetWebScriptTest method testCSVStrategy.

public void testCSVStrategy() throws Exception {
    TestWebScriptServer.GetRequest req = new TestWebScriptServer.GetRequest(URL);
    Response response = sendRequest(req, Status.STATUS_OK, admin);
    // default excel, delimiter is a comma ","
    assertEquals("The response CSV body was not correct.", "User Name,First Name,Last Name\n", response.getContentAsString());
    req = new TestWebScriptServer.GetRequest(URL + "?" + DeclarativeSpreadsheetWebScript.PARAM_REQ_DELIMITER + "=%2C");
    response = sendRequest(req, Status.STATUS_OK, admin);
    // delimiter is a comma ","
    assertEquals("The response CSV body was not correct.", "User Name,First Name,Last Name\n", response.getContentAsString());
    req = new TestWebScriptServer.GetRequest(URL + "?" + DeclarativeSpreadsheetWebScript.PARAM_REQ_DELIMITER + "=%09");
    response = sendRequest(req, Status.STATUS_OK, admin);
    // delimiter is a tab space "\t"
    assertEquals("The response CSV body was not correct.", "User Name\tFirst Name\tLast Name\n", response.getContentAsString());
    req = new TestWebScriptServer.GetRequest(URL + "?" + DeclarativeSpreadsheetWebScript.PARAM_REQ_DELIMITER + "=%3B");
    response = sendRequest(req, Status.STATUS_OK, admin);
    // delimiter is a semicolon ";"
    assertEquals("The response CSV body was not correct.", "User Name;First Name;Last Name\n", response.getContentAsString());
}
Also used : Response(org.springframework.extensions.webscripts.TestWebScriptServer.Response) TestWebScriptServer(org.springframework.extensions.webscripts.TestWebScriptServer)

Example 5 with Response

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

the class LoginTest method testAuthenticationGetJSON.

/**
 * Positive test - login and retrieve a ticket,
 * - via json method
 */
public void testAuthenticationGetJSON() throws Exception {
    /**
     * Login via get method to return json
     */
    String loginURL = "/api/login.json?u=" + USER_ONE + "&pw=" + USER_ONE;
    Response resp = sendRequest(new GetRequest(loginURL), Status.STATUS_OK);
    JSONObject result = new JSONObject(resp.getContentAsString());
    JSONObject data = result.getJSONObject("data");
    String ticket = data.getString("ticket");
    assertNotNull("ticket is null", ticket);
    /**
     * This is now testing the framework ... With a different format.
     */
    String login2URL = "/api/login?u=" + USER_ONE + "&pw=" + USER_ONE + "&format=json";
    Response resp2 = sendRequest(new GetRequest(login2URL), Status.STATUS_OK);
    JSONObject result2 = new JSONObject(resp2.getContentAsString());
    JSONObject data2 = result2.getJSONObject("data");
    String ticket2 = data2.getString("ticket");
    assertNotNull("ticket is null", ticket2);
}
Also used : Response(org.springframework.extensions.webscripts.TestWebScriptServer.Response) JSONObject(org.json.JSONObject) GetRequest(org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest)

Aggregations

Response (org.springframework.extensions.webscripts.TestWebScriptServer.Response)281 JSONObject (org.json.JSONObject)228 GetRequest (org.springframework.extensions.webscripts.TestWebScriptServer.GetRequest)171 JSONArray (org.json.JSONArray)116 PostRequest (org.springframework.extensions.webscripts.TestWebScriptServer.PostRequest)84 JSONTokener (org.json.JSONTokener)39 PutRequest (org.springframework.extensions.webscripts.TestWebScriptServer.PutRequest)37 NodeRef (org.alfresco.service.cmr.repository.NodeRef)34 DeleteRequest (org.springframework.extensions.webscripts.TestWebScriptServer.DeleteRequest)32 HashMap (java.util.HashMap)24 ArrayList (java.util.ArrayList)16 TestWebScriptServer (org.springframework.extensions.webscripts.TestWebScriptServer)16 Serializable (java.io.Serializable)14 QName (org.alfresco.service.namespace.QName)14 Date (java.util.Date)13 JSONStringer (org.json.JSONStringer)13 UserTransaction (javax.transaction.UserTransaction)12 WorkflowDefinition (org.alfresco.service.cmr.workflow.WorkflowDefinition)12 ReplicationDefinition (org.alfresco.service.cmr.replication.ReplicationDefinition)11 WorkflowPath (org.alfresco.service.cmr.workflow.WorkflowPath)11