org.apache.sling.api.scripting.SlingScriptHelper Java Examples

The following examples show how to use org.apache.sling.api.scripting.SlingScriptHelper. 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: InjectorSpecificAnnotationModel.java    From sling-org-apache-sling-models-impl with Apache License 2.0 6 votes vote down vote up
@Inject
public InjectorSpecificAnnotationModel(
        @ValueMapValue(name = "first", optional = true) String first,
        @ValueMapValue(name = "second", optional = true) String secondWithOtherName,
        @ValueMapValue(name = "log", optional = true) Logger log,
        @ScriptVariable(optional = true, name = "sling") SlingScriptHelper helper,
        @RequestAttribute(optional = true, name = "attribute") Object requestAttribute,
        @OSGiService(optional = true) Logger service,
        @ChildResource(optional = true, name = "child1") Resource childResource
) {
    this.first = first;
    this.secondWithOtherName = secondWithOtherName;
    this.log = log;
    this.helper = helper;
    this.requestAttribute = requestAttribute;
    this.service = service;
    this.childResource = childResource;
}
 
Example #2
Source File: ExportServlet.java    From sling-org-apache-sling-models-impl with Apache License 2.0 6 votes vote down vote up
private void addScriptBindings(SlingScriptHelper scriptHelper, SlingHttpServletRequest request, SlingHttpServletResponse response)
        throws IOException {
    SimpleBindings bindings = new SimpleBindings();
    bindings.put(SLING, scriptHelper);
    bindings.put(RESOURCE, request.getResource());
    bindings.put(SlingModelsScriptEngineFactory.RESOLVER, request.getResource().getResourceResolver());
    bindings.put(REQUEST, request);
    bindings.put(RESPONSE, response);
    try {
        bindings.put(READER, request.getReader());
    } catch (Exception e) {
        bindings.put(READER, new BufferedReader(new StringReader("")));
    }
    bindings.put(OUT, response.getWriter());
    bindings.put(LOG, logger);

    scriptEngineFactory.invokeBindingsValuesProviders(bindingsValuesProvidersByContext, bindings);

    SlingBindings slingBindings = new SlingBindings();
    slingBindings.putAll(bindings);

    request.setAttribute(SlingBindings.class.getName(), slingBindings);

}
 
Example #3
Source File: IsProductListPageServlet.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
    final Config cfg = new Config(request.getResource());
    final SlingScriptHelper sling = ((SlingBindings) request.getAttribute(SlingBindings.class.getName())).getSling();
    final ExpressionHelper ex = new ExpressionHelper(sling.getService(ExpressionResolver.class), request);
    final String path = ex.getString(cfg.get("path", String.class));
    boolean decision = isProductListPage(path, request.getResourceResolver());
    request.setAttribute(RenderCondition.class.getName(), new SimpleRenderCondition(decision));
    if (decision) {
        prepareCatalogPathProperty(path, request);
    }
}
 
Example #4
Source File: BlogView.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * Sightly component initialization.
 */
@Override
public void activate() {
    resource = getResource();
    request = getRequest();
    resolver = getResourceResolver();
    listView = Arrays.asList(request.getRequestPathInfo().getSelectors()).contains(LIST_VIEW_SELECTOR);

    SlingScriptHelper scriptHelper = getSlingScriptHelper();
    linkRewriter = scriptHelper.getService(LinkRewriterService.class);

    getBlog(resource);
}
 
Example #5
Source File: Recaptcha.java    From publick-sling-blog with Apache License 2.0 5 votes vote down vote up
/**
 * 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 #6
Source File: InjectorSpecificAnnotationTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
@Test
public void testScriptVariableConstructor() throws InvalidSyntaxException {
    SlingBindings bindings = new SlingBindings();
    SlingScriptHelper helper = mock(SlingScriptHelper.class);
    bindings.setSling(helper);
    when(request.getAttribute(SlingBindings.class.getName())).thenReturn(bindings);

    org.apache.sling.models.testmodels.classes.constructorinjection.InjectorSpecificAnnotationModel model
            = factory.getAdapter(request, org.apache.sling.models.testmodels.classes.constructorinjection.InjectorSpecificAnnotationModel.class);
    assertNotNull("Could not instanciate model", model);
    assertEquals(helper, model.getHelper());
}
 
Example #7
Source File: InjectorSpecificAnnotationTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
@Test
public void testScriptVariableField() throws InvalidSyntaxException {
    SlingBindings bindings = new SlingBindings();
    SlingScriptHelper helper = mock(SlingScriptHelper.class);
    bindings.setSling(helper);
    when(request.getAttribute(SlingBindings.class.getName())).thenReturn(bindings);

    InjectorSpecificAnnotationModel model = factory.getAdapter(request, InjectorSpecificAnnotationModel.class);
    assertNotNull("Could not instanciate model", model);
    assertEquals(helper, model.getHelper());
}
 
Example #8
Source File: SlingObjectInjector.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
private SlingHttpServletResponse getSlingHttpServletResponse(final SlingHttpServletRequest request) {
    SlingScriptHelper scriptHelper = getSlingScriptHelper(request);
    if (scriptHelper != null) {
        return scriptHelper.getResponse();
    }
    return null;
}
 
Example #9
Source File: SlingObjectInjector.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
private SlingScriptHelper getSlingScriptHelper(final SlingHttpServletRequest request) {
    SlingBindings bindings = (SlingBindings) request.getAttribute(SlingBindings.class.getName());
    if (bindings != null) {
        return bindings.getSling();
    }
    return null;
}
 
Example #10
Source File: IsProductDetailPageServletTest.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
    servlet = new IsProductDetailPageServlet();
    request = mock(SlingHttpServletRequest.class);
    response = mock(SlingHttpServletResponse.class);

    SlingBindings slingBindings = mock(SlingBindings.class);
    Map<String, Object> requestAttributes = new HashMap<>();
    doAnswer(invocation -> requestAttributes.put((String) invocation.getArguments()[0], invocation.getArguments()[1])).when(request)
        .setAttribute(anyString(), anyObject());
    when(request.getAttribute(anyString())).thenAnswer(invocationOnMock -> requestAttributes.get(invocationOnMock.getArguments()[0]));
    requestAttributes.put(SlingBindings.class.getName(), slingBindings);
    SlingScriptHelper slingScriptHelper = mock(SlingScriptHelper.class);
    when(slingBindings.getSling()).thenReturn(slingScriptHelper);
    ExpressionResolver expressionResolver = mock(ExpressionResolver.class);
    when(slingScriptHelper.getService(ExpressionResolver.class)).thenReturn(expressionResolver);

    Resource resource = mock(Resource.class);
    when(request.getResource()).thenReturn(resource);
    resourceProperties = new ModifiableMappedValueMapDecorator(new HashMap<>());
    when(resource.getValueMap()).thenReturn(resourceProperties);
    ResourceResolver resourceResolver = spy(context.resourceResolver());
    when(request.getResourceResolver()).thenReturn(resourceResolver);
    CommerceBasePathsService pathsService = mock(CommerceBasePathsService.class);
    when(pathsService.getProductsBasePath()).thenReturn(DEFAULT_CATALOGPATH);
    when(resourceResolver.adaptTo(CommerceBasePathsService.class)).thenReturn(pathsService);

    when(expressionResolver.resolve(anyString(), (Locale) anyObject(), (Class<? extends Object>) anyObject(),
        (SlingHttpServletRequest) anyObject())).thenAnswer((Answer<Object>) invocation -> long.class.equals(invocation
            .getArguments()[2]) ? Long.valueOf((String) invocation.getArguments()[0]) : invocation.getArguments()[0]);

    when(resource.getPath()).thenAnswer(invocationOnMock -> resourceProperties.get("path"));
}
 
Example #11
Source File: IsProductDetailPageServlet.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
    final Config cfg = new Config(request.getResource());
    final SlingScriptHelper sling = ((SlingBindings) request.getAttribute(SlingBindings.class.getName())).getSling();
    final ExpressionHelper ex = new ExpressionHelper(sling.getService(ExpressionResolver.class), request);
    final String path = ex.getString(cfg.get("path", String.class));
    boolean decision = isProductDetailPage(path, request.getResourceResolver());
    request.setAttribute(RenderCondition.class.getName(), new SimpleRenderCondition(decision));
    if (decision) {
        prepareCatalogPathProperty(path, request);
    }
}
 
Example #12
Source File: ConfigurationColumnPreview.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@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 #13
Source File: SearchDataSourceServlet.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws IOException {
    final String PARAMETER_OFFSET = "_commerce_offset";
    final String PARAMETER_LIMIT = "_commerce_limit";
    final String PARAMETER_COMMERCE_TYPE = "_commerce_commerce_type";
    final Config cfg = new Config(request.getResource().getChild(Config.DATASOURCE));
    final SlingScriptHelper sling = ((SlingBindings) request.getAttribute(SlingBindings.class.getName())).getSling();
    final ExpressionHelper ex = new ExpressionHelper(sling.getService(ExpressionResolver.class), request);
    final String itemRT = cfg.get("itemResourceType", String.class);
    final long offset = ex.get(cfg.get("offset", "0"), long.class);
    final long limit = ex.get(cfg.get("limit", "20"), long.class);
    final String commerceType = ex.get(cfg.get("commerceType", "product"), String.class);

    Map<String, Object> queryParameters = new HashMap<>(request.getParameterMap());
    queryParameters.put(PARAMETER_OFFSET, String.valueOf(offset));
    queryParameters.put(PARAMETER_LIMIT, String.valueOf(limit));
    queryParameters.put(PARAMETER_COMMERCE_TYPE, commerceType);

    final String rootPath = request.getParameter("root");

    String rootCategoryId = new CatalogSearchSupport(request.getResourceResolver()).findCategoryId(rootPath);
    if (rootCategoryId != null) {
        queryParameters.put(CATEGORY_ID_PARAMETER, rootCategoryId);
        queryParameters.put(CATEGORY_PATH_PARAMETER, rootPath);
    }
    String queryString = new ObjectMapper().writeValueAsString(queryParameters);
    try {
        Iterator<Resource> virtualResults = request.getResourceResolver().findResources(queryString, VIRTUAL_PRODUCT_QUERY_LANGUAGE);

        final DataSource ds = new SimpleDataSource(new TransformIterator<>(virtualResults, r -> new ResourceWrapper(r) {
            public String getResourceType() {
                return itemRT;
            }
        }));

        request.setAttribute(DataSource.class.getName(), ds);
    } catch (Exception x) {
        response.sendError(500, x.getMessage());
        LOGGER.error("Error finding resources", x);
    }
}
 
Example #14
Source File: IsProductListPageServletTest.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
    servlet = new IsProductListPageServlet();
    request = mock(SlingHttpServletRequest.class);
    response = mock(SlingHttpServletResponse.class);

    SlingBindings slingBindings = mock(SlingBindings.class);
    Map<String, Object> requestAttributes = new HashMap<>();
    doAnswer(invocation -> requestAttributes.put((String) invocation.getArguments()[0], invocation.getArguments()[1])).when(request)
        .setAttribute(anyString(), anyObject());
    when(request.getAttribute(anyString())).thenAnswer(invocationOnMock -> requestAttributes.get(invocationOnMock.getArguments()[0]));
    requestAttributes.put(SlingBindings.class.getName(), slingBindings);
    SlingScriptHelper slingScriptHelper = mock(SlingScriptHelper.class);
    when(slingBindings.getSling()).thenReturn(slingScriptHelper);
    ExpressionResolver expressionResolver = mock(ExpressionResolver.class);
    when(slingScriptHelper.getService(ExpressionResolver.class)).thenReturn(expressionResolver);

    Resource resource = mock(Resource.class);
    when(request.getResource()).thenReturn(resource);
    resourceProperties = new ModifiableMappedValueMapDecorator(new HashMap<>());
    when(resource.getValueMap()).thenReturn(resourceProperties);
    ResourceResolver resourceResolver = spy(context.resourceResolver());
    when(request.getResourceResolver()).thenReturn(resourceResolver);
    CommerceBasePathsService pathsService = mock(CommerceBasePathsService.class);
    when(pathsService.getProductsBasePath()).thenReturn("/var/commerce/products");
    when(resourceResolver.adaptTo(CommerceBasePathsService.class)).thenReturn(pathsService);

    when(expressionResolver.resolve(anyString(), (Locale) anyObject(), (Class<? extends Object>) anyObject(),
        (SlingHttpServletRequest) anyObject())).thenAnswer((Answer<Object>) invocation -> long.class.equals(invocation
            .getArguments()[2]) ? Long.valueOf((String) invocation.getArguments()[0]) : invocation.getArguments()[0]);

    when(resource.getPath()).thenAnswer(invocationOnMock -> resourceProperties.get("path"));
}
 
Example #15
Source File: ChildrenDataSourceServletTest.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@Before
public void before() {
    servlet = new ChildrenDataSourceServlet();
    request = mock(SlingHttpServletRequest.class);
    response = mock(SlingHttpServletResponse.class);
    SlingBindings slingBindings = mock(SlingBindings.class);
    SlingScriptHelper slingScriptHelper = mock(SlingScriptHelper.class);
    Resource resource = mock(Resource.class);
    Resource dataSourceResource = mock(Resource.class);
    dataSourceProperties = new ModifiableMappedValueMapDecorator(new HashMap<>());
    ResourceResolver resourceResolver = mock(ResourceResolver.class);
    CommerceBasePathsService commerceBasePathsService = mock(CommerceBasePathsService.class);
    ExpressionResolver expressionResolver = mock(ExpressionResolver.class);
    Resource parentResource = mockFolderResource("path");
    children = new ArrayList<>();

    when(resourceResolver.getResource(TEST_PATH)).thenReturn(parentResource);
    when(slingBindings.getSling()).thenReturn(slingScriptHelper);
    when(request.getResource()).thenReturn(resource);
    when(resource.getChild(Config.DATASOURCE)).thenReturn(dataSourceResource);
    when(dataSourceResource.getValueMap()).thenReturn(dataSourceProperties);
    when(request.getResourceResolver()).thenReturn(resourceResolver);
    when(slingScriptHelper.getService(ExpressionResolver.class)).thenReturn(expressionResolver);
    when(slingScriptHelper.getService(CommerceBasePathsService.class)).thenReturn(commerceBasePathsService);
    when(expressionResolver.resolve(anyString(), (Locale) anyObject(), (Class<? extends Object>) anyObject(),
        (SlingHttpServletRequest) anyObject())).thenAnswer((Answer<Object>) invocation -> invocation.getArguments()[0]);
    Map<String, Object> requestAttributes = new HashMap<>();
    requestAttributes.put(SlingBindings.class.getName(), slingBindings);
    doAnswer(invocation -> requestAttributes.put((String) invocation.getArguments()[0], invocation.getArguments()[1])).when(request)
        .setAttribute(anyString(), anyObject());
    when(request.getAttribute(anyString())).thenAnswer(invocationOnMock -> requestAttributes.get(invocationOnMock.getArguments()[0]));
    when(parentResource.listChildren()).thenAnswer(invocationOnMock -> children.iterator());
}
 
Example #16
Source File: FieldInitializerTest.java    From commerce-cif-connector with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    SlingScriptHelper sling = mock(SlingScriptHelper.class);
    bindings.put(SlingBindings.SLING, sling);
    ExpressionResolver expressionResolver = mock(ExpressionResolver.class);
    when(expressionResolver.resolve(anyString(), any(), any(), (SlingHttpServletRequest) any())).thenAnswer(
        invocationOnMock -> invocationOnMock.getArguments()[0]);
    when(sling.getService(ExpressionResolver.class)).thenReturn(expressionResolver);
    CommerceBasePathsService pathService = mock(CommerceBasePathsService.class);
    when(pathService.getProductsBasePath()).thenReturn(PRODUCTS_BASE_PATH);
    when(sling.getService(CommerceBasePathsService.class)).thenReturn(pathService);
    doAnswer(invocationOnMock -> {
        includedResourceSample = (Resource) invocationOnMock.getArguments()[0];
        return null;
    }).when(sling).include(any(Resource.class));
    request = mock(SlingHttpServletRequest.class);
    when(request.getRequestURI()).thenReturn("some_request_uri");
    bindings.put(SlingBindings.REQUEST, request);
    requestPathInfo = mock(RequestPathInfo.class);
    when(request.getRequestPathInfo()).thenReturn(requestPathInfo);
    valueMap = new ModifiableValueMapDecorator(new HashMap<>());
    bindings.put(WCMBindingsConstants.NAME_PROPERTIES, valueMap);

    ResourceResolver resourceResolver = mock(ResourceResolver.class);
    when(request.getResourceResolver()).thenReturn(resourceResolver);
    PageManager pageManager = mock(PageManager.class);
    when(resourceResolver.adaptTo(PageManager.class)).thenReturn(pageManager);
    Page page = mock(Page.class);
    when(pageManager.getContainingPage(anyString())).thenReturn(page);
    contentResource = mock(Resource.class);
    contentResourceProperties = new ModifiableValueMapDecorator(new HashMap<>());
    when(contentResource.getValueMap()).thenReturn(contentResourceProperties);
    when(page.getContentResource()).thenReturn(contentResource);
}
 
Example #17
Source File: children.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response){

        final SlingScriptHelper sling = getScriptHelper(request);

        final ExpressionHelper ex = new ExpressionHelper(sling.getService(ExpressionResolver.class), request);
        final Config dsCfg = new Config(request.getResource().getChild(Config.DATASOURCE));
        final CommerceBasePathsService cbps = sling.getService(CommerceBasePathsService.class);

        final String query = ex.getString(dsCfg.get("query", String.class));

        final String parentPath;
        final String searchName;
        final String rootPath = ex.getString(dsCfg.get("rootPath", cbps.getProductsBasePath()));

        if (query != null) {
            final int slashIndex = query.lastIndexOf('/');
            if (slashIndex < 0) {
                parentPath = rootPath;
                searchName = query.toLowerCase();
            } else if (!query.startsWith(rootPath)) {
                parentPath = rootPath;
                searchName = null;
            } else if (slashIndex == query.length() - 1) {
                parentPath = query;
                searchName = null;
            } else {
                parentPath = query.substring(0, slashIndex + 1);
                searchName = query.substring(slashIndex + 1).toLowerCase();
            }
        } else {
            parentPath = ex.getString(dsCfg.get("path", String.class));
            searchName = null;
        }

        final Resource parent = request.getResourceResolver().getResource(parentPath);

        final DataSource ds;
        if (parent == null) {
            ds = EmptyDataSource.instance();
        } else {
            final Integer offset = ex.get(dsCfg.get("offset", String.class), Integer.class);
            final Integer limit = ex.get(dsCfg.get("limit", String.class), Integer.class);
            final String itemRT = dsCfg.get("itemResourceType", String.class);
            final String filter = ex.getString(dsCfg.get("filter", String.class));

            final Collection<Predicate<Resource>> predicates = new ArrayList<>(2);
            predicates.add(createPredicate(filter));

            if (searchName != null) {
                final Pattern searchNamePattern = Pattern.compile(Pattern.quote(searchName), Pattern.CASE_INSENSITIVE);
                predicates.add(resource -> searchNamePattern.matcher(resource.getName()).lookingAt());
            }

            final Predicate predicate = PredicateUtils.allPredicate(predicates);
            final Transformer transformer = createTransformer(itemRT, predicate);


            final List<Resource> list;
            if (FILTER_CATEGORY.equals(filter)) {
                class CategoryFinder extends AbstractResourceVisitor {
                    private CategoryPredicate categoryPredicate = new CategoryPredicate();
                    private List<Resource> categories = new ArrayList<Resource>();
                    @Override
                    protected void visit(Resource res) {
                        if (categoryPredicate.evaluate(res)) {
                            categories.add(res);
                        }
                    }
                };
                CategoryFinder categoryFinder = new CategoryFinder();
                categoryFinder.accept(parent);
                list = IteratorUtils.toList(new FilterIterator(categoryFinder.categories.iterator(), predicate));
            } else {
                list =IteratorUtils.toList(new FilterIterator(parent.listChildren(), predicate));
            }

            //force reloading the children of the root node to hit the virtual resource provider
            if (rootPath.equals(parentPath)) {
                for (int i = 0; i < list.size(); i++) {
                    list.set(i, request.getResourceResolver().getResource(list.get(i).getPath()));
                }
            }

            @SuppressWarnings("unchecked")
            DataSource datasource = new AbstractDataSource() {

                public Iterator<Resource> iterator() {
                    Collections.sort(list, Comparator.comparing(Resource::getName));
                    return new TransformIterator(new PagingIterator<>(list.iterator(), offset, limit), transformer);
                }
            };

            ds = datasource;
        }

        request.setAttribute(DataSource.class.getName(), ds);
    }
 
Example #18
Source File: children.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
private static SlingScriptHelper getScriptHelper(ServletRequest request) {
    SlingBindings bindings = (SlingBindings) request.getAttribute(SlingBindings.class.getName());
    return bindings.getSling();
}
 
Example #19
Source File: BindingsModel.java    From sling-org-apache-sling-models-impl with Apache License 2.0 4 votes vote down vote up
public SlingScriptHelper getSling() {
    return sling;
}
 
Example #20
Source File: BindingsModel.java    From sling-org-apache-sling-models-impl with Apache License 2.0 4 votes vote down vote up
public SlingScriptHelper getSling() {
    return sling;
}
 
Example #21
Source File: BindingsModel.java    From sling-org-apache-sling-models-impl with Apache License 2.0 4 votes vote down vote up
@Inject
public BindingsModel(@Named("sling") SlingScriptHelper sling) {
    this.sling = sling;
}
 
Example #22
Source File: InjectorSpecificAnnotationModel.java    From sling-org-apache-sling-models-impl with Apache License 2.0 4 votes vote down vote up
public SlingScriptHelper getHelper() {
    return helper;
}
 
Example #23
Source File: SlingObjectInjector.java    From sling-org-apache-sling-models-impl with Apache License 2.0 4 votes vote down vote up
@Override
public Object getValue(final @NotNull Object adaptable, final String name, final @NotNull Type type, final @NotNull AnnotatedElement element,
        final @NotNull DisposalCallbackRegistry callbackRegistry) {

    // only class types are supported
    if (!(type instanceof Class<?>)) {
        return null;
    }
    Class<?> requestedClass = (Class<?>) type;

    // validate input
    if (adaptable instanceof SlingHttpServletRequest) {
        SlingHttpServletRequest request = (SlingHttpServletRequest) adaptable;
        if (requestedClass.equals(ResourceResolver.class)) {
            return request.getResourceResolver();
        }
        if (requestedClass.equals(Resource.class) && element.isAnnotationPresent(SlingObject.class)) {
            return request.getResource();
        }
        if (requestedClass.equals(SlingHttpServletRequest.class) || requestedClass.equals(HttpServletRequest.class)) {
            return request;
        }
        if (requestedClass.equals(SlingHttpServletResponse.class)
                || requestedClass.equals(HttpServletResponse.class)) {
            return getSlingHttpServletResponse(request);
        }
        if (requestedClass.equals(SlingScriptHelper.class)) {
            return getSlingScriptHelper(request);
        }
    } else if (adaptable instanceof ResourceResolver) {
        ResourceResolver resourceResolver = (ResourceResolver) adaptable;
        if (requestedClass.equals(ResourceResolver.class)) {
            return resourceResolver;
        }
    } else if (adaptable instanceof Resource) {
        Resource resource = (Resource) adaptable;
        if (requestedClass.equals(ResourceResolver.class)) {
            return resource.getResourceResolver();
        }
        if (requestedClass.equals(Resource.class) && element.isAnnotationPresent(SlingObject.class)) {
            return resource;
        }
    }

    return null;
}
 
Example #24
Source File: NoNameModel.java    From sling-org-apache-sling-models-impl with Apache License 2.0 4 votes vote down vote up
public SlingScriptHelper getSling() {
    return sling;
}
 
Example #25
Source File: NoNameModel.java    From sling-org-apache-sling-models-impl with Apache License 2.0 4 votes vote down vote up
@Inject
public NoNameModel(SlingScriptHelper sling) {
    this.sling = sling;
}
 
Example #26
Source File: InjectorSpecificAnnotationModel.java    From sling-org-apache-sling-models-impl with Apache License 2.0 4 votes vote down vote up
public SlingScriptHelper getHelper() {
    return helper;
}
 
Example #27
Source File: ChildrenDataSourceServlet.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
private static SlingScriptHelper getScriptHelper(ServletRequest request) {
    SlingBindings bindings = (SlingBindings) request.getAttribute(SlingBindings.class.getName());
    return bindings.getSling();
}
 
Example #28
Source File: SearchDataSourceServletTest.java    From commerce-cif-connector with Apache License 2.0 4 votes vote down vote up
@Before
public void before() {
    servlet = new SearchDataSourceServlet();
    request = mock(SlingHttpServletRequest.class);
    response = spy(SlingHttpServletResponse.class);
    SlingBindings slingBindings = mock(SlingBindings.class);
    SlingScriptHelper slingScriptHelper = mock(SlingScriptHelper.class);
    Resource resource = mock(Resource.class);
    Resource dataSourceResource = mock(Resource.class);
    dataSourceProperties = new ModifiableMappedValueMapDecorator(new HashMap<>());
    resourceResolver = mock(ResourceResolver.class);

    results = new ArrayList<>();
    when(resourceResolver.findResources(anyString(), anyString())).thenAnswer(invocation -> {
        queryStringSample = String.valueOf(invocation.getArguments()[0]);
        return queryStringSample.contains("\"fulltext\":[\"something\"]") ? results.iterator() : Collections.emptyIterator();
    });
    CommerceBasePathsService commerceBasePathsService = mock(CommerceBasePathsService.class);
    ExpressionResolver expressionResolver = mock(ExpressionResolver.class);

    Resource parentResource = ChildrenDataSourceServletTest.mockFolderResource("path");

    when(resourceResolver.getResource(TEST_PATH)).thenReturn(parentResource);
    when(slingBindings.getSling()).thenReturn(slingScriptHelper);
    when(request.getResource()).thenReturn(resource);
    when(resource.getChild(Config.DATASOURCE)).thenReturn(dataSourceResource);
    when(dataSourceResource.getValueMap()).thenReturn(dataSourceProperties);
    when(request.getResourceResolver()).thenReturn(resourceResolver);
    when(slingScriptHelper.getService(ExpressionResolver.class)).thenReturn(expressionResolver);
    when(slingScriptHelper.getService(CommerceBasePathsService.class)).thenReturn(commerceBasePathsService);
    when(expressionResolver.resolve(anyString(), (Locale) anyObject(), (Class<? extends Object>) anyObject(),
        (SlingHttpServletRequest) anyObject())).thenAnswer((Answer<Object>) invocation -> long.class.equals(invocation
            .getArguments()[2]) ? Long.valueOf((String) invocation.getArguments()[0]) : invocation.getArguments()[0]);
    Map<String, Object> requestAttributes = new HashMap<>();
    requestAttributes.put(SlingBindings.class.getName(), slingBindings);
    doAnswer(invocation -> requestAttributes.put((String) invocation.getArguments()[0], invocation.getArguments()[1])).when(request)
        .setAttribute(anyString(), anyObject());
    when(request.getAttribute(anyString())).thenAnswer(invocationOnMock -> requestAttributes.get(invocationOnMock.getArguments()[0]));

    requestParameterMap = new HashMap<>();
    when(request.getParameterMap()).thenAnswer(invocation -> requestParameterMap);
    final Resource rootResource = mock(Resource.class);
    when(rootResource.getName()).thenReturn("root");
    rootResourceProperties = new ModifiableMappedValueMapDecorator(new HashMap<>());
    when(resourceResolver.getResource("rootPath")).thenReturn(rootResource);
    when(rootResource.getValueMap()).thenAnswer(invocationOnMock -> rootResourceProperties);
    queryStringSample = null;
}
 
Example #29
Source File: SlingObjectInjectorRequestTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 4 votes vote down vote up
@Test
public void testInvalid() {
    Object result = this.injector.getValue(this, null, SlingScriptHelper.class, this.annotatedElement, registry);
    assertNull(result);
}
 
Example #30
Source File: SlingObjectInjectorRequestTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 4 votes vote down vote up
@Test
public void testScriptHelper() {
    Object result = this.injector
            .getValue(this.request, null, SlingScriptHelper.class, this.annotatedElement, registry);
    assertSame(this.scriptHelper, result);
}