Search in sources :

Example 6 with SearchResult

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

the class ListImplTest method testSearchListType.

@Test
protected void testSearchListType() throws Exception {
    Session mockSession = mock(Session.class);
    SimpleSearch mockSimpleSearch = mock(SimpleSearch.class);
    context.registerAdapter(ResourceResolver.class, Session.class, mockSession);
    context.registerAdapter(Resource.class, SimpleSearch.class, mockSimpleSearch);
    SearchResult searchResult = mock(SearchResult.class);
    when(mockSimpleSearch.getResult()).thenReturn(searchResult);
    when(searchResult.getResources()).thenReturn(Collections.singletonList(Objects.requireNonNull(context.resourceResolver().getResource("/content/list/pages/page_1/jcr:content"))).iterator());
    List list = getListUnderTest(LIST_6);
    checkListConsistencyByPaths(list, new String[] { "/content/list/pages/page_1" });
    Utils.testJSONExport(list, Utils.getTestExporterJSONPath(testBase, LIST_6));
}
Also used : SimpleSearch(com.day.cq.search.SimpleSearch) SearchResult(com.day.cq.search.result.SearchResult) List(com.adobe.cq.wcm.core.components.models.List) Session(javax.jcr.Session) Test(org.junit.jupiter.api.Test)

Example 7 with SearchResult

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

the class ContentFragmentListImplTest method testListWithOneFragment.

@SuppressWarnings("unchecked")
private void testListWithOneFragment(String listName) {
    Resource resource = context.resourceResolver().getResource("/content/dam/contentfragments-for-list/text-only");
    if (resource != null) {
        Resource DAMFragment = Mockito.spy(resource);
        Query query = Mockito.mock(Query.class);
        SearchResult searchResult = Mockito.mock(SearchResult.class);
        Iterator<Resource> iterator = Mockito.mock(Iterator.class);
        ResourceResolver spyResolver = Mockito.spy(DAMFragment.getResourceResolver());
        when(query.getResult()).thenReturn(searchResult);
        when(searchResult.getResources()).thenReturn(iterator);
        when(iterator.hasNext()).thenReturn(true, false);
        when(iterator.next()).thenReturn(DAMFragment);
        when(DAMFragment.getResourceResolver()).thenReturn(spyResolver);
        Mockito.doNothing().when(spyResolver).close();
        when(queryBuilderMock.createQuery(Mockito.any(PredicateGroup.class), Mockito.any(Session.class))).thenReturn(query);
        ContentFragmentList contentFragmentList = getModelInstanceUnderTest(listName);
        assertEquals(ContentFragmentListImpl.RESOURCE_TYPE_V1, contentFragmentList.getExportedType());
        assertEquals(contentFragmentList.getListItems().size(), 1);
        Utils.testJSONExport(contentFragmentList, Utils.getTestExporterJSONPath(TEST_BASE, listName));
        Mockito.doCallRealMethod().when(spyResolver).close();
    }
}
Also used : Query(com.day.cq.search.Query) ContentFragmentList(com.adobe.cq.wcm.core.components.models.contentfragment.ContentFragmentList) Resource(org.apache.sling.api.resource.Resource) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) SearchResult(com.day.cq.search.result.SearchResult) PredicateGroup(com.day.cq.search.PredicateGroup) Session(javax.jcr.Session)

Example 8 with SearchResult

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

the class ContentFragmentListImplTest method setUp.

@BeforeEach
@SuppressWarnings("unchecked")
void setUp() throws NoSuchFieldException, IllegalAccessException {
    super.setUp();
    // Load additional content for content list model
    context.load().json(TEST_BASE + "/test-content.json", "/content/tests");
    context.load().json("/contentfragmentlist/test-content-dam-contentfragments.json", "/content/dam/contentfragments-for-list");
    Query query = Mockito.mock(Query.class);
    SearchResult searchResult = Mockito.mock(SearchResult.class);
    Iterator<Resource> iterator = Mockito.mock(Iterator.class);
    Resource resource = Mockito.mock(Resource.class);
    leakingResourceResolverMock = Mockito.mock(ResourceResolver.class);
    when(query.getResult()).thenReturn(searchResult);
    when(searchResult.getResources()).thenReturn(iterator);
    when(iterator.hasNext()).thenReturn(true, false);
    when(iterator.next()).thenReturn(resource);
    when(resource.getResourceResolver()).thenReturn(leakingResourceResolverMock);
    when(queryBuilderMock.createQuery(Mockito.any(PredicateGroup.class), Mockito.any(Session.class))).thenReturn(query);
}
Also used : Query(com.day.cq.search.Query) Resource(org.apache.sling.api.resource.Resource) ResourceResolver(org.apache.sling.api.resource.ResourceResolver) SearchResult(com.day.cq.search.result.SearchResult) PredicateGroup(com.day.cq.search.PredicateGroup) Session(javax.jcr.Session) BeforeEach(org.junit.jupiter.api.BeforeEach)

Example 9 with SearchResult

use of com.day.cq.search.result.SearchResult 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 10 with SearchResult

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

the class ListImpl method getSearchListItems.

/**
 * Get the list items if using the search source type.
 *
 * @return The search list items.
 */
private Stream<Page> getSearchListItems() {
    Optional<Page> searchRoot = getRootPage(PN_SEARCH_IN);
    String query = properties.get(PN_SEARCH_QUERY, String.class);
    if (!StringUtils.isBlank(query) && searchRoot.isPresent()) {
        SimpleSearch search = resource.adaptTo(SimpleSearch.class);
        if (search != null) {
            search.setQuery(query);
            search.setSearchIn(searchRoot.get().getPath());
            search.addPredicate(new Predicate("type", "type").set("type", NameConstants.NT_PAGE));
            int limit = properties.get(PN_SEARCH_LIMIT, SEARCH_LIMIT_DEFAULT);
            search.setHitsPerPage(limit);
            return safeGetSearchResult(search).map(SearchResult::getResources).map(it -> (Iterable<Resource>) () -> it).map(it -> StreamSupport.stream(it.spliterator(), false)).orElseGet(Stream::empty).filter(Objects::nonNull).map(currentPage.getPageManager()::getContainingPage).filter(Objects::nonNull);
        }
    }
    return Stream.empty();
}
Also used : ValueMap(org.apache.sling.api.resource.ValueMap) JsonProperty(com.fasterxml.jackson.annotation.JsonProperty) Arrays(java.util.Arrays) LoggerFactory(org.slf4j.LoggerFactory) ArrayUtils(org.apache.commons.lang3.ArrayUtils) StringUtils(org.apache.commons.lang3.StringUtils) Page(com.day.cq.wcm.api.Page) SlingHttpServletRequest(org.apache.sling.api.SlingHttpServletRequest) TagManager(com.day.cq.tagging.TagManager) Style(com.day.cq.wcm.api.designer.Style) SearchResult(com.day.cq.search.result.SearchResult) ScriptVariable(org.apache.sling.models.annotations.injectorspecific.ScriptVariable) RepositoryException(javax.jcr.RepositoryException) Locale(java.util.Locale) ObjectUtils(org.apache.commons.lang3.ObjectUtils) Model(org.apache.sling.models.annotations.Model) StreamSupport(java.util.stream.StreamSupport) Predicate(com.day.cq.search.Predicate) ComponentExporter(com.adobe.cq.export.json.ComponentExporter) Collator(java.text.Collator) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) SimpleSearch(com.day.cq.search.SimpleSearch) List(com.adobe.cq.wcm.core.components.models.List) Collection(java.util.Collection) Resource(org.apache.sling.api.resource.Resource) Collectors(java.util.stream.Collectors) Exporter(org.apache.sling.models.annotations.Exporter) Serializable(java.io.Serializable) Objects(java.util.Objects) Nullable(org.jetbrains.annotations.Nullable) Stream(java.util.stream.Stream) ExporterConstants(com.adobe.cq.export.json.ExporterConstants) NameConstants(com.day.cq.wcm.api.NameConstants) PostConstruct(javax.annotation.PostConstruct) Optional(java.util.Optional) Comparator(java.util.Comparator) NotNull(org.jetbrains.annotations.NotNull) AbstractComponentImpl(com.adobe.cq.wcm.core.components.util.AbstractComponentImpl) SimpleSearch(com.day.cq.search.SimpleSearch) Objects(java.util.Objects) Page(com.day.cq.wcm.api.Page) SearchResult(com.day.cq.search.result.SearchResult) Predicate(com.day.cq.search.Predicate)

Aggregations

SearchResult (com.day.cq.search.result.SearchResult)16 Query (com.day.cq.search.Query)12 Resource (org.apache.sling.api.resource.Resource)11 Session (javax.jcr.Session)10 PredicateGroup (com.day.cq.search.PredicateGroup)8 QueryBuilder (com.day.cq.search.QueryBuilder)7 ResourceResolver (org.apache.sling.api.resource.ResourceResolver)7 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)5 List (com.adobe.cq.wcm.core.components.models.List)3 Hit (com.day.cq.search.result.Hit)3 Iterator (java.util.Iterator)3 Objects (java.util.Objects)3 StreamSupport (java.util.stream.StreamSupport)3 RepositoryException (javax.jcr.RepositoryException)3 SlingHttpServletRequest (org.apache.sling.api.SlingHttpServletRequest)3 ValueMap (org.apache.sling.api.resource.ValueMap)3 ListItem (com.adobe.cq.wcm.core.components.models.ListItem)2 SimpleDataSource (com.adobe.granite.ui.components.ds.SimpleDataSource)2 SimpleSearch (com.day.cq.search.SimpleSearch)2