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

The following examples show how to use org.apache.sling.api.scripting.SlingBindings. 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: HandlebarsScriptEngine.java    From sling-samples with Apache License 2.0 6 votes vote down vote up
@Override
public Object eval(String script, ScriptContext context) throws ScriptException {
    final Resource resource = (Resource) context.getBindings(ScriptContext.ENGINE_SCOPE).get(SlingBindings.RESOURCE);
    final PrintWriter out = (PrintWriter) context.getBindings(ScriptContext.ENGINE_SCOPE).get(SlingBindings.OUT);

    try {
        final Handlebars handlebars = setupHandlebars();
        final Template template = handlebars.compileInline(script);
        out.println(template.apply(getData(resource)));
    } catch(IOException ioe) {
        final ScriptException up = new ScriptException("IOException in eval");
        up.initCause(ioe);
        throw up;
    }
    return null;
}
 
Example #2
Source File: ProductCarouselImplTest.java    From aem-core-cif-components with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    Page page = context.currentPage(PAGE);
    context.currentResource(PRODUCTCAROUSEL);
    carouselResource = Mockito.spy(context.resourceResolver().getResource(PRODUCTCAROUSEL));

    Query rootQuery = Utils.getQueryFromResource("graphql/magento-graphql-productcarousel-result.json");
    products = rootQuery.getProducts().getItems();

    GraphqlClient graphqlClient = Utils.setupGraphqlClientWithHttpResponseFrom("graphql/magento-graphql-productcarousel-result.json");
    Mockito.when(carouselResource.adaptTo(ComponentsConfiguration.class)).thenReturn(MOCK_CONFIGURATION_OBJECT);
    context.registerAdapter(Resource.class, GraphqlClient.class, (Function<Resource, GraphqlClient>) input -> input.getValueMap().get(
        "cq:graphqlClient") != null ? graphqlClient : null);

    // This sets the page attribute injected in the models with @Inject or @ScriptVariable
    SlingBindings slingBindings = (SlingBindings) context.request().getAttribute(SlingBindings.class.getName());
    slingBindings.setResource(carouselResource);
    slingBindings.put(WCMBindingsConstants.NAME_CURRENT_PAGE, page);

    productSkuArray = (String[]) carouselResource.getValueMap().get("product"); // The HTL script uses an alias here
    slingBindings.put("productSkuList", productSkuArray);

    productCarousel = context.request().adaptTo(ProductCarouselImpl.class);
}
 
Example #3
Source File: CommerceTeaserImplTest.java    From aem-core-cif-components with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    Page page = context.currentPage(PAGE);
    context.currentResource(TEASER);
    commerceTeaserResource = context.resourceResolver().getResource(TEASER);

    // This sets the page attribute injected in the models with @Inject or @ScriptVariable
    SlingBindings slingBindings = (SlingBindings) context.request().getAttribute(SlingBindings.class.getName());
    slingBindings.setResource(commerceTeaserResource);
    slingBindings.put(WCMBindingsConstants.NAME_CURRENT_PAGE, page);

    // Configure the component to create deep links to specific pages
    context.request().setAttribute(WCMMode.class.getName(), WCMMode.EDIT);

    commerceTeaser = context.request().adaptTo(CommerceTeaserImpl.class);
}
 
Example #4
Source File: ProductTeaserImplTest.java    From aem-core-cif-components with Apache License 2.0 6 votes vote down vote up
@Test
public void testVirtualProduct() throws IOException {
    Page page = context.currentPage(PAGE);
    context.currentResource(PRODUCTTEASER_VIRTUAL);
    Resource teaserResource = Mockito.spy(context.resourceResolver().getResource(PRODUCTTEASER_VIRTUAL));
    Mockito.when(teaserResource.adaptTo(ComponentsConfiguration.class)).thenReturn(MOCK_CONFIGURATION_OBJECT);

    GraphqlClient graphqlClient = Utils.setupGraphqlClientWithHttpResponseFrom("graphql/magento-graphql-virtualproduct-result.json");
    context.registerAdapter(Resource.class, GraphqlClient.class, (Function<Resource, GraphqlClient>) input -> input.getValueMap().get(
        "cq:graphqlClient", String.class) != null ? graphqlClient : null);

    SlingBindings slingBindings = (SlingBindings) context.request().getAttribute(SlingBindings.class.getName());
    slingBindings.setResource(teaserResource);
    slingBindings.put(WCMBindingsConstants.NAME_CURRENT_PAGE, page);
    slingBindings.put(WCMBindingsConstants.NAME_PROPERTIES, teaserResource.getValueMap());

    productTeaser = context.request().adaptTo(ProductTeaserImpl.class);
    Assert.assertTrue(productTeaser.isVirtualProduct());
}
 
Example #5
Source File: ProductTeaserImplTest.java    From aem-core-cif-components with Apache License 2.0 6 votes vote down vote up
@Test
public void verifyProductTeaserNoGraphqlCLient() {
    Page page = context.currentPage(PAGE);
    context.currentResource(PRODUCTTEASER_NOCLIENT);
    Resource teaserResource = Mockito.spy(context.resourceResolver().getResource(PRODUCTTEASER_NOCLIENT));
    Mockito.when(teaserResource.adaptTo(GraphqlClient.class)).thenReturn(null);

    // This sets the page attribute injected in the models with @Inject or @ScriptVariable
    SlingBindings slingBindings = (SlingBindings) context.request().getAttribute(SlingBindings.class.getName());
    slingBindings.setResource(teaserResource);
    slingBindings.put(WCMBindingsConstants.NAME_CURRENT_PAGE, page);
    slingBindings.put(WCMBindingsConstants.NAME_PROPERTIES, teaserResource.getValueMap());

    ProductTeaserImpl productTeaserNoClient = context.request().adaptTo(ProductTeaserImpl.class);

    Assert.assertNull(productTeaserNoClient.getProductRetriever());
    Assert.assertNull(productTeaserNoClient.getUrl());
}
 
Example #6
Source File: ProductTeaserImplTest.java    From aem-core-cif-components with Apache License 2.0 6 votes vote down vote up
public void setUp(String resourcePath, boolean deepLink) throws Exception {
    Page page = context.currentPage(PAGE);
    context.currentResource(resourcePath);
    teaserResource = Mockito.spy(context.resourceResolver().getResource(resourcePath));

    Query rootQuery = Utils.getQueryFromResource("graphql/magento-graphql-productteaser-result.json");
    product = rootQuery.getProducts().getItems().get(0);

    GraphqlClient graphqlClient = Utils.setupGraphqlClientWithHttpResponseFrom("graphql/magento-graphql-productteaser-result.json");
    Mockito.when(teaserResource.adaptTo(ComponentsConfiguration.class)).thenReturn(MOCK_CONFIGURATION_OBJECT);
    context.registerAdapter(Resource.class, GraphqlClient.class, (Function<Resource, GraphqlClient>) input -> input.getValueMap().get(
        "cq:graphqlClient", String.class) != null ? graphqlClient : null);

    // This sets the page attribute injected in the models with @Inject or @ScriptVariable
    SlingBindings slingBindings = (SlingBindings) context.request().getAttribute(SlingBindings.class.getName());
    slingBindings.setResource(teaserResource);
    slingBindings.put(WCMBindingsConstants.NAME_CURRENT_PAGE, page);
    slingBindings.put(WCMBindingsConstants.NAME_PROPERTIES, teaserResource.getValueMap());

    if (deepLink) {
        // Configure the component to create deep links to specific pages
        context.request().setAttribute(WCMMode.class.getName(), WCMMode.EDIT);
    }

    productTeaser = context.request().adaptTo(ProductTeaserImpl.class);
}
 
Example #7
Source File: ProductCollectionImplTest.java    From aem-core-cif-components with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() {

    context.currentResource(PRODUCT_COLLECTION);

    MockRequestPathInfo requestPathInfo = (MockRequestPathInfo) context.request().getRequestPathInfo();
    requestPathInfo.setSelectorString("6");

    // This sets the page attribute injected in the models with @Inject or @ScriptVariable
    Resource productCollectionResource = context.resourceResolver().getResource(PRODUCT_COLLECTION);
    SlingBindings slingBindings = getSlingBindings(PRODUCT_COLLECTION);

    XSSAPI xssApi = mock(XSSAPI.class);
    when(xssApi.filterHTML(Mockito.anyString())).then(i -> i.getArgumentAt(0, String.class));
    slingBindings.put("xssApi", xssApi);

    Style style = mock(Style.class);
    when(style.get(Mockito.anyString(), Mockito.anyInt())).then(i -> i.getArgumentAt(1, Object.class));
    slingBindings.put("currentStyle", style);

    SightlyWCMMode wcmMode = mock(SightlyWCMMode.class);
    when(wcmMode.isDisabled()).thenReturn(false);
    slingBindings.put("wcmmode", wcmMode);
}
 
Example #8
Source File: GraphqlServletTest.java    From aem-core-cif-components with Apache License 2.0 6 votes vote down vote up
@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: 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 #10
Source File: ResourceOverridingRequestWrapper.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
@Override
public Object getAttribute(String name) {
    if (SlingBindings.class.getName().equals(name)) {
        return bindings;
    } else {
        return super.getAttribute(name);
    }
}
 
Example #11
Source File: RelatedProductsImplTest.java    From aem-core-cif-components with Apache License 2.0 5 votes vote down vote up
private void setUp(RelationType relationType, String jsonResponsePath, boolean addSlugInSelector) throws Exception {
    Page page = context.currentPage(PAGE);
    String resourcePath = RESOURCES_PATHS.get(relationType);
    context.currentResource(resourcePath);
    relatedProductsResource = Mockito.spy(context.resourceResolver().getResource(resourcePath));

    if (addSlugInSelector) {
        MockRequestPathInfo requestPathInfo = (MockRequestPathInfo) context.request().getRequestPathInfo();
        requestPathInfo.setSelectorString("endurance-watch");
    }

    GraphqlClient graphqlClient = null;
    if (jsonResponsePath != null) {
        Query rootQuery = Utils.getQueryFromResource(jsonResponsePath);
        ProductInterface product = rootQuery.getProducts().getItems().get(0);
        products = PRODUCTS_GETTER.get(relationType).apply(product);
        graphqlClient = Utils.setupGraphqlClientWithHttpResponseFrom(jsonResponsePath);
        GraphqlClient finalGraphqlClient = graphqlClient;
        context.registerAdapter(Resource.class, GraphqlClient.class,
            (Function<Resource, GraphqlClient>) input -> input.getValueMap().get("cq:graphqlClient", String.class) != null
                ? finalGraphqlClient
                : null);
    }

    // This sets the page attribute injected in the models with @Inject or @ScriptVariable
    SlingBindings slingBindings = (SlingBindings) context.request().getAttribute(SlingBindings.class.getName());
    slingBindings.setResource(relatedProductsResource);
    slingBindings.put(WCMBindingsConstants.NAME_CURRENT_PAGE, page);
    slingBindings.put("properties", relatedProductsResource.getValueMap());

    relatedProducts = context.request().adaptTo(RelatedProductsImpl.class);
}
 
Example #12
Source File: SearchResultsImplTest.java    From aem-core-cif-components with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    Page page = Mockito.spy(context.currentPage(PAGE));
    context.currentResource(SEARCHRESULTS);
    Resource searchResultsResource = context.resourceResolver().getResource(SEARCHRESULTS);

    GraphqlClient graphqlClient = new GraphqlClientImpl();
    Whitebox.setInternalState(graphqlClient, "gson", QueryDeserializer.getGson());
    Whitebox.setInternalState(graphqlClient, "client", httpClient);
    Whitebox.setInternalState(graphqlClient, "httpMethod", HttpMethod.POST);

    Utils.setupHttpResponse("graphql/magento-graphql-introspection-result.json", httpClient, HttpStatus.SC_OK, "{__type");
    Utils.setupHttpResponse("graphql/magento-graphql-attributes-result.json", httpClient, HttpStatus.SC_OK, "{customAttributeMetadata");
    Utils.setupHttpResponse("graphql/magento-graphql-search-result.json", httpClient, HttpStatus.SC_OK, "{products");

    // This is needed by the SearchResultsService used by the productlist component
    pageResource = Mockito.spy(page.adaptTo(Resource.class));
    when(page.adaptTo(Resource.class)).thenReturn(pageResource);
    context.registerAdapter(Resource.class, GraphqlClient.class, (Function<Resource, GraphqlClient>) input -> input.getValueMap().get(
        "cq:graphqlClient") != null ? graphqlClient : null);

    // This sets the page attribute injected in the models with @Inject or @ScriptVariable
    SlingBindings slingBindings = (SlingBindings) context.request().getAttribute(SlingBindings.class.getName());
    slingBindings.setResource(searchResultsResource);
    slingBindings.put(WCMBindingsConstants.NAME_CURRENT_PAGE, page);
    slingBindings.put(WCMBindingsConstants.NAME_PROPERTIES, searchResultsResource.getValueMap());

    XSSAPI xssApi = mock(XSSAPI.class);
    when(xssApi.filterHTML(Mockito.anyString())).then(i -> i.getArgumentAt(0, String.class));
    slingBindings.put("xssApi", xssApi);

    Style style = mock(Style.class);
    when(style.get(Mockito.anyString(), Mockito.anyInt())).then(i -> i.getArgumentAt(1, Object.class));
    slingBindings.put("currentStyle", style);

    SightlyWCMMode wcmMode = mock(SightlyWCMMode.class);
    when(wcmMode.isDisabled()).thenReturn(false);
    slingBindings.put("wcmmode", wcmMode);
}
 
Example #13
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 #14
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 #15
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 #16
Source File: InjectorSpecificAnnotationTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    factory = AdapterFactoryTest.createModelAdapterFactory();

    osgiInjector = new OSGiServiceInjector();
    osgiInjector.activate(bundleContext);

    BindingsInjector bindingsInjector = new BindingsInjector();
    ValueMapInjector valueMapInjector = new ValueMapInjector();
    ChildResourceInjector childResourceInjector = new ChildResourceInjector();
    RequestAttributeInjector requestAttributeInjector = new RequestAttributeInjector();

    factory.bindInjector(bindingsInjector,
            Collections.<String, Object> singletonMap(Constants.SERVICE_ID, 1L));
    factory.bindInjector(valueMapInjector,
            Collections.<String, Object> singletonMap(Constants.SERVICE_ID, 2L));
    factory.bindInjector(childResourceInjector,
            Collections.<String, Object> singletonMap(Constants.SERVICE_ID, 3L));
    factory.bindInjector(requestAttributeInjector,
            Collections.<String, Object> singletonMap(Constants.SERVICE_ID, 4L));
    factory.bindInjector(osgiInjector, Collections.<String, Object> singletonMap(Constants.SERVICE_ID, 5L));

    factory.bindStaticInjectAnnotationProcessorFactory(bindingsInjector,
            Collections.<String, Object> singletonMap(Constants.SERVICE_ID, 1L));
    factory.injectAnnotationProcessorFactories = Collections.<InjectAnnotationProcessorFactory>singletonList(valueMapInjector);
    factory.injectAnnotationProcessorFactories2 = Collections.<InjectAnnotationProcessorFactory2>singletonList(childResourceInjector);
    factory.bindStaticInjectAnnotationProcessorFactory(requestAttributeInjector,
            Collections.<String, Object> singletonMap(Constants.SERVICE_ID, 4L));
    factory.bindStaticInjectAnnotationProcessorFactory(osgiInjector,
            Collections.<String, Object> singletonMap(Constants.SERVICE_ID, 5L));
    factory.bindViaProvider(new BeanPropertyViaProvider(), null);

    SlingBindings bindings = new SlingBindings();
    bindings.setLog(log);
    Mockito.when(request.getAttribute(SlingBindings.class.getName())).thenReturn(bindings);

    factory.adapterImplementations.addClassesAsAdapterAndImplementation(InjectorSpecificAnnotationModel.class, org.apache.sling.models.testmodels.classes.constructorinjection.InjectorSpecificAnnotationModel.class);
}
 
Example #17
Source File: MultipleInjectorTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    bindings = new SlingBindings();

    factory = AdapterFactoryTest.createModelAdapterFactory();
    // binding injector should be asked first as it has a lower service ranking!
    factory.bindInjector(bindingsInjector, new ServicePropertiesMap(1, 1));
    factory.bindInjector(attributesInjector, new ServicePropertiesMap(2, 2));
    factory.bindStaticInjectAnnotationProcessorFactory(bindingsInjector, new ServicePropertiesMap(1, 1));

    when(request.getAttribute(SlingBindings.class.getName())).thenReturn(bindings);
    factory.adapterImplementations.addClassesAsAdapterAndImplementation(
            ForTwoInjectorsWithSource.class, ForTwoInjectors.class, ForTwoInjectorsWithInvalidSource.class);
}
 
Example #18
Source File: ResourceOverridingRequestWrapper.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
ResourceOverridingRequestWrapper(SlingHttpServletRequest wrappedRequest, Resource resource,
                                        AdapterManager adapterManager, SlingModelsScriptEngineFactory scriptEngineFactory,
                                        BindingsValuesProvidersByContext bindingsValuesProvidersByContext) {
    super(wrappedRequest);
    this.resource = resource;
    this.adapterManager = adapterManager;

    SlingBindings existingBindings = (SlingBindings) wrappedRequest.getAttribute(SlingBindings.class.getName());

    SimpleBindings bindings = new SimpleBindings();
    if (existingBindings != null) {
        bindings.put(SLING, existingBindings.getSling());
        bindings.put(RESPONSE, existingBindings.getResponse());
        bindings.put(READER, existingBindings.getReader());
        bindings.put(OUT, existingBindings.getOut());
        bindings.put(LOG, existingBindings.getLog());
    }
    bindings.put(REQUEST, this);
    bindings.put(RESOURCE, resource);
    bindings.put(SlingModelsScriptEngineFactory.RESOLVER, resource.getResourceResolver());

    scriptEngineFactory.invokeBindingsValuesProviders(bindingsValuesProvidersByContext, bindings);

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

    this.bindings = slingBindings;

}
 
Example #19
Source File: RequestInjectionTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() {
    SlingBindings bindings = new SlingBindings();
    bindings.setSling(sling);
    bindings.setLog(LoggerFactory.getLogger("test"));
    when(request.getAttribute(SlingBindings.class.getName())).thenReturn(bindings);

    factory = AdapterFactoryTest.createModelAdapterFactory();
    factory.bindInjector(new BindingsInjector(), new ServicePropertiesMap(1, 1));
    factory.adapterImplementations.addClassesAsAdapterAndImplementation(BindingsModel.class, org.apache.sling.models.testmodels.classes.constructorinjection.BindingsModel.class);
}
 
Example #20
Source File: RequestWrapperTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
private Matcher<Bindings> bindingsHasResource(final Resource resource) {
    return new TypeSafeMatcher<Bindings>() {
        @Override
        protected boolean matchesSafely(Bindings bindings) {
            return bindings.get(SlingBindings.RESOURCE) == resource;
        }

        @Override
        public void describeTo(Description description) {
            description.appendText("a bindings object with the resource " + resource);
        }
    };
}
 
Example #21
Source File: BindingsInjector.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
@Override
public Object getValue(@NotNull Object adaptable, String name, @NotNull Type type, @NotNull AnnotatedElement element,
        @NotNull DisposalCallbackRegistry callbackRegistry) {
    if (adaptable == ObjectUtils.NULL) {
        return null;
    }
    SlingBindings bindings = getBindings(adaptable);
    if (bindings == null) {
        return null;
    }
    return bindings.get(name);
}
 
Example #22
Source File: BindingsInjector.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
private SlingBindings getBindings(Object adaptable) {
    if (adaptable instanceof SlingBindings) {
        return (SlingBindings) adaptable;
    } else if (adaptable instanceof ServletRequest) {
        ServletRequest request = (ServletRequest) adaptable;
        return (SlingBindings) request.getAttribute(SlingBindings.class.getName());
    } else {
        return null;
    }
}
 
Example #23
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 #24
Source File: RequestInjectionTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
@Test
public void testNamedInjectionConstructor() {
    org.apache.sling.models.testmodels.classes.constructorinjection.BindingsModel model
            = factory.getAdapter(request, org.apache.sling.models.testmodels.classes.constructorinjection.BindingsModel.class);
    assertNotNull(model.getSling());
    assertEquals(sling, model.getSling());
    assertEquals("test", model.getLog().getName());

    verify(request, times(1)).getAttribute(SlingBindings.class.getName());
}
 
Example #25
Source File: RequestInjectionTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
@Test
public void testNamedInjectionField() {
    BindingsModel model = factory.getAdapter(request, BindingsModel.class);
    assertNotNull(model.getSling());
    assertEquals(sling, model.getSling());
    assertEquals("test", model.getLog().getName());
    verify(request, times(1)).getAttribute(SlingBindings.class.getName());
}
 
Example #26
Source File: SlingObjectInjectorRequestTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    SlingBindings bindings = new SlingBindings();
    bindings.put(SlingBindings.SLING, this.scriptHelper);
    when(this.request.getResourceResolver()).thenReturn(this.resourceResolver);
    when(this.request.getResource()).thenReturn(this.resource);
    when(this.request.getAttribute(SlingBindings.class.getName())).thenReturn(bindings);
    when(this.scriptHelper.getResponse()).thenReturn(this.response);
}
 
Example #27
Source File: BindingsInjectorTest.java    From sling-org-apache-sling-models-impl with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    when(request.getAttribute(SlingBindings.class.getName())).thenReturn(bindings);
    when(bindings.get(STRING_PARAM)).thenReturn(STRING_VALUE);
    when(bindings.get(INTEGER_PARAM)).thenReturn(INTEGER_VALUE);
    when(bindings.get(CLASS_PARAM)).thenReturn(CLASS_INSTANCE);
}
 
Example #28
Source File: ProductCarouselImplEmptyTest.java    From aem-core-cif-components with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    carouselResource = Mockito.spy(context.resourceResolver().getResource(PRODUCTCAROUSEL));
    // GraphQL client is not available
    Mockito.when(carouselResource.adaptTo(GraphqlClient.class)).thenReturn(null);
    // This sets the page attribute injected in the models with @Inject or @ScriptVariable
    slingBindings = (SlingBindings) context.request().getAttribute(SlingBindings.class.getName());
    slingBindings.setResource(carouselResource);
    Page page = context.currentPage(PAGE);
    slingBindings.put(WCMBindingsConstants.NAME_CURRENT_PAGE, page);
}
 
Example #29
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 #30
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();
    }
}