All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.adobe.aemds.guide.utils.GuideProgressiveUtils Maven / Gradle / Ivy

package com.adobe.aemds.guide.utils;

import com.adobe.aemds.guide.progressive.GuideProgressiveCompletionInfo;
import com.adobe.aemds.guide.progressive.GuideProgressiveSectionInfo;
import com.adobe.aemds.guide.service.GuideException;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.io.JSONWriter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.StringWriter;
import java.util.List;

/**
 * @pad.exclude Exclude from Published API.
 */
public class GuideProgressiveUtils {
    private static Logger logger = LoggerFactory.getLogger(GuideProgressiveUtils.class);

    private static String getSectionJson(Object section){
        if(section instanceof GuideProgressiveSectionInfo){
            return ((GuideProgressiveSectionInfo)section).convertToJSON();
        } else if(section instanceof GuideProgressiveCompletionInfo){
            return ((GuideProgressiveCompletionInfo)section).convertToJSON();
        } else {
            return null;
        }
    }

    /**
     * Utility to convert the given section list into JSON
     * @param allSections
     */
    public static String convertToJson(List allSections){
        // In case of on section, we return an json object representing that section
        // in case of multiple sections, we return an array of sections
        if(allSections.size() == 1){
            return getSectionJson(allSections.get(0));
        } else {
            StringWriter jsonStringWriter = new StringWriter();
            JSONWriter jsonWriter = new JSONWriter(jsonStringWriter);
            try {
                jsonWriter.array();
                for(int i=0; i < allSections.size(); i++){
                    jsonWriter.value(getSectionJson(allSections.get(i)));
                }
                jsonWriter.endArray();
            } catch (JSONException ex) {
                throw new GuideException(ex.getMessage(), ex);
            }
            return jsonStringWriter.toString();
        }
    }

    /**
     * Utility to check if the guide node class is part of the top level progressive view model
     * @param guideNodeClass
     */
    public static boolean isGuideProgressiveFieldModel(String guideNodeClass) {
        return GuideConstants.GUIDE_PROGRESSIVE_FIELDS_CLASS_NAMES.indexOf(guideNodeClass) >=0;
    }

}