Search in sources :

Example 1 with SearcherException

use of org.alfresco.repo.search.SearcherException in project acs-community-packaging by Alfresco.

the class BaseAssociationEditor method getAvailableOptions.

/**
 * Retrieves the available options for the current association
 *
 * @param context Faces Context
 * @param contains The contains part of the query
 */
protected void getAvailableOptions(FacesContext context, String contains) {
    AssociationDefinition assocDef = getAssociationDefinition(context);
    if (assocDef != null) {
        // find and show all the available options for the current association
        String type = assocDef.getTargetClass().getName().toString();
        if (type.equals(ContentModel.TYPE_AUTHORITY_CONTAINER.toString())) {
            UserTransaction tx = null;
            try {
                tx = Repository.getUserTransaction(context, true);
                tx.begin();
                String safeContains = null;
                if (contains != null && contains.length() > 0) {
                    safeContains = Utils.remove(contains.trim(), "\"");
                    safeContains = safeContains.toLowerCase();
                }
                // get all available groups
                AuthorityService authorityService = Repository.getServiceRegistry(context).getAuthorityService();
                Set<String> groups = authorityService.getAllAuthoritiesInZone(AuthorityService.ZONE_APP_DEFAULT, AuthorityType.GROUP);
                this.availableOptions = new ArrayList<NodeRef>(groups.size());
                // get the NodeRef for each matching group
                AuthorityDAO authorityDAO = (AuthorityDAO) FacesContextUtils.getRequiredWebApplicationContext(context).getBean("authorityDAO");
                if (authorityDAO != null) {
                    List<String> matchingGroups = new ArrayList<String>();
                    String groupDisplayName;
                    for (String group : groups) {
                        // get display name, if not present strip prefix from group id
                        groupDisplayName = authorityService.getAuthorityDisplayName(group);
                        if (groupDisplayName == null || groupDisplayName.length() == 0) {
                            groupDisplayName = group.substring(PermissionService.GROUP_PREFIX.length());
                        }
                        // otherwise just add the group name to the sorted set
                        if (safeContains != null) {
                            if (groupDisplayName.toLowerCase().indexOf(safeContains) != -1) {
                                matchingGroups.add(group);
                            }
                        } else {
                            matchingGroups.add(group);
                        }
                    }
                    // sort the group names
                    Collections.sort(matchingGroups, new SimpleStringComparator());
                    // go through the sorted set and get the NodeRef for each group
                    for (String groupName : matchingGroups) {
                        NodeRef groupRef = authorityDAO.getAuthorityNodeRefOrNull(groupName);
                        if (groupRef != null) {
                            this.availableOptions.add(groupRef);
                        }
                    }
                }
                // commit the transaction
                tx.commit();
            } catch (Throwable err) {
                Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, Repository.ERROR_GENERIC), err.getMessage()), err);
                this.availableOptions = Collections.<NodeRef>emptyList();
                try {
                    if (tx != null) {
                        tx.rollback();
                    }
                } catch (Exception tex) {
                }
            }
        } else if (type.equals(ContentModel.TYPE_PERSON.toString())) {
            List<Pair<QName, String>> filter = (contains != null && contains.trim().length() > 0) ? Utils.generatePersonFilter(contains.trim()) : null;
            // Always sort by last name, then first name
            List<Pair<QName, Boolean>> sort = new ArrayList<Pair<QName, Boolean>>();
            sort.add(new Pair<QName, Boolean>(ContentModel.PROP_LASTNAME, true));
            sort.add(new Pair<QName, Boolean>(ContentModel.PROP_FIRSTNAME, true));
            // Log the filtering
            if (logger.isDebugEnabled())
                logger.debug("Query filter: " + filter);
            // How many to limit too?
            int maxResults = Application.getClientConfig(context).getSelectorsSearchMaxResults();
            if (maxResults <= 0) {
                maxResults = Utils.getPersonMaxResults();
            }
            List<PersonInfo> persons = Repository.getServiceRegistry(context).getPersonService().getPeople(filter, true, sort, new PagingRequest(maxResults, null)).getPage();
            // Save the results
            List<NodeRef> nodes = new ArrayList<NodeRef>(persons.size());
            for (PersonInfo person : persons) {
                nodes.add(person.getNodeRef());
            }
            this.availableOptions = nodes;
        } else {
            // for all other types/aspects perform a lucene search
            StringBuilder query = new StringBuilder("+TYPE:\"");
            if (assocDef.getTargetClass().isAspect()) {
                query = new StringBuilder("+ASPECT:\"");
            } else {
                query = new StringBuilder("+TYPE:\"");
            }
            query.append(type);
            query.append("\"");
            if (contains != null && contains.trim().length() != 0) {
                String safeContains = null;
                if (contains != null && contains.length() > 0) {
                    safeContains = Utils.remove(contains.trim(), "\"");
                    safeContains = safeContains.toLowerCase();
                }
                query.append(" AND +@");
                String nameAttr = Repository.escapeQName(QName.createQName(NamespaceService.CONTENT_MODEL_1_0_URI, "name"));
                query.append(nameAttr);
                query.append(":\"*" + safeContains + "*\"");
            }
            int maxResults = Application.getClientConfig(context).getSelectorsSearchMaxResults();
            if (logger.isDebugEnabled()) {
                logger.debug("Query: " + query.toString());
                logger.debug("Max results size: " + maxResults);
            }
            SearchParameters searchParams = new SearchParameters();
            searchParams.addStore(Repository.getStoreRef());
            searchParams.setLanguage(SearchService.LANGUAGE_LUCENE);
            searchParams.setQuery(query.toString());
            if (maxResults > 0) {
                searchParams.setLimit(maxResults);
                searchParams.setLimitBy(LimitBy.FINAL_SIZE);
            }
            ResultSet results = null;
            try {
                results = Repository.getServiceRegistry(context).getSearchService().query(searchParams);
                this.availableOptions = results.getNodeRefs();
            } catch (SearcherException se) {
                logger.info("Search failed for: " + query, se);
                Utils.addErrorMessage(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_QUERY));
            } finally {
                if (results != null) {
                    results.close();
                }
            }
        }
        if (logger.isDebugEnabled())
            logger.debug("Found " + this.availableOptions.size() + " available options");
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) PersonInfo(org.alfresco.service.cmr.security.PersonService.PersonInfo) QName(org.alfresco.service.namespace.QName) AuthorityService(org.alfresco.service.cmr.security.AuthorityService) ArrayList(java.util.ArrayList) AuthorityDAO(org.alfresco.repo.security.authority.AuthorityDAO) SearcherException(org.alfresco.repo.search.SearcherException) AbortProcessingException(javax.faces.event.AbortProcessingException) IOException(java.io.IOException) PagingRequest(org.alfresco.query.PagingRequest) NodeRef(org.alfresco.service.cmr.repository.NodeRef) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) AssociationDefinition(org.alfresco.service.cmr.dictionary.AssociationDefinition) SearcherException(org.alfresco.repo.search.SearcherException) ResultSet(org.alfresco.service.cmr.search.ResultSet) ArrayList(java.util.ArrayList) List(java.util.List) Pair(org.alfresco.util.Pair)

Example 2 with SearcherException

use of org.alfresco.repo.search.SearcherException 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");
    }
}
Also used : UserTransaction(javax.transaction.UserTransaction) QName(org.alfresco.service.namespace.QName) Node(org.alfresco.web.bean.repository.Node) MapNode(org.alfresco.web.bean.repository.MapNode) ResultSetRow(org.alfresco.service.cmr.search.ResultSetRow) MapNode(org.alfresco.web.bean.repository.MapNode) SearcherException(org.alfresco.repo.search.SearcherException) InvalidNodeRefException(org.alfresco.service.cmr.repository.InvalidNodeRefException) AbortProcessingException(javax.faces.event.AbortProcessingException) IOException(java.io.IOException) TypeDefinition(org.alfresco.service.cmr.dictionary.TypeDefinition) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) NodeRef(org.alfresco.service.cmr.repository.NodeRef) SearcherException(org.alfresco.repo.search.SearcherException) ResultSet(org.alfresco.service.cmr.search.ResultSet) InvalidNodeRefException(org.alfresco.service.cmr.repository.InvalidNodeRefException)

Aggregations

IOException (java.io.IOException)2 AbortProcessingException (javax.faces.event.AbortProcessingException)2 UserTransaction (javax.transaction.UserTransaction)2 SearcherException (org.alfresco.repo.search.SearcherException)2 NodeRef (org.alfresco.service.cmr.repository.NodeRef)2 ResultSet (org.alfresco.service.cmr.search.ResultSet)2 SearchParameters (org.alfresco.service.cmr.search.SearchParameters)2 QName (org.alfresco.service.namespace.QName)2 ArrayList (java.util.ArrayList)1 List (java.util.List)1 PagingRequest (org.alfresco.query.PagingRequest)1 AuthorityDAO (org.alfresco.repo.security.authority.AuthorityDAO)1 AssociationDefinition (org.alfresco.service.cmr.dictionary.AssociationDefinition)1 TypeDefinition (org.alfresco.service.cmr.dictionary.TypeDefinition)1 InvalidNodeRefException (org.alfresco.service.cmr.repository.InvalidNodeRefException)1 ResultSetRow (org.alfresco.service.cmr.search.ResultSetRow)1 AuthorityService (org.alfresco.service.cmr.security.AuthorityService)1 PersonInfo (org.alfresco.service.cmr.security.PersonService.PersonInfo)1 Pair (org.alfresco.util.Pair)1 MapNode (org.alfresco.web.bean.repository.MapNode)1