com.day.cq.wcm.api.PageManager Java Examples

The following examples show how to use com.day.cq.wcm.api.PageManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CatalogSearchSupport.java    From commerce-cif-connector with Apache License 2.0 7 votes vote down vote up
/**
 * Searches for the {@link #PN_CATALOG_PATH} property at the specified path or its parent pages.
 *
 * @param path a path in the content repository
 * @return the value of the {@link #PN_CATALOG_PATH} property or {@code null} if not found
 */
public String findCatalogPath(String path) {
    if (StringUtils.isBlank(path)) {
        return null;
    }
    Page parentPage = resolver.adaptTo(PageManager.class).getContainingPage(path);
    if (parentPage == null) {
        return null;
    }

    ConfigurationBuilder configBuilder = parentPage.getContentResource().adaptTo(ConfigurationBuilder.class);
    if (configBuilder != null) {
        ValueMap properties = configBuilder.name(CLOUDCONFIGS_BUCKET_NAME + "/" + COMMERCE_CONFIG_NAME).asValueMap();
        if (properties.containsKey(PN_CATALOG_PATH)) {
            return properties.get(PN_CATALOG_PATH, String.class);
        }
    }

    InheritanceValueMap inheritedProperties = new HierarchyNodeInheritanceValueMap(parentPage.getContentResource());
    return inheritedProperties.getInherited(PN_CATALOG_PATH, String.class);
}
 
Example #2
Source File: SiteNavigation.java    From aem-core-cif-components with Apache License 2.0 7 votes vote down vote up
/**
 * Retrieves a generic page based on a page or page ancestors using the page path configured
 * via the property of the root page.
 *
 * @param pageTypeProperty The name of the JCR property on the root page that points to the generic page
 * @param page the page for looking up the property
 * @return the generic page
 */
@Nullable
private static Page getGenericPage(String pageTypeProperty, Page page) {
    final InheritanceValueMap properties = new HierarchyNodeInheritanceValueMap(page.getContentResource());
    String utilityPagePath = properties.getInherited(pageTypeProperty, String.class);
    if (StringUtils.isBlank(utilityPagePath)) {
        LOGGER.warn("Page property {} not found at {}", pageTypeProperty, page.getPath());
        return null;
    }

    PageManager pageManager = page.getPageManager();
    Page categoryPage = pageManager.getPage(utilityPagePath);
    if (categoryPage == null) {
        LOGGER.warn("No page found at {}", utilityPagePath);
        return null;
    }
    return categoryPage;
}
 
Example #3
Source File: IsProductDetailPageServlet.java    From commerce-cif-connector with Apache License 2.0 6 votes vote down vote up
private boolean isProductDetailPage(String path, ResourceResolver resourceResolver) {
    if (StringUtils.isBlank(path)) {
        return false;
    }

    Resource resource = resourceResolver.resolve(path);
    if (resource instanceof NonExistingResource) {
        return false;
    }

    Page page = resourceResolver.adaptTo(PageManager.class).getPage(resource.getPath());
    if (page == null) {
        return false;
    }

    Resource pageContent = page.getContentResource();
    if (pageContent == null) {
        return false;
    }

    boolean val = containsComponent(PRODUCT_RT, pageContent);

    return val;
}
 
Example #4
Source File: IsProductListPageServlet.java    From commerce-cif-connector with Apache License 2.0 6 votes vote down vote up
private boolean isProductListPage(String path, ResourceResolver resourceResolver) {
    if (StringUtils.isBlank(path)) {
        return false;
    }

    Resource resource = resourceResolver.resolve(path);
    if (resource instanceof NonExistingResource) {
        return false;
    }

    Page page = resourceResolver.adaptTo(PageManager.class).getPage(resource.getPath());
    if (page == null) {
        return false;
    }

    Resource pageContent = page.getContentResource();
    if (pageContent == null) {
        return false;
    }

    boolean val = containsComponent(PRODUCT_LIST_RT, pageContent);

    return val;
}
 
Example #5
Source File: GraphqlProductViewHandlerTest.java    From commerce-cif-connector with Apache License 2.0 6 votes vote down vote up
@Test
public void testCategoryConstraintSearchQuery() throws RepositoryException {
    Mockito.when(servletRequest.getHeader("Referer")).thenReturn("editor.html/test/page.html");
    PageManager pageManager = Mockito.mock(PageManager.class);
    Mockito.when(resourceResolver.adaptTo(PageManager.class)).thenReturn(pageManager);
    Page page = Mockito.mock(Page.class);
    Mockito.when(pageManager.getContainingPage("/test/page")).thenReturn(page);
    Resource contentResource = Mockito.mock(Resource.class);
    Mockito.when(page.getContentResource()).thenReturn(contentResource);
    ModifiableValueMapDecorator valueMap = new ModifiableValueMapDecorator(new HashMap<>());
    Mockito.when(contentResource.getValueMap()).thenReturn(valueMap);
    valueMap.put(PN_CATALOG_PATH, "/catalog/path");
    Resource resource = Mockito.mock(Resource.class);
    Mockito.when(resourceResolver.getResource("/catalog/path")).thenReturn(resource);
    ModifiableValueMapDecorator properties = new ModifiableValueMapDecorator(new HashMap<>());
    Mockito.when(resource.getValueMap()).thenReturn(properties);
    properties.put("cq:commerceType", "category");
    properties.put("cifId", "1");

    ViewQuery viewQuery = viewHandler.createQuery(servletRequest, null, "query=trail");
    PredicateGroup predicateGroup = ((GraphqlProductViewHandler.GQLViewQuery) viewQuery).predicateGroup;
    Assert.assertNotNull(predicateGroup.getByName("3_" + CATEGORY_ID_PARAMETER));
    Assert.assertEquals(predicateGroup.getByName("3_" + CATEGORY_ID_PARAMETER).get(CATEGORY_ID_PARAMETER), "1");
    Assert.assertNotNull(predicateGroup.getByName("4_" + CATEGORY_PATH_PARAMETER));
    Assert.assertEquals(predicateGroup.getByName("4_" + CATEGORY_PATH_PARAMETER).get(CATEGORY_PATH_PARAMETER), "/catalog/path");
}
 
Example #6
Source File: NavigationImpl.java    From aem-core-cif-components with Apache License 2.0 6 votes vote down vote up
private void addItems(PageManager pageManager, AbstractNavigationItem parent,
    com.adobe.cq.wcm.core.components.models.NavigationItem currentWcmItem, List<NavigationItem> itemList) {
    Page page = pageManager.getPage(currentWcmItem.getPath());
    if (shouldExpandCatalogRoot(page)) {
        expandCatalogRoot(page, itemList);
    } else {
        NavigationItem item;
        if (isCatalogRoot(page)) {
            item = new CatalogPageNavigationItem(null, page, currentWcmItem);
        } else {
            String title = currentWcmItem.getTitle();
            String url = currentWcmItem.getURL();
            boolean active = currentWcmItem.isActive();
            item = new PageNavigationItem(parent, title, url, active, currentWcmItem);
        }
        itemList.add(item);
    }
}
 
Example #7
Source File: ProductComponent.java    From AEM-DataLayer with Apache License 2.0 6 votes vote down vote up
@Override
public void updateDataLayer(DataLayer dataLayer) {

	com.perficient.aem.datalayer.api.Product product = new com.perficient.aem.datalayer.api.Product();
	ProductInfo productInfo = product.getProductInfo();
	productInfo.setDescription(productData.getDescription());
	productInfo.setProductID(productData.getPath());
	productInfo.setProductImage(dataLayer.getConfig().getUrlPrefix() + productData.getImageUrl());
	productInfo.setProductName(productData.getTitle());
	productInfo.setProductThumbnail(dataLayer.getConfig().getUrlPrefix() + productData.getThumbnailUrl());
	Page page = resource.getResourceResolver().adaptTo(PageManager.class).getContainingPage(resource);
	productInfo.setProductURL(DataLayerUtil.getSiteUrl(page, dataLayer.getConfig()));
	productInfo.setSku(productData.getSKU());
	product.setProductInfo(productInfo);
	dataLayer.addProduct(product);
	
	Component component = new Component();
	component.getComponentInfo().setComponentID(resource.getPath());
	component.addAttribute("type", "product");
	dataLayer.addComponent(component);
}
 
Example #8
Source File: AEMDataLayerInterceptorFilter.java    From AEM-DataLayer with Apache License 2.0 6 votes vote down vote up
private boolean isApplicable(SlingHttpServletRequest request) {
	Object appliable = request.getAttribute(REQUEST_PROPERTY_AEM_DATALAYER_APPLICABLE);
	if (appliable == null) {
		Resource resource = request.getResource();
		PageManager pMgr = resource.getResourceResolver().adaptTo(PageManager.class);
		Page page = pMgr.getContainingPage(resource);
		AEMDataLayerConfig config = AEMDataLayerConfig.getDataLayerConfig(page);
		if (config != null) {
			DataLayer dataLayer = new DataLayer(config, page);
			request.setAttribute(DataLayerConstants.REQUEST_PROPERTY_AEM_DATALAYER, dataLayer);
			request.setAttribute(REQUEST_PROPERTY_AEM_DATALAYER_APPLICABLE, Boolean.TRUE);
			return true;
		} else {
			request.setAttribute(REQUEST_PROPERTY_AEM_DATALAYER_APPLICABLE, Boolean.FALSE);
			return false;
		}
	} else {
		return Boolean.TRUE.equals(appliable);
	}
}
 
Example #9
Source File: FieldInitializerTest.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    SlingScriptHelper sling = mock(SlingScriptHelper.class);
    bindings.put(SlingBindings.SLING, sling);
    ExpressionResolver expressionResolver = mock(ExpressionResolver.class);
    when(expressionResolver.resolve(anyString(), any(), any(), (SlingHttpServletRequest) any())).thenAnswer(
        invocationOnMock -> invocationOnMock.getArguments()[0]);
    when(sling.getService(ExpressionResolver.class)).thenReturn(expressionResolver);
    CommerceBasePathsService pathService = mock(CommerceBasePathsService.class);
    when(pathService.getProductsBasePath()).thenReturn(PRODUCTS_BASE_PATH);
    when(sling.getService(CommerceBasePathsService.class)).thenReturn(pathService);
    doAnswer(invocationOnMock -> {
        includedResourceSample = (Resource) invocationOnMock.getArguments()[0];
        return null;
    }).when(sling).include(any(Resource.class));
    request = mock(SlingHttpServletRequest.class);
    when(request.getRequestURI()).thenReturn("some_request_uri");
    bindings.put(SlingBindings.REQUEST, request);
    requestPathInfo = mock(RequestPathInfo.class);
    when(request.getRequestPathInfo()).thenReturn(requestPathInfo);
    valueMap = new ModifiableValueMapDecorator(new HashMap<>());
    bindings.put(WCMBindingsConstants.NAME_PROPERTIES, valueMap);

    ResourceResolver resourceResolver = mock(ResourceResolver.class);
    when(request.getResourceResolver()).thenReturn(resourceResolver);
    PageManager pageManager = mock(PageManager.class);
    when(resourceResolver.adaptTo(PageManager.class)).thenReturn(pageManager);
    Page page = mock(Page.class);
    when(pageManager.getContainingPage(anyString())).thenReturn(page);
    contentResource = mock(Resource.class);
    contentResourceProperties = new ModifiableValueMapDecorator(new HashMap<>());
    when(contentResource.getValueMap()).thenReturn(contentResourceProperties);
    when(page.getContentResource()).thenReturn(contentResource);
}
 
Example #10
Source File: PageTypeRenderConditionServlet.java    From aem-core-cif-components with Apache License 2.0 5 votes vote down vote up
private boolean checkPageType(SlingHttpServletRequest slingRequest, String pageType) {
    if (StringUtils.isBlank(pageType)) {
        LOGGER.error("{} property is not defined at {}", PAGE_TYPE_PROPERTY, slingRequest.getResource().getPath());
        return false;
    }

    // the caller is a page properties dialog
    if (!StringUtils.contains(slingRequest.getPathInfo(), PAGE_PROPERTIES)) {
        return false;
    }

    PageManager pageManager = slingRequest.getResourceResolver().adaptTo(PageManager.class);
    // the page path is in the "item" request parameter
    String pagePath = slingRequest.getParameter("item");
    Page page = pageManager.getPage(pagePath);
    if (page == null) {
        return false;
    }

    Page parentPage = page.getParent();
    if (parentPage == null) {
        return false;
    }

    // perform the appropriate checks according to the pageType property
    if (PAGE_TYPE_PRODUCT.equals(pageType)) {
        Page productPage = SiteNavigation.getProductPage(page);
        return productPage != null && productPage.getPath().equals(parentPage.getPath());
    } else if (PAGE_TYPE_CATEGORY.equals(pageType)) {
        Page categoryPage = SiteNavigation.getCategoryPage(page);
        return categoryPage != null && categoryPage.getPath().equals(parentPage.getPath());
    }

    return false;
}
 
Example #11
Source File: NavigationImpl.java    From aem-core-cif-components with Apache License 2.0 5 votes vote down vote up
@Override
public List<NavigationItem> getItems() {
    if (items == null) {
        items = new ArrayList<>();
        PageManager pageManager = currentPage.getPageManager();
        for (com.adobe.cq.wcm.core.components.models.NavigationItem wcmItem : wcmNavigation.getItems()) {
            addItems(pageManager, null, wcmItem, this.items);
        }
    }
    return items;
}
 
Example #12
Source File: NavigationImpl.java    From aem-core-cif-components with Apache License 2.0 5 votes vote down vote up
@Override
public List<NavigationItem> getItems() {
    final List<com.adobe.cq.wcm.core.components.models.NavigationItem> children = wcmItem.getChildren();
    if (children == null) {
        return Collections.emptyList();
    }

    List<NavigationItem> items = new ArrayList<>();
    for (com.adobe.cq.wcm.core.components.models.NavigationItem item : children) {
        PageManager pageManager = currentPage.getPageManager();
        addItems(pageManager, this, item, items);
    }
    return items;
}
 
Example #13
Source File: ResourceResolverImpl.java    From jackalope with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <AdapterType> AdapterType adaptTo(Class<AdapterType> type) {
    if (type.equals(Session.class)) return (AdapterType)session;
    if (type.equals(PageManager.class)) return (AdapterType)new PageManagerImpl(this);
    else return null;
}
 
Example #14
Source File: SearchResultsServiceImpl.java    From aem-core-cif-components with Apache License 2.0 4 votes vote down vote up
@Nonnull
@Override
public Pair<CategoryInterface, SearchResultsSet> performSearch(
    final SearchOptions searchOptions,
    final Resource resource,
    final Page productPage,
    final SlingHttpServletRequest request,
    final Consumer<ProductInterfaceQuery> productQueryHook,
    final AbstractCategoryRetriever categoryRetriever) {

    SearchResultsSetImpl searchResultsSet = new SearchResultsSetImpl();
    searchResultsSet.setSearchOptions(searchOptions);

    Page page = resource.getResourceResolver().adaptTo(PageManager.class).getContainingPage(resource);

    if (magentoGraphqlClient == null) {
        magentoGraphqlClient = MagentoGraphqlClient.create(resource, page);
    }

    if (magentoGraphqlClient == null) {
        LOGGER.error("The search result service was unable to create a new MagentoGraphqlClient.");
        return new ImmutablePair<>(null, searchResultsSet);
    }

    // We will use the search filter service to retrieve all of the potential available filters the commerce system
    // has available for querying against
    List<FilterAttributeMetadata> availableFilters = searchFilterService.retrieveCurrentlyAvailableCommerceFilters(page);
    SorterKey currentSorterKey = prepareSorting(searchOptions, searchResultsSet);

    // Next we generate the graphql query and actually query the commerce system
    String queryString = generateQueryString(searchOptions, availableFilters, productQueryHook, categoryRetriever, currentSorterKey);
    LOGGER.debug("Generated query string {}", queryString);
    GraphqlResponse<Query, Error> response = magentoGraphqlClient.execute(queryString);

    // If we have any errors returned we'll log them and return an empty search result
    if (response.getErrors() != null && response.getErrors().size() > 0) {
        response.getErrors().stream()
            .forEach(err -> LOGGER.error("An error has occurred: {} ({})", err.getMessage(), err.getCategory()));
        return new ImmutablePair<>(response.getData() != null ? response.getData().getCategory() : null, searchResultsSet);
    }

    // Finally we transform the results to something useful and expected by other the Sling Models and wider display layer
    final List<ProductListItem> productListItems = extractProductsFromResponse(
        response.getData().getProducts().getItems(),
        productPage,
        request);
    final List<SearchAggregation> searchAggregations = extractSearchAggregationsFromResponse(response.getData().getProducts()
        .getAggregations(),
        searchOptions.getAllFilters(), availableFilters);
    searchResultsSet.setTotalResults(response.getData().getProducts().getTotalCount());
    searchResultsSet.setProductListItems(productListItems);
    searchResultsSet.setSearchAggregations(searchAggregations);

    return new ImmutablePair<>(response.getData().getCategory(), searchResultsSet);
}
 
Example #15
Source File: NavigationImplTest.java    From aem-core-cif-components with Apache License 2.0 4 votes vote down vote up
@Before
public void init() {
    navigation = new NavigationImpl();

    // current page
    Page currentPage = mock(Page.class);
    pageManager = mock(PageManager.class);
    when(currentPage.getPageManager()).thenReturn(pageManager);
    when(currentPage.getPath()).thenReturn("/content/currentPage");
    Resource currentPageContent = mock(Resource.class);
    Map<String, Object> currentPageProperties = new HashMap<>();
    currentPageProperties.put("cq:cifCategoryPage", CATEGORY_PAGE_PATH);
    Page categoryPage = mock(Page.class);
    when(categoryPage.getPath()).thenReturn(CATEGORY_PAGE_PATH);
    when(currentPageContent.getPath()).thenReturn(CATEGORY_PAGE_PATH + "/jcr:content");
    when(pageManager.getPage(CATEGORY_PAGE_PATH)).thenReturn(categoryPage);
    when(currentPageContent.getValueMap()).thenReturn(new ValueMapDecorator(currentPageProperties));
    when(currentPage.getContentResource()).thenReturn(currentPageContent);
    Resource categoryPageResource = new SyntheticResource(null, CATEGORY_PAGE_PATH, null);
    when(categoryPage.adaptTo(Resource.class)).thenReturn(categoryPageResource);
    Whitebox.setInternalState(navigation, "currentPage", currentPage);

    // WCM navigation model
    wcmNavigation = mock(com.adobe.cq.wcm.core.components.internal.models.v1.NavigationImpl.class);
    Whitebox.setInternalState(navigation, "wcmNavigation", wcmNavigation);
    navigationItems = new ArrayList<>();
    when(wcmNavigation.getItems()).thenReturn(navigationItems);

    // Magento category provider
    categoryProvider = mock(GraphQLCategoryProvider.class);
    Whitebox.setInternalState(navigation, "graphQLCategoryProvider", categoryProvider);
    categoryList = new ArrayList<>();
    when(categoryProvider.getChildCategories(any(), any())).thenReturn(categoryList);

    // URL provider
    UrlProviderImpl urlProvider = new UrlProviderImpl();
    urlProvider.activate(new MockUrlProviderConfiguration());
    Whitebox.setInternalState(navigation, "urlProvider", urlProvider);

    // current request
    request = mock(SlingHttpServletRequest.class);
    Whitebox.setInternalState(navigation, "request", request);
    when(request.getRequestURI()).thenReturn("uri");

    navigationModel = new NavigationModelImpl();
    Whitebox.setInternalState(navigationModel, "rootNavigation", navigation);
    Whitebox.setInternalState(navigationModel, "request", request);
}
 
Example #16
Source File: PageImpl.java    From jackalope with Apache License 2.0 4 votes vote down vote up
@Override
public PageManager getPageManager() {
    return resource != null ? resource.getResourceResolver().adaptTo(PageManager.class) : null;
}