use of org.springframework.extensions.webscripts.WebScriptException in project alfresco-remote-api by Alfresco.
the class NodeContentGet method execute.
/**
* @param req WebScriptRequest
* @param res WebScriptResponse
* @throws IOException
*/
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
ContentReader textReader = null;
Exception transformException = null;
String nodeIDString = req.getParameter("nodeId");
if (nodeIDString == null) {
throw new WebScriptException("nodeID parameter is required for GetNodeContent");
}
long nodeId = Long.valueOf(nodeIDString).longValue();
String propertyQName = req.getParameter("propertyQName");
QName propertyName = null;
if (propertyQName == null) {
propertyName = ContentModel.PROP_CONTENT;
} else {
propertyName = QName.createQName(propertyQName);
}
Pair<Long, NodeRef> pair = nodeDAO.getNodePair(nodeId);
if (pair == null) {
// If the node does not exists we treat it as if it has no content
// We could be trying to update the content of a node in the index that has been deleted.
res.setStatus(HttpStatus.SC_NO_CONTENT);
return;
}
NodeRef nodeRef = pair.getSecond();
// check If-Modified-Since header and set Last-Modified header as appropriate
Date modified = (Date) nodeService.getProperty(nodeRef, ContentModel.PROP_MODIFIED);
// May be null - if so treat as just changed
if (modified == null) {
modified = new Date();
}
long modifiedSince = -1;
String modifiedSinceStr = req.getHeader("If-Modified-Since");
if (modifiedSinceStr != null) {
try {
modifiedSince = dateFormat.parse(modifiedSinceStr).getTime();
} catch (Throwable e) {
if (logger.isWarnEnabled()) {
logger.warn("Browser sent badly-formatted If-Modified-Since header: " + modifiedSinceStr);
}
}
if (modifiedSince > 0L) {
// round the date to the ignore millisecond value which is not supplied by header
long modDate = (modified.getTime() / 1000L) * 1000L;
if (modDate <= modifiedSince) {
res.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
return;
}
}
}
ContentReader reader = contentService.getReader(nodeRef, propertyName);
if (reader == null) {
res.setStatus(HttpStatus.SC_NO_CONTENT);
return;
}
try {
// get the transformer
TransformationOptions options = new TransformationOptions();
options.setUse("index");
options.setSourceNodeRef(nodeRef);
transformerDebug.pushAvailable(reader.getContentUrl(), reader.getMimetype(), MimetypeMap.MIMETYPE_TEXT_PLAIN, options);
long sourceSize = reader.getSize();
List<ContentTransformer> transformers = contentService.getActiveTransformers(reader.getMimetype(), sourceSize, MimetypeMap.MIMETYPE_TEXT_PLAIN, options);
transformerDebug.availableTransformers(transformers, sourceSize, options, "SolrIndexer");
if (transformers.isEmpty()) {
res.setHeader(TRANSFORM_STATUS_HEADER, "noTransform");
res.setStatus(HttpStatus.SC_NO_CONTENT);
return;
}
ContentTransformer transformer = transformers.get(0);
// Perform transformation catering for mimetype AND encoding
ContentWriter writer = contentService.getTempWriter();
writer.setMimetype(MimetypeMap.MIMETYPE_TEXT_PLAIN);
// Expect transformers to produce UTF-8
writer.setEncoding("UTF-8");
try {
long start = System.currentTimeMillis();
transformer.transform(reader, writer, options);
long transformDuration = System.currentTimeMillis() - start;
res.setHeader(TRANSFORM_DURATION_HEADER, String.valueOf(transformDuration));
} catch (ContentIOException | UnsupportedTransformationException e) {
transformException = e;
}
if (transformException == null) {
// point the reader to the new-written content
textReader = writer.getReader();
// Check that the reader is a view onto something concrete
if (textReader == null || !textReader.exists()) {
transformException = new ContentIOException("The transformation did not write any content, yet: \n" + " transformer: " + transformer + "\n" + " temp writer: " + writer);
}
}
if (transformException != null) {
res.setHeader(TRANSFORM_STATUS_HEADER, "transformFailed");
res.setHeader(TRANSFORM_EXCEPTION_HEADER, transformException.getMessage());
res.setStatus(HttpStatus.SC_NO_CONTENT);
} else {
res.setStatus(HttpStatus.SC_OK);
streamContentImpl(req, res, textReader, null, null, false, modified, String.valueOf(modified.getTime()), null, null);
}
} finally {
transformerDebug.popAvailable();
}
}
use of org.springframework.extensions.webscripts.WebScriptException 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.WebScriptException in project alfresco-remote-api by Alfresco.
the class KeywordSearch method search.
/**
* Execute the search
*/
private SearchResult search(String searchTerms, int startPage, int itemsPerPage, Locale locale, WebScriptRequest req) {
SearchResult searchResult = null;
ResultSet results = null;
try {
// construct search statement
String[] terms = searchTerms.split(" ");
searchTerms = searchTerms.replaceAll("\"", """);
// Escape special characters in the terms, so that they can't confuse the parser
for (int i = 0; i < terms.length; i++) {
terms[i] = SearchLanguageConversion.escapeLuceneQuery(terms[i]);
}
Map<String, Object> statementModel = new HashMap<String, Object>(7, 1.0f);
statementModel.put("args", createArgs(req));
statementModel.put("terms", terms);
Writer queryWriter = new StringWriter(1024);
renderFormatTemplate(QUERY_FORMAT, statementModel, queryWriter);
String query = queryWriter.toString();
// execute query
if (logger.isDebugEnabled()) {
logger.debug("Search parameters: searchTerms=" + searchTerms + ", startPage=" + startPage + ", itemsPerPage=" + itemsPerPage + ", search locale=" + locale.toString());
logger.debug("Issuing lucene search: " + query);
}
SearchParameters parameters = new SearchParameters();
parameters.addStore(SEARCH_STORE);
parameters.setLanguage(SearchService.LANGUAGE_LUCENE);
parameters.setQuery(query);
if (locale != null) {
parameters.addLocale(locale);
}
results = searchService.query(parameters);
int totalResults = results.length();
if (logger.isDebugEnabled())
logger.debug("Results: " + totalResults + " rows (limited: " + results.getResultSetMetaData().getLimitedBy() + ")");
// are we out-of-range
int totalPages = (totalResults / itemsPerPage);
totalPages += (totalResults % itemsPerPage != 0) ? 1 : 0;
if (totalPages != 0 && (startPage < 1 || startPage > totalPages)) {
throw new WebScriptException("Start page " + startPage + " is outside boundary of " + totalPages + " pages");
}
// construct search result
searchResult = new SearchResult();
searchResult.setSearchTerms(searchTerms);
searchResult.setLocale(locale);
searchResult.setItemsPerPage(itemsPerPage);
searchResult.setStartPage(startPage);
searchResult.setTotalResults(totalResults);
if (totalResults == 0) {
searchResult.setTotalPages(0);
searchResult.setStartIndex(0);
searchResult.setTotalPageItems(0);
} else {
searchResult.setTotalPages(totalPages);
searchResult.setStartIndex(((startPage - 1) * itemsPerPage) + 1);
searchResult.setTotalPageItems(Math.min(itemsPerPage, totalResults - searchResult.getStartIndex() + 1));
}
SearchTemplateNode[] nodes = new SearchTemplateNode[searchResult.getTotalPageItems()];
for (int i = 0; i < searchResult.getTotalPageItems(); i++) {
NodeRef node = results.getNodeRef(i + searchResult.getStartIndex() - 1);
// Make the search resilient to invalid nodes
if (!nodeService.exists(node)) {
continue;
}
float score = results.getScore(i + searchResult.getStartIndex() - 1);
nodes[i] = new SearchTemplateNode(node, score);
}
searchResult.setResults(nodes);
return searchResult;
} finally {
if (results != null) {
results.close();
}
}
}
use of org.springframework.extensions.webscripts.WebScriptException in project alfresco-remote-api by Alfresco.
the class SearchProxy method execute.
/* (non-Javadoc)
* @see org.alfresco.web.scripts.WebScript#execute(org.alfresco.web.scripts.WebScriptRequest, org.alfresco.web.scripts.WebScriptResponse)
*/
public void execute(WebScriptRequest req, WebScriptResponse res) throws IOException {
String extensionPath = req.getExtensionPath();
String[] extensionPaths = extensionPath.split("/");
if (extensionPaths.length != 2) {
throw new WebScriptException("OpenSearch engine has not been specified as /{engine}/{format}");
}
// retrieve search engine configuration
String engine = extensionPaths[0];
EngineConfig engineConfig = searchConfig.getEngine(engine);
if (engineConfig == null) {
throw new WebScriptException("OpenSearch engine '" + engine + "' does not exist");
}
// retrieve engine url as specified by format
String format = extensionPaths[1];
String mimetype = formatRegistry.getMimeType(null, format);
if (mimetype == null) {
throw new WebScriptException("Format '" + format + "' does not map to a registered mimetype");
}
Map<String, String> engineUrls = engineConfig.getUrls();
String engineUrl = engineUrls.get(mimetype);
if (engineUrl == null) {
throw new WebScriptException("Url mimetype '" + mimetype + "' does not exist for engine '" + engine + "'");
}
// replace template url arguments with actual arguments specified on request
int engineUrlArgIdx = engineUrl.indexOf("?");
if (engineUrlArgIdx != -1) {
engineUrl = engineUrl.substring(0, engineUrlArgIdx);
}
if (req.getQueryString() != null) {
engineUrl += "?" + req.getQueryString();
}
if (logger.isDebugEnabled())
logger.debug("Mapping engine '" + engine + "' (mimetype '" + mimetype + "') to url '" + engineUrl + "'");
// NOTE: This web script must be executed in a HTTP servlet environment
if (!(res.getRuntime() instanceof WebScriptServletRuntime)) {
throw new WebScriptException("Search Proxy must be executed in HTTP Servlet environment");
}
HttpServletResponse servletRes = WebScriptServletRuntime.getHttpServletResponse(res);
SearchEngineHttpProxy proxy = new SearchEngineHttpProxy(req.getServerPath() + req.getServiceContextPath(), engine, engineUrl, servletRes, Collections.singletonMap("User-Agent", req.getHeader("User-Agent")));
proxy.service();
}
use of org.springframework.extensions.webscripts.WebScriptException in project alfresco-remote-api by Alfresco.
the class AbstractBlogWebScript method executeImpl.
@Override
protected Map<String, Object> executeImpl(WebScriptRequest req, Status status, Cache cache) {
Map<String, String> templateVars = req.getServiceMatch().getTemplateVars();
if (templateVars == null) {
String error = "No parameters supplied";
throw new WebScriptException(Status.STATUS_BAD_REQUEST, error);
}
// Parse the JSON, if supplied
JSONObject json = null;
String contentType = req.getContentType();
if (contentType != null && contentType.indexOf(';') != -1) {
contentType = contentType.substring(0, contentType.indexOf(';'));
}
if (MimetypeMap.MIMETYPE_JSON.equals(contentType)) {
JSONParser parser = new JSONParser();
try {
json = (JSONObject) parser.parse(req.getContent().getContent());
} catch (IOException io) {
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Invalid JSON: " + io.getMessage());
} catch (ParseException pe) {
throw new WebScriptException(Status.STATUS_BAD_REQUEST, "Invalid JSON: " + pe.getMessage());
}
}
// Did they request it by node reference or site?
NodeRef nodeRef = null;
SiteInfo site = null;
BlogPostInfo blog = null;
if (templateVars.containsKey("site")) {
// Site, and Optionally Blog Post
String siteName = templateVars.get("site");
site = siteService.getSite(siteName);
if (site == null) {
String error = "Could not find site: " + siteName;
throw new WebScriptException(Status.STATUS_NOT_FOUND, error);
}
// Did they give a blog post name too?
if (templateVars.containsKey("path")) {
String name = templateVars.get("path");
blog = blogService.getBlogPost(siteName, name);
if (blog == null) {
String error = "Could not find blog '" + name + "' for site '" + site.getShortName() + "'";
throw new WebScriptException(Status.STATUS_NOT_FOUND, error);
}
nodeRef = blog.getNodeRef();
} else {
// The NodeRef is the container (if it exists)
if (siteService.hasContainer(siteName, BlogServiceImpl.BLOG_COMPONENT)) {
nodeRef = siteService.getContainer(siteName, BlogServiceImpl.BLOG_COMPONENT);
}
}
} else if (templateVars.containsKey("store_type") && templateVars.containsKey("store_id") && templateVars.containsKey("id")) {
// NodeRef, should be a Blog Post
StoreRef store = new StoreRef(templateVars.get("store_type"), templateVars.get("store_id"));
nodeRef = new NodeRef(store, templateVars.get("id"));
if (!nodeService.exists(nodeRef)) {
String error = "Could not find node: " + nodeRef;
throw new WebScriptException(Status.STATUS_NOT_FOUND, error);
}
// Try to build the appropriate object for it
blog = blogService.getForNodeRef(nodeRef);
// See if it's actually attached to a site
if (blog != null) {
NodeRef container = blog.getContainerNodeRef();
if (container != null) {
NodeRef maybeSite = nodeService.getPrimaryParent(container).getParentRef();
if (maybeSite != null) {
// Try to make it a site, will return Null if it isn't one
site = siteService.getSite(maybeSite);
}
}
}
} else {
String error = "Unsupported template parameters found";
throw new WebScriptException(Status.STATUS_BAD_REQUEST, error);
}
// Have the real work done
return executeImpl(site, nodeRef, blog, req, json, status, cache);
}
Aggregations