Search in sources :

Example 36 with SearchParameters

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

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

the class SearchMapper method toSearchParameters.

/**
 * Turn the SearchQuery params serialized by Jackson into the Java SearchParameters object
 * @param params
 * @return SearchParameters
 */
public SearchParameters toSearchParameters(Params params, SearchQuery searchQuery, SearchRequestContext searchRequestContext) {
    ParameterCheck.mandatory("query", searchQuery.getQuery());
    SearchParameters sp = new SearchParameters();
    setDefaults(sp);
    fromLocalization(sp, searchQuery.getLocalization());
    fromQuery(sp, searchQuery.getQuery());
    fromPaging(sp, params.getPaging());
    fromSort(sp, searchQuery.getSort());
    fromTemplate(sp, searchQuery.getTemplates());
    validateInclude(searchQuery.getInclude());
    fromDefault(sp, searchQuery.getDefaults());
    fromFilterQuery(sp, searchQuery.getFilterQueries());
    fromFacetQuery(sp, searchQuery.getFacetQueries());
    fromPivot(sp, searchQuery.getStats(), searchQuery.getFacetFields(), searchQuery.getFacetRanges(), searchQuery.getPivots(), searchRequestContext);
    fromStats(sp, searchQuery.getStats());
    fromFacetFields(sp, searchQuery.getFacetFields());
    fromSpellCheck(sp, searchQuery.getSpellcheck());
    fromHighlight(sp, searchQuery.getHighlight());
    fromFacetIntervals(sp, searchQuery.getFacetIntervals());
    fromRange(sp, searchQuery.getFacetRanges());
    fromScope(sp, searchQuery.getScope(), searchRequestContext);
    fromLimits(sp, searchQuery.getLimits());
    return sp;
}
Also used : SearchParameters(org.alfresco.service.cmr.search.SearchParameters)

Example 38 with SearchParameters

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

the class ResultMapperTests method testToSearchContext.

@Test
public void testToSearchContext() throws Exception {
    ResultSet results = mockResultset(Collections.emptyList(), Collections.emptyList());
    SearchQuery searchQuery = helper.searchQueryFromJson();
    SearchRequestContext searchRequest = SearchRequestContext.from(searchQuery);
    SearchParameters searchParams = searchMapper.toSearchParameters(EMPTY_PARAMS, searchQuery, searchRequest);
    SearchContext searchContext = mapper.toSearchContext((SolrJSONResultSet) results, searchRequest, searchQuery, 0);
    assertEquals(34l, searchContext.getConsistency().getlastTxId());
    assertEquals(6, searchContext.getFacetQueries().size());
    assertEquals(0, searchContext.getFacetQueries().get(0).getCount());
    assertEquals("cm:created:bob", searchContext.getFacetQueries().get(0).getFilterQuery());
    assertEquals("small", searchContext.getFacetQueries().get(0).getLabel());
    assertEquals("searchInsteadFor", searchContext.getSpellCheck().getType());
    assertEquals(1, searchContext.getSpellCheck().getSuggestions().size());
    assertEquals("alfresco", searchContext.getSpellCheck().getSuggestions().get(0));
    assertEquals(1, searchContext.getFacetsFields().size());
    assertEquals("content.size", searchContext.getFacetsFields().get(0).getLabel());
    // Facet intervals
    List<GenericFacetResponse> intervalFacets = searchContext.getFacets().stream().filter(f -> f.getType().equals(FACET_TYPE.interval)).collect(Collectors.toList());
    assertEquals(2, intervalFacets.size());
    assertEquals("creator", intervalFacets.get(0).getLabel());
    assertEquals("last", intervalFacets.get(0).getBuckets().get(0).getLabel());
    assertEquals("cm:creator:<\"a\" TO \"b\"]", intervalFacets.get(0).getBuckets().get(0).getFilterQuery());
    Metric[] metrics = intervalFacets.get(0).getBuckets().get(0).getMetrics().toArray(new Metric[intervalFacets.get(0).getBuckets().get(0).getMetrics().size()]);
    assertEquals(METRIC_TYPE.count, metrics[0].getType());
    assertEquals("4", metrics[0].getValue().get("count"));
    // Requests search Query
    assertNotNull(searchContext.getRequest());
    assertEquals("great", searchContext.getRequest().getQuery().getUserQuery());
    // Pivot
    assertEquals(7, searchContext.getFacets().size());
    GenericFacetResponse pivotFacet = searchContext.getFacets().get(4);
    assertEquals(FACET_TYPE.pivot, pivotFacet.getType());
    assertEquals("creator", pivotFacet.getLabel());
    assertEquals(2, pivotFacet.getBuckets().size());
    GenericBucket pivotBucket = pivotFacet.getBuckets().get(1);
    assertEquals("mjackson", pivotBucket.getLabel());
    assertEquals("creator:\"mjackson\"", pivotBucket.getFilterQuery());
    metrics = pivotBucket.getMetrics().toArray(new Metric[pivotBucket.getMetrics().size()]);
    assertEquals("{count=7}", metrics[0].getValue().toString());
    assertEquals(1, pivotBucket.getFacets().size());
    GenericFacetResponse nestedFacet = pivotBucket.getFacets().get(0);
    assertEquals(FACET_TYPE.pivot, nestedFacet.getType());
    assertEquals("mylabel", nestedFacet.getLabel());
    assertEquals(2, nestedFacet.getBuckets().size());
    GenericBucket nestedBucket = nestedFacet.getBuckets().get(0);
    assertEquals("mjackson", nestedBucket.getLabel());
    assertEquals("modifier:\"mjackson\"", nestedBucket.getFilterQuery());
    metrics = nestedBucket.getMetrics().toArray(new Metric[nestedBucket.getMetrics().size()]);
    assertEquals("{count=3}", metrics[0].getValue().toString());
    GenericBucket nestedBucket2 = nestedFacet.getBuckets().get(1);
    assertEquals("admin", nestedBucket2.getLabel());
    assertEquals("modifier:\"admin\"", nestedBucket2.getFilterQuery());
    metrics = nestedBucket2.getMetrics().toArray(new Metric[nestedBucket2.getMetrics().size()]);
    assertEquals("{count=4}", metrics[0].getValue().toString());
    // Stats
    GenericFacetResponse statsFacet = searchContext.getFacets().get(5);
    assertEquals(FACET_TYPE.stats, statsFacet.getType());
    assertEquals("created", statsFacet.getLabel());
    Set<Metric> statsMetrics = statsFacet.getBuckets().get(0).getMetrics();
    assertEquals(8, statsMetrics.size());
    assertTrue(statsMetrics.contains(new SimpleMetric(METRIC_TYPE.sumOfSquares, 2.1513045770343806E27)));
    assertTrue(statsMetrics.contains(new SimpleMetric(METRIC_TYPE.min, "2011-02-15T20:16:27.080Z")));
    assertTrue(statsMetrics.contains(new SimpleMetric(METRIC_TYPE.max, "2017-04-10T15:06:30.143Z")));
    assertTrue(statsMetrics.contains(new SimpleMetric(METRIC_TYPE.mean, "2016-09-05T04:20:12.898Z")));
    assertTrue(statsMetrics.contains(new SimpleMetric(METRIC_TYPE.countValues, 990)));
    assertTrue(statsMetrics.contains(new SimpleMetric(METRIC_TYPE.missing, 290)));
    assertTrue(statsMetrics.contains(new SimpleMetric(METRIC_TYPE.sum, 1.458318720769983E15)));
    assertTrue(statsMetrics.contains(new SimpleMetric(METRIC_TYPE.stddev, 5.6250677994522545E10)));
    statsFacet = searchContext.getFacets().get(6);
    assertEquals("numericLabel", statsFacet.getLabel());
    statsMetrics = statsFacet.getBuckets().get(0).getMetrics();
    assertEquals(7, statsMetrics.size());
    assertTrue(statsMetrics.contains(new SimpleMetric(METRIC_TYPE.sumOfSquares, 0)));
    assertTrue(statsMetrics.contains(new SimpleMetric(METRIC_TYPE.countValues, 0)));
    assertTrue(statsMetrics.contains(new SimpleMetric(METRIC_TYPE.missing, 0)));
    assertTrue(statsMetrics.contains(new SimpleMetric(METRIC_TYPE.sum, 0)));
    assertTrue(statsMetrics.contains(new SimpleMetric(METRIC_TYPE.stddev, 0)));
    JSONArray dVals = new JSONArray(Arrays.asList(12, 13, 14, 15, 16, 17, 1));
    assertTrue(statsMetrics.contains(new ListMetric(METRIC_TYPE.distinctValues, dVals)));
    JSONArray pers = new JSONArray(Arrays.asList("0.99", 20.0685, "0.0", 12.0));
    assertTrue(statsMetrics.contains(new PercentileMetric(METRIC_TYPE.percentiles, pers)));
    assertEquals("min must be excluded because its null", 0, statsMetrics.stream().filter(metric -> METRIC_TYPE.min.equals(metric.getType())).count());
    assertEquals("max must be excluded because its null", 0, statsMetrics.stream().filter(metric -> METRIC_TYPE.max.equals(metric.getType())).count());
    assertEquals("mean must be excluded because its NaN", 0, statsMetrics.stream().filter(metric -> METRIC_TYPE.mean.equals(metric.getType())).count());
}
Also used : SearchQuery(org.alfresco.rest.api.search.model.SearchQuery) Arrays(java.util.Arrays) SearchContext(org.alfresco.rest.api.search.context.SearchContext) GenericBucket(org.alfresco.repo.search.impl.solr.facet.facetsresponse.GenericBucket) VersionService(org.alfresco.service.cmr.version.VersionService) Matchers.anyBoolean(org.mockito.Matchers.anyBoolean) JSONException(org.json.JSONException) TestCase.assertNotNull(junit.framework.TestCase.assertNotNull) JSONObject(org.json.JSONObject) PercentileMetric(org.alfresco.repo.search.impl.solr.facet.facetsresponse.PercentileMetric) Params(org.alfresco.rest.framework.resource.parameters.Params) Node(org.alfresco.rest.api.model.Node) Map(java.util.Map) METRIC_TYPE(org.alfresco.repo.search.impl.solr.facet.facetsresponse.Metric.METRIC_TYPE) SearchMapper(org.alfresco.rest.api.search.impl.SearchMapper) NodeService(org.alfresco.service.cmr.repository.NodeService) TestCase.assertFalse(junit.framework.TestCase.assertFalse) ResultSet(org.alfresco.service.cmr.search.ResultSet) VersionHistory(org.alfresco.service.cmr.version.VersionHistory) EmptyResultSet(org.alfresco.repo.search.EmptyResultSet) DeletedNodes(org.alfresco.rest.api.DeletedNodes) FacetQueryContext(org.alfresco.rest.api.search.context.FacetQueryContext) Set(java.util.Set) TestCase.assertNull(junit.framework.TestCase.assertNull) Collectors(java.util.stream.Collectors) Serializable(java.io.Serializable) Matchers.any(org.mockito.Matchers.any) List(java.util.List) Version2Model(org.alfresco.repo.version.Version2Model) VersionImpl(org.alfresco.repo.version.common.VersionImpl) Stream(java.util.stream.Stream) EntityNotFoundException(org.alfresco.rest.framework.core.exceptions.EntityNotFoundException) CollectionWithPagingInfo(org.alfresco.rest.framework.resource.parameters.CollectionWithPagingInfo) TestCase.assertTrue(junit.framework.TestCase.assertTrue) SpellCheckContext(org.alfresco.rest.api.search.context.SpellCheckContext) AuthenticationUtil(org.alfresco.repo.security.authentication.AuthenticationUtil) SearchSQLQuery(org.alfresco.rest.api.search.model.SearchSQLQuery) TestCase.assertEquals(junit.framework.TestCase.assertEquals) Mockito.mock(org.mockito.Mockito.mock) NodeVersionsRelation(org.alfresco.rest.api.nodes.NodeVersionsRelation) LimitBy(org.alfresco.service.cmr.search.LimitBy) TupleList(org.alfresco.rest.api.search.model.TupleList) StoreMapper(org.alfresco.rest.api.search.impl.StoreMapper) BeforeClass(org.junit.BeforeClass) Metric(org.alfresco.repo.search.impl.solr.facet.facetsresponse.Metric) SearchRequestContext(org.alfresco.rest.api.search.context.SearchRequestContext) SimpleMetric(org.alfresco.repo.search.impl.solr.facet.facetsresponse.SimpleMetric) NodeRef(org.alfresco.service.cmr.repository.NodeRef) Version(org.alfresco.service.cmr.version.Version) UserInfo(org.alfresco.rest.api.model.UserInfo) GeneralHighlightParameters(org.alfresco.service.cmr.search.GeneralHighlightParameters) HashMap(java.util.HashMap) Matchers.anyString(org.mockito.Matchers.anyString) ArrayList(java.util.ArrayList) Answer(org.mockito.stubbing.Answer) InvocationOnMock(org.mockito.invocation.InvocationOnMock) ResultMapper(org.alfresco.rest.api.search.impl.ResultMapper) GUID(org.alfresco.util.GUID) QName(org.alfresco.service.namespace.QName) PropertyLookupRegistry(org.alfresco.rest.api.lookups.PropertyLookupRegistry) StoreRef(org.alfresco.service.cmr.repository.StoreRef) NodesImpl(org.alfresco.rest.api.impl.NodesImpl) FieldHighlightParameters(org.alfresco.service.cmr.search.FieldHighlightParameters) JSONTokener(org.json.JSONTokener) Matchers.notNull(org.mockito.Matchers.notNull) ServiceRegistry(org.alfresco.service.ServiceRegistry) IOException(java.io.IOException) HighlightEntry(org.alfresco.rest.api.search.model.HighlightEntry) Test(org.junit.Test) Mockito.when(org.mockito.Mockito.when) FacetFieldContext(org.alfresco.rest.api.search.context.FacetFieldContext) PersonPropertyLookup(org.alfresco.rest.api.lookups.PersonPropertyLookup) FACET_TYPE(org.alfresco.repo.search.impl.solr.facet.facetsresponse.GenericFacetResponse.FACET_TYPE) SearchQuery(org.alfresco.rest.api.search.model.SearchQuery) WebScriptRequest(org.springframework.extensions.webscripts.WebScriptRequest) ListMetric(org.alfresco.repo.search.impl.solr.facet.facetsresponse.ListMetric) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) Collections(java.util.Collections) SolrJSONResultSet(org.alfresco.repo.search.impl.lucene.SolrJSONResultSet) JSONArray(org.json.JSONArray) GenericFacetResponse(org.alfresco.repo.search.impl.solr.facet.facetsresponse.GenericFacetResponse) PercentileMetric(org.alfresco.repo.search.impl.solr.facet.facetsresponse.PercentileMetric) GenericFacetResponse(org.alfresco.repo.search.impl.solr.facet.facetsresponse.GenericFacetResponse) JSONArray(org.json.JSONArray) SearchContext(org.alfresco.rest.api.search.context.SearchContext) GenericBucket(org.alfresco.repo.search.impl.solr.facet.facetsresponse.GenericBucket) ListMetric(org.alfresco.repo.search.impl.solr.facet.facetsresponse.ListMetric) SearchRequestContext(org.alfresco.rest.api.search.context.SearchRequestContext) SearchParameters(org.alfresco.service.cmr.search.SearchParameters) ResultSet(org.alfresco.service.cmr.search.ResultSet) EmptyResultSet(org.alfresco.repo.search.EmptyResultSet) SolrJSONResultSet(org.alfresco.repo.search.impl.lucene.SolrJSONResultSet) SimpleMetric(org.alfresco.repo.search.impl.solr.facet.facetsresponse.SimpleMetric) PercentileMetric(org.alfresco.repo.search.impl.solr.facet.facetsresponse.PercentileMetric) Metric(org.alfresco.repo.search.impl.solr.facet.facetsresponse.Metric) SimpleMetric(org.alfresco.repo.search.impl.solr.facet.facetsresponse.SimpleMetric) ListMetric(org.alfresco.repo.search.impl.solr.facet.facetsresponse.ListMetric) Test(org.junit.Test)

Example 39 with SearchParameters

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

the class SearchMapperTests method fromStats.

@Test
public void fromStats() throws Exception {
    SearchParameters searchParameters = new SearchParameters();
    searchMapper.fromStats(searchParameters, null);
    List<StatsRequestParameters> statsRequestParameters = new ArrayList<>(1);
    statsRequestParameters.add(new StatsRequestParameters(null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null));
    try {
        searchMapper.fromStats(searchParameters, statsRequestParameters);
    } catch (IllegalArgumentException iae) {
        assertTrue(iae.getLocalizedMessage().contains("field is a mandatory parameter"));
    }
    statsRequestParameters.clear();
    statsRequestParameters.add(new StatsRequestParameters("cm:content", "myLabel", null, null, null, null, null, null, null, null, null, null, null, null, null, null));
    searchMapper.fromStats(searchParameters, statsRequestParameters);
    assertEquals(1, searchParameters.getStats().size());
    statsRequestParameters.clear();
    statsRequestParameters.add(new StatsRequestParameters("cm:content", "myLabel", Arrays.asList(3.4f, 12f, 10f), null, null, null, null, null, null, null, null, null, null, null, null, null));
    searchMapper.fromStats(searchParameters, statsRequestParameters);
    assertEquals(1, searchParameters.getStats().size());
    statsRequestParameters.clear();
    statsRequestParameters.add(new StatsRequestParameters("cm:content", "myLabel", Arrays.asList(-3.4f), null, null, null, null, null, null, null, null, null, null, null, null, null));
    try {
        searchMapper.fromStats(searchParameters, statsRequestParameters);
    } catch (IllegalArgumentException iae) {
        assertTrue(iae.getLocalizedMessage().contains("Invalid percentile -3.4"));
    }
    statsRequestParameters.clear();
    statsRequestParameters.add(new StatsRequestParameters("cm:content", "myLabel", Arrays.asList(101f), null, null, null, null, null, null, null, null, null, null, null, null, null));
    try {
        searchMapper.fromStats(searchParameters, statsRequestParameters);
    } catch (IllegalArgumentException iae) {
        assertTrue(iae.getLocalizedMessage().contains("Invalid percentile 101"));
    }
    statsRequestParameters.clear();
    statsRequestParameters.add(new StatsRequestParameters("cm:content", "myLabel", null, null, null, null, null, null, null, null, null, null, null, true, 12f, null));
    try {
        searchMapper.fromStats(searchParameters, statsRequestParameters);
    } catch (IllegalArgumentException iae) {
        assertTrue(iae.getLocalizedMessage().contains("Invalid cardinality accuracy 12.0"));
    }
    statsRequestParameters.clear();
    statsRequestParameters.add(new StatsRequestParameters("cm:content", "myLabel", null, null, null, null, null, null, null, null, null, null, null, null, 12f, null));
    searchMapper.fromStats(searchParameters, statsRequestParameters);
    // cardinality is ignored if not true
    assertEquals(1, searchParameters.getStats().size());
}
Also used : SearchParameters(org.alfresco.service.cmr.search.SearchParameters) ArrayList(java.util.ArrayList) StatsRequestParameters(org.alfresco.service.cmr.search.StatsRequestParameters) Test(org.junit.Test)

Example 40 with SearchParameters

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

the class SearchMapperTests method facetRange.

@Test
public void facetRange() {
    SearchParameters searchParameters = new SearchParameters();
    List<RangeParameters> rangeParams = new ArrayList<RangeParameters>();
    rangeParams.add(new RangeParameters(null, null, null, null, false, null, null, null, null));
    try {
        searchMapper.fromRange(searchParameters, rangeParams);
        fail();
    } catch (IllegalArgumentException iae) {
        assertNotNull(iae);
    }
    rangeParams.clear();
    rangeParams.add(new RangeParameters("content.size", "0", "100000", "1000", true, null, null, null, null));
    searchMapper.fromRange(searchParameters, rangeParams);
    assertEquals(searchParameters.getRanges(), rangeParams);
    rangeParams.clear();
    List<String> includes = new ArrayList<String>();
    includes.add("lower");
    List<String> other = new ArrayList<String>();
    includes.add("before");
    rangeParams.add(new RangeParameters("content.size", "0", "100000", "1000", true, other, includes, null, null));
    searchMapper.fromRange(searchParameters, rangeParams);
    assertEquals(searchParameters.getRanges(), rangeParams);
    // Assert multiple ranges
    rangeParams.add(new RangeParameters("created", "2015-09-29T10:45:15.729Z", "2016-09-29T10:45:15.729Z", "+100DAY", true, other, includes, null, null));
    searchMapper.fromRange(searchParameters, rangeParams);
    assertEquals(searchParameters.getRanges(), rangeParams);
    assertEquals(2, searchParameters.getRanges().size());
}
Also used : SearchParameters(org.alfresco.service.cmr.search.SearchParameters) ArrayList(java.util.ArrayList) RangeParameters(org.alfresco.service.cmr.search.RangeParameters) Test(org.junit.Test)

Aggregations

SearchParameters (org.alfresco.service.cmr.search.SearchParameters)56 Test (org.junit.Test)28 ResultSet (org.alfresco.service.cmr.search.ResultSet)20 NodeRef (org.alfresco.service.cmr.repository.NodeRef)19 ArrayList (java.util.ArrayList)15 SearchRequestContext (org.alfresco.rest.api.search.context.SearchRequestContext)11 IOException (java.io.IOException)10 InvalidArgumentException (org.alfresco.rest.framework.core.exceptions.InvalidArgumentException)10 HashMap (java.util.HashMap)8 SearchQuery (org.alfresco.rest.api.search.model.SearchQuery)8 JSONObject (org.json.JSONObject)8 List (java.util.List)7 QName (org.alfresco.service.namespace.QName)7 JSONTokener (org.json.JSONTokener)7 AlfrescoRuntimeException (org.alfresco.error.AlfrescoRuntimeException)6 SearchSQLQuery (org.alfresco.rest.api.search.model.SearchSQLQuery)6 Params (org.alfresco.rest.framework.resource.parameters.Params)6 StoreRef (org.alfresco.service.cmr.repository.StoreRef)6 GeneralHighlightParameters (org.alfresco.service.cmr.search.GeneralHighlightParameters)6 JSONArray (org.json.JSONArray)6