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;
}
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());
}
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());
}
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);
}
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();
}
}
}
Aggregations