org.apache.sling.api.resource.Resource Java Examples
The following examples show how to use
org.apache.sling.api.resource.Resource.
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: RelationTypesDataSourceServlet.java From aem-core-cif-components with Apache License 2.0 | 7 votes |
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { ResourceBundle resourceBundle = request.getResourceBundle(null); List<Resource> values = new ArrayList<>(); for (RelationType relationType : RelationType.values()) { ValueMap vm = new ValueMapDecorator(new HashMap<String, Object>()); vm.put("value", relationType); vm.put("text", toText(resourceBundle, relationType.getText())); values.add(new ValueMapResource(request.getResourceResolver(), new ResourceMetadata(), JcrConstants.NT_UNSTRUCTURED, vm)); } DataSource ds = new SimpleDataSource(values.iterator()); request.setAttribute(DataSource.class.getName(), ds); }
Example #2
Source File: GraphqlServletTest.java From aem-core-cif-components with Apache License 2.0 | 6 votes |
private static AemContext createContext(String contentPath) { return new AemContext( (AemContextCallback) context -> { // Load page structure context.load().json(contentPath, "/content"); context.registerService(ImplementationPicker.class, new ResourceTypeImplementationPicker()); UrlProviderImpl urlProvider = new UrlProviderImpl(); urlProvider.activate(new MockUrlProviderConfiguration()); context.registerService(UrlProvider.class, urlProvider); context.registerInjectActivateService(new SearchFilterServiceImpl()); context.registerInjectActivateService(new SearchResultsServiceImpl()); context.registerAdapter(Resource.class, ComponentsConfiguration.class, (Function<Resource, ComponentsConfiguration>) input -> MOCK_CONFIGURATION_OBJECT); }, ResourceResolverType.JCR_MOCK); }
Example #3
Source File: InjectorSpecificAnnotationTest.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 6 votes |
@Test public void testOrderForValueAnnotationField() { // make sure that that the correct injection is used // make sure that log is adapted from value map // and not coming from request attribute Logger logFromValueMap = LoggerFactory.getLogger(this.getClass()); Map<String, Object> map = new HashMap<String, Object>(); map.put("first", "first-value"); map.put("log", logFromValueMap); ValueMap vm = new ValueMapDecorator(map); Resource res = mock(Resource.class); when(res.adaptTo(ValueMap.class)).thenReturn(vm); when(request.getResource()).thenReturn(res); InjectorSpecificAnnotationModel model = factory.getAdapter(request, InjectorSpecificAnnotationModel.class); assertNotNull("Could not instanciate model", model); assertEquals("first-value", model.getFirst()); assertEquals(logFromValueMap, model.getLog()); }
Example #4
Source File: SearchFilterServiceImpl.java From aem-core-cif-components with Apache License 2.0 | 6 votes |
@Override public List<FilterAttributeMetadata> retrieveCurrentlyAvailableCommerceFilters(final Page page) { // This is used to configure the cache in the GraphqlClient with a cache name of // --> com.adobe.cq.commerce.core.search.services.SearchFilterService Resource resource = new SyntheticResource(null, (String) null, SearchFilterService.class.getName()); // First we query Magento for the required attribute and filter information MagentoGraphqlClient magentoGraphqlClient = MagentoGraphqlClient.create(resource, page); final List<__InputValue> availableFilters = fetchAvailableSearchFilters(magentoGraphqlClient); final List<Attribute> attributes = fetchAttributeMetadata(magentoGraphqlClient, availableFilters); // Then we combine this data into a useful set of data usable by other systems FilterAttributeMetadataConverter converter = new FilterAttributeMetadataConverter(attributes); return availableFilters.stream().map(converter).collect(Collectors.toList()); }
Example #5
Source File: BaseEncryptionTest.java From sling-whiteboard with Apache License 2.0 | 6 votes |
/** * Tests the decryption and handling of pre-existing values * * @throws NoSuchPaddingException * @throws NoSuchAlgorithmException * @throws InvalidKeyException */ @Test public void testPreEncryptedArrayofValues() { Resource resource = context.resourceResolver().getResource(ARRAY_PATH); ValueMap map = resource.adaptTo(ValueMap.class); EncryptableValueMap encryptionMap = resource.adaptTo(EncryptableValueMap.class); // verify original is encrypted String[] value = map.get(encryptedProperty, String[].class); assertNotEquals("foo", value[0]); assertNotEquals("dog", value[1]); // get decrypted values and validate value = (String[]) encryptionMap.get(encryptedProperty); assertArrayEquals(new String[] { "foo", "dog" }, value); // decrypt pre-encrypted properties encryptionMap.decrypt(encryptedProperty); value = (String[]) map.get(encryptedProperty); assertArrayEquals(new String[] { "foo", "dog" }, value); }
Example #6
Source File: FetcherUtil.java From sling-samples with Apache License 2.0 | 6 votes |
/** Return the "source" Resource to use, preferably the one provided * by the DataFetchingEnvironment, otherwise the supplied base Resource. */ static Resource getSourceResource(SlingDataFetcherEnvironment env) { Resource result = env.getCurrentResource(); String path = null; final Object o = env.getParentObject(); if(o instanceof Map) { final Map<?, ?> m = (Map<?,?>)o; path = String.valueOf(m.get("path")); } if(path != null) { final Resource r = result.getResourceResolver().getResource(result, path); if(r != null) { result = r; } } return result; }
Example #7
Source File: NPEfix19_nineteen_t.java From coming with MIT License | 6 votes |
private boolean isJcrData(Resource resource){ boolean jcrData = false; if (resource!= null) { ValueMap props = resource.adaptTo(ValueMap.class); if (props != null && props.containsKey(PROP_JCR_DATA) ) { jcrData = true; } else { Resource jcrContent = resource.getChild(JCR_CONTENT_LEAF); if (jcrContent!= null) { props = jcrContent.adaptTo(ValueMap.class); if (props != null && props.containsKey(PROP_JCR_DATA) ) { jcrData = true; } } } } return jcrData; }
Example #8
Source File: GraphqlServletTest.java From aem-core-cif-components with Apache License 2.0 | 6 votes |
@Test public void testProductCarouselModel() throws ServletException { Resource resource = prepareModel(PRODUCT_CAROUSEL_RESOURCE); String[] productSkuList = (String[]) resource.getValueMap().get("product"); // The HTL script uses an alias here SlingBindings slingBindings = (SlingBindings) context.request().getAttribute(SlingBindings.class.getName()); slingBindings.put("productSkuList", productSkuList); ProductCarousel productCarouselModel = context.request().adaptTo(ProductCarousel.class); Assert.assertEquals(4, productCarouselModel.getProducts().size()); Assert.assertEquals("24-MB02", productCarouselModel.getProducts().get(0).getSKU()); // We make sure that all assets in the sample JSON response point to the DAM for (ProductListItem product : productCarouselModel.getProducts()) { Assert.assertTrue(product.getImageURL().startsWith(CIF_DAM_ROOT)); } }
Example #9
Source File: ProductImplTest.java From aem-core-cif-components with Apache License 2.0 | 6 votes |
private static AemContext createContext(String contentPath) { return new AemContext( (AemContextCallback) context -> { // Load page structure context.load().json(contentPath, "/content"); UrlProviderImpl urlProvider = new UrlProviderImpl(); urlProvider.activate(new MockUrlProviderConfiguration()); context.registerService(UrlProvider.class, urlProvider); context.registerAdapter(Resource.class, ComponentsConfiguration.class, (Function<Resource, ComponentsConfiguration>) input -> !input.getPath().contains("pageB") ? MOCK_CONFIGURATION_OBJECT : ComponentsConfiguration.EMPTY); }, ResourceResolverType.JCR_MOCK); }
Example #10
Source File: GraphqlClientDataSourceServletTest.java From aem-core-cif-components with Apache License 2.0 | 6 votes |
@Test public void testDataSource() { // Stub out getGraphqlClients call List<Resource> resources = new ArrayList<Resource>(); resources.add(new GraphqlClientDataSourceServlet.GraphqlClientResource("my-name", "my-value", null)); GraphqlClientDataSourceServlet spyServlet = spy(servlet); Mockito.doReturn(resources).when(spyServlet).getGraphqlClients(any()); // Test doGet spyServlet.doGet(context.request(), context.response()); // Verify data source DataSource dataSource = (DataSource) context.request().getAttribute(DataSource.class.getName()); Assert.assertNotNull(dataSource); AtomicInteger size = new AtomicInteger(0); dataSource.iterator().forEachRemaining(resource -> { GraphqlClientDataSourceServlet.GraphqlClientResource client = (GraphqlClientDataSourceServlet.GraphqlClientResource) resource; Assert.assertEquals("my-name", client.getText()); Assert.assertEquals("my-value", client.getValue()); Assert.assertFalse(client.getSelected()); size.incrementAndGet(); }); Assert.assertEquals(1, size.get()); }
Example #11
Source File: ScriptFinderImpl.java From APM with Apache License 2.0 | 6 votes |
@Override public Script find(String scriptPath, ResourceResolver resolver) { Script result = null; if (StringUtils.isNotEmpty(scriptPath)) { Resource resource; if (isAbsolute(scriptPath)) { resource = resolver.getResource(scriptPath); } else { resource = resolver.getResource(SCRIPT_PATH + "/" + scriptPath); } if (resource != null && ScriptModel.isScript(resource)) { result = resource.adaptTo(ScriptModel.class); } } return result; }
Example #12
Source File: ResourceModelClassesTest.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 6 votes |
@Test public void testArrayPrimitivesModel() { Map<String, Object> map = new HashMap<>(); map.put("intArray", new int[] { 1, 2, 9, 8 }); map.put("secondIntArray", new Integer[] {1, 2, 9, 8}); ValueMap vm = new ValueMapDecorator(map); Resource res = mock(Resource.class); when(res.adaptTo(ValueMap.class)).thenReturn(vm); ArrayPrimitivesModel model = factory.getAdapter(res, ArrayPrimitivesModel.class); assertNotNull(model); int[] primitiveIntArray = model.getIntArray(); assertEquals(4, primitiveIntArray.length); assertEquals(2, primitiveIntArray[1]); int[] secondPrimitiveIntArray = model.getSecondIntArray(); assertEquals(4, secondPrimitiveIntArray.length); assertEquals(2, secondPrimitiveIntArray[1]); }
Example #13
Source File: DefaultHtmlServlet.java From sling-whiteboard with Apache License 2.0 | 6 votes |
@Override protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException { final Resource r = request.getResource(); final String resourceType = r.getResourceType(); final ResourceSchema m = registry.getSchema(resourceType); if(m == null) { response.sendError( HttpServletResponse.SC_BAD_REQUEST, "ResourceSchema not found for resource type " + resourceType + " at " + request.getResource().getPath()); return; } response.setCharacterEncoding("UTF-8"); response.setContentType("text/html"); renderingLogic.render(r, m, new HtmlResourceRenderer(registry, request, response.getWriter())); response.getWriter().flush(); }
Example #14
Source File: GraphqlQueryLanguageProviderTest.java From commerce-cif-connector with Apache License 2.0 | 6 votes |
@Test public void testQueryLanguageProviderDefaultPagination() throws IOException { // The search request coming from com.adobe.cq.commerce.impl.omnisearch.ProductsOmniSearchHandler is serialized in JSON String jsonRequest = getResource("commerce-products-omni-search-request3.json"); String json = getResource("magento-graphql-simple-products.json"); Type type = TypeToken.getParameterized(GraphqlResponse.class, Query.class, Error.class).getType(); GraphqlResponse<Query, Error> response = QueryDeserializer.getGson().fromJson(json, type); List<ProductInterface> products = response.getData().getProducts().getItems(); Mockito.when(graphqlDataService.searchProducts(any(), any(), any(), any(), any())).thenReturn(products); Iterator<Resource> it = queryLanguageProvider.findResources(ctx, jsonRequest, VIRTUAL_PRODUCT_QUERY_LANGUAGE); // No limit and offset in query --> so we expect page 1 and size 20 Mockito.verify(graphqlDataService).searchProducts(eq("gloves"), any(), eq(1), eq(20), any()); // The JSON response contains 3 products and the query requested 20 products assertEquals(3, Iterators.size(it)); }
Example #15
Source File: NPEfix19_nineteen_s.java From coming with MIT License | 6 votes |
private boolean isJcrData(Resource resource){ boolean jcrData = false; if (resource!= null) { ValueMap props = resource.adaptTo(ValueMap.class); if (props.containsKey(PROP_JCR_DATA) ) { jcrData = true; } else { Resource jcrContent = resource.getChild(JCR_CONTENT_LEAF); if (jcrContent!= null) { props = jcrContent.adaptTo(ValueMap.class); if (props.containsKey(PROP_JCR_DATA) ) { jcrData = true; } } } } return jcrData; }
Example #16
Source File: PageManagerImpl.java From jackalope with Apache License 2.0 | 6 votes |
@Override public void delete(Resource resource, boolean shallow, boolean autoSave) throws WCMException { if (resource == null) return; Node node = resource.adaptTo(Node.class); if (node == null) return; try { session.removeItem(node.getPath()); if (autoSave) { session.save(); } } catch (RepositoryException e) { throw new WCMException("Could not delete resource.", e); } }
Example #17
Source File: GeometrixxMediaArticleBody.java From aem-solr-search with Apache License 2.0 | 6 votes |
public GeometrixxMediaArticleBody(Resource resource) throws SlingModelsException { if (null == resource) { LOG.info("Resource is null"); throw new SlingModelsException("Resource is null"); } if (ResourceUtil.isNonExistingResource(resource)) { LOG.warn("Can't adapt non existent resource: '{}'", resource.getPath()); throw new SlingModelsException( "Can't adapt non existent resource." + resource.getPath()); } this.resource = resource; }
Example #18
Source File: GraphqlResourceProviderTest.java From commerce-cif-connector with Apache License 2.0 | 6 votes |
@Test public void testCategoryTree() throws IOException { Utils.setupHttpResponse("magento-graphql-categorylist-root.json", httpClient, HttpStatus.SC_OK, "{categoryList(filters:{ids:{eq:\"4\""); Utils.setupHttpResponse("magento-graphql-categorylist-dresses.json", httpClient, HttpStatus.SC_OK, "{categoryList(filters:{url_key:{eq:\"venia-dresses\""); Resource root = provider.getResource(resolveContext, CATALOG_ROOT_PATH, null, null); assertNotNull(root); Iterator<Resource> it = provider.listChildren(resolveContext, root); assertNotNull(it); assertTrue(it.hasNext()); while (it.hasNext()) { Resource category = it.next(); assertTrue(category.getPath().substring(CATALOG_ROOT_PATH.length() + 1).split("/").length == 1); assertNull(category.adaptTo(Product.class)); if ("venia-dresses".equals(category.getName())) { // deep read cifId String cifId = category.getValueMap().get(CIF_ID, String.class); assertEquals(cifId, category.getValueMap().get("./" + CIF_ID, String.class)); } } }
Example #19
Source File: SyntheticResourceFilter.java From sling-org-apache-sling-dynamic-include with Apache License 2.0 | 6 votes |
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request; final String resourceType = getResourceTypeFromSuffix(slingRequest); final Configuration config = configurationWhiteboard.getConfiguration(slingRequest, resourceType); if (config == null || !config.hasIncludeSelector(slingRequest) || !ResourceUtil.isSyntheticResource(slingRequest.getResource()) || (config.hasExtensionSet() && !config.hasExtension(slingRequest))) { chain.doFilter(request, response); return; } final RequestDispatcherOptions options = new RequestDispatcherOptions(); options.setForceResourceType(resourceType); String resourcePath = StringUtils.substringBefore(slingRequest.getRequestPathInfo().getResourcePath(), "."); Resource resource = slingRequest.getResourceResolver().resolve(resourcePath); final RequestDispatcher dispatcher = slingRequest.getRequestDispatcher(resource, options); dispatcher.forward(request, response); }
Example #20
Source File: ResourceModelClassesTest.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 5 votes |
@Test public void testRequiredPropertyMissingModelOptionalStrategy() { Map<String, Object> map = new HashMap<>(); map.put("first", "first-value"); ValueMap vm = spy(new ValueMapDecorator(map)); Resource res = mock(Resource.class); when(res.adaptTo(ValueMap.class)).thenReturn(vm); ResourceModelWithRequiredFieldOptionalStrategy model = factory.getAdapter(res, ResourceModelWithRequiredFieldOptionalStrategy.class); assertNull(model); verify(vm).get("optional1", String.class); verify(vm).get("required1", String.class); }
Example #21
Source File: EncryptionKeyStoreTest.java From sling-whiteboard with Apache License 2.0 | 5 votes |
@SuppressWarnings("serial") @Before public synchronized void setUp() throws GeneralSecurityException, IOException { context.load().json("/data2.json", START_PATH); JCEKSKeyProvider kp = new JCEKSKeyProvider(); kp.init(getConfig()); AesGcmEncryptionProvider encryptionProvider = new AesGcmEncryptionProvider(); injectKeyProvider(encryptionProvider, kp); encryptionProvider.init(new Configuration() { @Override public Class<? extends Annotation> annotationType() { return null; } @Override public String keyProvider_target() { return null; } @Override public String encryptionPrefix() { return "\uD83D\uDD12"; } }); context.registerService(EncryptionProvider.class, encryptionProvider); context.registerService(AdapterFactory.class, adapterFactory(encryptionProvider), new HashMap<String, Object>() { { put(AdapterFactory.ADAPTABLE_CLASSES, new String[] { Resource.class.getName() }); put(AdapterFactory.ADAPTER_CLASSES, new String[] { EncryptableValueMap.class.getName() }); } }); this.encryptedProperty = "bar"; }
Example #22
Source File: OptionalPrimitivesTest.java From sling-org-apache-sling-models-impl with Apache License 2.0 | 5 votes |
@Test public void testFieldInjectionClass() { ValueMap vm = ValueMap.EMPTY; Resource res = mock(Resource.class); when(res.adaptTo(ValueMap.class)).thenReturn(vm); org.apache.sling.models.testmodels.classes.OptionalPrimitivesModel model = factory.getAdapter(res, org.apache.sling.models.testmodels.classes.OptionalPrimitivesModel.class); assertNotNull(model); // make sure primitives are initialized with initial value assertEquals(0, model.getByteValue()); assertEquals(0, model.getShortValue()); assertEquals(0, model.getIntValue()); assertEquals(0L, model.getLongValue()); assertEquals(0.0f, model.getFloatValue(), 0.00001d); assertEquals(0.0d, model.getDoubleValue(), 0.00001d); assertEquals('\u0000', model.getCharValue()); assertEquals(false, model.getBooleanValue()); // make sure object wrapper of primitives are null assertNull(model.getByteObjectValue()); assertNull(model.getShortObjectValue()); assertNull(model.getIntObjectValue()); assertNull(model.getLongObjectValue()); assertNull(model.getFloatObjectValue()); assertNull(model.getDoubleObjectValue()); assertNull(model.getCharObjectValue()); assertNull(model.getBooleanObjectValue()); }
Example #23
Source File: ConfigurationColumnPreview.java From commerce-cif-connector with Apache License 2.0 | 5 votes |
@PostConstruct protected void initModel() { Config cfg = new Config(request.getResource()); final SlingScriptHelper sling = ((SlingBindings) request.getAttribute(SlingBindings.class.getName())).getSling(); ExpressionResolver expressionResolver = sling.getService(ExpressionResolver.class); final ExpressionHelper ex = new ExpressionHelper(expressionResolver, request); String itemResourcePath = ex.getString(cfg.get("path", String.class)); LOG.debug("Item in preview is at path {}", itemResourcePath); itemResource = request.getResourceResolver().getResource(itemResourcePath); if (itemResource == null) { return; } isFolder = itemResource.isResourceType(JcrConstants.NT_FOLDER) || itemResource.isResourceType(JcrResourceConstants.NT_SLING_FOLDER) || itemResource .isResourceType(JcrResourceConstants.NT_SLING_ORDERED_FOLDER); if (isFolder) { properties = itemResource.getValueMap(); } else { Resource jcrContent = itemResource.getChild(JcrConstants.JCR_CONTENT); properties = jcrContent != null ? jcrContent.getValueMap() : itemResource.getValueMap(); } }
Example #24
Source File: ContentResourceShouldBeNullCheckedCheck.java From AEM-Rules-for-SonarQube with Apache License 2.0 | 5 votes |
private void notSafeUseOfResourceAfterIfWithNullCheck(Resource resource) { Page page = resource.adaptTo(Page.class); Resource contentResource = page.getContentResource("test"); if (contentResource != null) { // do something } Iterable<Resource> children = contentResource.getChildren(); // Noncompliant }
Example #25
Source File: CatalogDataResourceProviderManagerImpl.java From commerce-cif-connector with Apache License 2.0 | 5 votes |
private boolean isRelevantPath(String path) { boolean isRelevant = path.startsWith(CONF_ROOT) && WATCHED_PROPERTIES.stream().anyMatch(path::endsWith); ; return isRelevant || findDataRoots(resolver).stream() .map(Resource::getPath) .anyMatch(path::startsWith); }
Example #26
Source File: NavigationDataFetcher.java From sling-samples with Apache License 2.0 | 5 votes |
/** * If r is an article, add previous/next navigation based on article filenames */ private void maybeAddPrevNext(Map<String, Object> result, Resource r) { final String propName = "filename"; if (Constants.ARTICLE_RESOURCE_SUPERTYPE.equals(r.getResourceSuperType())) { final String filename = r.adaptTo(ValueMap.class).get(propName, String.class); if (filename != null) { result.put("previous", getNextOrPreviousPath(r, propName, filename, false)); result.put("next", getNextOrPreviousPath(r, propName, filename, true)); } } }
Example #27
Source File: MessageStoreImplRepositoryTestUtil.java From sling-samples with Apache License 2.0 | 5 votes |
static void assertLayer(Resource root, List<String> types, int depth) { for (Resource child : root.getChildren()) { final ModifiableValueMap m = child.adaptTo(ModifiableValueMap.class); if (m.keySet().contains(MessageStoreImplRepositoryTest.TEST_RT_KEY)) { String type = m.get(MessageStoreImplRepositoryTest.TEST_RT_KEY, String.class); assertEquals(String.format("Expecting %s to have %s type", child.getPath(), types.get(depth)), types.get(depth), type); } if (child.getChildren().iterator().hasNext()) { assertLayer(child, types, depth+1); } } }
Example #28
Source File: RatingServiceImplTest.java From sling-samples with Apache License 2.0 | 5 votes |
@Test public void getRatingsResourcePath() { context.load().json("/slingshot.json", SlingshotConstants.APP_ROOT_PATH); RatingsServiceImpl service = new RatingsServiceImpl(); Resource resource = context.resourceResolver().getResource(SlingshotConstants.APP_ROOT_PATH+"/users/admin/hobby"); String ratingsResourcePath = service.getRatingsResourcePath(resource); assertThat(ratingsResourcePath, equalTo("/content/slingshot/users/admin/ugc/ratings/hobby")); }
Example #29
Source File: MockedResourceResolver.java From sling-samples with Apache License 2.0 | 5 votes |
public void delete(Resource resource) throws PersistenceException { if (resources.contains(resource)) { resources.remove(resource); Node node = resource.adaptTo(Node.class); try { node.remove(); } catch (RepositoryException e) { throw new PersistenceException("RepositoryException: "+e, e); } } else { throw new UnsupportedOperationException("Not implemented"); } }
Example #30
Source File: TestServlet.java From aem-ide-tooling-4-intellij with Apache License 2.0 | 5 votes |
@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 TestServlet 3"); }