@Override public int performAction(Resource res) throws RepositoryException { // get value map and node ValueMap vm = res.adaptTo(ValueMap.class); Node node = res.adaptTo(Node.class); int propsModified = 0; PropertyIterator pIter = node.getProperties(); while (pIter.hasNext()) { Property prop = pIter.nextProperty(); if (isModifiable(prop)) { boolean modified = doModifications(prop); if (modified) { // increase our modification count propsModified++; } } else { // move on to next property } } return propsModified; }
/** * 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; }
@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(); }
public static void extractTranslation(final JSONWriter writer, final Resource translationResource) throws JSONException, IOException { final Iterable<Resource> translations = translationResource.getChildren(); final ValueMap props = translationResource.adaptTo(ValueMap.class); String languageLabel = (String) props.get("language"); if (null == languageLabel) { languageLabel = (String) props.get("mtlanguage"); if (null == languageLabel) { return; } } writer.key(ContentTypeDefinitions.LABEL_TRANSLATION); writer.object(); writer.key("mtlanguage"); if (languageLabel.equals("nb")) { // SPECIAL CASE FOR LEGACY EXPORTER ONLY: // the label for norwegian changed between 6.0 and 6.1 // (i.e. this section must be removed for 6.1 exporter) languageLabel = "no"; } writer.value(languageLabel); writer.key("jcr:created"); writer.value(props.get("jcr:created", Long.class)); writer.key("jcr:createdBy"); writer.value(props.get("jcr:createdBy")); if (translations.iterator().hasNext()) { writer.key(ContentTypeDefinitions.LABEL_TRANSLATIONS); final JSONWriter translationObjects = writer.object(); UGCExportHelper.extractTranslations(translationObjects, translations); writer.endObject(); } writer.endObject(); }
@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()); }
@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); } }
@Override protected void doGet(final SlingHttpServletRequest req, final SlingHttpServletResponse resp) throws ServletException, IOException { final Resource resource = req.getResource(); resp.getOutputStream().println(resource.toString()); resp.getOutputStream().println("This content is generated by the SimpleServlet"); }
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; }
/** * 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; } }
/** * Extract the value of a MultiFieldPanel property into a list of maps. Will never return a null * map, but may return an empty one. Invalid property values are logged and skipped. * * @param resource the resource * @param name the property name * @return a list of maps. */ @Function public static List<Map<String, String>> getMultiFieldPanelValues(Resource resource, String name) { ValueMap map = resource.adaptTo(ValueMap.class); List<Map<String, String>> results = new ArrayList<Map<String, String>>(); if (map.containsKey(name)) { String[] values = map.get(name, new String[0]); for (String value : values) { try { JSONObject parsed = new JSONObject(value); Map<String, String> columnMap = new HashMap<String, String>(); for (Iterator<String> iter = parsed.keys(); iter.hasNext(); ) { String key = iter.next(); String innerValue = parsed.getString(key); columnMap.put(key, innerValue); } results.add(columnMap); } catch (JSONException e) { log.error( String.format("Unable to parse JSON in %s property of %s", name, resource.getPath()), e); } } } return results; }
private Collection<Tag> collectResourceTags(Resource resource, boolean recurse) { if (resource == null) { return Collections.emptyList(); } Set<Tag> treeTags = new HashSet<Tag>(); Queue<Resource> searchResources = new LinkedList<Resource>(); searchResources.add(resource); while (!searchResources.isEmpty()) { Resource searchResource = searchResources.poll(); if (recurse) { CollectionUtils.addAll(searchResources, searchResource.listChildren()); } String[] tags = resource.getValueMap().get(TagConstants.PN_TAGS, String[].class); if (tags == null) { continue; } for (String tagStr : tags) { Tag tag = resolve(tagStr); if (tag != null) { treeTags.add(tag); } } } return treeTags; }
/** * 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; }
@Test public void testOtherParentParsysResource() { parsysResource = context.create().resource(page.getContentResource().getPath() + "/parsysOther"); par1Resource = context.create().resource(parsysResource.getPath() + "/par1"); context.request().setAttribute(RA_PARSYS_PARENT_RESOURCE, parsysResource); WCMMode.EDIT.toRequest(context.request()); Parsys parsys = context.request().adaptTo(Parsys.class); List<Item> items = parsys.getItems(); assertEquals(2, items.size()); Item item1 = items.get(0); assertEquals(par1Resource.getPath(), item1.getResourcePath()); assertNull(item1.getResourceType()); assertEquals(SECTION_DEFAULT_CLASS_NAME, item1.getCssClassName()); assertFalse(item1.isNewArea()); Item item2 = items.get(1); assertEquals(NEWAREA_RESOURCE_PATH, item2.getResourcePath()); assertEquals(FALLBACK_NEWAREA_RESOURCE_TYPE, item2.getResourceType()); assertEquals( NEWAREA_CSS_CLASS_NAME + " " + SECTION_DEFAULT_CLASS_NAME, item2.getCssClassName()); assertTrue(item2.isNewArea()); }
@Before public void setUp() { MockSlingExtensions.setUp(context); context.addModelsForPackage("io.wcm.wcm.parsys.controller"); context.request().setAttribute(ComponentContext.CONTEXT_ATTR_NAME, componentContext); when(componentContext.getComponent()).thenReturn(component); when(component.getPath()).thenReturn(RESOURCE_TYPE_SAMPLE); when(component.getProperties()).thenReturn(ImmutableValueMap.of()); page = context.create().page("/content/page1", "/apps/sample/templates/test1"); parsysResource = context.create().resource(page.getContentResource().getPath() + "/parsys"); par1Resource = context .create() .resource( parsysResource.getPath() + "/par1", ImmutableValueMap.of("sling:resourceType", COMPONENT_PATH_1)); par2Resource = context .create() .resource( parsysResource.getPath() + "/par2", ImmutableValueMap.of("sling:resourceType", COMPONENT_PATH_2)); context.currentResource(parsysResource); }
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { Resource resource = request.getResource(); Node node = resource.adaptTo(Node.class); Content content = resource.adaptTo(Content.class); if (node != null) { try { Session jcrSession = request.getResourceResolver().adaptTo(Session.class); JSONWriter write = new JSONWriter(response.getWriter()); FileUtils.writeLinkNode(node, jcrSession, write); } catch (JSONException e) { response.sendError(500, "Unable to parse JSON."); } catch (RepositoryException e) { LOGGER.warn("Unable to get file info for link."); response.sendError(500, "Unable get file info."); } } else { try { org.sakaiproject.nakamura.api.lite.Session session = resource.adaptTo(org.sakaiproject.nakamura.api.lite.Session.class); JSONWriter write = new JSONWriter(response.getWriter()); FileUtils.writeLinkNode(content, session, write); } catch (StorageClientException e) { LOGGER.warn("Unable to get file info for link."); response.sendError(500, "Unable get file info."); } catch (JSONException e) { response.sendError(500, "Unable to parse JSON."); } } }
/** * Retrieves a {@link Node} identified by the given <code>path</code>. * * @param path The path. * @param session The {@link Session}. * @return The node. */ protected Node getNode(final String path, final Session session) { final Resource res = getResourceResolver(session).getResource(path); if (res != null) { return res.adaptTo(Node.class); } return null; }
private void updateEncodingPresets(Resource configResource, S7Config s7Config, String typeHandle) throws RepositoryException { // Get the presets from S7 and store them on the node // List<Scene7PropertySet> propertySets = scene7Service.getPropertySets(typeHandle, s7Config); String path = configResource.getPath() + "/" + Scene7PresetsService.REL_PATH_ENCODING_PRESETS; Node node = prepNode(configResource.getResourceResolver(), path); Node presetNode; int i = 0; for (Scene7PropertySet propertySet : propertySets) { String handle = propertySet.getSetHandle(); String nodeName = getNodeName(handle); if (StringUtils.isNotBlank(nodeName)) { presetNode = node.addNode(nodeName); presetNode.setProperty("handle", handle); Map<String, String> properties = propertySet.getProperties(); for (String key : properties.keySet()) { String value = properties.get(key); key = StringUtils.uncapitalize(key); presetNode.setProperty(key, value); } } } }
/** {@inheritDoc} */ public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { try { Resource resource = request.getResource(); Node node = resource.adaptTo(Node.class); if (node == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Version version = versionService.saveNode(node, request.getRemoteUser()); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); ExtendedJSONWriter write = new ExtendedJSONWriter(response.getWriter()); write.object(); write.key("versionName"); write.value(version.getName()); ExtendedJSONWriter.writeNodeContentsToWriter(write, version); write.endObject(); } catch (RepositoryException e) { LOGGER.info("Failed to save version ", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); return; } catch (JSONException e) { LOGGER.info("Failed to save version ", e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage()); return; } }
@Before public void setUp() throws Exception { context.load().json("/json-import-samples/content.json", "/content/sample/en"); Resource resource = this.context.resourceResolver().getResource("/content/sample/en"); this.page = resource.adaptTo(Page.class); }
@Override public Page getPage(final String path) { Resource resource = this.resourceResolver.getResource(path); if (resource != null) { return resource.adaptTo(Page.class); } return null; }
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); } }
/** * Get the comment system for the given resource. * * @param r The resource for which to retrieve the comment system. * @param session The {@link Session}. * @return The {@link com.day.cq.collab.commons.CommentSystem}. */ protected CommentSystem getCommentSystem(final Resource r, final Session session) { final Resource res = getResourceResolver(session).resolve(r.getPath()); if (null != res) { return res.adaptTo(CommentSystem.class); } else { return null; } }
@Override public Template getTemplate(final String templatePath) { Resource resource = this.resourceResolver.getResource(templatePath); if (resource != null) { return resource.adaptTo(Template.class); } else { return null; } }
public AbstractJcrVoucher(Resource resource) throws CommerceException { this.resource = resource; page = resource.adaptTo(Page.class); if (page == null || !ResourceUtil.isA( resource.getChild("jcr:content"), AbstractJcrVoucher.VOUCHER_RESOURCE_TYPE)) { throw new CommerceException("Resource is not a JcrVoucher."); } }
/** * The promotion associated with the voucher. Promotions are used to apply some change to the * shopping cart once the voucher has been added. * * @return The voucher's promotion */ public Promotion getPromotion() { ValueMap properties = resource.adaptTo(ValueMap.class); String promoPath = properties.get("jcr:content/promotion", String.class); if (promoPath != null && promoPath.length() > 0) { Resource promoResource = resource.getResourceResolver().getResource(promoPath); return (promoResource == null) ? null : promoResource.adaptTo(Promotion.class); } else { return null; } }
/** * Given the relative path of a comment, delete the index for that comment. * * @param relPath the relative path of the comment. */ public void delete(final String relPath, final ResourceResolver resolver) throws RepositoryException { final Resource folder = resolver.getResource(path + relPath); if (folder == null) { return; } final Node folderNode = folder.adaptTo(Node.class); folderNode.remove(); }
private List<Tag> getNamespacesList() { Resource tagRoot = resourceResolver.getResource(TAGS_ROOT); List<Tag> namespaces = new ArrayList<Tag>(); for (Iterator<Resource> resources = tagRoot.listChildren(); resources.hasNext(); ) { Resource resource = resources.next(); Tag tag = resource.adaptTo(Tag.class); if (tag != null) { namespaces.add(tag); } } return namespaces; }
private void copyContent(Resource source, Resource target, boolean skipPrimaryType) throws PersistenceException { ValueMap sourceProps = source.adaptTo(ValueMap.class); ModifiableValueMap targetProps = target.adaptTo(ModifiableValueMap.class); for (Map.Entry<String, Object> entry : sourceProps.entrySet()) { if (skipPrimaryType && StringUtils.equals(entry.getKey(), JcrConstants.JCR_PRIMARYTYPE)) { continue; } targetProps.put(entry.getKey(), entry.getValue()); } copyChildren(source, target); }
private void updateViewerPresets(Resource configResource, S7Config s7Config) throws RepositoryException { // Get the presets from S7 and store them on the node // List<Scene7Asset> assets = scene7Service.searchAssets( s7Config.getBasePath(), Boolean.TRUE, Boolean.TRUE, new String[] {"ViewerPreset"}, null, new String[] { "assetArray/items/assetHandle", "assetArray/items/type", "assetArray/items/name", "assetArray/items/viewerPresetInfo" }, null, s7Config); if (assets.size() > 0) { String path = configResource.getPath() + "/" + Scene7PresetsService.REL_PATH_VIEWER_PRESETS; Node node = prepNode(configResource.getResourceResolver(), path); int i = 0; for (Scene7Asset asset : assets) { String name = asset.getName(); String type = asset.getViewerPresetType(); Node presetNode = node.addNode("preset" + i); presetNode.setProperty("name", name); presetNode.setProperty("type", (type != null ? type : "")); presetNode.setProperty("config", s7Config.getBasePath() + name); Map<String, String> viewerPresetConfigurationSettings = asset.getViewerPresetConfigurationSettings(); if (viewerPresetConfigurationSettings != null && !viewerPresetConfigurationSettings.isEmpty()) { presetNode = presetNode.addNode("settings"); for (Entry<String, String> entry : viewerPresetConfigurationSettings.entrySet()) { String settingName = entry.getKey(); String value = entry.getValue(); if (settingName != null && value != null) { presetNode.setProperty(settingName, value); } } } i++; } } }
@Override public Tag resolve(String tagID) { try { String path = getPathFromID(tagID); Resource tagResource = resourceResolver.getResource(path); if (tagResource != null) { return tagResource.adaptTo(Tag.class); } } catch (InvalidTagFormatException e) { // ignore } return null; }