use of com.adobe.cq.wcm.core.components.internal.link.LinkHandler in project aem-core-wcm-components by Adobe-Marketing-Cloud.
the class NavigationItemImplTest method test.
@Test
protected void test() {
Page page = mock(Page.class);
when(page.getProperties()).thenReturn(ValueMap.EMPTY);
LinkHandler linkHandler = mock(LinkHandler.class);
Component component = mock(Component.class);
NavigationItemImpl navigationItem = new NavigationItemImpl(page, true, true, linkHandler, 0, Collections.emptyList(), "id", component);
assertEquals(page, navigationItem.getPage());
assertTrue(navigationItem.isActive());
assertEquals(Collections.emptyList(), navigationItem.getChildren());
assertEquals(0, navigationItem.getLevel());
}
use of com.adobe.cq.wcm.core.components.internal.link.LinkHandler in project aem-core-wcm-components by Adobe-Marketing-Cloud.
the class ContainerImplTest method setUp.
@BeforeEach
public void setUp() {
context.load().json(TEST_BASE + CoreComponentTestContext.TEST_CONTENT_JSON, CONTAINING_PAGE);
context.registerService(FormStructureHelperFactory.class, resource -> formStructureHelper);
context.registerService(SlingModelFilter.class, new SlingModelFilter() {
private final Set<String> IGNORED_NODE_NAMES = new HashSet<String>() {
{
add(NameConstants.NN_RESPONSIVE_CONFIG);
add(MSMNameConstants.NT_LIVE_SYNC_CONFIG);
add("cq:annotations");
}
};
@Override
public Map<String, Object> filterProperties(Map<String, Object> map) {
return map;
}
@Override
public Iterable<Resource> filterChildResources(Iterable<Resource> childResources) {
return StreamSupport.stream(childResources.spliterator(), false).filter(r -> !IGNORED_NODE_NAMES.contains(r.getName())).collect(Collectors.toList());
}
});
context.registerAdapter(MockSlingHttpServletRequest.class, LinkHandler.class, new LinkHandler());
FormsHelperStubber.createStub();
}
use of com.adobe.cq.wcm.core.components.internal.link.LinkHandler 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.adobe.cq.wcm.core.components.internal.link.LinkHandler in project aem-core-wcm-components by Adobe-Marketing-Cloud.
the class Utils method getWrappedImageResourceWithInheritance.
/**
* Wraps an image resource with the properties and child resources of the inherited featured image of either
* the linked page or the page containing the resource.
*
* @param resource The image resource
* @param linkHandler The link handler
* @param currentStyle The style of the image resource
* @param currentPage The page containing the image resource
* @return The wrapped image resource augmented with inherited properties and child resource if inheritance is enabled, the plain image resource otherwise.
*/
public static Resource getWrappedImageResourceWithInheritance(Resource resource, LinkHandler linkHandler, Style currentStyle, Page currentPage) {
if (resource == null) {
LOGGER.error("The resource is not defined");
return null;
}
if (linkHandler == null) {
LOGGER.error("The link handler is not defined");
return null;
}
ValueMap properties = resource.getValueMap();
String fileReference = properties.get(DownloadResource.PN_REFERENCE, String.class);
Resource fileResource = resource.getChild(DownloadResource.NN_FILE);
boolean imageFromPageImage = properties.get(PN_IMAGE_FROM_PAGE_IMAGE, StringUtils.isEmpty(fileReference) && fileResource == null);
boolean altValueFromPageImage = properties.get(PN_ALT_VALUE_FROM_PAGE_IMAGE, imageFromPageImage);
if (imageFromPageImage) {
Resource inheritedResource = null;
String linkURL = properties.get(ImageResource.PN_LINK_URL, String.class);
boolean actionsEnabled = (currentStyle != null) ? !currentStyle.get(Teaser.PN_ACTIONS_DISABLED, !properties.get(Teaser.PN_ACTIONS_ENABLED, true)) : properties.get(Teaser.PN_ACTIONS_ENABLED, true);
Resource firstAction = Optional.of(resource).map(res -> res.getChild(Teaser.NN_ACTIONS)).map(actions -> actions.getChildren().iterator().next()).orElse(null);
if (StringUtils.isNotEmpty(linkURL)) {
// the inherited resource is the featured image of the linked page
Optional<Link> link = linkHandler.getLink(resource);
inheritedResource = link.map(link1 -> (Page) link1.getReference()).map(ComponentUtils::getFeaturedImage).orElse(null);
} else if (actionsEnabled && firstAction != null) {
// the inherited resource is the featured image of the first action's page (the resource is assumed to be a teaser)
inheritedResource = Optional.of(linkHandler.getLink(firstAction, Teaser.PN_ACTION_LINK)).map(link1 -> {
if (link1.isPresent()) {
Page linkedPage = (Page) link1.get().getReference();
return Optional.ofNullable(linkedPage).map(ComponentUtils::getFeaturedImage).orElse(null);
}
return null;
}).orElse(null);
} else {
// the inherited resource is the featured image of the current page
inheritedResource = Optional.ofNullable(currentPage).map(page -> {
Template template = page.getTemplate();
// make sure the resource is part of the currentPage or of its template
if (StringUtils.startsWith(resource.getPath(), currentPage.getPath()) || (template != null && StringUtils.startsWith(resource.getPath(), template.getPath()))) {
return ComponentUtils.getFeaturedImage(currentPage);
}
return null;
}).orElse(null);
}
Map<String, String> overriddenProperties = new HashMap<>();
Map<String, Resource> overriddenChildren = new HashMap<>();
String inheritedFileReference = null;
Resource inheritedFileResource = null;
String inheritedAlt = null;
String inheritedAltValueFromDAM = null;
if (inheritedResource != null) {
// Define the inherited properties
ValueMap inheritedProperties = inheritedResource.getValueMap();
inheritedFileReference = inheritedProperties.get(DownloadResource.PN_REFERENCE, String.class);
inheritedFileResource = inheritedResource.getChild(DownloadResource.NN_FILE);
inheritedAlt = inheritedProperties.get(ImageResource.PN_ALT, String.class);
inheritedAltValueFromDAM = inheritedProperties.get(PN_ALT_VALUE_FROM_DAM, String.class);
}
overriddenProperties.put(DownloadResource.PN_REFERENCE, inheritedFileReference);
overriddenChildren.put(DownloadResource.NN_FILE, inheritedFileResource);
// don't inherit the image title from the page image
overriddenProperties.put(PN_TITLE_VALUE_FROM_DAM, "false");
if (altValueFromPageImage) {
overriddenProperties.put(ImageResource.PN_ALT, inheritedAlt);
overriddenProperties.put(PN_ALT_VALUE_FROM_DAM, inheritedAltValueFromDAM);
} else {
overriddenProperties.put(PN_ALT_VALUE_FROM_DAM, "false");
}
return new CoreResourceWrapper(resource, resource.getResourceType(), null, overriddenProperties, overriddenChildren);
}
return resource;
}
use of com.adobe.cq.wcm.core.components.internal.link.LinkHandler in project aem-core-wcm-components by Adobe-Marketing-Cloud.
the class AdaptiveImageServlet method doGet.
@Override
protected void doGet(@NotNull SlingHttpServletRequest request, @NotNull SlingHttpServletResponse response) throws IOException {
Timer.Context requestDuration = metrics.startDurationRecording();
try {
metrics.markServletInvocation();
RequestPathInfo requestPathInfo = request.getRequestPathInfo();
List<String> selectorList = selectorToList(requestPathInfo.getSelectorString());
String suffix = requestPathInfo.getSuffix();
String imageName = StringUtils.isNotEmpty(suffix) ? FilenameUtils.getName(suffix) : "";
if (StringUtils.isNotEmpty(suffix)) {
String suffixExtension = FilenameUtils.getExtension(suffix);
if (StringUtils.isNotEmpty(suffixExtension)) {
if (!suffixExtension.equals(requestPathInfo.getExtension())) {
LOGGER.error("The suffix part defines a different extension than the request: {}.", suffix);
metrics.markImageErrors();
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
} else {
LOGGER.error("Invalid suffix: {}.", suffix);
metrics.markImageErrors();
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
}
Resource component = request.getResource();
ResourceResolver resourceResolver = request.getResourceResolver();
if (!component.isResourceType(IMAGE_RESOURCE_TYPE)) {
// image coming from template; need to switch resource
Resource componentCandidate = null;
PageManager pageManager = resourceResolver.adaptTo(PageManager.class);
if (pageManager != null) {
Page page = pageManager.getContainingPage(component);
if (page != null) {
Template template = page.getTemplate();
if (template != null) {
if (StringUtils.isNotEmpty(suffix)) {
long lastModifiedSuffix = getRequestLastModifiedSuffix(suffix);
String relativeTemplatePath = lastModifiedSuffix == 0 ? // no timestamp info, but extension is valid; get resource name
suffix.substring(0, suffix.lastIndexOf('.')) : // timestamp info, get parent path from suffix
suffix.substring(0, suffix.lastIndexOf("/" + String.valueOf(lastModifiedSuffix)));
String imagePath = ResourceUtil.normalize(template.getPath() + relativeTemplatePath);
if (StringUtils.isNotEmpty(imagePath) && !template.getPath().equals(imagePath)) {
componentCandidate = resourceResolver.getResource(imagePath);
}
}
}
}
}
if (componentCandidate == null) {
LOGGER.error("Unable to retrieve an image from this page's template.");
metrics.markImageErrors();
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
component = componentCandidate;
}
LinkHandler linkHandler = request.adaptTo(LinkHandler.class);
Style currentStyle = WCMUtils.getStyle(request);
Page currentPage = Optional.ofNullable(resourceResolver.adaptTo(PageManager.class)).map(pageManager -> pageManager.getContainingPage(request.getResource())).orElse(null);
Resource wrappedImageResourceWithInheritance = getWrappedImageResourceWithInheritance(component, linkHandler, currentStyle, currentPage);
ImageComponent imageComponent = new ImageComponent(wrappedImageResourceWithInheritance);
if (imageComponent.source == Source.NOCONTENT || imageComponent.source == Source.NONEXISTING) {
LOGGER.error("Either the image from {} does not have a valid file reference" + " or the containing page does not have a valid featured image", component.getPath());
metrics.markImageErrors();
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
ValueMap componentProperties = component.getValueMap();
long lastModifiedEpoch = 0;
Calendar lastModifiedDate = componentProperties.get(JcrConstants.JCR_LASTMODIFIED, Calendar.class);
if (lastModifiedDate == null) {
lastModifiedDate = componentProperties.get(NameConstants.PN_PAGE_LAST_MOD, Calendar.class);
}
if (lastModifiedDate != null) {
lastModifiedEpoch = lastModifiedDate.getTimeInMillis();
}
Asset asset = null;
if (imageComponent.source == Source.ASSET) {
asset = imageComponent.imageResource.adaptTo(Asset.class);
if (asset == null) {
LOGGER.error("Unable to adapt resource {} used by image {} to an asset.", imageComponent.imageResource.getPath(), component.getPath());
metrics.markImageErrors();
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
long assetLastModifiedEpoch = asset.getLastModified();
if (assetLastModifiedEpoch > lastModifiedEpoch) {
lastModifiedEpoch = assetLastModifiedEpoch;
}
}
long requestLastModifiedSuffix = getRequestLastModifiedSuffix(suffix);
if (requestLastModifiedSuffix >= 0 && requestLastModifiedSuffix != lastModifiedEpoch) {
String redirectLocation = getRedirectLocation(request, lastModifiedEpoch);
if (StringUtils.isNotEmpty(redirectLocation)) {
response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
response.setHeader("Location", redirectLocation);
return;
} else {
LOGGER.error("Unable to determine correct redirect location.");
metrics.markImageErrors();
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
}
if (!handleIfModifiedSinceHeader(request, response, lastModifiedEpoch)) {
Map<String, Integer> transformationMap = getTransformationMap(selectorList, component);
Integer jpegQualityInPercentage = transformationMap.get(SELECTOR_QUALITY_KEY);
double quality = jpegQualityInPercentage / 100.0d;
int resizeWidth = transformationMap.get(SELECTOR_WIDTH_KEY);
String imageType = getImageType(requestPathInfo.getExtension());
if (imageComponent.source == Source.FILE) {
transformAndStreamFile(response, componentProperties, resizeWidth, quality, imageComponent.imageResource, imageType, imageName);
} else if (imageComponent.source == Source.ASSET) {
transformAndStreamAsset(response, componentProperties, resizeWidth, quality, asset, imageType, imageName);
}
metrics.markImageStreamed();
}
} catch (IllegalArgumentException e) {
LOGGER.error("Invalid image request", e.getMessage());
metrics.markImageErrors();
response.sendError(HttpServletResponse.SC_NOT_FOUND);
} finally {
requestDuration.stop();
}
}
Aggregations