Search in sources :

Example 11 with ResultSet

use of org.alfresco.service.cmr.search.ResultSet 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 12 with ResultSet

use of org.alfresco.service.cmr.search.ResultSet in project acs-community-packaging by Alfresco.

the class UIContentSelector 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) {
    // query for all content in the current repository
    StringBuilder query = new StringBuilder("+TYPE:\"");
    query.append(ContentModel.TYPE_CONTENT);
    query.append("\"");
    if (contains != null && contains.length() > 0) {
        String safeContains = SearchLanguageConversion.escapeLuceneQuery(contains.trim());
        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);
    }
    // setup search parameters, including limiting the results
    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();
    } finally {
        if (results != null) {
            results.close();
        }
    }
    if (logger.isDebugEnabled())
        logger.debug("Found " + this.availableOptions.size() + " available options");
}
Also used : SearchParameters(org.alfresco.service.cmr.search.SearchParameters) ResultSet(org.alfresco.service.cmr.search.ResultSet)

Example 13 with ResultSet

use of org.alfresco.service.cmr.search.ResultSet in project records-management by Alfresco.

the class BootstrapTestDataGet method patchLoadedData.

/**
 * Temp method to patch AMP'ed data
 *
 * @param searchService
 * @param nodeService
 * @param recordsManagementService
 * @param recordsManagementActionService
 */
public static void patchLoadedData(final SearchService searchService, final NodeService nodeService, final RecordsManagementService recordsManagementService, final RecordsManagementActionService recordsManagementActionService, final PermissionService permissionService, final AuthorityService authorityService, final RecordsManagementSecurityService recordsManagementSecurityService, final RecordsManagementSearchBehaviour recordManagementSearchBehaviour, final DispositionService dispositionService, final RecordFolderService recordFolderService) {
    AuthenticationUtil.RunAsWork<Object> runAsWork = new AuthenticationUtil.RunAsWork<Object>() {

        public Object doWork() {
            java.util.List<NodeRef> rmRoots = recordsManagementService.getFilePlans();
            logger.info("Bootstraping " + rmRoots.size() + " rm roots ...");
            for (NodeRef rmRoot : rmRoots) {
                if (permissionService.getInheritParentPermissions(rmRoot)) {
                    logger.info("Updating permissions for rm root: " + rmRoot);
                    permissionService.setInheritParentPermissions(rmRoot, false);
                }
                String allRoleShortName = RMAuthority.ALL_ROLES_PREFIX + rmRoot.getId();
                String allRoleGroupName = authorityService.getName(AuthorityType.GROUP, allRoleShortName);
                if (!authorityService.authorityExists(allRoleGroupName)) {
                    logger.info("Creating all roles group for root node: " + rmRoot.toString());
                    // Create "all" role group for root node
                    String allRoles = authorityService.createAuthority(AuthorityType.GROUP, allRoleShortName, RMAuthority.ALL_ROLES_DISPLAY_NAME, new HashSet<String>(Arrays.asList(RMAuthority.ZONE_APP_RM)));
                    // Put all the role groups in it
                    Set<Role> roles = recordsManagementSecurityService.getRoles(rmRoot);
                    for (Role role : roles) {
                        logger.info("   - adding role group " + role.getRoleGroupName() + " to all roles group");
                        authorityService.addAuthority(allRoles, role.getRoleGroupName());
                    }
                    // Set the permissions
                    permissionService.setPermission(rmRoot, allRoles, RMPermissionModel.READ_RECORDS, true);
                }
            }
            // Make sure all the containers do not inherit permissions
            ResultSet rs = searchService.query(SPACES_STORE, SearchService.LANGUAGE_FTS_ALFRESCO, "TYPE:\"rma:recordsManagementContainer\"");
            try {
                logger.info("Bootstraping " + rs.length() + " record containers ...");
                for (NodeRef container : rs.getNodeRefs()) {
                    String containerName = (String) nodeService.getProperty(container, ContentModel.PROP_NAME);
                    // Set permissions
                    if (permissionService.getInheritParentPermissions(container)) {
                        logger.info("Updating permissions for record container: " + containerName);
                        permissionService.setInheritParentPermissions(container, false);
                    }
                }
            } finally {
                rs.close();
            }
            // fix up the test dataset to fire initial events for disposition schedules
            rs = searchService.query(SPACES_STORE, SearchService.LANGUAGE_FTS_ALFRESCO, "TYPE:\"rma:recordFolder\"");
            try {
                logger.info("Bootstraping " + rs.length() + " record folders ...");
                for (NodeRef recordFolder : rs.getNodeRefs()) {
                    String folderName = (String) nodeService.getProperty(recordFolder, ContentModel.PROP_NAME);
                    // Set permissions
                    if (permissionService.getInheritParentPermissions(recordFolder)) {
                        logger.info("Updating permissions for record folder: " + folderName);
                        permissionService.setInheritParentPermissions(recordFolder, false);
                    }
                    if (!nodeService.hasAspect(recordFolder, ASPECT_DISPOSITION_LIFECYCLE)) {
                        // See if the folder has a disposition schedule that needs to be applied
                        DispositionSchedule ds = dispositionService.getDispositionSchedule(recordFolder);
                        if (ds != null) {
                            // Fire action to "set-up" the folder correctly
                            logger.info("Setting up bootstraped record folder: " + folderName);
                            recordFolderService.setupRecordFolder(recordFolder);
                        }
                    }
                    // fixup the search behaviour aspect for the record folder
                    logger.info("Setting up search aspect for record folder: " + folderName);
                    recordManagementSearchBehaviour.fixupSearchAspect(recordFolder);
                }
            } finally {
                rs.close();
            }
            return null;
        }
    };
    AuthenticationUtil.runAs(runAsWork, AuthenticationUtil.getAdminUserName());
}
Also used : DispositionSchedule(org.alfresco.module.org_alfresco_module_rm.disposition.DispositionSchedule) Role(org.alfresco.module.org_alfresco_module_rm.security.Role) NodeRef(org.alfresco.service.cmr.repository.NodeRef) AuthenticationUtil(org.alfresco.repo.security.authentication.AuthenticationUtil) ResultSet(org.alfresco.service.cmr.search.ResultSet)

Example 14 with ResultSet

use of org.alfresco.service.cmr.search.ResultSet in project records-management by Alfresco.

the class DispositionLifecycleJobExecuterUnitTest method testPagination.

/**
 * Given the maximum page of elements for search service is 2
 *       and search service finds more than one page of elements
 * When the job executer runs
 * Then the executer retrieves both pages and iterates all elements
 */
@Test
public void testPagination() {
    final NodeRef node1 = generateNodeRef();
    final NodeRef node2 = generateNodeRef();
    final NodeRef node3 = generateNodeRef();
    final NodeRef node4 = generateNodeRef();
    // mock the search service to return the right page
    when(mockedSearchService.query(any(SearchParameters.class))).thenAnswer(new Answer<ResultSet>() {

        @Override
        public ResultSet answer(InvocationOnMock invocation) {
            SearchParameters params = invocation.getArgumentAt(0, SearchParameters.class);
            if (params.getSkipCount() == 0) {
                // mock first page
                ResultSet result1 = mock(ResultSet.class);
                when(result1.getNodeRefs()).thenReturn(Arrays.asList(node1, node2));
                when(result1.hasMore()).thenReturn(true);
                return result1;
            } else if (params.getSkipCount() == 2) {
                // mock second page
                ResultSet result2 = mock(ResultSet.class);
                when(result2.getNodeRefs()).thenReturn(Arrays.asList(node3, node4));
                when(result2.hasMore()).thenReturn(false);
                return result2;
            }
            throw new IndexOutOfBoundsException("Pagination did not stop after the second page!");
        }
    });
    // call the service
    executer.executeImpl();
    // check the loop iterated trough all the elements
    verify(mockedNodeService).exists(node1);
    verify(mockedNodeService).exists(node2);
    verify(mockedNodeService).exists(node3);
    verify(mockedNodeService).exists(node4);
    verify(mockedSearchService, times(2)).query(any(SearchParameters.class));
}
Also used : NodeRef(org.alfresco.service.cmr.repository.NodeRef) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ResultSet(org.alfresco.service.cmr.search.ResultSet) BaseUnitTest(org.alfresco.module.org_alfresco_module_rm.test.util.BaseUnitTest) Test(org.junit.Test)

Example 15 with ResultSet

use of org.alfresco.service.cmr.search.ResultSet in project records-management by Alfresco.

the class DataSetServiceImpl method patchLoadedData.

/**
 * Temp method to patch AMP'ed data
 */
private void patchLoadedData() {
    AuthenticationUtil.RunAsWork<Object> runAsWork = new AuthenticationUtil.RunAsWork<Object>() {

        public Object doWork() {
            Set<NodeRef> rmRoots = filePlanService.getFilePlans();
            logger.info("Bootstraping " + rmRoots.size() + " rm roots ...");
            for (NodeRef rmRoot : rmRoots) {
                if (permissionService.getInheritParentPermissions(rmRoot)) {
                    logger.info("Updating permissions for rm root: " + rmRoot);
                    permissionService.setInheritParentPermissions(rmRoot, false);
                }
                String allRoleShortName = RMAuthority.ALL_ROLES_PREFIX + rmRoot.getId();
                String allRoleGroupName = authorityService.getName(AuthorityType.GROUP, allRoleShortName);
                if (!authorityService.authorityExists(allRoleGroupName)) {
                    logger.info("Creating all roles group for root node: " + rmRoot.toString());
                    // Create "all" role group for root node
                    String allRoles = authorityService.createAuthority(AuthorityType.GROUP, allRoleShortName, RMAuthority.ALL_ROLES_DISPLAY_NAME, new HashSet<String>(Arrays.asList(RMAuthority.ZONE_APP_RM)));
                    // Put all the role groups in it
                    Set<Role> roles = filePlanRoleService.getRoles(rmRoot);
                    for (Role role : roles) {
                        logger.info("   - adding role group " + role.getRoleGroupName() + " to all roles group");
                        authorityService.addAuthority(allRoles, role.getRoleGroupName());
                    }
                    // Set the permissions
                    permissionService.setPermission(rmRoot, allRoles, RMPermissionModel.READ_RECORDS, true);
                }
            }
            // Make sure all the containers do not inherit permissions
            ResultSet rs = searchService.query(SPACES_STORE, SearchService.LANGUAGE_FTS_ALFRESCO, "TYPE:\"rma:recordsManagementContainer\"");
            try {
                logger.info("Bootstraping " + rs.length() + " record containers ...");
                for (NodeRef container : rs.getNodeRefs()) {
                    String containerName = (String) nodeService.getProperty(container, ContentModel.PROP_NAME);
                    // Set permissions
                    if (permissionService.getInheritParentPermissions(container)) {
                        logger.info("Updating permissions for record container: " + containerName);
                        permissionService.setInheritParentPermissions(container, false);
                    }
                }
            } finally {
                rs.close();
            }
            // fix up the test dataset to fire initial events for
            // disposition
            // schedules
            rs = searchService.query(SPACES_STORE, SearchService.LANGUAGE_FTS_ALFRESCO, "TYPE:\"rma:recordFolder\"");
            try {
                logger.info("Bootstraping " + rs.length() + " record folders ...");
                for (NodeRef recordFolder : rs.getNodeRefs()) {
                    String folderName = (String) nodeService.getProperty(recordFolder, ContentModel.PROP_NAME);
                    // Set permissions
                    if (permissionService.getInheritParentPermissions(recordFolder)) {
                        logger.info("Updating permissions for record folder: " + folderName);
                        permissionService.setInheritParentPermissions(recordFolder, false);
                    }
                    if (!nodeService.hasAspect(recordFolder, ASPECT_DISPOSITION_LIFECYCLE)) {
                        // See if the folder has a disposition schedule that
                        // needs
                        // to be applied
                        DispositionSchedule ds = dispositionService.getDispositionSchedule(recordFolder);
                        if (ds != null) {
                            // Fire action to "set-up" the folder correctly
                            logger.info("Setting up bootstraped record folder: " + folderName);
                            recordFolderService.setupRecordFolder(recordFolder);
                        }
                    }
                    // fixup the search behaviour aspect for the record
                    // folder
                    logger.info("Setting up search aspect for record folder: " + folderName);
                    recordsManagementSearchBehaviour.fixupSearchAspect(recordFolder);
                }
            } finally {
                rs.close();
            }
            return null;
        }
    };
    AuthenticationUtil.runAs(runAsWork, AuthenticationUtil.getAdminUserName());
}
Also used : Role(org.alfresco.module.org_alfresco_module_rm.role.Role) NodeRef(org.alfresco.service.cmr.repository.NodeRef) AuthenticationUtil(org.alfresco.repo.security.authentication.AuthenticationUtil) ResultSet(org.alfresco.service.cmr.search.ResultSet) DispositionSchedule(org.alfresco.module.org_alfresco_module_rm.disposition.DispositionSchedule)

Aggregations

ResultSet (org.alfresco.service.cmr.search.ResultSet)34 NodeRef (org.alfresco.service.cmr.repository.NodeRef)20 SearchParameters (org.alfresco.service.cmr.search.SearchParameters)20 EmptyResultSet (org.alfresco.repo.search.EmptyResultSet)12 SolrJSONResultSet (org.alfresco.repo.search.impl.lucene.SolrJSONResultSet)12 SearchRequestContext (org.alfresco.rest.api.search.context.SearchRequestContext)11 Test (org.junit.Test)11 SearchQuery (org.alfresco.rest.api.search.model.SearchQuery)10 ArrayList (java.util.ArrayList)9 SearchContext (org.alfresco.rest.api.search.context.SearchContext)9 Matchers.anyString (org.mockito.Matchers.anyString)9 IOException (java.io.IOException)8 HashMap (java.util.HashMap)8 ListMetric (org.alfresco.repo.search.impl.solr.facet.facetsresponse.ListMetric)8 Metric (org.alfresco.repo.search.impl.solr.facet.facetsresponse.Metric)8 PercentileMetric (org.alfresco.repo.search.impl.solr.facet.facetsresponse.PercentileMetric)8 SimpleMetric (org.alfresco.repo.search.impl.solr.facet.facetsresponse.SimpleMetric)8 QName (org.alfresco.service.namespace.QName)8 NodeService (org.alfresco.service.cmr.repository.NodeService)7 List (java.util.List)6