use of com.day.cq.commons.PathInfo in project acs-aem-commons by Adobe-Consulting-Services.
the class ErrorPageHandlerImpl method configure.
@SuppressWarnings("squid:S1149")
private void configure(ComponentContext componentContext) {
Dictionary<?, ?> config = componentContext.getProperties();
final String legacyPrefix = "prop.";
this.enabled = PropertiesUtil.toBoolean(config.get(PROP_ENABLED), PropertiesUtil.toBoolean(config.get(legacyPrefix + PROP_ENABLED), DEFAULT_ENABLED));
this.vanityDispatchCheckEnabled = PropertiesUtil.toBoolean(config.get(PROP_VANITY_DISPATCH_ENABLED), PropertiesUtil.toBoolean(config.get(legacyPrefix + PROP_VANITY_DISPATCH_ENABLED), DEFAULT_VANITY_DISPATCH_ENABLED));
/**
* Error Pages *
*/
this.systemErrorPagePath = PropertiesUtil.toString(config.get(PROP_ERROR_PAGE_PATH), PropertiesUtil.toString(config.get(legacyPrefix + PROP_ERROR_PAGE_PATH), DEFAULT_SYSTEM_ERROR_PAGE_PATH_DEFAULT));
this.errorPageExtension = PropertiesUtil.toString(config.get(PROP_ERROR_PAGE_EXTENSION), PropertiesUtil.toString(config.get(legacyPrefix + PROP_ERROR_PAGE_EXTENSION), DEFAULT_ERROR_PAGE_EXTENSION));
this.fallbackErrorName = PropertiesUtil.toString(config.get(PROP_FALLBACK_ERROR_NAME), PropertiesUtil.toString(config.get(legacyPrefix + PROP_FALLBACK_ERROR_NAME), DEFAULT_FALLBACK_ERROR_NAME));
this.pathMap = configurePathMap(PropertiesUtil.toStringArray(config.get(PROP_SEARCH_PATHS), PropertiesUtil.toStringArray(config.get(legacyPrefix + PROP_SEARCH_PATHS), DEFAULT_SEARCH_PATHS)));
/**
* Not Found Handling *
*/
this.notFoundBehavior = PropertiesUtil.toString(config.get(PROP_NOT_FOUND_DEFAULT_BEHAVIOR), DEFAULT_NOT_FOUND_DEFAULT_BEHAVIOR);
String[] tmpNotFoundExclusionPatterns = PropertiesUtil.toStringArray(config.get(PROP_NOT_FOUND_EXCLUSION_PATH_PATTERNS), DEFAULT_NOT_FOUND_EXCLUSION_PATH_PATTERNS);
this.notFoundExclusionPatterns = new ArrayList<Pattern>();
for (final String tmpPattern : tmpNotFoundExclusionPatterns) {
this.notFoundExclusionPatterns.add(Pattern.compile(tmpPattern));
}
/**
* Error Page Cache *
*/
int ttl = PropertiesUtil.toInteger(config.get(PROP_TTL), PropertiesUtil.toInteger(LEGACY_PROP_TTL, DEFAULT_TTL));
boolean serveAuthenticatedFromCache = PropertiesUtil.toBoolean(config.get(PROP_SERVE_AUTHENTICATED_FROM_CACHE), PropertiesUtil.toBoolean(LEGACY_PROP_SERVE_AUTHENTICATED_FROM_CACHE, DEFAULT_SERVE_AUTHENTICATED_FROM_CACHE));
try {
cache = new ErrorPageCacheImpl(ttl, serveAuthenticatedFromCache);
Dictionary<String, Object> serviceProps = new Hashtable<String, Object>();
serviceProps.put("jmx.objectname", "com.adobe.acs.commons:type=ErrorPageHandlerCache");
cacheRegistration = componentContext.getBundleContext().registerService(DynamicMBean.class.getName(), cache, serviceProps);
} catch (NotCompliantMBeanException e) {
log.error("Unable to create cache", e);
}
/**
* Error Images *
*/
this.errorImagesEnabled = PropertiesUtil.toBoolean(config.get(PROP_ERROR_IMAGES_ENABLED), DEFAULT_ERROR_IMAGES_ENABLED);
this.errorImagePath = PropertiesUtil.toString(config.get(PROP_ERROR_IMAGE_PATH), DEFAULT_ERROR_IMAGE_PATH);
// Absolute path
if (StringUtils.startsWith(this.errorImagePath, "/")) {
ResourceResolver serviceResourceResolver = null;
try {
Map<String, Object> authInfo = Collections.singletonMap(ResourceResolverFactory.SUBSERVICE, (Object) SERVICE_NAME);
serviceResourceResolver = resourceResolverFactory.getServiceResourceResolver(authInfo);
final Resource resource = serviceResourceResolver.resolve(this.errorImagePath);
if (resource != null && resource.isResourceType(JcrConstants.NT_FILE)) {
final PathInfo pathInfo = new PathInfo(this.errorImagePath);
if (!StringUtils.equals("img", pathInfo.getSelectorString()) || StringUtils.isBlank(pathInfo.getExtension())) {
log.warn("Absolute Error Image Path paths to nt:files should have '.img.XXX' " + "selector.extension");
}
}
} catch (LoginException e) {
log.error("Could not get admin resource resolver to inspect validity of absolute errorImagePath");
} finally {
if (serviceResourceResolver != null) {
serviceResourceResolver.close();
}
}
}
this.errorImageExtensions = PropertiesUtil.toStringArray(config.get(PROP_ERROR_IMAGE_EXTENSIONS), DEFAULT_ERROR_IMAGE_EXTENSIONS);
for (int i = 0; i < errorImageExtensions.length; i++) {
this.errorImageExtensions[i] = StringUtils.lowerCase(errorImageExtensions[i], Locale.ENGLISH);
}
final StringWriter sw = new StringWriter();
final PrintWriter pw = new PrintWriter(sw);
pw.println();
pw.printf("Enabled: %s", this.enabled).println();
pw.printf("System Error Page Path: %s", this.systemErrorPagePath).println();
pw.printf("Error Page Extension: %s", this.errorPageExtension).println();
pw.printf("Fallback Error Page Name: %s", this.fallbackErrorName).println();
pw.printf("Resource Not Found - Behavior: %s", this.notFoundBehavior).println();
pw.printf("Resource Not Found - Exclusion Path Patterns %s", Arrays.toString(tmpNotFoundExclusionPatterns)).println();
pw.printf("Cache - TTL: %s", ttl).println();
pw.printf("Cache - Serve Authenticated: %s", serveAuthenticatedFromCache).println();
pw.printf("Error Images - Enabled: %s", this.errorImagesEnabled).println();
pw.printf("Error Images - Path: %s", this.errorImagePath).println();
pw.printf("Error Images - Extensions: %s", Arrays.toString(this.errorImageExtensions)).println();
log.debug(sw.toString());
}
use of com.day.cq.commons.PathInfo in project acs-aem-commons by Adobe-Consulting-Services.
the class ErrorPageHandlerImpl method findFirstRealParentOrSelf.
/**
* Given the Request path, find the first Real Parent of the Request (even if the resource doesnt exist).
*
* @param request the request object
* @param errorResource the error resource
* @return
*/
private Resource findFirstRealParentOrSelf(SlingHttpServletRequest request, Resource errorResource) {
if (errorResource == null) {
log.debug("Error resource is null");
return null;
}
log.trace("Finding first real parent for [ {} ]", errorResource.getPath());
final ResourceResolver resourceResolver = errorResource.getResourceResolver();
// Get the lowest aggregate node ancestor for the errorResource
String path = StringUtils.substringBefore(errorResource.getPath(), JcrConstants.JCR_CONTENT);
Resource resource = errorResource;
if (!StringUtils.equals(path, errorResource.getPath())) {
// Only resolve the resource if the path of the errorResource is different from the cleaned up path; else
// we know the errorResource and what the path resolves to is the same
resource = resourceResolver.resolve(request, path);
}
// If the resource exists, then use it!
if (!ResourceUtil.isNonExistingResource(resource)) {
log.debug("Found real aggregate resource at [ {} }", resource.getPath());
return resource;
}
// Quick check for the Parent; Handles common case of deactivated pages
final Resource parent = resource.getParent();
if (parent != null && !ResourceUtil.isNonExistingResource(resource)) {
log.debug("Found real aggregate resource via getParent() at [ {} ]", parent.getPath());
return parent;
}
// Start checking the path until the first real ancestor is found
final PathInfo pathInfo = new PathInfo(resource.getPath());
String[] parts = StringUtils.split(pathInfo.getResourcePath(), '/');
for (int i = parts.length - 1; i >= 0; i--) {
String[] tmpArray = (String[]) ArrayUtils.subarray(parts, 0, i);
String candidatePath = "/".concat(StringUtils.join(tmpArray, '/'));
final Resource candidateResource = resourceResolver.resolve(request, candidatePath);
if (candidateResource != null && !ResourceUtil.isNonExistingResource(candidateResource)) {
log.debug("Found first real aggregate parent via path look-up at [ {} ]", candidateResource.getPath());
return candidateResource;
}
}
log.debug("Could not find real parent for [ {} ]", errorResource.getPath());
return null;
}
use of com.day.cq.commons.PathInfo in project acs-aem-commons by Adobe-Consulting-Services.
the class PostRedirectGetFormHelperImplTest method shouldRedirectForRenderForm.
@Test
public void shouldRedirectForRenderForm() throws Exception {
request.setParameterMap(ImmutableMap.<String, Object>of(":form", "x"));
final SlingHttpServletResponse spiedResponse = spy(response);
final Form form = formHelper.getForm("x", request, response);
formHelper.renderForm(form, requestResource, request, spiedResponse);
// check a redirect was requested
verify(spiedResponse).sendRedirect(redirectCaptor.capture());
PathInfo redirectPathInfo = new PathInfo(redirectCaptor.getValue());
// check where we are being redirected to
assertThat(redirectPathInfo.getExtension(), is(equalTo("html")));
assertThat(redirectPathInfo.getResourcePath(), is(equalTo("/test")));
assertThat(redirectPathInfo.getSuffix(), startsWith(SUFFIX));
}
use of com.day.cq.commons.PathInfo in project acs-aem-commons by Adobe-Consulting-Services.
the class VanityURLServiceImpl method dispatch.
public boolean dispatch(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException, RepositoryException {
if (request.getAttribute(VANITY_DISPATCH_CHECK_ATTR) != null) {
log.trace("Processing a previously vanity dispatched request. Skipping...");
return false;
}
request.setAttribute(VANITY_DISPATCH_CHECK_ATTR, true);
final String requestURI = request.getRequestURI();
final RequestPathInfo mappedPathInfo = new PathInfo(request.getResourceResolver(), requestURI);
final String candidateVanity = mappedPathInfo.getResourcePath();
final String pathScope = StringUtils.removeEnd(requestURI, candidateVanity);
log.debug("Candidate vanity URL to check and dispatch: [ {} ]", candidateVanity);
// 2) the candidate is in at least 1 sling:vanityPath under /content
if (!StringUtils.equals(candidateVanity, requestURI) && isVanityPath(pathScope, candidateVanity, request)) {
log.debug("Forwarding request to vanity resource [ {} ]", candidateVanity);
final RequestDispatcher requestDispatcher = request.getRequestDispatcher(candidateVanity);
requestDispatcher.forward(new ExtensionlessRequestWrapper(request), response);
return true;
}
return false;
}
Aggregations