@Test public void testNonSiteNode() throws RepositoryException, JSONException { SiteSearchResultProcessor siteSearchResultProcessor = new SiteSearchResultProcessor(); SiteService siteService = createMock(SiteService.class); siteSearchResultProcessor.bindSiteService(siteService); Row row = createMock(Row.class); Value val = createMock(Value.class); expect(val.getString()).andReturn(""); expect(row.getValue("jcr:path")).andReturn(val); expect(siteService.isSite(isA(Item.class))).andReturn(false); Node resultNode = createMock(Node.class); expect(resultNode.getPath()).andReturn(""); SlingHttpServletRequest request = createMock(SlingHttpServletRequest.class); ResourceResolver resourceResolver = createMock(ResourceResolver.class); Session session = createMock(Session.class); expect(request.getResourceResolver()).andReturn(resourceResolver); expect(resourceResolver.adaptTo(Session.class)).andReturn(session); expect(session.getItem("")).andReturn(resultNode); replay(); try { siteSearchResultProcessor.writeNode(request, null, null, row); fail(); } catch (JSONException e) { assertEquals("Unable to write non-site node result", e.getMessage()); } }
@Test public void testProperPoolId() throws ItemNotFoundException, RepositoryException, NoSuchAlgorithmException, UnsupportedEncodingException { SlingHttpServletRequest request = mock(SlingHttpServletRequest.class); HtmlResponse response = new HtmlResponse(); ResourceResolver resolver = mock(ResourceResolver.class); String poolId = "foobarbaz"; Resource resource = mock(Resource.class); // The tagnode Node tagNode = new MockNode("/path/to/tag"); tagNode.setProperty(SLING_RESOURCE_TYPE_PROPERTY, FilesConstants.RT_SAKAI_TAG); tagNode.setProperty(FilesConstants.SAKAI_TAG_NAME, "urban"); // The file we want to tag. Node fileNode = mock(Node.class); when(fileNode.getPath()).thenReturn("/path/to/file"); NodeType type = mock(NodeType.class); when(type.getName()).thenReturn("foo"); when(fileNode.getMixinNodeTypes()).thenReturn(new NodeType[] {type}); Property tagsProp = mock(Property.class); MockPropertyDefinition tagsPropDef = new MockPropertyDefinition(false); Value v = new MockValue("uuid-to-other-tag"); when(tagsProp.getDefinition()).thenReturn(tagsPropDef); when(tagsProp.getValue()).thenReturn(v); when(fileNode.getProperty(FilesConstants.SAKAI_TAGS)).thenReturn(tagsProp); when(fileNode.hasProperty(FilesConstants.SAKAI_TAGS)).thenReturn(true); // Stuff to check if this is a correct request when(session.getNode(CreateContentPoolServlet.hash(poolId))).thenReturn(tagNode); RequestParameter poolIdParam = mock(RequestParameter.class); when(resolver.adaptTo(Session.class)).thenReturn(session); when(resource.adaptTo(Node.class)).thenReturn(fileNode); when(poolIdParam.getString()).thenReturn(poolId); when(request.getResource()).thenReturn(resource); when(request.getResourceResolver()).thenReturn(resolver); when(request.getRequestParameter("key")).thenReturn(poolIdParam); when(request.getRemoteUser()).thenReturn("john"); // Actual tagging procedure Session adminSession = mock(Session.class); when(adminSession.getItem(fileNode.getPath())).thenReturn(fileNode); ValueFactory valueFactory = mock(ValueFactory.class); Value newValue = new MockValue("uuid-of-tag"); when(valueFactory.createValue(Mockito.anyString(), Mockito.anyInt())) .thenReturn(newValue) .thenReturn(newValue); when(adminSession.getValueFactory()).thenReturn(valueFactory).thenReturn(valueFactory); when(slingRepo.loginAdministrative(null)).thenReturn(adminSession); when(adminSession.hasPendingChanges()).thenReturn(true); operation.doRun(request, response, null); assertEquals(200, response.getStatusCode()); verify(adminSession).save(); verify(adminSession).logout(); }
@Test public void testManyReferenceToSinglePages() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); String path = "/content/geometrixx/en"; String path1 = "/content/geometrixx/en"; map.put("path", path); map.put("path1", path1); ValueMap vm = new ValueMapDecorator(map); when(resource.getValueMap()).thenReturn(vm); when(resource.getResourceResolver()).thenReturn(resolver); when(resolver.getResource(path)).thenReturn(res); when(resolver.getResource(path1)).thenReturn(res1); when(res.adaptTo(Page.class)).thenReturn(referredpage); when(res1.adaptTo(Page.class)).thenReturn(referredpage); when(referredpage.getName()).thenReturn("geometrixx"); when(referredpage1.getName()).thenReturn("geometrixx"); when(referredpage1.getPath()).thenReturn(path1); when(manager.getContainingPage(path1)).thenReturn(referredpage1); Calendar cal = GregorianCalendar.getInstance(); when(referredpage.getLastModified()).thenReturn(cal); when(referredpage1.getLastModified()).thenReturn(cal); List<Reference> actual = instance.findReferences(resource); assertNotNull(actual); assertEquals(1, actual.size()); assertEquals("geometrixx (Page)", actual.get(0).getName()); }
public Resource next() { Principal nextPrincipal = principals.nextPrincipal(); try { ResourceResolver resourceResolver = parent.getResourceResolver(); if (resourceResolver != null) { Session session = resourceResolver.adaptTo(Session.class); if (session != null) { UserManager userManager = AccessControlUtil.getUserManager(session); if (userManager != null) { Authorizable authorizable = userManager.getAuthorizable(nextPrincipal.getName()); if (authorizable != null) { String path; if (authorizable.isGroup()) { path = SYSTEM_USER_MANAGER_GROUP_PREFIX + nextPrincipal.getName(); } else { path = SYSTEM_USER_MANAGER_USER_PREFIX + nextPrincipal.getName(); } return new SakaiAuthorizableResource(authorizable, resourceResolver, path); } } } } } catch (RepositoryException re) { log.error("Exception while looking up authorizable resource.", re); } return null; }
/** * Converts the resource type to an absolute path. If it does not start with "/" the resource is * resolved via search paths using resource resolver. If not matching resource is found it is * returned unchanged. * * @param resourceType Resource type * @return Absolute resource type */ public static String makeAbsolute(String resourceType, ResourceResolver resourceResolver) { if (StringUtils.isEmpty(resourceType) || StringUtils.startsWith(resourceType, "/")) { return resourceType; } // first try to resolve path via component manager - because on publish instance the original // resource may not accessible ComponentManager componentManager = resourceResolver.adaptTo(ComponentManager.class); if (componentManager != null) { Component component = componentManager.getComponent(resourceType); if (component != null) { return component.getPath(); } else { return resourceType; } } // otherwise use resource resolver directly Resource resource = resourceResolver.getResource(resourceType); if (resource != null) { return resource.getPath(); } else { return resourceType; } }
@Test public void testFlush() throws Exception { final ResourceResolver resourceResolver = mock(ResourceResolver.class); final Session session = mock(Session.class); when(resourceResolver.adaptTo(Session.class)).thenReturn(session); final String path1 = "/content/foo"; final String path2 = "/content/bar"; dispatcherFlusher.flush(resourceResolver, path1, path2); verify(replicator, times(1)) .replicate( eq(session), eq(ReplicationActionType.ACTIVATE), eq(path1), any(ReplicationOptions.class)); verify(replicator, times(1)) .replicate( eq(session), eq(ReplicationActionType.ACTIVATE), eq(path2), any(ReplicationOptions.class)); verifyNoMoreInteractions(replicator); }
/** * Used to get Full form of URL from the Given Short Page URL * * @param pageFullPath * @return {@link String} * @throws Exception */ public static String getFullURLPath(String shortUrlPath) throws Exception { ResourceResolver resourceResolver = null; try { Bundle bndl = FrameworkUtil.getBundle(ResourceResolverFactory.class); BundleContext bundleContext = bndl.getBundleContext(); ServiceReference ref = bundleContext.getServiceReference(ResourceResolverFactory.class.getName()); ResourceResolverFactory resolverFactory = (ResourceResolverFactory) bundleContext.getService(ref); resourceResolver = resolverFactory.getAdministrativeResourceResolver(null); Resource resource = resourceResolver.resolve(shortUrlPath); if (null != resource) { return java.net.URLDecoder.decode(resource.getPath(), "UTF-8"); } else { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Resource doesn't exists..." + shortUrlPath); } } } catch (Exception e) { LOGGER.error( " Error while getting Full URL for the path :" + shortUrlPath + " and the error message is :", e); } finally { resourceResolver.close(); } return shortUrlPath; }
protected static String getFinalTarget(ResourceHandle resource, List<String> trace) throws RedirectLoopException { String finalTarget = null; if (resource.isValid()) { String path = resource.getPath(); if (trace.contains(path)) { throw new RedirectLoopException(trace, path); } String redirect = resource.getProperty(PROP_TARGET); if (StringUtils.isBlank(redirect)) { redirect = resource.getProperty(PROP_REDIRECT); } if (StringUtils.isNotBlank(redirect)) { trace.add(path); finalTarget = redirect; if (!URL_PATTERN.matcher(finalTarget).matches()) { ResourceResolver resolver = resource.getResourceResolver(); Resource targetResource = resolver.getResource(finalTarget); if (targetResource != null) { String target = getFinalTarget(ResourceHandle.use(targetResource), trace); if (StringUtils.isNotBlank(target)) { finalTarget = target; } } } } } return finalTarget; }
@Override public void sendMail(String emailRecipient, String message) { try { /*Should use subservice to get administrative resource resolver instead of this code*/ ResourceResolver resourceResolver = resourceResolverFactory.getAdministrativeResourceResolver(null); Resource templateResource = resourceResolver.getResource(RabbitMQUtil.EMAIL_TEMPLATE_PATH); if (templateResource.getChild("file") != null) { templateResource = templateResource.getChild("file"); } ArrayList<InternetAddress> emailRecipients = new ArrayList<InternetAddress>(); final MailTemplate mailTemplate = MailTemplate.create( templateResource.getPath(), templateResource.getResourceResolver().adaptTo(Session.class)); HtmlEmail email = new HtmlEmail(); Map<String, String> mailTokens = new HashMap<String, String>(); mailTokens.put("message", message); mailTokens.put("subject", "Dummy Subject"); mailTokens.put("email", emailRecipient); if (mailTemplate != null) { emailRecipients.add(new InternetAddress(emailRecipient)); email.setTo(emailRecipients); email.setSubject("Dummy Mail"); email.setTextMsg(message); messageGateway = messageGatewayService.getGateway(HtmlEmail.class); messageGateway.send(email); } } catch (Exception e) { /*Put message in queue again in case of exception.. Based on type of exception, it can be decided whether it has to be put in queue again or not*/ RabbitMQUtil.addMessageToQueue(scrService); e.printStackTrace(System.out); } }
private void badNodeNameParam(String name, String exception) throws RepositoryException { CreateSakaiUserServlet csus = new CreateSakaiUserServlet(); csus.requestTrustValidatorService = requestTrustValidatorService; JackrabbitSession session = createMock(JackrabbitSession.class); ResourceResolver rr = createMock(ResourceResolver.class); SlingHttpServletRequest request = createMock(SlingHttpServletRequest.class); UserManager userManager = createMock(UserManager.class); User user = createMock(User.class); expect(request.getResourceResolver()).andReturn(rr).anyTimes(); expect(rr.adaptTo(Session.class)).andReturn(session).anyTimes(); expect(session.getUserManager()).andReturn(userManager); expect(session.getUserID()).andReturn("userID"); expect(userManager.getAuthorizable("userID")).andReturn(user); expect(user.isAdmin()).andReturn(false); expect(request.getParameter(":create-auth")).andReturn("reCAPTCHA"); expect(request.getParameter(SlingPostConstants.RP_NODE_NAME)).andReturn(name); HtmlResponse response = new HtmlResponse(); replay(); try { csus.handleOperation(request, response, null); fail(); } catch (RepositoryException e) { assertEquals(exception, e.getMessage()); } verify(); }
@Test public void testGetEmailAddrsNull() throws Exception { ResourceResolver resolver = mock(ResourceResolver.class); String userPath = "/doesnotexist"; when(resolver.getResource(userPath)).thenReturn(null); String[] emails = SendTemplatedEmailUtils.getEmailAddrsFromUserPath(resolver, userPath); assertEquals(0, emails.length); }
public void testAnonymous() throws Exception { Session session = mock(Session.class); when(session.getUserID()).thenReturn(UserConstants.ANON_USERID); ResourceResolver resolver = mock(ResourceResolver.class); when(resolver.adaptTo(Session.class)).thenReturn(session); when(request.getResourceResolver()).thenReturn(resolver); makeRequest(); verify(response).sendError(HttpServletResponse.SC_FORBIDDEN); }
@Override public void deleteTag(Tag tag, boolean autoSave) throws AccessControlException { try { resourceResolver.delete(tag.adaptTo(Resource.class)); if (autoSave) { resourceResolver.commit(); resourceResolver.refresh(); } } catch (PersistenceException e) { log.error("error deleting tag", e); } }
protected static Map<String, Map<Long, ResponseValue>> getTallyResponses(Resource tallyResource) throws JSONException { Map<String, Map<Long, ResponseValue>> returnValue = new HashMap<String, Map<Long, ResponseValue>>(); final ResourceResolver resolver = tallyResource.getResourceResolver(); final String tallyPath = tallyResource.getPath(); if (!tallyPath.startsWith("/content/usergenerated")) { tallyResource = resolver.resolve("/content/usergenerated" + tallyPath); } final Resource responsesNode = tallyResource.getChild(TallyConstants.RESPONSES_PATH); if (responsesNode == null) { return null; } NestedBucketStorageSystem bucketSystem = getBucketSystem(responsesNode); if (null == bucketSystem) { return null; } final Iterator<Resource> buckets = bucketSystem.listBuckets(); while (buckets.hasNext()) { final Resource bucketResource = buckets.next(); final Node bucketNode = bucketResource.adaptTo(Node.class); try { final NodeIterator userNodesInBucket = bucketNode.getNodes(); while (userNodesInBucket.hasNext()) { final Node userNode = userNodesInBucket.nextNode(); final NestedBucketStorageSystem userBucketSystem = getBucketSystem(resolver.getResource(userNode.getPath())); final Iterator<Resource> userBuckets = userBucketSystem.listBuckets(); final Map<Long, ResponseValue> userReturnValue = new HashMap<Long, ResponseValue>(); while (userBuckets.hasNext()) { final NodeIterator userResponses = userBuckets.next().adaptTo(Node.class).getNodes(); while (userResponses.hasNext()) { final Node responseNode = userResponses.nextNode(); final Long responseTimestamp = responseNode.getProperty(TIMESTAMP_PROPERTY).getLong(); userReturnValue.put( responseTimestamp, new PollResponse(responseNode.getProperty(RESPONSE_PROPERTY).getString())); } } returnValue.put(userNode.getName(), userReturnValue); } } catch (final RepositoryException e) { throw new JSONException( "Error trying to read user responses from bucket in " + bucketResource.getPath(), e); } } return returnValue; }
/** * Use path instead of resource (e.g. if resource is synthetic or non existing) to determine a * typed parent. */ public ResourceHandle getParent(String resourceType, String path) { ResourceResolver resolver = getResolver(); Resource resource; while (((resource = resolver.getResource(path)) == null || !resource.isResourceType(resourceType)) && StringUtils.isNotBlank(path)) { int delimiter = path.lastIndexOf('/'); if (delimiter >= 0) { path = path.substring(0, delimiter); } else { break; } } return ResourceHandle.use(resource); }
/* * (non-Javadoc) * @see * org.apache.sling.api.resource.ResourceProvider#listChildren(org.apache * .sling.api.resource.Resource) */ public Iterator<Resource> listChildren(Resource parent) { if (parent == null) { throw new NullPointerException("parent is null"); } try { String path = parent.getPath(); ResourceResolver resourceResolver = parent.getResourceResolver(); // handle children of /system/userManager if (SYSTEM_USER_MANAGER_PATH.equals(path)) { List<Resource> resources = new ArrayList<Resource>(); if (resourceResolver != null) { resources.add(getResource(resourceResolver, SYSTEM_USER_MANAGER_USER_PATH)); resources.add(getResource(resourceResolver, SYSTEM_USER_MANAGER_GROUP_PATH)); } return resources.iterator(); } int searchType = -1; if (SYSTEM_USER_MANAGER_USER_PATH.equals(path)) { searchType = PrincipalManager.SEARCH_TYPE_NOT_GROUP; } else if (SYSTEM_USER_MANAGER_GROUP_PATH.equals(path)) { searchType = PrincipalManager.SEARCH_TYPE_GROUP; } if (searchType != -1) { PrincipalIterator principals = null; // TODO: this actually does not work correctly since the // jackrabbit findPrincipals API // currently does an exact match of the search filter so it // won't match a wildcard Session session = resourceResolver.adaptTo(Session.class); if (session != null) { PrincipalManager principalManager = AccessControlUtil.getPrincipalManager(session); principals = principalManager.findPrincipals(".*", PrincipalManager.SEARCH_TYPE_NOT_GROUP); } if (principals != null) { return new ChildrenIterator(parent, principals); } } } catch (RepositoryException re) { throw new SlingException("Error listing children of resource: " + parent.getPath(), re); } return null; }
private void initTagsStructure() { Resource defaultNamespace = resourceResolver.getResource(TAGS_ROOT + "/" + TagConstants.DEFAULT_NAMESPACE); // if it's already existing, then don't proceed any further if (defaultNamespace != null) { return; } Map<String, Object> etcProperties = new HashMap<String, Object>(); etcProperties.put(JcrConstants.JCR_PRIMARYTYPE, JcrResourceConstants.NT_SLING_FOLDER); Map<String, Object> tagsProperties = new HashMap<String, Object>(); tagsProperties.put(JcrConstants.JCR_PRIMARYTYPE, JcrResourceConstants.NT_SLING_FOLDER); tagsProperties.put(JcrConstants.JCR_TITLE, "Tags"); // locale strings that are recognized languages in child tags tagsProperties.put( "languages", new String[] {"en", "de", "es", "fr", "it", "pt_br", "zh_cn", "ch_tw", "ja", "ko_kr"}); try { ResourceUtil.getOrCreateResource(resourceResolver, "/etc", etcProperties, null, true); ResourceUtil.getOrCreateResource(resourceResolver, TAGS_ROOT, tagsProperties, null, true); createTag(TagConstants.DEFAULT_NAMESPACE_ID, "Standard Tags", null); } catch (PersistenceException | InvalidTagFormatException e) { log.error("Error creating tags tree", e); } }
/** * Returns the number of children that have to be displayed in the tree. * * <p>If there are more than <code>numChildrenToCheck</code> children (including the ones that * will not be displayed) <code>numChildrenToCheck + 1</code> is returned to indicate that there * could be more children. * * @param res parent resource * @param numChildrenToCheck The max number of children to check * @return list of child resources */ private int countChildren(Resource res, int numChildrenToCheck) { int count = 0; int totalCount = 0; Iterator<Resource> iter = resolver.listChildren(res); while (iter.hasNext() && totalCount <= numChildrenToCheck) { Resource child = iter.next(); if (shouldAddChild(child)) { // skip hidden (incl. "jcr:content") and non hierarchical nodes // see IsSiteAdminPredicate for the detailed conditions try { Node n = child.adaptTo(Node.class); if (!n.isNodeType(DamConstants.NT_DAM_ASSET)) { count++; } totalCount++; } catch (RepositoryException re) { // Ignored } } } if (totalCount == numChildrenToCheck + 1) { // avoid auto expand return totalCount; } return count; }
public TrainingProductImpl(Resource resource) { super(resource); resourceResolver = resource.getResourceResolver(); pageManager = resourceResolver.adaptTo(PageManager.class); productPage = pageManager.getContainingPage(resource); }
private boolean removeNode(String path) { Resource templateResource = resourceResolver.getResource(path); if (templateResource != null) { Node nodeToDelete = templateResource.adaptTo(Node.class); if (nodeToDelete != null) { try { nodeToDelete.remove(); TemplateUtils.saveNode(nodeToDelete); session.save(); return true; } catch (VersionException ex) { java.util.logging.Logger.getLogger(TemplateManagerDeleteServlet.class.getName()) .log(Level.SEVERE, null, ex); } catch (LockException ex) { java.util.logging.Logger.getLogger(TemplateManagerDeleteServlet.class.getName()) .log(Level.SEVERE, null, ex); } catch (ConstraintViolationException ex) { java.util.logging.Logger.getLogger(TemplateManagerDeleteServlet.class.getName()) .log(Level.SEVERE, null, ex); } catch (AccessDeniedException ex) { java.util.logging.Logger.getLogger(TemplateManagerDeleteServlet.class.getName()) .log(Level.SEVERE, null, ex); } catch (RepositoryException ex) { java.util.logging.Logger.getLogger(TemplateManagerDeleteServlet.class.getName()) .log(Level.SEVERE, null, ex); } finally { session.logout(); } } } return false; }
private void copyChildren(Resource source, Resource target) throws PersistenceException { for (Resource sourceChild : source.getChildren()) { Resource targetChild = resourceResolver.create( target, sourceChild.getName(), sourceChild.adaptTo(ValueMap.class)); copyChildren(sourceChild, targetChild); } }
@Test public void testRequestTrusted() throws RepositoryException { CreateSakaiUserServlet csus = new CreateSakaiUserServlet(); JackrabbitSession session = createMock(JackrabbitSession.class); ResourceResolver rr = createMock(ResourceResolver.class); expect(rr.adaptTo(Session.class)).andReturn(session); SlingHttpServletRequest request = createMock(SlingHttpServletRequest.class); UserManager userManager = createMock(UserManager.class); User user = createMock(User.class); expect(request.getResourceResolver()).andReturn(rr).anyTimes(); expect(rr.adaptTo(Session.class)).andReturn(session).anyTimes(); expect(session.getUserManager()).andReturn(userManager); expect(session.getUserID()).andReturn("userID"); expect(userManager.getAuthorizable("userID")).andReturn(user); expect(user.isAdmin()).andReturn(false); expect(request.getParameter(":create-auth")).andReturn("typeA"); RequestTrustValidatorService requestTrustValidatorService = createMock(RequestTrustValidatorService.class); RequestTrustValidator requestTrustValidator = createMock(RequestTrustValidator.class); expect(requestTrustValidatorService.getValidator("typeA")).andReturn(requestTrustValidator); expect(requestTrustValidator.getLevel()).andReturn(RequestTrustValidator.CREATE_USER); expect(requestTrustValidator.isTrusted(request)).andReturn(true); expect(request.getParameter(SlingPostConstants.RP_NODE_NAME)).andReturn("foo"); expect(request.getParameter("pwd")).andReturn("bar"); expect(request.getParameter("pwdConfirm")).andReturn("baz"); HtmlResponse response = new HtmlResponse(); csus.requestTrustValidatorService = requestTrustValidatorService; replay(); try { csus.handleOperation(request, response, null); fail(); } catch (RepositoryException e) { assertEquals("Password value does not match the confirmation password", e.getMessage()); } verify(); }
@Before public void setup() throws Exception { stringWriter = new StringWriter(); jsonWriter = new JSONWriter(stringWriter); activityNodes = new HashMap<String, Node>(); resourceNodes = new HashMap<String, Node>(); when(request.getResourceResolver()).thenReturn(resourceResolver); when(resourceResolver.adaptTo(Session.class)).thenReturn(session); }
public LockAwareComponentManager(ResourceResolver resolver) { this.wrapped = resolver.adaptTo(ComponentManager.class); this.lockManager = new ComponentLockRepository(resolver); try { principalIds = AuthorizableUtil.getPrincipalIds(resolver); } catch (RepositoryException e) { throw new IllegalStateException(e); // TODO } }
private ResourceResolver getResolver() { if (null == resolver || !resolver.isLive()) { try { resolver = resourceResolverFactory.getAdministrativeResourceResolver(null); } catch (LoginException le) { log.debug(le.getMessage()); } } return resolver; }
@Test public void testMissingResource() throws RepositoryException { // This shouldn't really happen, but hey! SlingHttpServletRequest request = mock(SlingHttpServletRequest.class); HtmlResponse response = new HtmlResponse(); ResourceResolver resolver = mock(ResourceResolver.class); when(resolver.adaptTo(Session.class)).thenReturn(session); Resource resource = mock(Resource.class); when(resource.adaptTo(Node.class)).thenReturn(null); when(request.getResource()).thenReturn(resource); when(request.getResourceResolver()).thenReturn(resolver); when(request.getRemoteUser()).thenReturn("john"); operation.doRun(request, response, null); assertEquals(400, response.getStatusCode()); }
private void doRequest( SlingHttpServletRequest request, SlingHttpServletResponse response, RequestInfo requestInfo, JSONWriter write) throws JSONException { // Look for a matching resource in the usual way. If one is found, // the resource will also be embedded with any necessary RequestPathInfo. String requestPath = requestInfo.getUrl(); ResourceResolver resourceResolver = request.getResourceResolver(); Resource resource = resourceResolver.resolve(request, requestPath); // Wrap the request and response. RequestWrapper requestWrapper = new RequestWrapper(request, requestInfo); ResponseWrapper responseWrapper = new ResponseWrapper(response); RequestDispatcher requestDispatcher; try { // Get the response try { if (resource != null) { LOGGER.info( "Dispatching to request path='{}', resource path='{}'", requestPath, resource.getPath()); requestDispatcher = request.getRequestDispatcher(resource); } else { LOGGER.info("Dispatching to request path='{}', no resource", requestPath); requestDispatcher = request.getRequestDispatcher(requestPath); } requestDispatcher.forward(requestWrapper, responseWrapper); } catch (ResourceNotFoundException e) { responseWrapper.setStatus(HttpServletResponse.SC_NOT_FOUND); } catch (SlingException e) { responseWrapper.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } // Write the response (status, headers, body) back to the client. writeResponse(write, responseWrapper, requestInfo); } catch (ServletException e) { writeFailedRequest(write, requestInfo); } catch (IOException e) { writeFailedRequest(write, requestInfo); } }
@Before public void setUp() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); String path = "/content/geometrixx/en"; map.put("path", path); ValueMap vm = new ValueMapDecorator(map); when(resource.getValueMap()).thenReturn(vm); when(resource.getResourceResolver()).thenReturn(resolver); when(resolver.adaptTo(PageManager.class)).thenReturn(manager); when(manager.getContainingPage(path)).thenReturn(referredpage); when(referredpage.getPath()).thenReturn(path); when(resource.listChildren()).thenReturn(iter); when(iter.hasNext()).thenReturn(false); when(resolver.getResource(path)).thenReturn(res); when(res.adaptTo(Page.class)).thenReturn(referredpage); when(referredpage.getName()).thenReturn("geometrixx"); Calendar cal = GregorianCalendar.getInstance(); when(referredpage.getLastModified()).thenReturn(cal); }
/** * Returns a list of child resources * * @param res parent resource * @return list of child resources */ private List<Resource> getChildren(Resource res) { List<Resource> children = new LinkedList<Resource>(); for (Iterator<Resource> iter = resolver.listChildren(res); iter.hasNext(); ) { Resource child = iter.next(); if (shouldAddChild(child)) { children.add(child); } } return children; }
protected void handlePageModification( PageModification mod, SolrClient solr, ResourceResolver resourceResolver) { String pagePath = mod.getPath(); boolean isAllowedPath = false; for (String basePath : basePaths) isAllowedPath |= pagePath.startsWith(basePath); if (!isAllowedPath) { LOG.debug("Page event not on one of the base paths. Ignoring event."); return; } Resource pageRes = resourceResolver.getResource(pagePath); LOG.info("Handling valid page modification " + mod); switch (mod.getType()) { case CREATED: case MODIFIED: case RESTORED: addOrUpdatePage(pageRes, solr); break; case DELETED: removePage(pagePath, solr); break; case MOVED: removePage(pagePath, solr); pageRes = resourceResolver.getResource(mod.getDestination()); addOrUpdatePage(pageRes, solr); break; // need version created to help with deletion on children, since only the parent receives a // deletion event. however, // as the parent resource no longer exists to iterate through, the only way to remove the // children is to assume if a // version is created but the resource doesn't exist, this must be either the deletion of a // parent or a the source // of a move (same result either way) // hmm, still doesn't work (usually. it's asynchronous so sometimes it is deleted, sometimes // it isn't) // TODO known bug when deleting a page with child pages, child pages not removed from solr /* case VERSION_CREATED: if (pageRes == null) removePage(pagePath, solr); break;*/ } }