Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
2.0 kB
2
Indexable
Never
package com.mca.core.models;

import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;
import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.injectorspecific.SlingObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Generic sling model for all multifield dialogs.
 * Pass the name of multifield node in a variable named {@link MultifieldModel nodeName} while calling this model class.
 *
 * @author Prashant Nair
 * @version 1.0
 */
@Model(adaptables = {SlingHttpServletRequest.class, Resource.class}, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class MultifieldModel {

    @Inject
    private String nodeName;

    @SlingObject
    private SlingHttpServletRequest request;

    private List<HashMap<String, String>> items;

    @PostConstruct
    protected void init() {
        if (null != request.getResource().getChild(nodeName)) {
            items = new ArrayList<>();
            Resource multiField = request.getResource().getChild(nodeName);
            if (multiField.hasChildren()) {
                Iterable<Resource> children = multiField.getChildren();
                for (Resource child : children) {
                    HashMap<String, String> mapItems = new HashMap<>();
                    ValueMap valueMap = child.adaptTo(ValueMap.class);
                    for (String key : valueMap.keySet()) {
                        mapItems.put(key, valueMap.get(key, String.class));
                    }
                    items.add(mapItems);
                }
            }
        }
    }

    public List<HashMap<String, String>> getItems() {
        return items;
    }
}
Leave a Comment