Sling Models with Sightly Part – IV (Key Annotations – II)

In this post, I will explain some important questions related to OSGi Services and Sling Models. These questions had been asked by some of my blog readers on the basis of my last blog.

So the Problem Statement is-

According to them, they have one interface with multiple service implementations and want to choose any one of these service implementations according to their need. So their questions were-

1. How to choose the desired service implementation from these service implementations in another services or servlets?
2. How to choose the desired service implementation from these service implementations in Sling Model Class?

I have created a demo implementation according to their requirement and for doing that I have created an interface named as TestService with a dummy method named as test(). Here is the code-

package services;
public interface TestService {
    void test();
}

Now, I have created two dummy service implementations of this interface. Here is the code for the first implementation named as TestServiceFirstImpl.

@Service
@Component(enabled = true,immediate = true,metatype = true)
public class TestServiceFirstImpl implements TestService {
    public void test() {
        System.out.println("inside first");
    }
}

Here is the code for my second implementation named as TestServiceSecondImpl.

@Service
@Component(enabled = true,immediate = true,metatype = true)
public class TestServiceSecondImpl  implements TestService {
    public void test() {
        System.out.println("inside second");
    }
}

Answer for the first question-
It is a two-step process. These steps are explained below-

Step 1
Add a new property that have a unique value for each and every service implementation. This property could be anything you want to add. For example, I am using service.label property for these services and on the basis of this property I will choose from these implementations.

Here are my new definitions for TestServiceFirstImpl class.

@Service
@Component(enabled = true,immediate = true,metatype = true)
@Property(name = "service.label", value = "first")
public class TestServiceFirstImpl implements TestService {
    public void test() {
        System.out.println("inside first");
    }
}

Code For TestServiceSecondImpl class.

@Service
@Component(enabled = true,immediate = true,metatype = true)
@Property(name = "service.label", value = "second")
public class TestServiceSecondImpl  implements TestService {

    public void test() {
        System.out.println("inside second");
    }
}

Step:- 2

Use @Reference annotation in another servlet or in OSGi Service with an extra attribute named as “target”. Just redefine this line as shown below-

@SlingServlet(paths="/bin/testService",extensions = "html",generateComponent = false)
@Component(enabled = true,immediate = true)
public class TestServlet extends SlingSafeMethodsServlet {

    @Reference(target = "(service.label=second)")
    TestService testService;

    protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response)throws ServletException, IOException{
        testService.test();
        response.getWriter().print(" CHECK YOUR LOGS ");
    }
}

Try to run your code, you will get the desired output.

Q2. How to choose these services in Sling Model class?

In Sling Model class you can call an external service using two annotations. These are-
1. @OSGiService
2. @Inject with @Source annotation

If you are using @OSGiService annotation then you have an attribute “filter”, here add your condition and you will get the desired implementation as shown below-

@OSGiService(filter = "(service.label=first)")
TestService testService;

If you are using @Inject with @Source annotation then you need to add one more annotation @Filter. Here is the new code-

    @Inject @Source("osgi-services")
    @Filter("(service.label=second)")
    TestService testService1;

Now here my complete working code that will show you the use of both of these two approaches.

@Model(adaptables = Resource.class)
public class ServiceResolver {


    @OSGiService(filter = "(service.label=first)")
    TestService testService;

    @Inject @Source("osgi-services")
    @Filter("(service.label=second)")
    TestService testService1;

    @PostConstruct
    public void activate(){
        System.out.println("Inside Post Constructor Method");
        testService.test();
        testService1.test();
    }

    @Inject
    @Default(values = "Ankur Chauhan")
    private String firstName;

    public String getFirstName() {
        return firstName;
    }
}
Q3. How am I testing these annotations in Sling Model class?

I have created a dummy component and that component calls these Sling Model classes. Sightly code snippet is-

<div data-sly-use.serviceResolver="sling.models.ServiceResolver">
   ${serviceResolver.firstName}
</div>

For complete working code, I am sharing the Git repository link.
https://bitbucket.org/accunitysoft/accunity-blog-snippets

Happy Coding..!!

Ankur Chauhan
Tech Lead

Sling Models with Sightly Part – III (Key Annotations – I)

Sling Models with Sightly Part III

The title of this blog is “Key Annotations – I” because In this post, I will explain two important annotations related to Sling Models and continue explaining other annotations in my coming posts. So for explaining two annotations, I have selected following two questions for this post.

1). How to include OSGI Services in Sling Model?
2). What is the use of @ResoucePath annotation?

I am assuming that you are using the latest versions of Sling Model APIs that I described in my previous blog.
For Answering first question, I have created an OSGi Service that have a dummy method as follows-

@Component(immediate = true,enabled = true,metatype = false)
@Service (DemoService.class)
public class DemoService {

    private Logger logger = LoggerFactory.getLogger(DemoService.class);

    public void dummyMethod(){
        logger.info("Inside Dummy Method, its working fine. ");
    }
}
Now, You can include OSGi Services in your Sling Models using two annotations, these are-

1. @OSGiService Annotations
2. @Inject Annotation

Here is the Sling Model class, that shows how to use these annotations?

@Model(adaptables = Resource.class)
public class ServiceInjector {

    @Inject @Default(values = "Ankur Chauhan")
    private String firstName;

    @Inject @Source("osgi-services")
    DemoService demoService;

    @OSGiService
    DemoService demoServiceX;

    @PostConstruct
    public void activate(){
        demoService.dummyMethod();
        demoServiceX.dummyMethod();
    }

    public String getFirstName() {
        return firstName;
    }
}

When you call this Model class then you will see that both of these two annotations working in the same manner.

Q1. What is the use of @ResoucePath annotations?

@ResoucePath annotation is a very handy annotation provide by Sling and using this annotation, you can convert a path into its resource object without writing any code. Let’s suppose you have a predefined path (e.g. /content/geometrixx/en) of the resource and want to convert that path into resource object then you can use @ResourcePath annotation.

Q2. How to use @ResoucePath annotation?

Here the code snippet that shows you the use of this annotation-

@Model(adaptables = Resource.class)
public class ServiceInjector {

    @Inject @Default(values = "Ankur Chauhan")
    private String firstName;

    @Inject @ResourcePath(path = "/content/geometrixx/en")
    Resource tempRes;

    @PostConstruct
    public void activate(){
        System.out.println( tempRes + " = Resource Path");
    }

    public String getFirstName() {
        return firstName;
    }
}
Q3. How am I testing these annotations?

I have created a dummy component and that component calls these Sling Model classes. Sightly code snippet is-

<div data-sly-use.serviceInjector="sling.models.ServiceInjector">
   ${serviceInjector.firstName}
</div>

For complete working code, I am sharing the Git repository link.
https://bitbucket.org/argildx/accunity-blog-snippets/src/master/

Happy Coding..!!

Ankur Chauhan
Tech Lead

New Features in AEM 6.1 Sightly

New Features in AEM 6.1 Sightly

In this blog, I will explain new features introduced in AEM6.1 Sightly. These features will make your sightly code more shorter and simple. These features are listed below.

  1. Introduction of <sly> tag.
  2. data-sly-repeat
  3. URL manipulation
  4. local for i18n

I will explain these features in the form of questionnaires, so let’s start.

Q1). What is the use of <sly> tag?

This tag is used to remove extra divs those are generated when we include a resource in our component’s HTML file using Sightly code.

Q2). We can do that using data-sly-unwrap, why <sly>?

For explaining this, Let’s consider we have to include a parsys component in our HTML without extra divs using data-sly-unwrap then your code line will be-

<div data-sly-resource="${@ path='par', resourceType='foundation/components/parsys'}" data-sly-unwrap="true" ></div> or
<div data-sly-resource="${@ path='par', resourceType='foundation/components/parsys'}" data-sly-unwrap ></div>

It will work fine but in this case, you have to first define a <div> tag to use data-sly-resource attribute and you also have to write data-sly-unwrap to remove this extra <div> tag.
Isn’t it simple if you don’t have to write this extra <div> tag and data-sly-unwrap.

Q3). How to use <sly> tag? or what is the syntax of <sly> tag?

If you want to write the same line using <sly> tag then code will be-

<sly data-sly-resource="${@ path='par', resourceType='foundation/components/parsys'}" /> or
<sly data-sly-resource="${@ path='par', resourceType='foundation/components/parsys'}"></sly>

Here, you can see the difference between old approach and <sly> tag.

Q4). will <sly> tag not generate any extra divs?

Yes, it will not generate any extra <div> tag or any HTML DOM element, you can think it as a replacement of data-sly-unwrap Sightly tag.

Q5). is data-sly-unwrap is deprecated or removed from AEM6.1 Sightly?

No, you can use it as well but as you have a much better <sly> tag then I think data-sly-unwrap is not required. I think, It is available only to support the AEM6.0 Sightly code.

Q6). What is the data-sly-repeat tag in Sightly?

This tag is used to iterate any of the list element.

Q7). Can we do that using data-sly-list in Sightly?

Yes, you can do that by using data-sly-list but the only difference is that, if you use data-sly-repeat, you will not have to provide any container element.

Q8). Not getting your point, could you please elaborate on your statement i.e. any container element?

Let us consider you want to iterate all child pages of currentPage object then first use data-sly-list you will write the code as –

<div data-sly-list="${ currentPage.listChildren }">
      ${item.name}
</div>

Output will be generated as –

test1 test2 test3 test4

And when you view the HTML element structure in you debugger then it will be –

<div>
   Test1
   Test2
   Test3
   Test4
<div>

Now use data-sly-repeat

<div data-sly-repeat="${ currentPage.listChildren }">
      ${item.name}
</div>

Output will be –

test1
test2
test3
test4

And when you view the HTML element structure in you debugger then it will be –

<div>
      test1
</div>
<div>
      test2
</div>
<div>
      test3
</div>
<div>
      test4
</div>

You can see these generated DOM elements in debugger’s Elements tab.

Q9). We can achieve same DOM structure using data-sly-list, is it required to use data-sly-repeat for the same?

No, it is not required but using data-sly-repeat your HTML code will become shorter. For ex. If you want to achieve

<div>
      test1
</div>
<div>
      test2
</div>
<div>
      test3
</div>
<div>
      test4
</div>

output then the code you have to write with data-sly-list will be –

<div data-sly-list="${ currentPage.listChildren }" data-sly-unwrap>
       <div> ${item.name} </div>
</div>

Here you have to add data-sly-unwrap and <div> tag for each element. But by using data-sly-repeat, These tags will not be required and your HTML looks more refined, simple and less complex.

Q10). What is URL manipulation in AEM6.1 Sightly?

In AEM 6.1 you can do some URL manipulations which are not available in AEM6.0 Sightly. Some of the examples are –
Adding extension, code is –

${'content/geometrixx/en'@ extension='json'}

Output will be –

content/geometrixx/en.json

Adding scheme (http or https) if required –

 ${'content/geometrixx/en'@ scheme='http', extension='json'}

Output will be –

http://content/geometrixx/en.json

Adding Selectors –

${'content/geometrixx/en'@  selectors='s1', extension='html'}

Output will be –

 content/geometrixx/en.s1.html

Adding Fragments –

 ${currentPage.path @ selectors='s1.s2', extension='html', fragment='blog'}

Output will be –

content/geometrixx/en.s1.s2.html#blog
Q11). What is the locale for i18n?

This locale is newly introduced object in AEM6.1. When we work with i18n in Sightly we can use this object to set custom locale. It can be used as –

${'Hello World' @ i18n, locale=request.locale}
Note –  This object is not present in AEM6.

I am also sharing the Git repository link where you can find demo examples for these properties.
Git repository link is –

https://bitbucket.org/argildx/accunity-blog-snippets/src/master/

Happy Coding..!!

Ankur Chauhan
Tech Lead