use of org.alfresco.service.cmr.search.ResultSet in project alfresco-remote-api by Alfresco.
the class QuickShareLinksImpl method findLinks.
public CollectionWithPagingInfo<QuickShareLink> findLinks(Parameters parameters) {
checkEnabled();
String queryString = "ASPECT:\"" + QuickShareModel.ASPECT_QSHARE.toString() + "\"";
SearchParameters sp = new SearchParameters();
// note: REST API query parameter (ie. where clause filter) - not to be confused with search query ;-)
Query q = parameters.getQuery();
if (q != null) {
// filtering via "where" clause
MapBasedQueryWalker propertyWalker = new MapBasedQueryWalker(FIND_SHARED_LINKS_QUERY_PROPERTIES, null);
QueryHelper.walk(q, propertyWalker);
String sharedByUserId = propertyWalker.getProperty(PARAM_SHAREDBY, WhereClauseParser.EQUALS, String.class);
if (sharedByUserId != null) {
if (People.DEFAULT_USER.equalsIgnoreCase(sharedByUserId)) {
sharedByUserId = AuthenticationUtil.getFullyAuthenticatedUser();
}
QueryParameterDefinition qpd = new QueryParameterDefImpl(QuickShareModel.PROP_QSHARE_SHAREDBY, dictionaryService.getDataType(DataTypeDefinition.TEXT), true, sharedByUserId);
sp.addQueryParameterDefinition(qpd);
String qsharedBy = QuickShareModel.PROP_QSHARE_SHAREDBY.toPrefixString(namespaceService);
queryString += " +@" + SearchLanguageConversion.escapeLuceneQuery(qsharedBy) + ":\"${" + qsharedBy + "}\"";
}
}
sp.setLanguage(SearchService.LANGUAGE_LUCENE);
sp.setQuery(queryString);
sp.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
Paging paging = parameters.getPaging();
PagingRequest pagingRequest = Util.getPagingRequest(paging);
sp.setSkipCount(pagingRequest.getSkipCount());
sp.setMaxItems(pagingRequest.getMaxItems());
sp.addSort("@" + ContentModel.PROP_MODIFIED, false);
ResultSet results = searchService.query(sp);
List<QuickShareLink> qsLinks = new ArrayList<>(results.length());
List<String> includeParam = parameters.getInclude();
for (ResultSetRow row : results) {
NodeRef nodeRef = row.getNodeRef();
qsLinks.add(getQuickShareInfo(nodeRef, false, includeParam));
}
results.close();
return CollectionWithPagingInfo.asPaged(paging, qsLinks, results.hasMore(), Long.valueOf(results.getNumberFound()).intValue());
}
use of org.alfresco.service.cmr.search.ResultSet in project alfresco-remote-api by Alfresco.
the class SearchApiWebscript method execute.
@Override
public void execute(WebScriptRequest webScriptRequest, WebScriptResponse webScriptResponse) throws IOException {
try {
// Turn JSON into a Java object respresentation
SearchQuery searchQuery = extractJsonContent(webScriptRequest, assistant.getJsonHelper(), SearchQuery.class);
// Parse the parameters
Params params = getParams(webScriptRequest, searchQuery.getFields(), searchQuery.getInclude(), searchQuery.getPaging());
// Make a copy of the request
SearchRequestContext searchRequestContext = SearchRequestContext.from(searchQuery);
// Turn the SearchQuery json into the Java SearchParameters object
SearchParameters searchParams = searchMapper.toSearchParameters(params, searchQuery, searchRequestContext);
// Call searchService
ResultSet results = searchService.query(searchParams);
// Turn solr results into JSON
CollectionWithPagingInfo<Node> resultJson = resultMapper.toCollectionWithPagingInfo(params, searchRequestContext, searchQuery, results);
// Post-process the request and pass in params, eg. params.getFilter()
Object toRender = helper.processAdditionsToTheResponse(null, null, null, params, resultJson);
// Write response
setResponse(webScriptResponse, DEFAULT_SUCCESS);
renderJsonResponse(webScriptResponse, toRender, assistant.getJsonHelper());
} catch (Exception exception) {
renderException(exception, webScriptResponse, assistant);
}
}
use of org.alfresco.service.cmr.search.ResultSet in project alfresco-remote-api by Alfresco.
the class SearchSQLApiWebscript method execute.
@Override
public void execute(WebScriptRequest webScriptRequest, WebScriptResponse res) throws IOException {
try {
// Turn JSON into a Java object representation
SearchSQLQuery searchQuery = extractJsonContent(webScriptRequest, assistant.getJsonHelper(), SearchSQLQuery.class);
SearchParameters sparams = buildSearchParameters(searchQuery);
ResultSet results = searchService.query(sparams);
FilteringResultSet frs = (FilteringResultSet) results;
SolrSQLJSONResultSet ssjr = (SolrSQLJSONResultSet) frs.getUnFilteredResultSet();
// When solr format is requested pass the solr output directly.
if (searchQuery.getFormat().equalsIgnoreCase("solr")) {
res.getWriter().write(ssjr.getSolrResponse());
} else {
CollectionWithPagingInfo<TupleList> nodes = resultMapper.toCollectionWithPagingInfo(ssjr.getDocs(), searchQuery);
renderJsonResponse(res, nodes, assistant.getJsonHelper());
}
setResponse(res, DEFAULT_SUCCESS);
} catch (Exception exception) {
renderException(exception, res, assistant);
}
}
use of org.alfresco.service.cmr.search.ResultSet 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.alfresco.service.cmr.search.ResultSet in project alfresco-remote-api by Alfresco.
the class ResultMapperTests method testFacetingGroupResponseV1.
@Test
public /**
* Test facet group with out facet fields
* @throws Exception
*/
void testFacetingGroupResponseV1() throws Exception {
String jsonQuery = "{\"query\": {\"query\": \"alfresco\"}, \"facetFormat\":\"V1\"," + "\"facetQueries\": [" + "{\"query\": \"content.size:[o TO 102400]\", \"label\": \"small\"}," + "{\"query\": \"content.size:[102400 TO 1048576]\", \"label\": \"medium\",\"group\":\"foo\"}," + "{\"query\": \"content.size:[1048576 TO 16777216]\", \"label\": \"large\"}]" + "}";
String expectedResponse = "{\"responseHeader\":{\"status\":0,\"QTime\":9},\"_original_parameters_\":\"org.apache.solr.common.params.DefaultSolrParams:{params(df=TEXT&alternativeDic=DEFAULT_DICTIONARY&fl=DBID,score&start=0&fq={!afts}AUTHORITY_FILTER_FROM_JSON&fq={!afts}TENANT_FILTER_FROM_JSON&rows=1000&locale=en_US&wt=json),defaults(carrot.url=id&spellcheck.collateExtendedResults=true&carrot.produceSummary=true&spellcheck.maxCollations=3&spellcheck.maxCollationTries=5&spellcheck.alternativeTermCount=2&spellcheck.extendedResults=false&defType=afts&spellcheck.maxResultsForSuggest=5&spellcheck=false&carrot.outputSubClusters=false&spellcheck.count=5&carrot.title=mltext@m___t@{http://www.alfresco.org/model/content/1.0}title&carrot.snippet=content@s___t@{http://www.alfresco.org/model/content/1.0}content&spellcheck.collate=true)}\",\"_field_mappings_\":{},\"_date_mappings_\":{},\"_range_mappings_\":{},\"_pivot_mappings_\":{},\"_interval_mappings_\":{},\"_stats_field_mappings_\":{},\"_stats_facet_mappings_\":{},\"_facet_function_mappings_\":{},\"response\":{\"numFound\":6,\"start\":0,\"maxScore\":0.7849362,\"docs\":[{\"DBID\":565,\"score\":0.7849362},{\"DBID\":566,\"score\":0.7849362},{\"DBID\":521,\"score\":0.3540957},{\"DBID\":514,\"score\":0.33025497},{\"DBID\":420,\"score\":0.32440513},{\"DBID\":415,\"score\":0.2780319}]}," + "\"spellcheck\":{\"searchInsteadFor\":\"alfresco\"}," + "\"facet_counts\":{\"facet_queries\": {\"small\": 52,\"large\": 0,\"medium\": 0}}," + "\"processedDenies\":true, \"lastIndexedTx\":34}";
ResultSet results = mockResultset(expectedResponse);
SearchQuery searchQuery = helper.extractFromJson(jsonQuery);
SearchRequestContext searchRequest = SearchRequestContext.from(searchQuery);
SearchContext searchContext = mapper.toSearchContext((SolrJSONResultSet) results, searchRequest, searchQuery, 0);
assertEquals(34l, searchContext.getConsistency().getlastTxId());
assertEquals(null, searchContext.getFacetQueries());
assertEquals(2, searchContext.getFacets().size());
assertEquals(2, searchContext.getFacets().get(0).getBuckets().size());
assertEquals("small", searchContext.getFacets().get(0).getBuckets().get(0).getLabel());
assertEquals("content.size:[o TO 102400]", searchContext.getFacets().get(0).getBuckets().get(0).getFilterQuery());
assertFalse(searchContext.getFacets().get(0).getBuckets().get(0).getMetrics().isEmpty());
Metric[] metrics = searchContext.getFacets().get(0).getBuckets().get(0).getMetrics().toArray(new Metric[searchContext.getFacets().get(0).getBuckets().get(0).getMetrics().size()]);
assertEquals(METRIC_TYPE.count, metrics[0].getType());
assertEquals("{count=52}", metrics[0].getValue().toString());
}
Aggregations