Example usage for org.apache.solr.client.solrj SolrQuery setRows

List of usage examples for org.apache.solr.client.solrj SolrQuery setRows

Introduction

In this page you can find the example usage for org.apache.solr.client.solrj SolrQuery setRows.

Prototype

public SolrQuery setRows(Integer rows) 

Source Link

Usage

From source file:edu.unc.lib.dl.search.solr.service.SolrSearchService.java

License:Apache License

/**
 * Attempts to retrieve the hierarchical facet from the facet field corresponding to fieldKey that matches the value
 * of searchValue. Retrieves and populates all tiers leading up to the tier number given in searchValue.
 * //from   w w w.  ja v  a  2  s.  co m
 * @param fieldKey
 *           Key of the facet field to search for the facet within.
 * @param searchValue
 *           Value to find a matching facet for, should be formatted <tier>,<value>
 * @param accessGroups
 * @return
 */
public FacetFieldObject getHierarchicalFacet(AbstractHierarchicalFacet facet, AccessGroupSet accessGroups) {
    QueryResponse queryResponse = null;
    SolrQuery solrQuery = new SolrQuery();
    StringBuilder query = new StringBuilder();
    query.append("[* TO *]");

    try {
        // Add access restrictions to query
        addAccessRestrictions(query, accessGroups);
    } catch (AccessRestrictionException e) {
        // If the user doesn't have any access groups, they don't have access to anything, return null.
        LOG.error(e.getMessage());
        return null;
    }
    solrQuery.setQuery(query.toString());
    solrQuery.setRows(0);

    solrQuery.setFacet(true);
    solrQuery.setFacetMinCount(1);

    String solrFieldName = solrSettings.getFieldName(facet.getFieldName());

    solrQuery.addFacetField(solrFieldName);
    solrQuery.setFacetPrefix(solrFieldName, facet.getSearchValue());

    LOG.debug("getHierarchicalFacet query: " + solrQuery.toString());
    try {
        queryResponse = server.query(solrQuery);
    } catch (SolrServerException e) {
        LOG.error("Error retrieving Solr object request: " + e);
        return null;
    }
    FacetField facetField = queryResponse.getFacetField(solrFieldName);
    if (facetField.getValueCount() == 0)
        return null;
    return facetFieldFactory.createFacetFieldObject(facet.getFieldName(),
            queryResponse.getFacetField(solrFieldName));
}

From source file:edu.unc.lib.dl.search.solr.service.SolrSearchService.java

License:Apache License

public Date getTimestamp(String pid, AccessGroupSet accessGroups) {
    QueryResponse queryResponse = null;/*from   w w w  .j a va2  s  .  com*/
    SolrQuery solrQuery = new SolrQuery();
    StringBuilder query = new StringBuilder();
    query.append(solrSettings.getFieldName(SearchFieldKeys.ID.name())).append(':')
            .append(SolrSettings.sanitize(pid));
    try {
        // Add access restrictions to query
        addAccessRestrictions(query, accessGroups);
    } catch (AccessRestrictionException e) {
        // If the user doesn't have any access groups, they don't have access to anything, return null.
        LOG.error("Error while attempting to add access restrictions to object " + pid, e);
        return null;
    }

    solrQuery.addField(solrSettings.getFieldName(SearchFieldKeys.TIMESTAMP.name()));

    solrQuery.setQuery(query.toString());
    solrQuery.setRows(1);

    LOG.debug("query: " + solrQuery.toString());
    try {
        queryResponse = server.query(solrQuery);
    } catch (SolrServerException e) {
        LOG.error("Error retrieving Solr object request: " + e);
        return null;
    }

    if (queryResponse.getResults().getNumFound() == 0)
        return null;
    return (Date) queryResponse.getResults().get(0).getFieldValue("timestamp");
}

From source file:edu.unc.lib.dl.search.solr.service.SolrSearchService.java

License:Apache License

/**
 * Constructs a SolrQuery object from the search state specified within a SearchRequest object. The request may
 * optionally request to retrieve facet results in addition to search results.
 * /*from w w  w .j  a v a 2 s .c  o m*/
 * @param searchRequest
 * @param isRetrieveFacetsRequest
 * @return
 */
protected SolrQuery generateSearch(SearchRequest searchRequest) {
    SearchState searchState = (SearchState) searchRequest.getSearchState();
    SolrQuery solrQuery = new SolrQuery();
    StringBuilder termQuery = new StringBuilder();

    // Generate search term query string
    addSearchFields(searchState, termQuery);

    // Add range Fields to the query
    addRangeFields(searchState, termQuery);

    // No query terms given, make it an everything query
    StringBuilder query = new StringBuilder();
    if (termQuery.length() == 0) {
        query.append("*:* ");
    } else {
        query.append('(').append(termQuery).append(')');
    }

    // Add access restrictions to query
    try {
        addAccessRestrictions(query, searchRequest.getAccessGroups());
    } catch (AccessRestrictionException e) {
        // If the user doesn't have any access groups, they don't have access to anything, return null.
        LOG.debug("User had no access groups", e);
        return null;
    }

    // Add query
    solrQuery.setQuery(query.toString());

    if (searchState.getResultFields() != null) {
        for (String field : searchState.getResultFields()) {
            String solrFieldName = solrSettings.getFieldName(field);
            if (solrFieldName != null)
                solrQuery.addField(solrFieldName);
        }
    }

    if (searchState.getRollup() != null && searchState.getRollup()) {
        solrQuery.set(GroupParams.GROUP, true);
        if (searchState.getRollupField() == null)
            solrQuery.set(GroupParams.GROUP_FIELD, solrSettings.getFieldName(SearchFieldKeys.ROLLUP_ID.name()));
        else
            solrQuery.set(GroupParams.GROUP_FIELD, solrSettings.getFieldName(searchState.getRollupField()));

        solrQuery.set(GroupParams.GROUP_TOTAL_COUNT, true);
        if (searchState.getFacetsToRetrieve() != null && searchState.getFacetsToRetrieve().size() > 0) {
            solrQuery.set(GroupParams.GROUP_FACET, true);
        }
    }

    // Add sort parameters
    List<SearchSettings.SortField> sortFields = searchSettings.sortTypes.get(searchState.getSortType());
    if (sortFields != null) {
        for (int i = 0; i < sortFields.size(); i++) {
            SearchSettings.SortField sortField = sortFields.get(i);
            SolrQuery.ORDER sortOrder = SolrQuery.ORDER.valueOf(sortField.getSortOrder());
            if (!searchState.getSortNormalOrder())
                sortOrder = sortOrder.reverse();
            solrQuery.addSort(solrSettings.getFieldName(sortField.getFieldName()), sortOrder);
        }
    }

    // Set requested resource types
    String resourceTypeFilter = this.getResourceTypeFilter(searchState.getResourceTypes());
    if (resourceTypeFilter != null) {
        solrQuery.addFilterQuery(resourceTypeFilter);
    }

    // Turn on faceting
    if (searchRequest.isRetrieveFacets()) {
        solrQuery.setFacet(true);
        solrQuery.setFacetMinCount(1);
        if (searchState.getBaseFacetLimit() != null)
            solrQuery.setFacetLimit(searchState.getBaseFacetLimit());

        if (searchState.getFacetsToRetrieve() != null) {
            // Add facet fields
            for (String facetName : searchState.getFacetsToRetrieve()) {
                String facetField = solrSettings.getFieldName(facetName);
                if (facetField != null)
                    solrQuery.addFacetField(solrSettings.getFieldName(facetName));
            }
        }
    }

    // Override the base facet limit if overrides are given.
    if (searchState.getFacetLimits() != null) {
        for (Entry<String, Integer> facetLimit : searchState.getFacetLimits().entrySet()) {
            solrQuery.add("f." + solrSettings.getFieldName(facetLimit.getKey()) + ".facet.limit",
                    facetLimit.getValue().toString());
        }
    }

    // Add facet limits
    Map<String, Object> facets = searchState.getFacets();
    if (facets != null) {
        Iterator<Entry<String, Object>> facetIt = facets.entrySet().iterator();
        while (facetIt.hasNext()) {
            Entry<String, Object> facetEntry = facetIt.next();

            if (facetEntry.getValue() instanceof String) {
                LOG.debug("Adding facet " + facetEntry.getKey() + " as a String");
                // Add Normal facets
                solrQuery.addFilterQuery(solrSettings.getFieldName(facetEntry.getKey()) + ":\""
                        + SolrSettings.sanitize((String) facetEntry.getValue()) + "\"");
            } else {
                LOG.debug("Adding facet " + facetEntry.getKey() + " as a "
                        + facetEntry.getValue().getClass().getName());
                facetFieldUtil.addToSolrQuery(facetEntry.getValue(), solrQuery);
            }
        }
    }

    // Scope hierarchical facet results to the highest tier selected within the facet tree
    if (searchRequest.isRetrieveFacets() && searchRequest.isApplyCutoffs()
            && searchState.getFacetsToRetrieve() != null) {
        Set<String> facetsQueried = searchState.getFacets().keySet();
        // Apply closing cutoff to all cutoff facets that are being retrieved but not being queried for
        for (String fieldKey : searchState.getFacetsToRetrieve()) {
            if (!facetsQueried.contains(fieldKey)) {
                facetFieldUtil.addDefaultFacetPivot(fieldKey, solrQuery);
            }
        }

        // Add individual facet field sorts if they are present.
        if (searchState.getFacetSorts() != null) {
            for (Entry<String, String> facetSort : searchState.getFacetSorts().entrySet()) {
                solrQuery.add("f." + solrSettings.getFieldName(facetSort.getKey()) + ".facet.sort",
                        facetSort.getValue());
            }
        }
    }

    // Set Navigation options
    if (searchState.getStartRow() != null)
        solrQuery.setStart(searchState.getStartRow());
    if (searchState.getRowsPerPage() != null)
        solrQuery.setRows(searchState.getRowsPerPage());

    return solrQuery;
}

From source file:edu.unc.lib.dl.ui.service.SolrQueryLayerService.java

License:Apache License

/**
 * Retrieves metadata fields for the parent collection pids contained by the supplied facet object.
 * /*  www . ja  v a2  s .com*/
 * @param parentCollectionFacet
 *           Facet object containing parent collection ids to lookup
 * @param accessGroups
 * @return
 */
public List<BriefObjectMetadataBean> getParentCollectionValues(FacetFieldObject parentCollectionFacet) {
    if (parentCollectionFacet == null || parentCollectionFacet.getValues() == null
            || parentCollectionFacet.getValues().size() == 0) {
        return null;
    }

    QueryResponse queryResponse = null;
    SolrQuery solrQuery = new SolrQuery();
    StringBuilder query = new StringBuilder();
    boolean first = true;

    query.append('(');
    for (GenericFacet pidFacet : parentCollectionFacet.getValues()) {
        if (pidFacet.getSearchValue() != null && pidFacet.getSearchValue().length() > 0) {
            if (first) {
                first = false;
            } else {
                query.append(" OR ");
            }
            query.append(solrSettings.getFieldName(SearchFieldKeys.ID.name())).append(':')
                    .append(SolrSettings.sanitize(pidFacet.getSearchValue()));
        }
    }
    query.append(')');

    // If no pids were added to the query, then there's nothing to look up
    if (first) {
        return null;
    }

    try {
        // Add access restrictions to query
        addAccessRestrictions(query);
    } catch (AccessRestrictionException e) {
        // If the user doesn't have any access groups, they don't have access to anything, return null.
        LOG.error("No access groups", e);
        return null;
    }

    solrQuery.setQuery(query.toString());

    solrQuery.setFacet(true);
    solrQuery.setFields(solrSettings.getFieldName(SearchFieldKeys.ID.name()),
            solrSettings.getFieldName(SearchFieldKeys.ANCESTOR_PATH.name()),
            solrSettings.getFieldName(SearchFieldKeys.TITLE.name()));

    solrQuery.setRows(parentCollectionFacet.getValues().size());

    try {
        queryResponse = this.executeQuery(solrQuery);
        return queryResponse.getBeans(BriefObjectMetadataBean.class);
    } catch (SolrServerException e) {
        LOG.error("Failed to execute query " + solrQuery.toString(), e);
    }
    return null;
}

From source file:edu.unc.lib.dl.ui.service.SolrQueryLayerService.java

License:Apache License

/**
 * Retrieves a list of the nearest windowSize neighbors within the nearest parent collection or folder around the
 * item metadata, based on the order field of the item. The first windowSize - 1 neighbors are retrieved to each side
 * of the item, and trimmed so that there are always windowSize - 1 neighbors surrounding the item if possible. If no
 * order field is available, a list of arbitrary windowSize neighbors is returned.
 * /*  www  . j a v a  2  s  . co  m*/
 * @param metadata
 *           Record which the window pivots around.
 * @param windowSize
 *           max number of items in the window. This includes the pivot, so odd numbers are recommended.
 * @param accessGroups
 *           Access groups of the user making this request.
 * @return
 */
public List<BriefObjectMetadataBean> getNeighboringItems(BriefObjectMetadataBean metadata, int windowSize,
        AccessGroupSet accessGroups) {

    // Get the common access restriction clause (starts with "AND ...")

    StringBuilder accessRestrictionClause = new StringBuilder();

    try {
        addAccessRestrictions(accessRestrictionClause, accessGroups);
    } catch (AccessRestrictionException e) {
        // If the user doesn't have any access groups, they don't have access to anything, return null.
        LOG.error(e.getMessage());
        return null;
    }

    // Prepare the common query object, including a filter for resource type and the
    // facet which selects only the item's siblings.

    SolrQuery solrQuery = new SolrQuery();

    solrQuery.setFacet(true);
    solrQuery.addFilterQuery(solrSettings.getFieldName(SearchFieldKeys.RESOURCE_TYPE.name()) + ":File "
            + solrSettings.getFieldName(SearchFieldKeys.RESOURCE_TYPE.name()) + ":Aggregate");

    CutoffFacet ancestorPath = null;

    if (metadata.getResourceType().equals(searchSettings.resourceTypeFile)
            || metadata.getResourceType().equals(searchSettings.resourceTypeAggregate)) {
        ancestorPath = metadata.getAncestorPathFacet();
    } else {
        ancestorPath = metadata.getPath();
    }

    if (ancestorPath != null) {
        // We want only objects at the same level of the hierarchy
        ancestorPath.setCutoff(ancestorPath.getHighestTier() + 1);

        facetFieldUtil.addToSolrQuery(ancestorPath, solrQuery);
    }

    // If this item has no display order, get arbitrary items surrounding it.

    Long pivotOrder = metadata.getDisplayOrder();

    if (pivotOrder == null) {

        LOG.debug("No display order, just querying for " + windowSize + " siblings");

        StringBuilder query = new StringBuilder();

        List<BriefObjectMetadataBean> list = null;

        query.append("*:*");
        query.append(accessRestrictionClause);
        solrQuery.setQuery(query.toString());

        solrQuery.setStart(0);
        solrQuery.setRows(windowSize);

        solrQuery.setSort(solrSettings.getFieldName(SearchFieldKeys.DISPLAY_ORDER.name()),
                SolrQuery.ORDER.desc);

        try {
            QueryResponse queryResponse = this.executeQuery(solrQuery);
            list = queryResponse.getBeans(BriefObjectMetadataBean.class);
        } catch (SolrServerException e) {
            LOG.error("Error retrieving Neighboring items: " + e);
            return null;
        }

        return list;

        // Otherwise, query for items surrounding this item.

    } else {

        LOG.debug("Display order is " + pivotOrder);

        // Find the right and left lists

        StringBuilder query;

        List<BriefObjectMetadataBean> leftList = null;
        List<BriefObjectMetadataBean> rightList = null;

        solrQuery.setStart(0);
        solrQuery.setRows(windowSize - 1);

        // Right list

        query = new StringBuilder();

        query.append(solrSettings.getFieldName(SearchFieldKeys.DISPLAY_ORDER.name())).append(":[")
                .append(pivotOrder + 1).append(" TO *]");
        query.append(accessRestrictionClause);
        solrQuery.setQuery(query.toString());

        solrQuery.setSort(solrSettings.getFieldName(SearchFieldKeys.DISPLAY_ORDER.name()), SolrQuery.ORDER.asc);

        try {
            QueryResponse queryResponse = this.executeQuery(solrQuery);
            rightList = queryResponse.getBeans(BriefObjectMetadataBean.class);
        } catch (SolrServerException e) {
            LOG.error("Error retrieving Neighboring items: " + e);
            return null;
        }

        LOG.debug("Got " + rightList.size() + " items for right list");

        // Left list

        // (Note that display order stuff is reversed.)

        query = new StringBuilder();

        query.append(solrSettings.getFieldName(SearchFieldKeys.DISPLAY_ORDER.name())).append(":[* TO ")
                .append(pivotOrder - 1).append("]");
        query.append(accessRestrictionClause);
        solrQuery.setQuery(query.toString());

        solrQuery.setSort(solrSettings.getFieldName(SearchFieldKeys.DISPLAY_ORDER.name()),
                SolrQuery.ORDER.desc);

        try {
            QueryResponse queryResponse = this.executeQuery(solrQuery);
            leftList = queryResponse.getBeans(BriefObjectMetadataBean.class);
        } catch (SolrServerException e) {
            LOG.error("Error retrieving Neighboring items: " + e);
            return null;
        }

        LOG.debug("Got " + leftList.size() + " items for left list");

        // Trim the lists

        int halfWindow = windowSize / 2;

        // If we have enough in both lists, trim both to be
        // halfWindow long.

        if (leftList.size() >= halfWindow && rightList.size() >= halfWindow) {

            LOG.debug("Trimming both lists");

            leftList.subList(halfWindow, leftList.size()).clear();
            rightList.subList(halfWindow, rightList.size()).clear();

            // If we don't have enough in the left list and we have extra in the right list,
            // try to pick up the slack by trimming fewer items from the right list.

        } else if (leftList.size() < halfWindow && rightList.size() > halfWindow) {

            LOG.debug("Picking up slack from right list");

            // How much extra do we need from the right list?

            int extra = halfWindow - leftList.size();

            // Only "take" the extra (ie, clear less of the right list) if we have it available.

            if (halfWindow + extra < rightList.size())
                rightList.subList(halfWindow + extra, rightList.size()).clear();

        } else if (rightList.size() < halfWindow && leftList.size() > halfWindow) {

            LOG.debug("Picking up slack from left list");

            int extra = halfWindow - rightList.size();

            if (halfWindow + extra < leftList.size())
                leftList.subList(halfWindow + extra, leftList.size()).clear();

        }

        // (Otherwise, we do no trimming, since both lists are smaller or the same size
        // as the window.)

        // Assemble the result.

        Collections.reverse(leftList);
        leftList.add(metadata);
        leftList.addAll(rightList);

        return leftList;

    }

}

From source file:edu.unc.lib.dl.ui.service.SolrQueryLayerService.java

License:Apache License

public long getChildrenCount(BriefObjectMetadataBean metadataObject, AccessGroupSet accessGroups) {
    QueryResponse queryResponse = null;//  w  w  w  . jav a2  s.  co m
    SolrQuery solrQuery = new SolrQuery();
    StringBuilder query = new StringBuilder("*:* ");

    try {
        // Add access restrictions to query
        addAccessRestrictions(query, accessGroups);
    } catch (AccessRestrictionException e) {
        // If the user doesn't have any access groups, they don't have access to anything, return null.
        LOG.error(e.getMessage());
        return -1;
    }

    solrQuery.setStart(0);
    solrQuery.setRows(0);

    solrQuery.setQuery(query.toString());

    query = new StringBuilder();
    query.append(solrSettings.getFieldName(SearchFieldKeys.ANCESTOR_PATH.name())).append(':')
            .append(SolrSettings.sanitize(metadataObject.getPath().getSearchValue())).append(",*");

    solrQuery.setFacet(true);
    solrQuery.addFilterQuery(query.toString());

    try {
        queryResponse = this.executeQuery(solrQuery);
        return queryResponse.getResults().getNumFound();
    } catch (SolrServerException e) {
        LOG.error("Error retrieving Solr search result request", e);
    }
    return -1;
}

From source file:edu.unc.lib.dl.ui.service.SolrQueryLayerService.java

License:Apache License

public void getChildrenCounts(List<BriefObjectMetadata> resultList, AccessGroupSet accessGroups,
        String countName, String queryAddendum, SolrQuery baseQuery) {
    long startTime = System.currentTimeMillis();
    if (resultList == null || resultList.size() == 0)
        return;//w  w  w . ja  v  a2  s  . com

    String ancestorPathField = solrSettings.getFieldName(SearchFieldKeys.ANCESTOR_PATH.name());
    SolrQuery solrQuery;
    if (baseQuery == null) {
        // Create a base query since we didn't receive one
        solrQuery = new SolrQuery();
        StringBuilder query = new StringBuilder("*:*");
        try {
            // Add access restrictions to query
            addAccessRestrictions(query, accessGroups);
        } catch (AccessRestrictionException e) {
            // If the user doesn't have any access groups, they don't have access to anything, return null.
            LOG.error(e.getMessage());
            return;
        }

        solrQuery.setStart(0);
        solrQuery.setRows(0);

        solrQuery.setQuery(query.toString());
    } else {
        // Starting from a base query
        solrQuery = baseQuery.getCopy();
        // Make sure we aren't returning any normal results
        solrQuery.setRows(0);
        // Remove all facet fields so we are only getting ancestor path
        if (solrQuery.getFacetFields() != null) {
            for (String facetField : solrQuery.getFacetFields()) {
                solrQuery.removeFacetField(facetField);
            }
        }
    }

    if (queryAddendum != null) {
        solrQuery.setQuery(solrQuery.getQuery() + " AND " + queryAddendum);
    }

    solrQuery.setFacet(true);
    solrQuery.setFacetMinCount(1);
    solrQuery.addFacetField(ancestorPathField);

    Integer countPageSize;
    try {
        countPageSize = new Integer(searchSettings.getProperty("search.facet.countPageSize"));
    } catch (NumberFormatException e) {
        countPageSize = 20;
    }

    solrQuery.add("f." + ancestorPathField + ".facet.limit", Integer.toString(Integer.MAX_VALUE));
    // Sort by value rather than count so that earlier tiers will come first in case the result gets cut off
    solrQuery.setFacetSort("index");

    java.util.Map<Integer, StringBuilder> tierQueryMap = new java.util.HashMap<Integer, StringBuilder>();
    java.util.Map<Integer, List<BriefObjectMetadata>> containerMap = new java.util.HashMap<Integer, List<BriefObjectMetadata>>();

    // Pare the list of ids we are searching for and assigning counts to down to just containers
    for (BriefObjectMetadata metadataObject : resultList) {
        if (metadataObject.getPath() != null && metadataObject.getContentModel() != null
                && metadataObject.getContentModel().contains(ContentModelHelper.Model.CONTAINER.toString())) {
            CutoffFacetNode highestTier = metadataObject.getPath().getHighestTierNode();
            StringBuilder tierQuery = tierQueryMap.get(highestTier.getTier());
            List<BriefObjectMetadata> containerObjects = containerMap.get(highestTier.getTier());
            if (tierQuery == null) {
                tierQuery = new StringBuilder();
                tierQueryMap.put(highestTier.getTier(), tierQuery);

                containerObjects = new ArrayList<BriefObjectMetadata>();
                containerMap.put(highestTier.getTier(), containerObjects);
            }

            if (tierQuery.length() == 0) {
                tierQuery.append(ancestorPathField).append(":(");
            } else {
                tierQuery.append(" OR ");
            }

            tierQuery.append(SolrSettings.sanitize(highestTier.getSearchValue())).append(",*");
            containerObjects.add(metadataObject);

            // If there are a lot of results, then do a partial lookup
            if (containerObjects.size() >= countPageSize) {
                tierQuery.append(")");
                this.executeChildrenCounts(tierQuery, containerObjects, solrQuery, countName,
                        highestTier.getTier());
                LOG.info("Partial query done at " + System.currentTimeMillis() + " ("
                        + (System.currentTimeMillis() - startTime) + ")");
                containerMap.remove(highestTier.getTier());
                tierQueryMap.remove(highestTier.getTier());
            }
        }
    }

    Iterator<java.util.Map.Entry<Integer, StringBuilder>> queryIt = tierQueryMap.entrySet().iterator();
    while (queryIt.hasNext()) {
        java.util.Map.Entry<Integer, StringBuilder> tierQueryEntry = queryIt.next();
        tierQueryEntry.getValue().append(')');
        this.executeChildrenCounts(tierQueryEntry.getValue(), containerMap.get(tierQueryEntry.getKey()),
                solrQuery, countName, tierQueryEntry.getKey());
    }
    LOG.info("Child count query done at " + System.currentTimeMillis() + " ("
            + (System.currentTimeMillis() - startTime) + ")");
}

From source file:edu.unc.lib.dl.ui.service.SolrQueryLayerService.java

License:Apache License

/**
 * Retrieves results for populating a hierarchical browse view. Supports all the regular navigation available to
 * searches. Results contain child counts for each item (all items returned are containers), and a map containing the
 * number of nested subcontainers per container. Children counts are retrieved based on facet counts.
 * /*from w w  w.j a v a  2s.  c  o m*/
 * @param browseRequest
 * @return
 */
public HierarchicalBrowseResultResponse getHierarchicalBrowseResults(HierarchicalBrowseRequest browseRequest) {
    AccessGroupSet accessGroups = browseRequest.getAccessGroups();
    SearchState browseState = (SearchState) browseRequest.getSearchState().clone();
    HierarchicalBrowseResultResponse browseResults = new HierarchicalBrowseResultResponse();

    CutoffFacet rootPath = null;
    BriefObjectMetadataBean rootNode = null;
    if (browseRequest.getRootPid() != null) {
        rootNode = getObjectById(
                new SimpleIdRequest(browseRequest.getRootPid(), browseRequest.getAccessGroups()));
        if (rootNode != null) {
            rootPath = rootNode.getPath();
            browseState.getFacets().put(SearchFieldKeys.ANCESTOR_PATH.name(), rootPath);
            browseResults.setSelectedContainer(rootNode);
        }
    }
    // Default the ancestor path to the collections object so we always have a root
    if (rootNode == null) {
        rootPath = (CutoffFacet) browseState.getFacets().get(SearchFieldKeys.ANCESTOR_PATH.name());
        if (rootPath == null) {
            rootPath = new CutoffFacet(SearchFieldKeys.ANCESTOR_PATH.name(),
                    "1," + this.collectionsPid.getPid());
            browseState.getFacets().put(SearchFieldKeys.ANCESTOR_PATH.name(), rootPath);
        }

        rootNode = getObjectById(new SimpleIdRequest(rootPath.getSearchKey(), browseRequest.getAccessGroups()));
    }
    boolean rootIsAStub = rootNode == null;
    if (rootIsAStub) {
        // Parent is not found, but children are, so make a stub for the parent.
        rootNode = new BriefObjectMetadataBean();
        rootNode.setId(rootPath.getSearchKey());
        rootNode.setAncestorPathFacet(rootPath);
    }

    SearchState hierarchyState = searchStateFactory.createHierarchyListSearchState();
    // Use the ancestor path facet from the state where we will have set a default value
    hierarchyState.getFacets().put(SearchFieldKeys.ANCESTOR_PATH.name(), rootPath);
    hierarchyState.setRowsPerPage(0);

    SearchRequest hierarchyRequest = new SearchRequest(hierarchyState, accessGroups, false);

    SolrQuery baseQuery = this.generateSearch(hierarchyRequest);
    // Get the set of all applicable containers
    SolrQuery hierarchyQuery = baseQuery.getCopy();
    hierarchyQuery.setRows(new Integer(searchSettings.getProperty("search.results.maxBrowsePerPage")));

    // Reusable query segment for limiting the results to just the depth asked for
    StringBuilder cutoffQuery = new StringBuilder();
    cutoffQuery.append('!').append(solrSettings.getFieldName(SearchFieldKeys.ANCESTOR_PATH.name())).append(":");
    cutoffQuery.append(rootPath.getHighestTier() + browseRequest.getRetrievalDepth());
    cutoffQuery.append(searchSettings.facetSubfieldDelimiter).append('*');
    hierarchyQuery.addFilterQuery(cutoffQuery.toString());

    SearchResultResponse results;
    try {
        results = this.executeSearch(hierarchyQuery, hierarchyState, false, false);
        browseResults.setSearchResultResponse(results);
    } catch (SolrServerException e) {
        LOG.error("Error while getting container results for hierarchical browse results", e);
        return null;
    }
    // Add the root node into the result set
    browseResults.getResultList().add(0, rootNode);

    if (browseRequest.isRetrieveFacets() && browseRequest.getSearchState().getFacetsToRetrieve() != null) {
        SearchState facetState = (SearchState) browseState.clone();
        facetState.setRowsPerPage(0);
        SearchRequest facetRequest = new SearchRequest(facetState, browseRequest.getAccessGroups(), true);
        SolrQuery facetQuery = this.generateSearch(facetRequest);
        try {
            SearchResultResponse facetResponse = this.executeSearch(facetQuery, facetState, true, false);
            browseResults.setFacetFields(facetResponse.getFacetFields());
        } catch (SolrServerException e) {
            LOG.warn("Failed to retrieve facet results for " + facetQuery.toString(), e);
        }
    }

    // Don't need to manipulate the container list any further unless either the root is a real record or there are
    // subcontainers
    if (!rootIsAStub || results.getResultCount() > 0) {
        // Get the children counts per container
        SearchRequest filteredChildrenRequest = new SearchRequest(browseState, browseRequest.getAccessGroups(),
                true);
        this.getChildrenCounts(results.getResultList(), accessGroups, "child", null,
                this.generateSearch(filteredChildrenRequest));

        this.getChildrenCounts(results.getResultList(), accessGroups, "containers",
                "contentModel:" + SolrSettings.sanitize(ContentModelHelper.Model.CONTAINER.toString()),
                this.generateSearch(filteredChildrenRequest));

        try {
            // If anything that constituted a search is in the request then trim out possible empty folders
            if (browseState.getFacets().size() > 1 || browseState.getRangeFields().size() > 0
                    || browseState.getSearchFields().size() > 0 || browseState.getAccessTypeFilter() != null) {
                // Get the list of any direct matches for the current query
                browseResults
                        .setMatchingContainerPids(this.getDirectContainerMatches(browseState, accessGroups));
                // Remove all containers that are not direct matches for the user's query and have 0 children
                browseResults.removeContainersWithoutContents();
            }
        } catch (SolrServerException e) {
            LOG.error("Error while getting children counts for hierarchical browse", e);
            return null;
        }
    }

    // Retrieve normal item search results, which are restricted to a max number per page
    if (browseRequest.isIncludeFiles() && browseState.getRowsPerPage() > 0) {
        browseState.getResourceTypes().add(searchSettings.resourceTypeFile);
        SearchState fileSearchState = new SearchState(browseState);
        List<String> resourceTypes = new ArrayList<String>();
        resourceTypes.add(searchSettings.resourceTypeFile);
        fileSearchState.setResourceTypes(resourceTypes);
        CutoffFacet ancestorPath = (CutoffFacet) fileSearchState.getFacets()
                .get(SearchFieldKeys.ANCESTOR_PATH.name());
        ancestorPath.setCutoff(rootPath.getHighestTier() + 1);
        fileSearchState.setFacetsToRetrieve(null);
        SearchRequest fileSearchRequest = new SearchRequest(fileSearchState, browseRequest.getAccessGroups());
        SearchResultResponse fileResults = this.getSearchResults(fileSearchRequest);
        browseResults.populateItemResults(fileResults.getResultList());
    }

    browseResults.generateResultTree();

    return browseResults;
}

From source file:edu.unc.lib.dl.ui.service.SolrQueryLayerService.java

License:Apache License

/**
 * Checks if an item is accessible given the specified access restrictions
 * //from  w w  w  .j ava2s.  c  o m
 * @param idRequest
 * @param accessType
 * @return
 */
public boolean isAccessible(SimpleIdRequest idRequest) {
    QueryResponse queryResponse = null;
    SolrQuery solrQuery = new SolrQuery();
    StringBuilder query = new StringBuilder();

    PID pid = new PID(idRequest.getId());
    String id = pid.getPid();
    String[] idParts = id.split("/");
    String datastream = null;
    if (idParts.length > 1) {
        id = idParts[0];
        datastream = idParts[1];
        solrQuery.addField(solrSettings.getFieldName(SearchFieldKeys.ROLE_GROUP.name()));
    }

    query.append(solrSettings.getFieldName(SearchFieldKeys.ID.name())).append(':')
            .append(SolrSettings.sanitize(id));

    try {
        // Add access restrictions to query
        addAccessRestrictions(query, idRequest.getAccessGroups());
    } catch (AccessRestrictionException e) {
        // If the user doesn't have any access groups, they don't have access to anything, return null.
        LOG.error(e.getMessage());
        return false;
    }

    solrQuery.setQuery(query.toString());
    if (datastream == null)
        solrQuery.setRows(0);
    else
        solrQuery.setRows(1);

    solrQuery.addField(solrSettings.getFieldName(SearchFieldKeys.ID.name()));

    LOG.debug("getObjectById query: " + solrQuery.toString());
    try {
        queryResponse = this.executeQuery(solrQuery);
        if (queryResponse.getResults().getNumFound() == 0)
            return false;
        if (datastream == null)
            return true;

        List<BriefObjectMetadataBean> results = queryResponse.getBeans(BriefObjectMetadataBean.class);
        BriefObjectMetadataBean metadata = results.get(0);

        return AccessUtil.permitDatastreamAccess(idRequest.getAccessGroups(), datastream, metadata);
    } catch (SolrServerException e) {
        LOG.error("Error retrieving Solr object request: " + e);
    }

    return false;
}

From source file:edu.unc.lib.dl.ui.service.SolrQueryLayerService.java

License:Apache License

/**
 * Determines if the user has adminRole permissions on any items
 * // w  ww.ja  v a 2  s . co m
 * @param accessGroups
 * @return
 */
public boolean hasAdminViewPermission(AccessGroupSet accessGroups) {
    if (accessGroups.contains(AccessGroupConstants.ADMIN_GROUP)) {
        return true;
    }
    StringBuilder query = new StringBuilder();
    String joinedGroups = accessGroups.joinAccessGroups(" OR ", null, true);
    query.append("adminGroup:(").append(joinedGroups).append(')');

    SolrQuery solrQuery = new SolrQuery();
    solrQuery.setQuery(query.toString());
    solrQuery.setRows(0);

    try {
        QueryResponse queryResponse = this.executeQuery(solrQuery);
        return queryResponse.getResults().getNumFound() > 0;
    } catch (SolrServerException e) {
        LOG.error("Error retrieving Solr object request: " + e);
    }
    return false;
}