Search in sources :

Example 56 with ResultSet

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

Example 57 with ResultSet

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

the class BaseReassignDialog method pickerCallback.

/**
 * Query callback method executed by the Generic Picker component.
 * This method is part of the contract to the Generic Picker, it is up to the backing bean
 * to execute whatever query is appropriate and return the results.
 *
 * @param filterIndex        Index of the filter drop-down selection
 * @param contains           Text from the contains textbox
 *
 * @return An array of SelectItem objects containing the results to display in the picker.
 */
public SelectItem[] pickerCallback(int filterIndex, String contains) {
    FacesContext context = FacesContext.getCurrentInstance();
    // quick exit if not enough characters entered for a search
    String search = contains.trim();
    int searchMin = Application.getClientConfig(context).getPickerSearchMinimum();
    if (search.length() < searchMin) {
        Utils.addErrorMessage(MessageFormat.format(Application.getMessage(context, MSG_SEARCH_MINIMUM), searchMin));
        return new SelectItem[0];
    }
    SelectItem[] items;
    UserTransaction tx = null;
    ResultSet resultSet = null;
    try {
        tx = Repository.getUserTransaction(context, true);
        tx.begin();
        int maxResults = Application.getClientConfig(context).getInviteUsersMaxResults();
        if (maxResults <= 0) {
            maxResults = Utils.getPersonMaxResults();
        }
        List<PersonInfo> persons = getPersonService().getPeople(Utils.generatePersonFilter(contains.trim()), true, Utils.generatePersonSort(), new PagingRequest(maxResults, null)).getPage();
        ArrayList<SelectItem> itemList = new ArrayList<SelectItem>(persons.size());
        for (PersonInfo person : persons) {
            String username = person.getUserName();
            if (AuthenticationUtil.getGuestUserName().equals(username) == false) {
                String firstName = person.getFirstName();
                String lastName = person.getLastName();
                String name = (firstName != null ? firstName : "") + ' ' + (lastName != null ? lastName : "");
                SelectItem item = new SortableSelectItem(username, name + " [" + username + "]", lastName != null ? lastName : username);
                itemList.add(item);
            }
        }
        items = new SelectItem[itemList.size()];
        itemList.toArray(items);
        Arrays.sort(items);
        // commit the transaction
        tx.commit();
    } catch (Throwable err) {
        Utils.addErrorMessage(MessageFormat.format(Application.getMessage(FacesContext.getCurrentInstance(), Repository.ERROR_GENERIC), err.getMessage()), err);
        try {
            if (tx != null) {
                tx.rollback();
            }
        } catch (Exception tex) {
        }
        items = new SelectItem[0];
    } finally {
        if (resultSet != null) {
            resultSet.close();
        }
    }
    return items;
}
Also used : UserTransaction(javax.transaction.UserTransaction) FacesContext(javax.faces.context.FacesContext) PersonInfo(org.alfresco.service.cmr.security.PersonService.PersonInfo) ArrayList(java.util.ArrayList) SortableSelectItem(org.alfresco.web.ui.common.SortableSelectItem) PagingRequest(org.alfresco.query.PagingRequest) SortableSelectItem(org.alfresco.web.ui.common.SortableSelectItem) SelectItem(javax.faces.model.SelectItem) ResultSet(org.alfresco.service.cmr.search.ResultSet)

Example 58 with ResultSet

use of org.alfresco.service.cmr.search.ResultSet 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();
}
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) InvalidNodeRefException(org.alfresco.service.cmr.repository.InvalidNodeRefException) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) NodeRef(org.alfresco.service.cmr.repository.NodeRef) ResultSet(org.alfresco.service.cmr.search.ResultSet)

Example 59 with ResultSet

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;
}
Also used : HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HttpServletRequest(javax.servlet.http.HttpServletRequest) NodeRef(org.alfresco.service.cmr.repository.NodeRef) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) ResultSet(org.alfresco.service.cmr.search.ResultSet) WebScriptServletRequest(org.springframework.extensions.webscripts.servlet.WebScriptServletRequest) StoreRef(org.alfresco.service.cmr.repository.StoreRef) HttpSession(javax.servlet.http.HttpSession) ChildAssociationRef(org.alfresco.service.cmr.repository.ChildAssociationRef) RetryingTransactionCallback(org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback) AlfrescoRuntimeException(org.alfresco.error.AlfrescoRuntimeException)

Example 60 with ResultSet

use of org.alfresco.service.cmr.search.ResultSet in project alfresco-remote-api by Alfresco.

the class SharedLinkApiTest method testSharedLinkFindIncludeAspects.

@Test
public void testSharedLinkFindIncludeAspects() throws Exception {
    PublicApiClient.Favourites favouritesProxy = publicApiClient.favourites();
    QuickShareLinksImpl quickShareLinks = applicationContext.getBean("quickShareLinks", QuickShareLinksImpl.class);
    ServiceDescriptorRegistry serviceRegistry = applicationContext.getBean("ServiceRegistry", ServiceDescriptorRegistry.class);
    SearchService mockSearchService = mock(SearchService.class);
    serviceRegistry.setMockSearchService(mockSearchService);
    // As user 1 ...
    setRequestContext(user1);
    Paging paging = getPaging(0, 100);
    String content = "The quick brown fox jumps over the lazy dog.";
    String fileName1 = "fileOne_" + RUNID + ".txt";
    String fileName2 = "fileTwo_" + RUNID + ".txt";
    // As user 1 create 2 text files in -my- folder (i.e. User's Home)
    setRequestContext(user1);
    String file1Id = createTextFile(getMyNodeId(), fileName1, content).getId();
    String file2Id = createTextFile(getMyNodeId(), fileName2, content).getId();
    // Create shared links to file 1 and 2
    QuickShareLink body = new QuickShareLink();
    body.setNodeId(file1Id);
    post(URL_SHARED_LINKS, toJsonAsStringNonNull(body), 201);
    body = new QuickShareLink();
    body.setNodeId(file2Id);
    post(URL_SHARED_LINKS, toJsonAsStringNonNull(body), 201);
    // Favourite file with file1Id file as user 1
    Favourite file1Favourite = makeFileFavourite(file1Id);
    favouritesProxy.createFavourite(user1, file1Favourite, null);
    // Find shared links without include=isFavorite
    ResultSet mockResultSet = mockResultSet(Arrays.asList(file1Id, file2Id));
    when(mockSearchService.query(any())).thenReturn(mockResultSet);
    quickShareLinks.afterPropertiesSet();
    HttpResponse response = getAll(URL_SHARED_LINKS, paging, null, 200);
    List<QuickShareLink> sharedLinks = RestApiUtil.parseRestApiEntries(response.getJsonResponse(), QuickShareLink.class);
    assertEquals(2, sharedLinks.size());
    QuickShareLink resQuickShareLink1 = sharedLinks.get(0);
    QuickShareLink resQuickShareLink2 = sharedLinks.get(1);
    assertNull("aspectNames was not requested therefore it should not be included", resQuickShareLink1.getAspectNames());
    assertNull("aspectNames was not requested therefore it should not be included", resQuickShareLink2.getAspectNames());
    // Find shared links with include=isFavorite
    mockResultSet = mockResultSet(Arrays.asList(file1Id, file2Id));
    when(mockSearchService.query(any())).thenReturn(mockResultSet);
    quickShareLinks.afterPropertiesSet();
    Map<String, String> params = new HashMap<>();
    params.put("include", "aspectNames");
    response = getAll(URL_SHARED_LINKS, paging, params, 200);
    sharedLinks = RestApiUtil.parseRestApiEntries(response.getJsonResponse(), QuickShareLink.class);
    assertEquals(2, sharedLinks.size());
    resQuickShareLink1 = sharedLinks.get(0);
    resQuickShareLink2 = sharedLinks.get(1);
    assertNotNull("aspectNames was not requested therefore it should not be included", resQuickShareLink1.getAspectNames());
    assertNotNull("aspectNames was not requested therefore it should not be included", resQuickShareLink2.getAspectNames());
    serviceRegistry.setMockSearchService(null);
    quickShareLinks.afterPropertiesSet();
}
Also used : HashMap(java.util.HashMap) Paging(org.alfresco.rest.api.tests.client.PublicApiClient.Paging) HttpResponse(org.alfresco.rest.api.tests.client.HttpResponse) QuickShareLinksImpl(org.alfresco.rest.api.impl.QuickShareLinksImpl) ServiceDescriptorRegistry(org.alfresco.repo.service.ServiceDescriptorRegistry) SearchService(org.alfresco.service.cmr.search.SearchService) ResultSet(org.alfresco.service.cmr.search.ResultSet) PublicApiClient(org.alfresco.rest.api.tests.client.PublicApiClient) QuickShareLink(org.alfresco.rest.api.model.QuickShareLink) Favourite(org.alfresco.rest.api.tests.client.data.Favourite) Test(org.junit.Test)

Aggregations

ResultSet (org.alfresco.service.cmr.search.ResultSet)112 NodeRef (org.alfresco.service.cmr.repository.NodeRef)57 SearchParameters (org.alfresco.service.cmr.search.SearchParameters)49 ArrayList (java.util.ArrayList)25 HashMap (java.util.HashMap)22 SolrJSONResultSet (org.alfresco.repo.search.impl.lucene.SolrJSONResultSet)20 Test (org.junit.Test)20 ChildAssociationRef (org.alfresco.service.cmr.repository.ChildAssociationRef)17 QName (org.alfresco.service.namespace.QName)16 StoreRef (org.alfresco.service.cmr.repository.StoreRef)14 ResultSetRow (org.alfresco.service.cmr.search.ResultSetRow)14 HashSet (java.util.HashSet)13 EmptyResultSet (org.alfresco.repo.search.EmptyResultSet)13 SearchService (org.alfresco.service.cmr.search.SearchService)13 NodeService (org.alfresco.service.cmr.repository.NodeService)12 IOException (java.io.IOException)11 List (java.util.List)11 SearchRequestContext (org.alfresco.rest.api.search.context.SearchRequestContext)11 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)10 PagingLuceneResultSet (org.alfresco.repo.search.impl.lucene.PagingLuceneResultSet)10