Henry Kuijpers created SLING-11881:
--------------------------------------

             Summary: @ChildResource Collection<MyModel> in combination with 
@PostConstruct Boolean method can cause injection to stop working
                 Key: SLING-11881
                 URL: https://issues.apache.org/jira/browse/SLING-11881
             Project: Sling
          Issue Type: Bug
          Components: Sling Models
    Affects Versions: Sling Models Impl 1.4.0
            Reporter: Henry Kuijpers


Let's say we have a Sling Model with a parameter:
{code:java}
@ChildResource(name = "links", injectionStrategy = OPTIONAL) final 
Collection<Link> links)
{code}

And Link is implemented as follows:
{code:java}
@Model(adaptables = Resource.class, adapters = LinkModel.class)
public class Link {
    private final String url;

    @Inject
    public LinkModel(@ValueMapValue(name = "url", injectionStrategy = 
InjectionStrategy.OPTIONAL) final String url) {
        this.url = url;
    }

    @PostConstruct
    public boolean activate() {
        // Returning false here indicates that the model is not valid (null 
will be returned, instead of the instantiated model)
        return StringUtils.isNotEmpty(url);
    }
}
{code}

In case the content structure looks like this:
{code}
items/item0/jcr:primaryType=nt:unstructured
items/item0/url=test0
items/item1/jcr:primaryType=nt:unstructured
items/item2/jcr:primaryType=nt:unstructured
items/item2/url=test2
{code}
I would expect the following to be the value of the @ChildResource parameter, 
when adapting:
links=[url=test0, url=test2]

However, an empty collection is injected instead.

I believe this is because of the following lines:
https://github.com/apache/sling-org-apache-sling-models-impl/blob/a348e50f9321af27dea513d0367b813d3afce9e2/src/main/java/org/apache/sling/models/impl/ModelAdapterFactory.java#L1044

The logic here seems to be that if one of the various items cannot be adapted, 
an empty collection is returned, instead of a collection ommitting the item 
that could not be adapted.



--
This message was sent by Atlassian Jira
(v8.20.10#820010)

Reply via email to