Search in sources :

Example 1 with PredicateGroup

use of com.day.cq.search.PredicateGroup in project aem-core-wcm-components by Adobe-Marketing-Cloud.

the class SearchResultServlet method getResults.

/**
 * Gets the search results.
 *
 * @param request The search request.
 * @param searchComponent The search component.
 * @param pageManager A PageManager.
 * @return List of search results.
 */
@NotNull
private List<ListItem> getResults(@NotNull final SlingHttpServletRequest request, @NotNull final Search searchComponent, @NotNull final PageManager pageManager) {
    List<ListItem> results = new ArrayList<>();
    String fulltext = request.getParameter(PARAM_FULLTEXT);
    if (fulltext == null || fulltext.length() < searchComponent.getSearchTermMinimumLength()) {
        return results;
    }
    long resultsOffset = Optional.ofNullable(request.getParameter(PARAM_RESULTS_OFFSET)).map(Long::parseLong).orElse(0L);
    Map<String, String> predicatesMap = new HashMap<>();
    predicatesMap.put(FulltextPredicateEvaluator.FULLTEXT, fulltext);
    predicatesMap.put(PathPredicateEvaluator.PATH, searchComponent.getSearchRootPagePath());
    predicatesMap.put(TypePredicateEvaluator.TYPE, NameConstants.NT_PAGE);
    PredicateGroup predicates = PredicateConverter.createPredicates(predicatesMap);
    ResourceResolver resourceResolver = request.getResource().getResourceResolver();
    Query query = queryBuilder.createQuery(predicates, resourceResolver.adaptTo(Session.class));
    if (searchComponent.getResultsSize() != 0) {
        query.setHitsPerPage(searchComponent.getResultsSize());
    }
    if (resultsOffset != 0) {
        query.setStart(resultsOffset);
    }
    SearchResult searchResult = query.getResult();
    LinkHandler linkHandler = request.adaptTo(LinkHandler.class);
    // Query builder has a leaking resource resolver, so the following work around is required.
    ResourceResolver leakingResourceResolver = null;
    try {
        Iterator<Resource> resourceIterator = searchResult.getResources();
        while (resourceIterator.hasNext()) {
            Resource resource = resourceIterator.next();
            // Get a reference to QB's leaking resource resolver
            if (leakingResourceResolver == null) {
                leakingResourceResolver = resource.getResourceResolver();
            }
            Optional.of(resource).map(res -> resourceResolver.getResource(res.getPath())).map(pageManager::getContainingPage).map(page -> new PageListItemImpl(linkHandler, page, searchComponent.getId(), null)).ifPresent(results::add);
        }
    } finally {
        if (leakingResourceResolver != null) {
            leakingResourceResolver.close();
        }
    }
    return results;
}
Also used : ResourceResolver(org.apache.sling.api.resource.ResourceResolver) ScriptHelper(org.apache.sling.scripting.core.ScriptHelper) TypePredicateEvaluator(com.day.cq.search.eval.TypePredicateEvaluator) StringUtils(org.apache.commons.lang3.StringUtils) Page(com.day.cq.wcm.api.Page) SlingBindings(org.apache.sling.api.scripting.SlingBindings) SlingHttpServletRequest(org.apache.sling.api.SlingHttpServletRequest) SearchResult(com.day.cq.search.result.SearchResult) PredicateConverter(com.day.cq.search.PredicateConverter) Map(java.util.Map) PageListItemImpl(com.adobe.cq.wcm.core.components.internal.models.v1.PageListItemImpl) Search(com.adobe.cq.wcm.core.components.models.Search) PN_FRAGMENT_VARIATION_PATH(com.adobe.cq.wcm.core.components.models.ExperienceFragment.PN_FRAGMENT_VARIATION_PATH) PathPredicateEvaluator(com.day.cq.search.eval.PathPredicateEvaluator) Session(javax.jcr.Session) Servlet(javax.servlet.Servlet) SlingHttpServletResponse(org.apache.sling.api.SlingHttpServletResponse) StandardCharsets(java.nio.charset.StandardCharsets) BundleContext(org.osgi.framework.BundleContext) Objects(java.util.Objects) PageManager(com.day.cq.wcm.api.PageManager) Nullable(org.jetbrains.annotations.Nullable) List(java.util.List) Query(com.day.cq.search.Query) Optional(java.util.Optional) SlingSafeMethodsServlet(org.apache.sling.api.servlets.SlingSafeMethodsServlet) NotNull(org.jetbrains.annotations.NotNull) FulltextPredicateEvaluator(com.day.cq.search.eval.FulltextPredicateEvaluator) ModelFactory(org.apache.sling.models.factory.ModelFactory) LinkHandler(com.adobe.cq.wcm.core.components.internal.link.LinkHandler) HashMap(java.util.HashMap) LanguageManager(com.day.cq.wcm.api.LanguageManager) ArrayList(java.util.ArrayList) Component(org.osgi.service.component.annotations.Component) StreamSupport(java.util.stream.StreamSupport) Activate(org.osgi.service.component.annotations.Activate) SearchImpl(com.adobe.cq.wcm.core.components.internal.models.v1.SearchImpl) QueryBuilder(com.day.cq.search.QueryBuilder) Iterator(java.util.Iterator) ListItem(com.adobe.cq.wcm.core.components.models.ListItem) HttpServletResponse(javax.servlet.http.HttpServletResponse) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Resource(org.apache.sling.api.resource.Resource) IOException(java.io.IOException) LiveRelationshipManager(com.day.cq.wcm.msm.api.LiveRelationshipManager) LocalizationUtils(com.adobe.cq.wcm.core.components.internal.LocalizationUtils) PredicateGroup(com.day.cq.search.PredicateGroup) Template(com.day.cq.wcm.api.Template) NameConstants(com.day.cq.wcm.api.NameConstants) Reference(org.osgi.service.component.annotations.Reference) Query(com.day.cq.search.Query) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Resource(org.apache.sling.api.resource.Resource) SearchResult(com.day.cq.search.result.SearchResult) PredicateGroup(com.day.cq.search.PredicateGroup) PageListItemImpl(com.adobe.cq.wcm.core.components.internal.models.v1.PageListItemImpl) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) ListItem(com.adobe.cq.wcm.core.components.models.ListItem) LinkHandler(com.adobe.cq.wcm.core.components.internal.link.LinkHandler) Session(javax.jcr.Session) NotNull(org.jetbrains.annotations.NotNull)

Example 2 with PredicateGroup

use of com.day.cq.search.PredicateGroup in project acs-aem-commons by Adobe-Consulting-Services.

the class OnDeployScriptBaseTest method testSearchAndUpdateResourceType.

@Test
public void testSearchAndUpdateResourceType() throws RepositoryException {
    Node contentRoot = resourceResolver.getResource("/content").adaptTo(Node.class);
    Node node1 = contentRoot.addNode("search-and-update-node1");
    node1.setProperty("sling:resourceType", "mysite/type/old");
    Node node2 = contentRoot.addNode("search-and-update-node2");
    node2.setProperty("sling:resourceType", "mysite/type/old");
    final Query query = mock(Query.class);
    SearchResult result = mock(SearchResult.class);
    when(result.getNodes()).thenReturn(Arrays.asList(node1, node2).iterator());
    when(query.getResult()).thenReturn(result);
    when(queryBuilder.createQuery(any(PredicateGroup.class), any(Session.class))).then(new Answer<Query>() {

        @Override
        public Query answer(InvocationOnMock invocationOnMock) throws Throwable {
            PredicateGroup pg = invocationOnMock.getArgumentAt(0, PredicateGroup.class);
            assertEquals("-1", pg.getParameters().get("limit"));
            assertEquals("path", pg.get(0).getType());
            assertEquals("/content", pg.get(0).getParameters().get("path"));
            assertEquals("property", pg.get(1).getType());
            assertEquals("sling:resourceType", pg.get(1).getParameters().get("property"));
            assertEquals("mysite/type/old", pg.get(1).getParameters().get("value"));
            return query;
        }
    });
    onDeployScript.searchAndUpdateResourceType("mysite/type/old", "mysite/type/new");
    assertEquals("mysite/type/new", node1.getProperty("sling:resourceType").getString());
    assertEquals("mysite/type/new", node2.getProperty("sling:resourceType").getString());
}
Also used : Query(com.day.cq.search.Query) InvocationOnMock(org.mockito.invocation.InvocationOnMock) Node(javax.jcr.Node) SearchResult(com.day.cq.search.result.SearchResult) PredicateGroup(com.day.cq.search.PredicateGroup) Session(javax.jcr.Session) Test(org.junit.Test)

Example 3 with PredicateGroup

use of com.day.cq.search.PredicateGroup in project aem-core-wcm-components by Adobe-Marketing-Cloud.

the class SearchResultServletTest method setUpQueryBuilder.

/**
 * Sets up a mock query builder.
 * If there are any results then `this.spyResolver` will be set to a non-null value.
 *
 * Note: any query executed on the query builder configured by calling this method will simply list all of the
 * child pages of the search path. No actual search, or other predicates on the query will be honoured. Therefore,
 * the results from the query builder cannot be trusted for testing purposes beyond testing the search root and
 * the handling / transformation of results.
 */
public void setUpQueryBuilder() {
    doAnswer(invocationOnQueryBuilder -> {
        PredicateGroup predicateGroup = invocationOnQueryBuilder.getArgument(0);
        Query query = Mockito.mock(Query.class);
        doAnswer(invocationOnQuery -> {
            SearchResult result = Mockito.mock(SearchResult.class);
            doAnswer(invocationOnResult -> {
                String searchPath = predicateGroup.getByName(PathPredicateEvaluator.PATH).get(PathPredicateEvaluator.PATH);
                Iterator<Resource> res = Objects.requireNonNull(this.context.resourceResolver().getResource(searchPath)).listChildren();
                List<Resource> resources = StreamSupport.stream(Spliterators.spliteratorUnknownSize(res, Spliterator.ORDERED), false).filter(r -> r.isResourceType("cq:Page")).collect(Collectors.toList());
                if (resources.size() > 0) {
                    this.spyResolver = Mockito.spy(this.context.resourceResolver());
                    doNothing().when(spyResolver).close();
                    Resource spyResource = Mockito.spy(resources.get(0));
                    doAnswer(invocationOnMock3 -> spyResolver).when(spyResource).getResourceResolver();
                    resources.set(0, spyResource);
                }
                return resources.iterator();
            }).when(result).getResources();
            return result;
        }).when(query).getResult();
        return query;
    }).when(mockQueryBuilder).createQuery(any(), any());
}
Also used : ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) BeforeEach(org.junit.jupiter.api.BeforeEach) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Spliterators(java.util.Spliterators) Mock(org.mockito.Mock) AemContext(io.wcm.testing.mock.aem.junit5.AemContext) ArrayList(java.util.ArrayList) SimpleModule(com.fasterxml.jackson.databind.module.SimpleModule) SearchResult(com.day.cq.search.result.SearchResult) ExtendWith(org.junit.jupiter.api.extension.ExtendWith) CoreComponentTestContext(com.adobe.cq.wcm.core.components.context.CoreComponentTestContext) ImmutableList(com.google.common.collect.ImmutableList) Map(java.util.Map) StreamSupport(java.util.stream.StreamSupport) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) LinkedList(java.util.LinkedList) QueryBuilder(com.day.cq.search.QueryBuilder) MockSlingHttpServletRequest(org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletRequest) MockitoExtension(org.mockito.junit.jupiter.MockitoExtension) MockRequestPathInfo(org.apache.sling.testing.mock.sling.servlet.MockRequestPathInfo) Iterator(java.util.Iterator) PathPredicateEvaluator(com.day.cq.search.eval.PathPredicateEvaluator) ImmutableMap(com.google.common.collect.ImmutableMap) ListItem(com.adobe.cq.wcm.core.components.models.ListItem) HttpServletResponse(javax.servlet.http.HttpServletResponse) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Resource(org.apache.sling.api.resource.Resource) IOException(java.io.IOException) SimpleAbstractTypeResolver(com.fasterxml.jackson.databind.module.SimpleAbstractTypeResolver) AemContextExtension(io.wcm.testing.mock.aem.junit5.AemContextExtension) Collectors(java.util.stream.Collectors) LiveRelationshipManager(com.day.cq.wcm.msm.api.LiveRelationshipManager) Objects(java.util.Objects) Test(org.junit.jupiter.api.Test) Nullable(org.jetbrains.annotations.Nullable) Mockito(org.mockito.Mockito) List(java.util.List) PredicateGroup(com.day.cq.search.PredicateGroup) Query(com.day.cq.search.Query) MockSlingHttpServletResponse(org.apache.sling.testing.mock.sling.servlet.MockSlingHttpServletResponse) NotNull(org.jetbrains.annotations.NotNull) Spliterator(java.util.Spliterator) JsonIgnoreProperties(com.fasterxml.jackson.annotation.JsonIgnoreProperties) Query(com.day.cq.search.Query) Resource(org.apache.sling.api.resource.Resource) SearchResult(com.day.cq.search.result.SearchResult) PredicateGroup(com.day.cq.search.PredicateGroup)

Example 4 with PredicateGroup

use of com.day.cq.search.PredicateGroup in project aem-core-wcm-components by Adobe-Marketing-Cloud.

the class ModelDataSourceServlet method doGet.

@Override
protected void doGet(@NotNull SlingHttpServletRequest request, @NotNull SlingHttpServletResponse response) throws ServletException, IOException {
    DataSource dataSource = EmptyDataSource.instance();
    ResourceResolver resourceResolver = request.getResourceResolver();
    QueryBuilder queryBuilder = resourceResolver.adaptTo(QueryBuilder.class);
    if (queryBuilder != null) {
        Map<String, String> parameterMap = new HashMap<>();
        parameterMap.put("path", "/conf");
        parameterMap.put("type", NT_TEMPLATE);
        parameterMap.put("p.limit", "-1");
        parameterMap.put("1_property", JcrConstants.JCR_CONTENT + "/model/" + ResourceResolver.PROPERTY_RESOURCE_TYPE);
        parameterMap.put("1_property.value", "wcm/scaffolding/components/scaffolding");
        PredicateGroup predicateGroup = PredicateGroup.create(parameterMap);
        Session session = resourceResolver.adaptTo(Session.class);
        Query query = queryBuilder.createQuery(predicateGroup, session);
        SearchResult searchResult = query.getResult();
        // Query builder has a leaking resource resolver, so the following work around is required.
        ResourceResolver leakingResourceResolver = null;
        try {
            // Iterate over the hits if you need special information
            List<Resource> resources = new LinkedList<>();
            for (Iterator<Resource> resourceIterator = searchResult.getResources(); resourceIterator.hasNext(); ) {
                Resource resource = resourceIterator.next();
                if (leakingResourceResolver == null) {
                    // Get a reference to query builder's leaking resource resolver
                    leakingResourceResolver = resource.getResourceResolver();
                }
                ValueMap modelValueMap = resource.getValueMap();
                String modelTitle = modelValueMap.get(JcrConstants.JCR_CONTENT + "/" + JcrConstants.JCR_TITLE, resource.getName());
                String modelPath = resource.getPath();
                Resource syntheticResource = createResource(resourceResolver, modelTitle, modelPath);
                resources.add(syntheticResource);
            }
            dataSource = new SimpleDataSource(resources.iterator());
        } finally {
            if (leakingResourceResolver != null) {
                // Always close the leaking query builder resource resolver.
                leakingResourceResolver.close();
            }
        }
    }
    request.setAttribute(DataSource.class.getName(), dataSource);
}
Also used : Query(com.day.cq.search.Query) HashMap(java.util.HashMap) ValueMap(org.apache.sling.api.resource.ValueMap) Resource(org.apache.sling.api.resource.Resource) SearchResult(com.day.cq.search.result.SearchResult) QueryBuilder(com.day.cq.search.QueryBuilder) PredicateGroup(com.day.cq.search.PredicateGroup) LinkedList(java.util.LinkedList) SimpleDataSource(com.adobe.granite.ui.components.ds.SimpleDataSource) EmptyDataSource(com.adobe.granite.ui.components.ds.EmptyDataSource) DataSource(com.adobe.granite.ui.components.ds.DataSource) SimpleDataSource(com.adobe.granite.ui.components.ds.SimpleDataSource) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Session(javax.jcr.Session)

Example 5 with PredicateGroup

use of com.day.cq.search.PredicateGroup in project aem-core-wcm-components by Adobe-Marketing-Cloud.

the class ContentFragmentListImpl method initModel.

@PostConstruct
private void initModel() {
    // Default path limits search to DAM
    if (StringUtils.isEmpty(parentPath)) {
        parentPath = DEFAULT_DAM_PARENT_PATH;
    }
    if (StringUtils.isEmpty(modelPath)) {
        LOG.warn("Please provide a model path");
        return;
    }
    Session session = resourceResolver.adaptTo(Session.class);
    if (session == null) {
        LOG.warn("Session was null therefore no query was executed");
        return;
    }
    QueryBuilder queryBuilder = resourceResolver.adaptTo(QueryBuilder.class);
    if (queryBuilder == null) {
        LOG.warn("Query builder was null therefore no query was executed");
        return;
    }
    Map<String, String> queryParameterMap = new HashMap<>();
    queryParameterMap.put("path", parentPath);
    queryParameterMap.put("type", NT_DAM_ASSET);
    queryParameterMap.put("p.limit", Integer.toString(maxItems));
    queryParameterMap.put("1_property", JcrConstants.JCR_CONTENT + "/data/cq:model");
    queryParameterMap.put("1_property.value", modelPath);
    if (StringUtils.isNotEmpty(orderBy)) {
        queryParameterMap.put("orderby", "@" + orderBy);
        if (StringUtils.isNotEmpty(sortOrder)) {
            queryParameterMap.put("orderby.sort", sortOrder);
        }
    }
    ArrayList<String> allTags = new ArrayList<>();
    if (tagNames != null && tagNames.length > 0) {
        allTags.addAll(Arrays.asList(tagNames));
    }
    if (!allTags.isEmpty()) {
        // Check for the taggable mixin
        queryParameterMap.put("2_property", JcrConstants.JCR_CONTENT + "/metadata/" + JcrConstants.JCR_MIXINTYPES);
        queryParameterMap.put("2_property.value", TagConstants.NT_TAGGABLE);
        // Check for the actual tags (by default, tag are or'ed)
        queryParameterMap.put("tagid.property", JcrConstants.JCR_CONTENT + "/metadata/cq:tags");
        for (int i = 0; i < allTags.size(); i++) {
            queryParameterMap.put(String.format("tagid.%d_value", i + 1), allTags.get(i));
        }
    }
    PredicateGroup predicateGroup = PredicateGroup.create(queryParameterMap);
    Query query = queryBuilder.createQuery(predicateGroup, session);
    SearchResult searchResult = query.getResult();
    LOG.debug("Query statement: '{}'", searchResult.getQueryStatement());
    // Query builder has a leaking resource resolver, so the following work around is required.
    ResourceResolver leakingResourceResolver = null;
    try {
        // Iterate over the hits if you need special information
        Iterator<Resource> resourceIterator = searchResult.getResources();
        while (resourceIterator.hasNext()) {
            Resource resource = resourceIterator.next();
            if (leakingResourceResolver == null) {
                // Get a reference to QB's leaking resource resolver
                leakingResourceResolver = resource.getResourceResolver();
            }
            DAMContentFragment contentFragmentModel = new DAMContentFragmentImpl(resource, contentTypeConverter, null, elementNames);
            items.add(contentFragmentModel);
        }
    } finally {
        if (leakingResourceResolver != null) {
            // Always close the leaking query builder resource resolver
            leakingResourceResolver.close();
        }
    }
}
Also used : Query(com.day.cq.search.Query) Resource(org.apache.sling.api.resource.Resource) SearchResult(com.day.cq.search.result.SearchResult) QueryBuilder(com.day.cq.search.QueryBuilder) PredicateGroup(com.day.cq.search.PredicateGroup) DAMContentFragment(com.adobe.cq.wcm.core.components.models.contentfragment.DAMContentFragment) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) Session(javax.jcr.Session) PostConstruct(javax.annotation.PostConstruct)

Aggregations

PredicateGroup (com.day.cq.search.PredicateGroup)5 Query (com.day.cq.search.Query)5 SearchResult (com.day.cq.search.result.SearchResult)5 QueryBuilder (com.day.cq.search.QueryBuilder)4 Session (javax.jcr.Session)4 Resource (org.apache.sling.api.resource.Resource)4 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)4 ListItem (com.adobe.cq.wcm.core.components.models.ListItem)2 PathPredicateEvaluator (com.day.cq.search.eval.PathPredicateEvaluator)2 LiveRelationshipManager (com.day.cq.wcm.msm.api.LiveRelationshipManager)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 Iterator (java.util.Iterator)2 LinkedList (java.util.LinkedList)2 List (java.util.List)2 Map (java.util.Map)2 Objects (java.util.Objects)2 StreamSupport (java.util.stream.StreamSupport)2