use of org.alfresco.service.cmr.search.SearchParameters in project acs-community-packaging by Alfresco.
the class BrowseBean method searchBrowseNodes.
/**
* Search for a list of nodes using the specific search context
*
* @param searchContext To use to perform the search
*/
private void searchBrowseNodes(SearchContext searchContext) {
long startTime = 0;
if (logger.isDebugEnabled())
startTime = System.currentTimeMillis();
// get the searcher object to build the query
String query = searchContext.buildQuery(getMinimumSearchLength());
if (query == null) {
// failed to build a valid query, the user probably did not enter the
// minimum text required to construct a valid search
Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), MSG_SEARCH_MINIMUM), new Object[] { getMinimumSearchLength() }));
this.containerNodes = Collections.<Node>emptyList();
this.contentNodes = Collections.<Node>emptyList();
return;
}
// perform the search against the repo
UserTransaction tx = null;
ResultSet results = null;
try {
tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true);
tx.begin();
// build up the search parameters
SearchParameters sp = new SearchParameters();
sp.setLanguage(SearchService.LANGUAGE_LUCENE);
sp.setQuery(query);
sp.addStore(Repository.getStoreRef());
// limit search results size as configured
int searchLimit = Application.getClientConfig(FacesContext.getCurrentInstance()).getSearchMaxResults();
if (searchLimit > 0) {
sp.setLimitBy(LimitBy.FINAL_SIZE);
sp.setLimit(searchLimit);
}
sp.setBulkFetchEnabled(Application.getClientConfig(FacesContext.getCurrentInstance()).isBulkFetchEnabled());
results = this.getSearchService().query(sp);
if (logger.isDebugEnabled())
logger.debug("Search results returned: " + results.length());
// create a list of items from the results
this.containerNodes = new ArrayList<Node>(results.length());
this.contentNodes = new ArrayList<Node>(results.length());
if (results.length() != 0) {
// in case of dynamic config, only lookup once
Set<NodeEventListener> nodeEventListeners = getNodeEventListeners();
for (ResultSetRow row : results) {
NodeRef nodeRef = row.getNodeRef();
if (this.getNodeService().exists(nodeRef)) {
// find it's type so we can see if it's a node we are interested in
QName type = this.getNodeService().getType(nodeRef);
// make sure the type is defined in the data dictionary
TypeDefinition typeDef = this.getDictionaryService().getType(type);
if (typeDef != null) {
MapNode node = null;
// look for Space or File nodes
if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_FOLDER) && this.getDictionaryService().isSubClass(type, ContentModel.TYPE_SYSTEM_FOLDER) == false) {
// create our Node representation
node = new MapNode(nodeRef, this.getNodeService(), false);
node.addPropertyResolver("path", this.resolverPath);
node.addPropertyResolver("displayPath", this.resolverDisplayPath);
node.addPropertyResolver("icon", this.resolverSpaceIcon);
node.addPropertyResolver("smallIcon", this.resolverSmallIcon);
this.containerNodes.add(node);
} else if (this.getDictionaryService().isSubClass(type, ContentModel.TYPE_CONTENT)) {
// create our Node representation
node = new MapNode(nodeRef, this.getNodeService(), false);
setupCommonBindingProperties(node);
node.addPropertyResolver("path", this.resolverPath);
node.addPropertyResolver("displayPath", this.resolverDisplayPath);
this.contentNodes.add(node);
} else // look for File Link object node
if (ApplicationModel.TYPE_FILELINK.equals(type)) {
// create our File Link Node representation
node = new MapNode(nodeRef, this.getNodeService(), false);
// only display the user has the permissions to navigate to the target of the link
NodeRef destRef = (NodeRef) node.getProperties().get(ContentModel.PROP_LINK_DESTINATION);
if (new Node(destRef).hasPermission(PermissionService.READ) == true) {
node.addPropertyResolver("url", this.resolverLinkUrl);
node.addPropertyResolver("downloadUrl", this.resolverLinkDownload);
node.addPropertyResolver("webdavUrl", this.resolverLinkWebdavUrl);
node.addPropertyResolver("cifsPath", this.resolverLinkCifsPath);
node.addPropertyResolver("fileType16", this.resolverFileType16);
node.addPropertyResolver("fileType32", this.resolverFileType32);
node.addPropertyResolver("lang", this.resolverLang);
node.addPropertyResolver("path", this.resolverPath);
node.addPropertyResolver("displayPath", this.resolverDisplayPath);
this.contentNodes.add(node);
}
} else if (ApplicationModel.TYPE_FOLDERLINK.equals(type)) {
// create our Folder Link Node representation
node = new MapNode(nodeRef, this.getNodeService(), false);
// only display the user has the permissions to navigate to the target of the link
NodeRef destRef = (NodeRef) node.getProperties().get(ContentModel.PROP_LINK_DESTINATION);
if (new Node(destRef).hasPermission(PermissionService.READ) == true) {
node.addPropertyResolver("icon", this.resolverSpaceIcon);
node.addPropertyResolver("smallIcon", this.resolverSmallIcon);
node.addPropertyResolver("path", this.resolverPath);
node.addPropertyResolver("displayPath", this.resolverDisplayPath);
this.containerNodes.add(node);
}
}
// inform any listeners that a Node wrapper has been created
if (node != null) {
for (NodeEventListener listener : nodeEventListeners) {
listener.created(node, type);
}
}
} else {
if (logger.isWarnEnabled())
logger.warn("Found invalid object in database: id = " + nodeRef + ", type = " + type);
}
} else {
if (logger.isWarnEnabled())
logger.warn("Missing object returned from search indexes: id = " + nodeRef + " search query: " + query);
}
}
}
// commit the transaction
tx.commit();
} catch (InvalidNodeRefException refErr) {
Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_NODEREF), new Object[] { refErr.getNodeRef() }), refErr);
this.containerNodes = Collections.<Node>emptyList();
this.contentNodes = Collections.<Node>emptyList();
try {
if (tx != null) {
tx.rollback();
}
} catch (Exception tex) {
}
} catch (SearcherException serr) {
logger.info("Search failed for: " + query, serr);
Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_QUERY));
this.containerNodes = Collections.<Node>emptyList();
this.contentNodes = Collections.<Node>emptyList();
try {
if (tx != null) {
tx.rollback();
}
} catch (Exception tex) {
}
} catch (Throwable err) {
Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_SEARCH), new Object[] { err.getMessage() }), err);
this.containerNodes = Collections.<Node>emptyList();
this.contentNodes = Collections.<Node>emptyList();
try {
if (tx != null) {
tx.rollback();
}
} catch (Exception tex) {
}
} finally {
if (results != null) {
results.close();
}
}
if (logger.isDebugEnabled()) {
long endTime = System.currentTimeMillis();
logger.debug("Time to query and build map nodes: " + (endTime - startTime) + "ms");
}
}
use of org.alfresco.service.cmr.search.SearchParameters in project acs-community-packaging by Alfresco.
the class TrashcanDialog method getItems.
/**
* @return the list of deleted items to display
*/
public List<Node> getItems() {
// to get deleted items from deleted items store
// use a search to find the items - also filters by name/username
List<Node> itemNodes = null;
UserTransaction tx = null;
ResultSet results = null;
try {
tx = Repository.getUserTransaction(FacesContext.getCurrentInstance(), true);
tx.begin();
// get the root node to the deleted items store
if (getArchiveRootRef() != null && property.isShowItems()) {
String query = buildSearchQuery();
SearchParameters sp = new SearchParameters();
sp.setLanguage(SearchService.LANGUAGE_LUCENE);
sp.setQuery(query);
// the Archived Node store
sp.addStore(getArchiveRootRef().getStoreRef());
results = getSearchService().query(sp);
itemNodes = new ArrayList<Node>(results.length());
}
if (results != null && results.length() != 0) {
for (ResultSetRow row : results) {
NodeRef nodeRef = row.getNodeRef();
if (getNodeService().exists(nodeRef)) {
QName type = getNodeService().getType(nodeRef);
MapNode node = new MapNode(nodeRef, getNodeService(), false);
node.addPropertyResolver("locationPath", resolverLocationPath);
node.addPropertyResolver("displayPath", resolverDisplayPath);
node.addPropertyResolver("deletedDate", resolverDeletedDate);
node.addPropertyResolver("deletedBy", resolverDeletedBy);
node.addPropertyResolver("isFolder", resolverIsFolder);
if (getDictionaryService().isSubClass(type, ContentModel.TYPE_FOLDER) == true && getDictionaryService().isSubClass(type, ContentModel.TYPE_SYSTEM_FOLDER) == false) {
node.addPropertyResolver("typeIcon", this.resolverSmallIcon);
} else {
node.addPropertyResolver("typeIcon", this.resolverFileType16);
}
itemNodes.add(node);
}
}
}
tx.commit();
} catch (Throwable err) {
Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), new Object[] { err.getMessage() }), err);
try {
if (tx != null) {
tx.rollback();
}
} catch (Exception tex) {
}
} finally {
if (results != null) {
results.close();
}
}
property.setListedItems((itemNodes != null ? itemNodes : Collections.<Node>emptyList()));
return property.getListedItems();
}
use of org.alfresco.service.cmr.search.SearchParameters in project SearchServices by Alfresco.
the class AbstractQParser method getSearchParameters.
protected Pair<SearchParameters, Boolean> getSearchParameters() {
SearchParameters searchParameters = new SearchParameters();
Boolean isFilter = Boolean.FALSE;
Iterable<ContentStream> streams = req.getContentStreams();
JSONObject json = (JSONObject) req.getContext().get(ALFRESCO_JSON);
if (json == null) {
if (streams != null) {
try {
Reader reader = null;
for (ContentStream stream : streams) {
reader = new BufferedReader(new InputStreamReader(stream.getStream(), "UTF-8"));
}
// TODO - replace with streaming-based solution e.g. SimpleJSON ContentHandler
if (reader != null) {
json = new JSONObject(new JSONTokener(reader));
req.getContext().put(ALFRESCO_JSON, json);
}
} catch (JSONException e) {
// This is expected when there is no json element to the request
} catch (IOException e) {
throw new AlfrescoRuntimeException("IO Error parsing query parameters", e);
}
}
}
if (json != null) {
try {
if (getString() != null) {
if (getString().equals(AUTHORITY_FILTER_FROM_JSON)) {
isFilter = Boolean.TRUE;
ArrayList<String> tenantList = new ArrayList<String>(1);
JSONArray tenants = json.getJSONArray("tenants");
for (int i = 0; i < tenants.length(); i++) {
String tenantString = tenants.getString(i);
tenantList.add(tenantString);
}
ArrayList<String> authorityList = new ArrayList<String>(1);
JSONArray authorities = json.getJSONArray("authorities");
for (int i = 0; i < authorities.length(); i++) {
String authorityString = authorities.getString(i);
authorityList.add(authorityString);
}
char separator = getSeparator(authorityList);
StringBuilder authQuery = new StringBuilder();
StringBuilder denyQuery = new StringBuilder();
for (String tenant : tenantList) {
for (String authority : authorityList) {
if (separator == 0) {
if (authQuery.length() > 0) {
authQuery.append(" ");
denyQuery.append(" ");
}
switch(AuthorityType.getAuthorityType(authority)) {
case USER:
authQuery.append("|AUTHORITY:\"").append(authority).append("\"");
denyQuery.append("|DENIED:\"").append(authority).append("\"");
break;
case GROUP:
case EVERYONE:
case GUEST:
if (tenant.length() == 0) {
// Default tenant matches 4.0
authQuery.append("|AUTHORITY:\"").append(authority).append("\"");
denyQuery.append("|DENIED:\"").append(authority).append("\"");
} else {
authQuery.append("|AUTHORITY:\"").append(authority).append("@").append(tenant).append("\"");
denyQuery.append("|DENIED:\"").append(authority).append("@").append(tenant).append("\"");
}
break;
default:
authQuery.append("|AUTHORITY:\"").append(authority).append("\"");
denyQuery.append("|DENIED:\"").append(authority).append("\"");
break;
}
} else {
if (authQuery.length() == 0) {
authset = true;
authQuery.append("|AUTHSET:\"");
denyQuery.append("|DENYSET:\"");
}
switch(AuthorityType.getAuthorityType(authority)) {
case USER:
authQuery.append(separator).append(authority);
denyQuery.append(separator).append(authority);
break;
case GROUP:
case EVERYONE:
case GUEST:
if (tenant.length() == 0) {
// Default tenant matches 4.0
authQuery.append(separator).append(authority);
denyQuery.append(separator).append(authority);
} else {
authQuery.append(separator).append(authority).append("@").append(tenant);
denyQuery.append(separator).append(authority).append("@").append(tenant);
}
break;
default:
authQuery.append(separator).append(authority);
denyQuery.append(separator).append(authority);
break;
}
}
}
}
if (separator != 0) {
authQuery.append("\"");
denyQuery.append("\"");
}
if (authQuery.length() > 0) {
// Default to true for safety reasons.
final boolean anyDenyDenies = json.optBoolean("anyDenyDenies", true);
if (anyDenyDenies) {
authQuery.insert(0, "(").append(") AND NOT (").append(denyQuery).append(")");
// Record that the clause has been added.
// We only ever set this to true for solr4+
req.getContext().put("processedDenies", Boolean.TRUE);
}
searchParameters.setQuery(authQuery.toString());
}
} else if (getString().equals(TENANT_FILTER_FROM_JSON)) {
isFilter = Boolean.TRUE;
ArrayList<String> tenantList = new ArrayList<String>(1);
JSONArray tenants = json.getJSONArray("tenants");
for (int i = 0; i < tenants.length(); i++) {
String tenantString = tenants.getString(i);
tenantList.add(tenantString);
}
StringBuilder tenantQuery = new StringBuilder();
for (String tenant : tenantList) {
if (tenantQuery.length() > 0) {
tenantQuery.append(" ");
}
if (tenant.length() > 0) {
tenantQuery.append("|TENANT:\"").append(tenant).append("\"");
} else {
// TODO: Need to check for the default tenant or no tenant (4.0) or we force a reindex
// requirement later ...
// Better to add default tenant to the 4.0 index
tenantQuery.append("|TENANT:\"").append("_DEFAULT_").append("\"");
// tenantQuery.append(" |(+ISNODE:T -TENANT:*)");
}
}
searchParameters.setQuery(tenantQuery.toString());
} else if (getString().equals(RERANK_QUERY_FROM_CONTEXT)) {
String searchTerm = getParam("spellcheck.q");
searchParameters.setQuery(searchTerm);
}
} else {
String query = json.getString("query");
if (query != null) {
searchParameters.setQuery(query);
}
}
JSONArray locales = json.getJSONArray("locales");
for (int i = 0; i < locales.length(); i++) {
String localeString = locales.getString(i);
Locale locale = DefaultTypeConverter.INSTANCE.convert(Locale.class, localeString);
searchParameters.addLocale(locale);
}
JSONArray templates = json.getJSONArray("templates");
for (int i = 0; i < templates.length(); i++) {
JSONObject template = templates.getJSONObject(i);
String name = template.getString("name");
String queryTemplate = template.getString("template");
searchParameters.addQueryTemplate(name, queryTemplate);
}
JSONArray allAttributes = json.getJSONArray("allAttributes");
for (int i = 0; i < allAttributes.length(); i++) {
String allAttribute = allAttributes.getString(i);
searchParameters.addAllAttribute(allAttribute);
}
searchParameters.setDefaultFTSOperator(Operator.valueOf(json.getString("defaultFTSOperator")));
searchParameters.setDefaultFTSFieldConnective(Operator.valueOf(json.getString("defaultFTSFieldOperator")));
if (json.has("mlAnalaysisMode")) {
searchParameters.setMlAnalaysisMode(MLAnalysisMode.valueOf(json.getString("mlAnalaysisMode")));
}
searchParameters.setNamespace(json.getString("defaultNamespace"));
JSONArray textAttributes = json.getJSONArray("textAttributes");
for (int i = 0; i < textAttributes.length(); i++) {
String textAttribute = textAttributes.getString(i);
searchParameters.addTextAttribute(textAttribute);
}
searchParameters.setQueryConsistency(QueryConsistency.valueOf(json.getString("queryConsistency")));
} catch (JSONException e) {
// This is expected when there is no json element to the request
}
}
if (json != null) {
if (log.isDebugEnabled()) {
log.debug(json.toString());
}
}
if (searchParameters.getQuery() == null) {
searchParameters.setQuery(getString());
}
if (searchParameters.getLocales().size() == 0) {
searchParameters.addLocale(I18NUtil.getLocale());
}
String defaultField = getParam(CommonParams.DF);
if (defaultField != null) {
searchParameters.setDefaultFieldName(defaultField);
}
if (autoDetectQueryLocale) {
String searchTerm = getParam("spellcheck.q");
if (searchTerm != null) {
searchParameters.setSearchTerm(searchTerm);
List<DetectedLanguage> detetcted = detectLanguage(searchTerm);
if ((detetcted != null) && (detetcted.size() > 0)) {
Locale detectedLocale = Locale.forLanguageTag(detetcted.get(0).getLangCode());
if (localeIsNotIncluded(searchParameters, detectedLocale)) {
searchParameters.addLocale(Locale.forLanguageTag(detectedLocale.getLanguage()));
}
}
}
}
if (fixedQueryLocales.size() > 0) {
for (String locale : fixedQueryLocales) {
searchParameters.addLocale(Locale.forLanguageTag(locale));
}
}
// searchParameters.setMlAnalaysisMode(getMLAnalysisMode());
searchParameters.setNamespace(NamespaceService.CONTENT_MODEL_1_0_URI);
return new Pair<SearchParameters, Boolean>(searchParameters, isFilter);
}
use of org.alfresco.service.cmr.search.SearchParameters in project records-management by Alfresco.
the class DispositionLifecycleJobExecuter method executeImpl.
/**
* @see org.alfresco.module.org_alfresco_module_rm.job.RecordsManagementJobExecuter#execute()
*/
public void executeImpl() {
try {
logger.debug("Job Starting");
if (dispositionActions != null && !dispositionActions.isEmpty()) {
boolean hasMore = true;
int skipCount = 0;
while (hasMore) {
SearchParameters params = new SearchParameters();
params.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
params.setLanguage(SearchService.LANGUAGE_FTS_ALFRESCO);
params.setQuery(getQuery());
params.setSkipCount(skipCount);
// execute search
ResultSet results = searchService.query(params);
List<NodeRef> resultNodes = results.getNodeRefs();
hasMore = results.hasMore();
// increase by page size
skipCount += resultNodes.size();
results.close();
if (logger.isDebugEnabled()) {
logger.debug("Processing " + resultNodes.size() + " nodes");
}
// process search results
for (NodeRef node : resultNodes) {
executeAction(node);
}
}
}
logger.debug("Job Finished");
} catch (AlfrescoRuntimeException exception) {
if (logger.isDebugEnabled()) {
logger.debug(exception);
}
}
}
use of org.alfresco.service.cmr.search.SearchParameters in project records-management by Alfresco.
the class PublishUpdatesJobExecuter method getUpdatedNodes.
/**
* Get a list of the nodes with updates pending publish
* @return List<NodeRef> list of node refences with updates pending publication
*/
private List<NodeRef> getUpdatedNodes() {
RetryingTransactionCallback<List<NodeRef>> execution = new RetryingTransactionHelper.RetryingTransactionCallback<List<NodeRef>>() {
@Override
public List<NodeRef> execute() {
// Build the query string
StringBuilder sb = new StringBuilder();
sb.append("ASPECT:\"rma:").append(ASPECT_UNPUBLISHED_UPDATE.getLocalName()).append("\"");
String query = sb.toString();
if (logger.isDebugEnabled()) {
logger.debug("Executing query " + query);
}
// Execute query to find updates awaiting publishing
List<NodeRef> resultNodes = null;
SearchParameters searchParameters = new SearchParameters();
searchParameters.setQuery(query);
searchParameters.addStore(StoreRef.STORE_REF_WORKSPACE_SPACESSTORE);
searchParameters.setLanguage(SearchService.LANGUAGE_FTS_ALFRESCO);
try {
ResultSet results = searchService.query(searchParameters);
try {
resultNodes = results.getNodeRefs();
} finally {
results.close();
}
} catch (AlfrescoRuntimeException exception) {
if (logger.isDebugEnabled()) {
logger.debug("Error executing query, " + exception.getMessage());
}
throw exception;
}
if (logger.isDebugEnabled()) {
logger.debug("Found " + resultNodes.size() + " disposition action definitions updates awaiting publishing.");
}
return resultNodes;
}
};
return retryingTransactionHelper.doInTransaction(execution, true);
}
Aggregations