Java Code Examples for org.apache.sling.api.resource.ValueMap#get()
The following examples show how to use
org.apache.sling.api.resource.ValueMap#get() .
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 |
/** * 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: BlogEdit.java From publick-sling-blog with Apache License 2.0 | 6 votes |
/** * Get the blog post properties if resource already exists otherwise * set the month and year properties to the current date. * * @param path The resource path to the blog post. */ private void getBlog(String path) { ResourceResolver resolver = resource.getResourceResolver(); Resource blog = resolver.getResource(path); if (blog != null) { ValueMap properties = blog.adaptTo(ValueMap.class); title = properties.get("title", String.class); month = properties.get("month", Long.class); year = properties.get("year", Long.class); url = properties.get("url", String.class); visible = Boolean.valueOf(properties.get("visible", false)); keywords = properties.get("keywords", String[].class); image = properties.get("image", String.class); content = properties.get("content", String.class); description = properties.get("description", String.class); url = blog.getName(); } else { /* Populate dropdowns with current date if creating new blog. */ month = ((long)Calendar.getInstance().get(Calendar.MONTH)) + 1; year = (long)Calendar.getInstance().get(Calendar.YEAR); } }
Example 3
Source File: TagQueryDataFetcher.java From sling-samples with Apache License 2.0 | 6 votes |
@Override public Object get(SlingDataFetcherEnvironment env) throws Exception { final Map<String, Object> result = new HashMap<>(); final List<Map<String, Object>> articles = new ArrayList<>(); final ValueMap vm = env.getCurrentResource().adaptTo(ValueMap.class); if (vm != null) { final String[] tags = vm.get("tags", String[].class); if (tags != null) { result.put("articles", articles); result.put("query", tags); final Iterator<Resource> it = env.getCurrentResource().getResourceResolver().findResources(jcrQuery(tags), "xpath"); // TODO should stop/paginate if too many results while (it.hasNext()) { articles.add(SlingWrappers.resourceWrapper(it.next())); } } } return result; }
Example 4
Source File: BaseEncryptionTest.java From sling-whiteboard with Apache License 2.0 | 5 votes |
/** * Tests Encodind and Decoding of an array of String values * * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException * @throws InvalidKeyException */ @Test public void testArrayofValues() { Resource resource = context.resourceResolver().getResource(ARRAY_PATH); ValueMap map = resource.adaptTo(ValueMap.class); EncryptableValueMap encrytionMap = resource.adaptTo(EncryptableValueMap.class); String property = "foo"; // get original values String[] value = encrytionMap.get(property, String[].class); assertArrayEquals(new String[] { "foo", "dog" }, value); // encrypt property and verifies it looks good encrytionMap.encrypt(property); value = encrytionMap.get(property, String[].class); assertArrayEquals(new String[] { "foo", "dog" }, value); // verify underlying map is encrypted value = map.get(property, String[].class); assertNotEquals("foo", value[0]); assertNotEquals("dog", value[1]); // decrypt the property and validate encrytionMap.decrypt(property); value = encrytionMap.get(property, String[].class); assertArrayEquals(new String[] { "foo", "dog" }, value); // verify underlying map is decrypted value = map.get(property, String[].class); assertArrayEquals(new String[] { "foo", "dog" }, value); }
Example 5
Source File: BlogPagination.java From publick-sling-blog with Apache License 2.0 | 5 votes |
/** * Initialize the Sightly component. * * Get services and properties. The entry point to the component. */ @Override public void activate() { resource = getResource(); request = getRequest(); scriptHelper = getSlingScriptHelper(); blogService = scriptHelper.getService(BlogService.class); ValueMap properties = resource.adaptTo(ValueMap.class); pageSize = properties.get(PAGE_SIZE_PROPERTY, Integer.class); currentPage = getCurrentIndex(); totalPages = getTotalPageCount(); }
Example 6
Source File: Recaptcha.java From publick-sling-blog with Apache License 2.0 | 5 votes |
/** * Initialization of the component. * * Reads the resource, gets the properties and site key. * * Options for "theme" are: * <ul> * <li>dark * <li>light (default) * </ul> * * Options for "type" are: * <ul> * <li>audio * <li>image (default) * </ul> * * Options for "size" are: * <ul> * <li>compact * <li>normal (default) * </ul> */ @Override public void activate() { SlingScriptHelper scriptHelper = getSlingScriptHelper(); RecaptchaService recaptchaService = scriptHelper.getService(RecaptchaService.class); if (recaptchaService == null) { show = false; } else { resource = getResource(); ValueMap properties = resource.adaptTo(ValueMap.class); String sizeProperty = properties.get(SIZE_PROPERTY, String.class); String themeProperty = properties.get(THEME_PROPERTY, String.class); String typeProperty = properties.get(TYPE_PROPERTY, String.class); boolean enableProperty = properties.get(ENABLE_PROPERTY, true); boolean enableService = recaptchaService.getEnabled(); siteKey = recaptchaService.getSiteKey(); if (enableService && enableProperty && StringUtils.isNotBlank(siteKey)) { show = true; if (THEME_DARK.equals(themeProperty)) { theme = themeProperty; } if (TYPE_AUDIO.equals(typeProperty)) { type = typeProperty; } if (SIZE_COMPACT.equals(sizeProperty)) { size = sizeProperty; } } else { show = false; } } }
Example 7
Source File: SubjectLettersEntropy.java From sling-samples with Apache License 2.0 | 5 votes |
private void countLetters(Resource r) { messages++; ValueMap properties = r.adaptTo(ValueMap.class); String subj = properties.get("Subject", (String) null); for (int i = 0; i < Math.min(subj.length(), SAMPLE_LENGTH); i++) { Character c = Character.toLowerCase(subj.charAt(i)); if (c.toString().matches("[a-z]")) { count[i][c-'a']++; } } }
Example 8
Source File: BlogView.java From publick-sling-blog with Apache License 2.0 | 5 votes |
/** * Get the blog post properties from the resource. * * @param blog The blog post resource. */ private void getBlog(Resource blog) { if (blog != null) { ValueMap properties = blog.adaptTo(ValueMap.class); title = properties.get("title", String.class); month = properties.get("month", Long.class); year = properties.get("year", Long.class); url = properties.get("url", String.class); visible = Boolean.valueOf(properties.get("visible", false)); keywords = properties.get("keywords", String[].class); content = properties.get("content", String.class); description = properties.get("description", String.class); image = properties.get("image", String.class); if (image != null) { image = resolver.map(image); } Date date = properties.get(JcrConstants.JCR_CREATED, Date.class); publishedDate = getDate(date, PUBLISHED_DATE_FORMAT); displayDate = getDate(date, DISPLAY_DATE_FORMAT); imageRelativePath = image; imageAbsolutePath = getAbsolutePath(image); } }
Example 9
Source File: UnauthenticatedRemoteResourceProviderTest.java From sling-whiteboard with Apache License 2.0 | 5 votes |
@Test void testResourceReadingFromMetaFile() { Resource hey = resourceProvider.getResource(resolveContext, "/content/test-1/hey", resourceContext, null); assertNotNull(hey, "Expected to find /content/test-1/hey"); assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, hey.getResourceType(), "Expected that /content/test-1/hey's resource type is " + ServletResolverConstants.DEFAULT_RESOURCE_TYPE); ValueMap heyProperties = hey.getValueMap(); assertEquals(1, heyProperties.size()); assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, heyProperties.get(ResourceResolver.PROPERTY_RESOURCE_TYPE, String.class)); assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, hey.getResourceType(), "Expected that /content/test-1/hey's resource type is " + ServletResolverConstants.DEFAULT_RESOURCE_TYPE); Resource joe = resourceProvider.getResource(resolveContext, "/content/test-1/hey/joe", resourceContext, null); assertNotNull(joe, "Expected to find /content/test-1/hey/joe"); assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, joe.getResourceType(), "Expected that /content/test-1/hey/joe's resource type is " + ServletResolverConstants.DEFAULT_RESOURCE_TYPE); ValueMap joeProperties = joe.getValueMap(); assertEquals(2, joeProperties.size()); assertEquals(ServletResolverConstants.DEFAULT_RESOURCE_TYPE, joeProperties.get(ResourceResolver.PROPERTY_RESOURCE_TYPE, String.class)); Calendar lastModified = joeProperties.get("lastModifiedDate", Calendar.class); assertNotNull(lastModified, String.format("Expected a lastModifiedDate property on %s", joe.getPath())); assertEquals(1407421980000L, lastModified.getTimeInMillis()); assertTrue(wrapsSameResource(joe, getChild(hey, "joe")), "Expected to get a cached representation of /content/test-1/hey/joe"); Iterator<Resource> joeChildren = resourceProvider.listChildren(resolveContext, joe); assertNull(joeChildren, String.format("Did not expect children resources for %s", joe.getPath())); }
Example 10
Source File: BaseEncryptionTest.java From sling-whiteboard with Apache License 2.0 | 5 votes |
/** * Tests encryption and decryption of a String value * */ @Test public void testUnencryptedString() { Resource resource = context.resourceResolver().getResource(START_PATH); ValueMap map = resource.adaptTo(ValueMap.class); EncryptableValueMap encrytionMap = resource.adaptTo(EncryptableValueMap.class); String property = "jcr:primaryType"; // get original value String value = encrytionMap.get(property, String.class); assertEquals("app:Page", value); // encrypt property and validate property appears to be the same encrytionMap.encrypt(property); value = encrytionMap.get(property, String.class); assertEquals("app:Page", value); // validate the underlying value is encrypted value = map.get(property, "fail"); assertNotEquals("app:Page", value); assertNotEquals("fail", value); // decrypt property and validate the underlying map is back to normal encrytionMap.decrypt(property); value = map.get(property, String.class); assertEquals("app:Page", value); }
Example 11
Source File: RemoteScriptExecutionActionReceiver.java From APM with Apache License 2.0 | 4 votes |
private InstanceDetails getInstanceDetails(ValueMap valueMap) { InstanceDetails.InstanceType instanceType = InstanceDetails.InstanceType .fromString(valueMap.get(HistoryEntryImpl.INSTANCE_TYPE, String.class)); return new InstanceDetails(valueMap.get(HistoryEntryImpl.INSTANCE_HOSTNAME, String.class), instanceType); }
Example 12
Source File: ResourcePathInjector.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 4 votes |
@Override public Object getValue(@NotNull Object adaptable, String name, @NotNull Type declaredType, @NotNull AnnotatedElement element, @NotNull DisposalCallbackRegistry callbackRegistry) { String[] resourcePaths = null; Path pathAnnotation = element.getAnnotation(Path.class); ResourcePath resourcePathAnnotation = element.getAnnotation(ResourcePath.class); if (pathAnnotation != null) { resourcePaths = getPathsFromAnnotation(pathAnnotation); } else if (resourcePathAnnotation != null) { resourcePaths = getPathsFromAnnotation(resourcePathAnnotation); } if (ArrayUtils.isEmpty(resourcePaths) && name != null) { // try the valuemap ValueMap map = getValueMap(adaptable); if (map != null) { resourcePaths = map.get(name, String[].class); } } if (ArrayUtils.isEmpty(resourcePaths)) { // could not find a path to inject return null; } ResourceResolver resolver = getResourceResolver(adaptable); if (resolver == null) { return null; } List<Resource> resources = getResources(resolver, resourcePaths, name); if (resources == null || resources.isEmpty()) { return null; } // unwrap/wrap if necessary if (isDeclaredTypeCollection(declaredType)) { return resources; } if (declaredType instanceof Class<?> && ((Class<?>)declaredType).isArray()){ return resources.toArray(new Resource[0]); } if (resources.size() == 1) { return resources.get(0); } else { // multiple resources to inject, but field is not a list LOG.warn("Cannot inject multiple resources into field {} since it is not declared as a list", name); return null; } }
Example 13
Source File: ValueMapInjector.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 4 votes |
@Override public Object getValue(@NotNull Object adaptable, String name, @NotNull Type type, @NotNull AnnotatedElement element, @NotNull DisposalCallbackRegistry callbackRegistry) { if (adaptable == ObjectUtils.NULL) { return null; } ValueMap map = getValueMap(adaptable); if (map == null) { return null; } else if (type instanceof Class<?>) { Class<?> clazz = (Class<?>) type; try { return map.get(name, clazz); } catch (ClassCastException e) { // handle case of primitive/wrapper arrays if (clazz.isArray()) { Class<?> componentType = clazz.getComponentType(); if (componentType.isPrimitive()) { Class<?> wrapper = ClassUtils.primitiveToWrapper(componentType); if (wrapper != componentType) { Object wrapperArray = map.get(name, Array.newInstance(wrapper, 0).getClass()); if (wrapperArray != null) { return unwrapArray(wrapperArray, componentType); } } } else { Class<?> primitiveType = ClassUtils.wrapperToPrimitive(componentType); if (primitiveType != componentType) { Object primitiveArray = map.get(name, Array.newInstance(primitiveType, 0).getClass()); if (primitiveArray != null) { return wrapArray(primitiveArray, componentType); } } } } return null; } } else if (type instanceof ParameterizedType) { // list support ParameterizedType pType = (ParameterizedType) type; if (pType.getActualTypeArguments().length != 1) { return null; } Class<?> collectionType = (Class<?>) pType.getRawType(); if (!(collectionType.equals(Collection.class) || collectionType.equals(List.class))) { return null; } Class<?> itemType = (Class<?>) pType.getActualTypeArguments()[0]; Object array = map.get(name, Array.newInstance(itemType, 0).getClass()); if (array == null) { return null; } return Arrays.asList((Object[]) array); } else { log.debug("ValueMapInjector doesn't support non-class types {}", type); return null; } }
Example 14
Source File: PageImpl.java From jackalope with Apache License 2.0 | 4 votes |
@Override public Calendar getOffTime() { ValueMap properties = getProperties(); return properties != null ? properties.get("offTime", Calendar.class) : null; }
Example 15
Source File: RemoteScriptExecutionActionReceiver.java From APM with Apache License 2.0 | 4 votes |
private Calendar getCalendar(ValueMap valueMap) { return valueMap.get(HistoryEntryImpl.EXECUTION_TIME, Calendar.class); }
Example 16
Source File: PageImpl.java From jackalope with Apache License 2.0 | 4 votes |
@Override public Calendar getLastModified() { ValueMap properties = getProperties(); Calendar lastModified = properties.get("cq:lastModified", Calendar.class); return lastModified != null ? lastModified : properties.get("jcr:lastModified", Calendar.class); }
Example 17
Source File: ModelPersistTest.java From sling-whiteboard with Apache License 2.0 | 4 votes |
@Test public void testMappedNames() throws RepositoryException, PersistenceException, IllegalArgumentException, IllegalAccessException, JsonProcessingException { // Create test beans BeanWithMappedNames.ChildBean child1 = new BeanWithMappedNames.ChildBean(); BeanWithMappedNames.ChildBean child2 = new BeanWithMappedNames.ChildBean(); BeanWithMappedNames.ChildBean child3 = new BeanWithMappedNames.ChildBean(); child1.setName("child-1"); child2.setName("child-2"); child3.setName("child-3"); BeanWithMappedNames bean = new BeanWithMappedNames(); bean.setWrong1("Name"); bean.setWrong2(new String[]{"foo", "bar", "baz"}); bean.setWrong3(child1); bean.setWrong4(Arrays.asList(child1, child2, child3)); bean.setWrong5(new HashMap<String, BeanWithMappedNames.ChildBean>() { { put("child1", child1); put("child2", child2); put("child3", child3); } }); bean.setWrong6(Boolean.TRUE); // Persist values jcrPersist.persist("/test/mapped", bean, rr); // Check that everything stored correctly Resource res = rr.getResource("/test/mapped"); ValueMap properties = res.getValueMap(); // Part 1: Simple property assertEquals("Name", properties.get("prop-1", String.class)); assertNull(properties.get("wrong1")); // Part 2: Array property String[] prop2 = properties.get("prop-2", String[].class); assertArrayEquals(prop2, new String[]{"foo", "bar", "baz"}); assertNull(properties.get("wrong2")); // Part 3: Object property assertNull(rr.getResource("/test/mapped/wrong3")); Resource childRes1 = rr.getResource("/test/mapped/child-1"); assertNotNull(childRes1); assertEquals("child-1", childRes1.getValueMap().get("name")); // Part 4: Object list property assertNull(rr.getResource("/test/mapped/wrong4")); Resource childRes2 = rr.getResource("/test/mapped/child-2"); assertNotNull(childRes2); assertEquals(StreamSupport .stream(childRes2.getChildren().spliterator(), false) .count(), 3L); // Part 5: Map-of-objects property assertNull(rr.getResource("/test/mapped/wrong5")); Resource childRes3 = rr.getResource("/test/mapped/child-3"); assertNotNull(childRes3); assertEquals(StreamSupport .stream(childRes3.getChildren().spliterator(), false) .count(), 3L); // Part 6: Boolean property assertNull(properties.get("wrong6")); assertNull(properties.get("isWrong6")); assertTrue(properties.get("prop-3", Boolean.class)); // Now confirm Jackson respects its mappings too ObjectMapper mapper = new ObjectMapper(); String json = mapper.writeValueAsString(bean); assertFalse("Should not have wrong property names: " + json, json.contains("wrong")); assertTrue("Should have prop-1" + json, json.contains("prop-1")); assertTrue("Should have prop-2" + json, json.contains("prop-2")); assertTrue("Should have prop-3" + json, json.contains("prop-3")); assertTrue("Should have child-1" + json, json.contains("child-1")); assertTrue("Should have child-2" + json, json.contains("child-2")); assertTrue("Should have child-3" + json, json.contains("child-3")); }
Example 18
Source File: Initializer.java From commerce-cif-connector with Apache License 2.0 | 4 votes |
@Override public void activate() { final ValueMap properties = getProperties(); final I18n i18n = new I18n(getRequest()); final ExpressionHelper ex = new ExpressionHelper(getSlingScriptHelper().getService(ExpressionResolver.class), getRequest()); final CommerceBasePathsService cbps = getSlingScriptHelper().getService(CommerceBasePathsService.class); // configure default properties for cifcategoryfield String defaultRootPath = new CatalogSearchSupport(getResourceResolver()).findCatalogPathForPicker(getRequest()); if (StringUtils.isBlank(defaultRootPath)) { defaultRootPath = cbps.getProductsBasePath(); } final String rootPath = ex.getString(properties.get("rootPath", defaultRootPath)); final String filter = properties.get("filter", "folderOrCategory"); final boolean multiple = properties.get("multiple", DEFAULT_SELECTION_MULTIPLE); final String selectionId = properties.get("selectionId", DEFAULT_SELECTION_TYPE); final String defaultEmptyText = "path".equals(selectionId) ? "Category path" : "Category ID"; final String emptyText = i18n.getVar(properties.get("emptyText", i18n.get(defaultEmptyText))); final String selectionCount = multiple ? "multiple" : "single"; String pickerSrc = DEFAULT_PICKER_SRC + "?root=" + Text.escape(rootPath) + "&filter=" + Text.escape(filter) + "&selectionCount=" + selectionCount + "&selectionId=" + Text.escape(selectionId); pickerSrc = properties.get("pickerSrc", pickerSrc); // suggestions disabled ValueMapResourceWrapper wrapper = new ValueMapResourceWrapper(getResource(), FIELD_SUPER_TYPE); ValueMap wrapperProperties = wrapper.adaptTo(ValueMap.class); wrapperProperties.putAll(properties); wrapperProperties.put("rootPath", rootPath); wrapperProperties.put("filter", filter); wrapperProperties.put("multiple", multiple); wrapperProperties.put("pickerSrc", pickerSrc); // needed to disable the default suggestions of pathfield wrapperProperties.put("suggestionSrc", ""); wrapperProperties.put("emptyText", emptyText); wrapperProperties.put("forceselection", true); getSlingScriptHelper().include(wrapper); }
Example 19
Source File: Button.java From publick-sling-blog with Apache License 2.0 | 4 votes |
/** * Initialization of the component. * * Reads the resource, gets the properties and creates the CSS * for the component. * * Options for "size" are: * <ul> * <li>large * <li>default * <li>small * <li>extraSmall * </ul> * * Options for "style" are: * <ul> * <li>default * <li>primary * <li>success * <li>info * <li>warning * <li>danger * <li>link * </ul> * * Options for "block" are true/false. */ @Override public void activate() { ValueMap properties = getProperties(); String size = properties.get("size", String.class); String style = properties.get("style", String.class); boolean block = properties.get("block", Boolean.class); StringBuilder css = new StringBuilder("btn"); if (size != null) { if (size.equals("large")) { css.append(" btn-lg"); } else if (size.equals("small")) { css.append(" btn-sm"); } else if (size.equals("extraSmall")) { css.append(" btn-xs"); } } if (block) { css.append(" btn-block"); } if (style != null) { if (style.equals("primary")) { css.append(" btn-primary"); } else if (style.equals("success")) { css.append(" btn-success"); } else if (style.equals("info")) { css.append(" btn-info"); } else if (style.equals("warning")) { css.append(" btn-warning"); } else if (style.equals("link")) { css.append(" btn-lnk"); } else { css.append(" btn-default"); } } cssClass = css.toString(); }
Example 20
Source File: PageImpl.java From jackalope with Apache License 2.0 | 4 votes |
@Override public boolean isHideInNav() { ValueMap props = getProperties(); return props.containsKey("hideInNav") ? props.get("hideInNav", Boolean.class) : false; }