Search in sources :

Example 11 with SearchResult

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

the class LastModifiedOperationImpl method getLastModifiedQuery.

private List<Resource> getLastModifiedQuery(final ResourceResolver resourceResolver, final String userId, final String relativeDateRange, final String nodeType, final String dateProperty, final int limit) {
    final List<Resource> resources = new ArrayList<Resource>();
    final Map<String, String> map = new HashMap<String, String>();
    map.put("path", "/content");
    map.put("type", nodeType);
    map.put("1_property", NameConstants.PN_PAGE_LAST_MOD_BY);
    map.put("1_property.value", userId);
    map.put("relativedaterange.property", dateProperty);
    map.put("relativedaterange.lowerBound", relativeDateRange);
    map.put("orderby", dateProperty);
    map.put("orderby.sort", "desc");
    map.put("p.limit", String.valueOf(limit));
    map.put("p.guessTotal", "true");
    try {
        log.debug("Lastmod QueryBuilder Map: {}", new JSONObject(map).toString(2));
    } catch (JSONException e) {
    // no-op
    }
    final Query query = queryBuilder.createQuery(PredicateGroup.create(map), resourceResolver.adaptTo(Session.class));
    final SearchResult result = query.getResult();
    for (final Hit hit : result.getHits()) {
        try {
            resources.add(hit.getResource());
        } catch (RepositoryException e) {
            log.error("Error resolving Hit to Resource [ {} ]. " + "Likely issue with lucene index being out of sync.", hit.toString());
        }
    }
    return resources;
}
Also used : Query(com.day.cq.search.Query) HashMap(java.util.HashMap) Resource(org.apache.sling.api.resource.Resource) ArrayList(java.util.ArrayList) JSONException(org.apache.sling.commons.json.JSONException) SearchResult(com.day.cq.search.result.SearchResult) RepositoryException(javax.jcr.RepositoryException) Hit(com.day.cq.search.result.Hit) JSONObject(org.apache.sling.commons.json.JSONObject) Session(javax.jcr.Session)

Example 12 with SearchResult

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

the class OnDeployScriptBaseTest method testSearchAndUpdateResourceTypeWhenNoNodesFound.

@Test
public void testSearchAndUpdateResourceTypeWhenNoNodesFound() throws RepositoryException {
    Query query = mock(Query.class);
    SearchResult result = mock(SearchResult.class);
    when(result.getNodes()).thenReturn(Collections.EMPTY_LIST.iterator());
    when(query.getResult()).thenReturn(result);
    when(queryBuilder.createQuery(any(PredicateGroup.class), any(Session.class))).thenReturn(query);
    onDeployScript.searchAndUpdateResourceType("mysite/type/old", "mysite/type/new");
    assertLogText("No nodes found with resource type: mysite/type/old");
}
Also used : Query(com.day.cq.search.Query) SearchResult(com.day.cq.search.result.SearchResult) PredicateGroup(com.day.cq.search.PredicateGroup) Session(javax.jcr.Session) Test(org.junit.Test)

Example 13 with SearchResult

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

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

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

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