Search in sources :

Example 16 with PagingRequest

use of org.alfresco.query.PagingRequest in project alfresco-remote-api by Alfresco.

the class AbstractDiscussionWebScript method renderTopic.

/*
     * Was topicpost.lib.js getTopicPostData / getTopicPostDataFromTopicAndPosts
     * 
     * TODO Switch the FTL to prefer the Info object rather than the ScriptNode
     */
protected Map<String, Object> renderTopic(TopicInfo topic, SiteInfo site) {
    // Fetch the primary post
    PostInfo primaryPost = discussionService.getPrimaryPost(topic);
    if (primaryPost == null) {
        throw new WebScriptException(Status.STATUS_PRECONDITION_FAILED, "First (primary) post was missing from the topic, can't fetch");
    }
    // Fetch the most recent reply
    PostInfo mostRecentPost = discussionService.getMostRecentPost(topic);
    // Find out how many replies there are
    int numReplies;
    if (mostRecentPost.getNodeRef().equals(primaryPost.getNodeRef())) {
        // Only the one post in the topic
        mostRecentPost = null;
        numReplies = 0;
    } else {
        // Use this trick to get the number of posts in the topic,
        // but without needing to get lots of data and objects
        PagingRequest paging = new PagingRequest(1);
        paging.setRequestTotalCountMax(MAX_QUERY_ENTRY_COUNT);
        PagingResults<PostInfo> posts = discussionService.listPosts(topic, paging);
        // The primary post is in the list, so exclude from the reply count
        numReplies = posts.getTotalResultCount().getFirst() - 1;
    }
    // Build the details
    Map<String, Object> item = new HashMap<String, Object>();
    item.put(KEY_IS_TOPIC_POST, true);
    item.put(KEY_TOPIC, topic.getNodeRef());
    item.put(KEY_POST, primaryPost.getNodeRef());
    item.put(KEY_CAN_EDIT, canUserEditPost(primaryPost, site));
    item.put(KEY_AUTHOR, buildPerson(topic.getCreator()));
    // The reply count is one less than all posts (first is the primary one)
    item.put("totalReplyCount", numReplies);
    // Add the topic site
    item.put("site", topic.getShortSiteName());
    // We want details on the most recent post
    if (mostRecentPost != null) {
        item.put("lastReply", mostRecentPost.getNodeRef());
        item.put("lastReplyBy", buildPerson(mostRecentPost.getCreator()));
    }
    // Include the tags
    item.put("tags", topic.getTags());
    // All done
    return item;
}
Also used : WebScriptException(org.springframework.extensions.webscripts.WebScriptException) HashMap(java.util.HashMap) PostInfo(org.alfresco.service.cmr.discussion.PostInfo) JSONObject(org.json.simple.JSONObject) PagingRequest(org.alfresco.query.PagingRequest)

Example 17 with PagingRequest

use of org.alfresco.query.PagingRequest in project alfresco-remote-api by Alfresco.

the class ForumTopicsFilteredGet method executeImpl.

/**
 * @param site SiteInfo
 * @param nodeRef Not required. It is only included because it is overriding the parent class.
 * @param topic Not required. It is only included because it is overriding the parent class.
 * @param post Not required. It is only included because it is overriding the parent class.
 * @param req WebScriptRequest
 * @param status Not required. It is only included because it is overriding the parent class.
 * @param cache Not required. It is only included because it is overriding the parent class.
 *
 * @return Map
 */
@Override
protected Map<String, Object> executeImpl(SiteInfo site, NodeRef nodeRef, TopicInfo topic, PostInfo post, WebScriptRequest req, JSONObject json, Status status, Cache cache) {
    // They shouldn't be trying to list of an existing Post or Topic
    if (topic != null || post != null) {
        String error = "Can't list Topics inside an existing Topic or Post";
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, error);
    }
    // Set search filter to users topics or all topics
    String pAuthor = req.getParameter("topics");
    String author = DEFAULT_TOPIC_AUTHOR;
    if (pAuthor != null) {
        author = pAuthor;
    }
    // Set the number of days in the past to search from
    String pDaysAgo = req.getParameter("history");
    int daysAgo = DEFAULT_TOPIC_LATEST_POST_DAYS_AGO;
    if (pDaysAgo != null) {
        try {
            daysAgo = Integer.parseInt(pDaysAgo);
        } catch (NumberFormatException e) {
        // do nothing. history has already been preset to the default value.
        }
    }
    // Get the complete search query
    Pair<String, String> searchQuery = getSearchQuery(site, author, daysAgo);
    // Get the filtered topics
    PagingRequest paging = buildPagingRequest(req);
    PagingResults<TopicInfo> topics = doSearch(searchQuery, false, paging);
    // Build the common model parts
    Map<String, Object> model = buildCommonModel(site, topic, post, req);
    // Have the topics rendered
    model.put("data", renderTopics(topics, paging, site));
    // All done
    return model;
}
Also used : WebScriptException(org.springframework.extensions.webscripts.WebScriptException) JSONObject(org.json.simple.JSONObject) PagingRequest(org.alfresco.query.PagingRequest) TopicInfo(org.alfresco.service.cmr.discussion.TopicInfo)

Example 18 with PagingRequest

use of org.alfresco.query.PagingRequest in project alfresco-remote-api by Alfresco.

the class ForumTopicsGet method executeImpl.

@Override
protected Map<String, Object> executeImpl(SiteInfo site, NodeRef nodeRef, TopicInfo topic, PostInfo post, WebScriptRequest req, JSONObject json, Status status, Cache cache) {
    // They shouldn't be trying to list of an existing Post or Topic
    if (topic != null || post != null) {
        String error = "Can't list Topics inside an existing Topic or Post";
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, error);
    }
    // Do we need to list or search?
    boolean tagSearch = false;
    String tag = req.getParameter("tag");
    if (tag != null && tag.length() > 0) {
        tagSearch = true;
        // Tags can be full unicode strings, so decode
        tag = URLDecoder.decode(tag);
    }
    // Get the topics
    boolean oldestTopicsFirst = false;
    PagingResults<TopicInfo> topics = null;
    PagingRequest paging = buildPagingRequest(req);
    if (tagSearch) {
        // Tag based is a search rather than a listing
        if (site != null) {
            topics = discussionService.findTopics(site.getShortName(), null, tag, oldestTopicsFirst, paging);
        } else {
            topics = discussionService.findTopics(nodeRef, null, tag, oldestTopicsFirst, paging);
        }
    } else {
        if (site != null) {
            topics = discussionService.listTopics(site.getShortName(), oldestTopicsFirst, paging);
        } else {
            topics = discussionService.listTopics(nodeRef, oldestTopicsFirst, buildPagingRequest(req));
        }
    }
    // been created yet, use the site for the permissions checking
    if (site != null && nodeRef == null) {
        nodeRef = site.getNodeRef();
    }
    // Build the common model parts
    Map<String, Object> model = buildCommonModel(site, topic, post, req);
    model.put("forum", nodeRef);
    // Have the topics rendered
    model.put("data", renderTopics(topics, paging, site));
    // All done
    return model;
}
Also used : WebScriptException(org.springframework.extensions.webscripts.WebScriptException) JSONObject(org.json.simple.JSONObject) TopicInfo(org.alfresco.service.cmr.discussion.TopicInfo) PagingRequest(org.alfresco.query.PagingRequest)

Example 19 with PagingRequest

use of org.alfresco.query.PagingRequest in project alfresco-remote-api by Alfresco.

the class ForumTopicsRecentGet method executeImpl.

@Override
protected Map<String, Object> executeImpl(SiteInfo site, NodeRef nodeRef, TopicInfo topic, PostInfo post, WebScriptRequest req, JSONObject json, Status status, Cache cache) {
    // They shouldn't be trying to list of an existing Post or Topic
    if (topic != null || post != null) {
        String error = "Can't list Topics inside an existing Topic or Post";
        throw new WebScriptException(Status.STATUS_BAD_REQUEST, error);
    }
    // Grab the date range to search over
    String numDaysS = req.getParameter("numdays");
    int numDays = RECENT_SEARCH_PERIOD_DAYS;
    if (numDaysS != null) {
        numDays = Integer.parseInt(numDaysS);
    }
    Date now = new Date();
    Date from = new Date(now.getTime() - numDays * ONE_DAY_MS);
    Date to = new Date(now.getTime() + ONE_DAY_MS);
    // Get the recent topics, newest first
    PagingResults<TopicInfo> topics = null;
    PagingRequest paging = buildPagingRequest(req);
    if (site != null) {
        topics = discussionService.listTopics(site.getShortName(), from, to, false, paging);
    } else {
        topics = discussionService.listTopics(nodeRef, from, to, false, paging);
    }
    // been created yet, use the site for the permissions checking
    if (site != null && nodeRef == null) {
        nodeRef = site.getNodeRef();
    }
    // Build the common model parts
    Map<String, Object> model = buildCommonModel(site, topic, post, req);
    model.put("forum", nodeRef);
    // Have the topics rendered
    model.put("data", renderTopics(topics, paging, site));
    // All done
    return model;
}
Also used : WebScriptException(org.springframework.extensions.webscripts.WebScriptException) JSONObject(org.json.simple.JSONObject) Date(java.util.Date) TopicInfo(org.alfresco.service.cmr.discussion.TopicInfo) PagingRequest(org.alfresco.query.PagingRequest)

Example 20 with PagingRequest

use of org.alfresco.query.PagingRequest 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)

Aggregations

PagingRequest (org.alfresco.query.PagingRequest)36 ArrayList (java.util.ArrayList)18 Pair (org.alfresco.util.Pair)12 NodeRef (org.alfresco.service.cmr.repository.NodeRef)11 HashMap (java.util.HashMap)10 JSONObject (org.json.simple.JSONObject)10 Paging (org.alfresco.rest.framework.resource.parameters.Paging)8 Map (java.util.Map)7 Date (java.util.Date)6 UserTransaction (javax.transaction.UserTransaction)6 WebScriptException (org.springframework.extensions.webscripts.WebScriptException)6 AbstractList (java.util.AbstractList)5 FacesContext (javax.faces.context.FacesContext)5 InvalidArgumentException (org.alfresco.rest.framework.core.exceptions.InvalidArgumentException)5 TopicInfo (org.alfresco.service.cmr.discussion.TopicInfo)5 PersonInfo (org.alfresco.service.cmr.security.PersonService.PersonInfo)5 AccessDeniedException (org.alfresco.repo.security.permissions.AccessDeniedException)4 SiteInfo (org.alfresco.service.cmr.site.SiteInfo)4 HashSet (java.util.HashSet)3 List (java.util.List)3