use of org.springframework.extensions.webscripts.servlet.WebScriptServletRequest 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");
}
}
use of org.springframework.extensions.webscripts.servlet.WebScriptServletRequest in project alfresco-remote-api by Alfresco.
the class NodeBrowserPost method executeImpl.
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
Map<String, Object> result = new HashMap<>(16);
// gather inputs
Map<String, String> returnParams = new HashMap<>(16);
String store = req.getParameter("nodebrowser-store");
String searcher = req.getParameter("nodebrowser-search");
String query = req.getParameter("nodebrowser-query");
String maxResults = req.getParameter("nodebrowser-query-maxresults");
String skipCount = req.getParameter("nodebrowser-query-skipcount");
String error = null;
StoreRef storeRef = new StoreRef(store);
// always a list of assoc refs from some result
List<ChildAssociationRef> assocRefs = Collections.<ChildAssociationRef>emptyList();
NodeRef currentNode = null;
// what action should be processed?
long timeStart = System.currentTimeMillis();
String actionValue = req.getParameter("nodebrowser-action-value");
String action = req.getParameter("nodebrowser-action");
final String execute = req.getParameter("nodebrowser-execute");
final String executeValue = req.getParameter("nodebrowser-execute-value");
String message = null;
try {
// this is done before the view action to ensure node state is correct
if (execute != null) {
switch(execute) {
case "delete":
{
transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>() {
@Override
public Void execute() throws Throwable {
// delete the node using the standard NodeService
nodeService.deleteNode(new NodeRef(executeValue));
return null;
}
}, false, true);
message = "nodebrowser.message.delete";
break;
}
case "fdelete":
{
transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>() {
@Override
public Void execute() throws Throwable {
// delete the node - but ensure that it is not archived
NodeRef ref = new NodeRef(executeValue);
nodeService.addAspect(ref, ContentModel.ASPECT_TEMPORARY, null);
nodeService.deleteNode(ref);
return null;
}
}, false, true);
message = "nodebrowser.message.delete";
break;
}
case "restore":
{
transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>() {
@Override
public Void execute() throws Throwable {
nodeService.restoreNode(new NodeRef(executeValue), null, null, null);
return null;
}
}, false, true);
message = "nodebrowser.message.restore";
break;
}
case "take-ownership":
{
transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>() {
@Override
public Void execute() throws Throwable {
ownableService.takeOwnership(new NodeRef(executeValue));
return null;
}
}, false, true);
message = "nodebrowser.message.take-ownership";
break;
}
case "delete-permissions":
{
transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>() {
@Override
public Void execute() throws Throwable {
NodeRef ref = new NodeRef(executeValue);
permissionService.deletePermissions(ref);
permissionService.setInheritParentPermissions(ref, true);
return null;
}
}, false, true);
message = "nodebrowser.message.delete-permissions";
break;
}
case "delete-property":
{
transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>() {
@Override
public Void execute() throws Throwable {
// argument value contains "NodeRef|QName" packed string
String[] parts = executeValue.split("\\|");
nodeService.removeProperty(new NodeRef(parts[0]), QName.createQName(parts[1]));
return null;
}
}, false, true);
message = "nodebrowser.message.delete-property";
break;
}
case "unlock":
{
transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionCallback<Void>() {
@Override
public Void execute() throws Throwable {
NodeRef ref = new NodeRef(executeValue);
if (cociService.isCheckedOut(ref)) {
NodeRef wcRef = cociService.getWorkingCopy(ref);
if (wcRef != null) {
cociService.cancelCheckout(wcRef);
}
} else {
lockService.unlock(ref);
}
return null;
}
}, false, true);
message = "nodebrowser.message.unlock";
break;
}
}
}
// the 'actionValue' param provides context as may other parameters such as 'query'
switch(action) {
// on Execute btn press and query present, perform search
case "search":
{
if (query != null && query.trim().length() != 0) {
switch(searcher) {
case "noderef":
{
// ensure node exists - or throw error
NodeRef nodeRef = new NodeRef(query);
boolean exists = getNodeService().exists(nodeRef);
if (!exists) {
throw new AlfrescoRuntimeException("Node " + nodeRef + " does not exist.");
}
currentNode = nodeRef;
// this is not really a search for results, it is a direct node reference
// so gather the child assocs as usual and update the action value for the UI location
assocRefs = getNodeService().getChildAssocs(currentNode);
actionValue = query;
action = "parent";
break;
}
case "selectnodes":
{
List<NodeRef> nodes = getSearchService().selectNodes(getNodeService().getRootNode(storeRef), query, null, getNamespaceService(), false);
assocRefs = new ArrayList<>(nodes.size());
for (NodeRef node : nodes) {
assocRefs.add(getNodeService().getPrimaryParent(node));
}
break;
}
default:
{
// perform search
SearchParameters params = new SearchParameters();
params.setQuery(query);
params.addStore(storeRef);
params.setLanguage(searcher);
if (maxResults != null && maxResults.length() != 0) {
params.setMaxItems(Integer.parseInt(maxResults));
params.setLimit(Integer.parseInt(maxResults));
}
if (skipCount != null && skipCount.length() != 0) {
params.setSkipCount(Integer.parseInt(skipCount));
}
ResultSet rs = getSearchService().query(params);
assocRefs = rs.getChildAssocRefs();
break;
}
}
}
break;
}
case "root":
{
// iterate the properties and children of a store root node
currentNode = getNodeService().getRootNode(storeRef);
assocRefs = getNodeService().getChildAssocs(currentNode);
break;
}
case "parent":
case "children":
{
currentNode = new NodeRef(actionValue);
assocRefs = getNodeService().getChildAssocs(currentNode);
break;
}
}
// get the required information from the assocRefs list and wrap objects
List<ChildAssocRefWrapper> wrappers = new ArrayList<>(assocRefs.size());
for (ChildAssociationRef ref : assocRefs) {
wrappers.add(new ChildAssocRefWrapper(ref));
}
result.put("children", wrappers);
} catch (Throwable e) {
// empty child list on error - current node will still be null
result.put("children", new ArrayList<>(0));
error = e.getMessage();
}
// current node info if any
if (currentNode != null) {
// node info
Map<String, Object> info = new HashMap<>(8);
info.put("nodeRef", currentNode.toString());
info.put("path", getNodeService().getPath(currentNode).toPrefixString(getNamespaceService()));
info.put("type", getNodeService().getType(currentNode).toPrefixString(getNamespaceService()));
ChildAssociationRef parent = getNodeService().getPrimaryParent(currentNode);
info.put("parent", parent.getParentRef() != null ? parent.getParentRef().toString() : "");
result.put("info", info);
// node properties
result.put("properties", getProperties(currentNode));
// parents
List<ChildAssociationRef> parents = getNodeService().getParentAssocs(currentNode);
List<ChildAssociation> assocs = new ArrayList<ChildAssociation>(parents.size());
for (ChildAssociationRef ref : parents) {
assocs.add(new ChildAssociation(ref));
}
result.put("parents", assocs);
// aspects
List<Aspect> aspects = getAspects(currentNode);
result.put("aspects", aspects);
// target assocs
List<PeerAssociation> targetAssocs = getAssocs(currentNode);
result.put("assocs", targetAssocs);
// source assocs
List<PeerAssociation> sourceAssocs = getSourceAssocs(currentNode);
result.put("sourceAssocs", sourceAssocs);
// permissions
Map<String, Object> permissionInfo = new HashMap<String, Object>();
permissionInfo.put("entries", getPermissions(currentNode));
permissionInfo.put("owner", getOwnableService().getOwner(currentNode));
permissionInfo.put("inherit", getInheritPermissions(currentNode));
result.put("permissions", permissionInfo);
}
// store result in session for the resulting GET request webscript
final String resultId = GUID.generate();
HttpServletRequest request = ((WebScriptServletRequest) req).getHttpServletRequest();
HttpSession session = request.getSession();
session.putValue(resultId, result);
// return params
returnParams.put("resultId", resultId);
returnParams.put("action", action);
returnParams.put("actionValue", actionValue);
returnParams.put("query", query);
returnParams.put("store", store);
returnParams.put("searcher", searcher);
returnParams.put("maxResults", maxResults);
returnParams.put("skipCount", skipCount);
returnParams.put("in", Long.toString(System.currentTimeMillis() - timeStart));
returnParams.put("e", error);
returnParams.put("m", message);
// redirect as all admin console pages do (follow standard pattern)
// The logic to generate the navigation section and server meta-data is all tied into alfresco-common.lib.js
// which is great for writing JS based JMX surfaced pages, but not so great for Java backed WebScripts.
status.setCode(301);
status.setRedirect(true);
status.setLocation(buildUrl(req, returnParams, execute != null && execute.length() != 0 ? execute : action));
return null;
}
use of org.springframework.extensions.webscripts.servlet.WebScriptServletRequest in project alfresco-remote-api by Alfresco.
the class PrepareTransferCommandProcessor 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) {
String transferRecordId = null;
// Read the transfer id from the request
// 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);
HttpServletRequest servletRequest = webScriptServletRequest.getHttpServletRequest();
String transferId = servletRequest.getParameter("transferId");
if (transferId == null) {
logger.debug("transferId is missing");
resp.setStatus(Status.STATUS_BAD_REQUEST);
return Status.STATUS_BAD_REQUEST;
}
try {
logger.debug("prepare transferId: " + transferId);
receiver.prepare(transferId);
// return the unique transfer id (the lock id)
StringWriter stringWriter = new StringWriter(300);
JSONWriter jsonWriter = new JSONWriter(stringWriter);
jsonWriter.startObject();
jsonWriter.writeValue("transferId", transferRecordId);
jsonWriter.endObject();
String response = stringWriter.toString();
resp.setContentType("application/json");
resp.setContentEncoding("UTF-8");
int length = response.getBytes("UTF-8").length;
resp.addHeader("Content-Length", "" + length);
resp.setStatus(Status.STATUS_OK);
resp.getWriter().write(response);
logger.debug("prepared transferId: " + transferId);
return Status.STATUS_OK;
} catch (Exception ex) {
logger.debug("in exception handler", ex);
receiver.end(transferRecordId);
if (ex instanceof TransferException) {
throw (TransferException) ex;
}
throw new TransferException(MSG_CAUGHT_UNEXPECTED_EXCEPTION, ex);
}
}
use of org.springframework.extensions.webscripts.servlet.WebScriptServletRequest in project alfresco-remote-api by Alfresco.
the class ReportCommandProcessor 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) {
// Read the transfer id from the request
// 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);
HttpServletRequest servletRequest = webScriptServletRequest.getHttpServletRequest();
String transferId = servletRequest.getParameter("transferId");
if (transferId == null) {
logger.debug("transferId is missing");
resp.setStatus(Status.STATUS_BAD_REQUEST);
return Status.STATUS_BAD_REQUEST;
}
try {
OutputStream out = resp.getOutputStream();
try {
resp.setContentType("text/xml");
resp.setContentEncoding("utf-8");
BufferedInputStream br = new BufferedInputStream(receiver.getProgressMonitor().getLogInputStream(transferId));
try {
byte[] buffer = new byte[1000];
int i = br.read(buffer);
while (i > 0) {
out.write(buffer, 0, i);
i = br.read(buffer);
}
} finally {
br.close();
}
} finally {
out.flush();
out.close();
}
return Status.STATUS_OK;
} catch (TransferException ex) {
throw ex;
} catch (Exception ex) {
throw new TransferException(MSG_CAUGHT_UNEXPECTED_EXCEPTION, ex);
}
}
use of org.springframework.extensions.webscripts.servlet.WebScriptServletRequest in project alfresco-remote-api by Alfresco.
the class StatusCommandProcessor 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) {
// Read the transfer id from the request
// 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);
HttpServletRequest servletRequest = webScriptServletRequest.getHttpServletRequest();
String transferId = servletRequest.getParameter("transferId");
if (transferId == null) {
logger.debug("transferId is missing");
resp.setStatus(Status.STATUS_BAD_REQUEST);
return Status.STATUS_BAD_REQUEST;
}
try {
TransferProgress progress = receiver.getProgressMonitor().getProgress(transferId);
if (logger.isDebugEnabled()) {
logger.debug(progress);
}
JSONObject progressObject = new JSONObject();
progressObject.put("transferId", transferId);
progressObject.put("status", progress.getStatus().toString());
progressObject.put("currentPosition", progress.getCurrentPosition());
progressObject.put("endPosition", progress.getEndPosition());
if (progress.getError() != null) {
JSONObject errorObject = errorSerializer.serialize(progress.getError());
progressObject.put("error", errorObject);
}
String response = progressObject.toString();
resp.setContentType("application/json");
resp.setContentEncoding("UTF-8");
int length = response.getBytes("UTF-8").length;
resp.addHeader("Content-Length", "" + length);
resp.setStatus(Status.STATUS_OK);
resp.getWriter().write(response);
return Status.STATUS_OK;
} catch (TransferException ex) {
throw ex;
} catch (Exception ex) {
throw new TransferException(MSG_CAUGHT_UNEXPECTED_EXCEPTION, ex);
}
}
Aggregations