Search in sources :

Example 11 with WebScriptRequest

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

the class PostContentCommandProcessor method process.

/*
     * (non-Javadoc)
     * 
     * @see org.alfresco.repo.web.scripts.transfer.CommandProcessor#process(org.alfresco.web.scripts.WebScriptRequest,
     * org.alfresco.web.scripts.WebScriptResponse)
     */
public int process(WebScriptRequest req, WebScriptResponse resp) {
    logger.debug("post content start");
    // 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);
    if (webScriptServletRequest == null) {
        resp.setStatus(Status.STATUS_BAD_REQUEST);
        return Status.STATUS_BAD_REQUEST;
    }
    HttpServletRequest servletRequest = webScriptServletRequest.getHttpServletRequest();
    // Read the transfer id from the request
    String transferId = servletRequest.getParameter("transferId");
    if ((transferId == null) || !ServletFileUpload.isMultipartContent(servletRequest)) {
        resp.setStatus(Status.STATUS_BAD_REQUEST);
        return Status.STATUS_BAD_REQUEST;
    }
    try {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(servletRequest);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            if (!item.isFormField()) {
                logger.debug("got content Mime Part : " + name);
                receiver.saveContent(transferId, item.getName(), item.openStream());
            }
        }
        // WebScriptServletRequest alfRequest = (WebScriptServletRequest)req;
        // String[] names = alfRequest.getParameterNames();
        // for(String name : names)
        // {
        // FormField item = alfRequest.getFileField(name);
        // 
        // if(item != null)
        // {
        // logger.debug("got content Mime Part : " + name);
        // receiver.saveContent(transferId, item.getName(), item.getInputStream());
        // }
        // else
        // {
        // //TODO - should this be an exception?
        // logger.debug("Unable to get content for Mime Part : " + name);
        // }
        // }
        logger.debug("success");
        resp.setStatus(Status.STATUS_OK);
    } catch (Exception ex) {
        logger.debug("exception caught", ex);
        if (transferId != null) {
            logger.debug("ending transfer", ex);
            receiver.end(transferId);
        }
        if (ex instanceof TransferException) {
            throw (TransferException) ex;
        }
        throw new TransferException(MSG_CAUGHT_UNEXPECTED_EXCEPTION, ex);
    }
    resp.setStatus(Status.STATUS_OK);
    return Status.STATUS_OK;
}
Also used : WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest) WebScriptRequest(org.springframework.extensions.webscripts.WebScriptRequest) WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) TransferException(org.alfresco.service.cmr.transfer.TransferException) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) WebScriptServletRequest(org.springframework.extensions.webscripts.servlet.WebScriptServletRequest) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) TransferException(org.alfresco.service.cmr.transfer.TransferException)

Example 12 with WebScriptRequest

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

the class PostSnapshotCommandProcessor method process.

/* (non-Javadoc)
     * @see org.alfresco.repo.web.scripts.transfer.CommandProcessor#process(org.alfresco.web.scripts.WebScriptRequest, org.alfresco.web.scripts.WebScriptResponse)
     */
public int process(WebScriptRequest req, WebScriptResponse resp) {
    int result = Status.STATUS_OK;
    // 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);
    if (webScriptServletRequest == null) {
        logger.debug("bad request, not assignable from");
        resp.setStatus(Status.STATUS_BAD_REQUEST);
        return Status.STATUS_BAD_REQUEST;
    }
    // We can't use the WebScriptRequest version of getParameter, since that may cause the content stream
    // to be parsed. Get hold of the raw HttpServletRequest and work with that.
    HttpServletRequest servletRequest = webScriptServletRequest.getHttpServletRequest();
    // Read the transfer id from the request
    String transferId = servletRequest.getParameter("transferId");
    if ((transferId == null) || !ServletFileUpload.isMultipartContent(servletRequest)) {
        logger.debug("bad request, not multipart");
        resp.setStatus(Status.STATUS_BAD_REQUEST);
        return Status.STATUS_BAD_REQUEST;
    }
    try {
        logger.debug("about to upload manifest file");
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(servletRequest);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (!item.isFormField() && TransferCommons.PART_NAME_MANIFEST.equals(item.getFieldName())) {
                logger.debug("got manifest file");
                receiver.saveSnapshot(transferId, item.openStream());
            }
        }
        logger.debug("success");
        resp.setStatus(Status.STATUS_OK);
        OutputStream out = resp.getOutputStream();
        resp.setContentType("text/xml");
        resp.setContentEncoding("utf-8");
        receiver.generateRequsite(transferId, out);
        out.close();
    } catch (Exception ex) {
        logger.debug("exception caught", ex);
        if (transferId != null) {
            logger.debug("ending transfer", ex);
            receiver.end(transferId);
        }
        if (ex instanceof TransferException) {
            throw (TransferException) ex;
        }
        throw new TransferException(MSG_CAUGHT_UNEXPECTED_EXCEPTION, ex);
    }
    return result;
}
Also used : WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest) WebScriptRequest(org.springframework.extensions.webscripts.WebScriptRequest) WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) TransferException(org.alfresco.service.cmr.transfer.TransferException) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) FileItemStream(org.apache.commons.fileupload.FileItemStream) OutputStream(java.io.OutputStream) WebScriptServletRequest(org.springframework.extensions.webscripts.servlet.WebScriptServletRequest) FileItemIterator(org.apache.commons.fileupload.FileItemIterator) TransferException(org.alfresco.service.cmr.transfer.TransferException)

Example 13 with WebScriptRequest

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

the class BaseRemoteStore method execute.

/**
 * Execute the webscript based on the request parameters
 */
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
    // NOTE: This web script must be executed in a HTTP Servlet environment
    // 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);
    if (webScriptServletRequest == null) {
        throw new WebScriptException("Remote Store access must be executed in HTTP Servlet environment");
    }
    HttpServletRequest httpReq = webScriptServletRequest.getHttpServletRequest();
    // the request path for the remote store
    String extPath = req.getExtensionPath();
    // values that we need to determine
    String methodName = null;
    String store = null;
    StringBuilder pathBuilder = new StringBuilder(128);
    // tokenize the path and figure out tokenized values
    StringTokenizer tokenizer = new StringTokenizer(extPath, "/");
    if (tokenizer.hasMoreTokens()) {
        methodName = tokenizer.nextToken();
        if (tokenizer.hasMoreTokens()) {
            String el = tokenizer.nextToken();
            if (TOKEN_STORE.equals(el)) {
                // if the token is TOKEN_STORE, then the next token is the id of the store
                store = tokenizer.nextToken();
                // reset element
                el = (tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null);
            }
            while (el != null) {
                pathBuilder.append('/');
                pathBuilder.append(el);
                el = (tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null);
            }
        }
    } else {
        throw new WebScriptException("Unable to tokenize web path: " + extPath);
    }
    // if we don't have a store, check whether it came in on a request parameter
    if (store == null) {
        store = req.getParameter(REQUEST_PARAM_STORE);
        if (store == null) {
            store = this.defaultStore;
        }
        if (store == null) {
            // this means that a store was not passed in and that we also didn't have a configured store
            throw new WebScriptException("Unable to determine which store to operate against." + " A store was not specified and a default was not provided.");
        }
    }
    String path = pathBuilder.toString();
    long start = 0;
    if (logger.isDebugEnabled()) {
        logger.debug("Remote method: " + methodName.toUpperCase() + "   Store Id: " + store + "   Path: " + path);
        start = System.nanoTime();
    }
    try {
        // generate enum from string method name - so we can use a fast switch table lookup
        APIMethod method = APIMethod.valueOf(methodName.toUpperCase());
        switch(method) {
            case LASTMODIFIED:
                validatePath(path);
                lastModified(res, store, path);
                break;
            case HAS:
                validatePath(path);
                hasDocument(res, store, path);
                break;
            case GET:
                validatePath(path);
                getDocument(res, store, path);
                break;
            case LIST:
                listDocuments(res, store, path, false);
                break;
            case LISTALL:
                listDocuments(res, store, path, true);
                break;
            case LISTPATTERN:
                listDocuments(res, store, path, req.getParameter("m"));
                break;
            case CREATE:
                validatePath(path);
                if (logger.isDebugEnabled())
                    logger.debug("CREATE: content length=" + httpReq.getContentLength());
                createDocument(res, store, path, httpReq.getInputStream());
                break;
            case CREATEMULTI:
                if (logger.isDebugEnabled())
                    logger.debug("CREATEMULTI: content length=" + httpReq.getContentLength());
                createDocuments(res, store, httpReq.getInputStream());
                break;
            case UPDATE:
                validatePath(path);
                if (logger.isDebugEnabled())
                    logger.debug("UPDATE: content length=" + httpReq.getContentLength());
                updateDocument(res, store, path, httpReq.getInputStream());
                break;
            case DELETE:
                validatePath(path);
                deleteDocument(res, store, path);
                break;
        }
    } catch (IllegalArgumentException enumErr) {
        throw new WebScriptException("Unknown method specified to remote store API: " + methodName);
    } catch (IOException ioErr) {
        throw new WebScriptException("Error during remote store API: " + ioErr.getMessage());
    }
    if (logger.isDebugEnabled()) {
        long end = System.nanoTime();
        logger.debug("Time to execute method: " + (end - start) / 1000000f + "ms");
    }
}
Also used : WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest) WebScriptRequest(org.springframework.extensions.webscripts.WebScriptRequest) WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest) HttpServletRequest(javax.servlet.http.HttpServletRequest) StringTokenizer(java.util.StringTokenizer) WebScriptException(org.springframework.extensions.webscripts.WebScriptException) WebScriptServletRequest(org.springframework.extensions.webscripts.servlet.WebScriptServletRequest) IOException(java.io.IOException)

Example 14 with WebScriptRequest

use of org.springframework.extensions.webscripts.WebScriptRequest 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)

Example 15 with WebScriptRequest

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

the class CMISHttpServletRequest method getBaseRequest.

/*
	 * Recursively unwrap req if it is a WrappingWebScriptRequest
	 */
private WebScriptRequest getBaseRequest(WebScriptRequest req) {
    WebScriptRequest ret = req;
    while (ret instanceof WrappingWebScriptRequest) {
        WrappingWebScriptRequest wrapping = (WrappingWebScriptRequest) req;
        ret = wrapping.getNext();
    }
    return ret;
}
Also used : WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest) WebScriptRequest(org.springframework.extensions.webscripts.WebScriptRequest) WrappingWebScriptRequest(org.springframework.extensions.webscripts.WrappingWebScriptRequest)

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