PublishDataSourceImpl.java 16.7 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.fasterxml.jackson.core.type.TypeReference
 *  com.fasterxml.jackson.databind.ObjectMapper
 *  org.apache.commons.lang3.StringUtils
 *  org.apache.sling.commons.json.JSONArray
 *  org.apache.sling.commons.json.JSONException
 *  org.apache.sling.commons.json.JSONObject
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.adobe.cq.mobile.dps.impl.ui;

import com.adobe.cq.mobile.dps.DPSArticle;
import com.adobe.cq.mobile.dps.DPSBanner;
import com.adobe.cq.mobile.dps.DPSCollection;
import com.adobe.cq.mobile.dps.DPSException;
import com.adobe.cq.mobile.dps.DPSProject;
import com.adobe.cq.mobile.dps.impl.DPSClient;
import com.adobe.cq.mobile.dps.impl.DPSPageManager;
import com.adobe.cq.mobile.dps.impl.ui.PerfTimer;
import com.adobe.cq.mobile.dps.ui.PublishDataSource;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TimerTask;
import org.apache.commons.lang3.StringUtils;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PublishDataSourceImpl
implements PublishDataSource {
    private static final Logger LOGGER = LoggerFactory.getLogger(PublishDataSourceImpl.class);
    private DPSProject project = null;
    private DPSPageManager dpsPageManager = null;
    private DPSClient dpsClient = null;
    private ObjectMapper jsonMapper;
    private final String JSON_KEY_DATA_FIELD = "data";
    private final String JSON_KEY_ERROR_FIELD = "errors";
    private final String SEARCH_TEXT = "text";
    private final String SEARCH_PATH = "rootPath";
    private final String ARTICLE_MARKER = "_A";
    private final String BANNER_MARKER = "_B";
    private final String COLLECTION_MARKER = "_C";
    private final String LAYOUT_MARKER = "_L";
    private final int CACHE_DURATION = 0;
    private static Map<String, JSONObject> dpsCache = new HashMap<String, JSONObject>();

    public PublishDataSourceImpl(DPSProject project, DPSPageManager dpsPageManager, DPSClient dpsClient) {
        this.project = project;
        this.dpsPageManager = dpsPageManager;
        this.dpsClient = dpsClient;
        this.jsonMapper = new ObjectMapper();
    }

    @Override
    public JSONObject getArticles(Map searchCriteria) throws DPSException {
        PerfTimer perfTimer = PerfTimer.startTimer(this, "getArticles");
        String cacheKey = (searchCriteria != null ? searchCriteria.toString() : this.project.getId()) + "_A";
        JSONObject articles = dpsCache.get(cacheKey);
        if (articles == null) {
            JSONObject ret = new JSONObject();
            try {
                JSONArray aemArticles = null;
                if (searchCriteria == null || searchCriteria.get("source") == null || searchCriteria.get("source").equals("AEM")) {
                    aemArticles = this.dpsPageManager.getAEMArticles(this.project);
                    aemArticles = this.filterEntities(aemArticles, searchCriteria);
                    ret.put("data", (Object)aemArticles);
                }
                this.addToCache(cacheKey, ret);
            }
            catch (DPSException ex) {
                this.addErrorToDataFeed(ret, ex);
            }
            catch (JSONException ex) {
                this.addErrorToDataFeed(ret, (Exception)ex);
            }
            articles = ret;
        }
        perfTimer.end();
        return articles;
    }

    @Override
    public JSONObject getCollection(DPSCollection dpsCollection) throws DPSException {
        PerfTimer perfTimer = PerfTimer.startTimer(this, "getCollection");
        JSONObject ret = new JSONObject();
        if (dpsCollection == null) {
            this.addErrorToDataFeed(ret, new DPSException("Illegal parameter (null) in getCollection"));
        } else {
            try {
                JSONObject collection = dpsCache.get(dpsCollection.getName() + "_C");
                if (collection == null) {
                    collection = this.dpsPageManager.getAEMCollection(dpsCollection, false, true, true);
                    if (collection.has("contentLinks") && collection.get("contentLinks") != null) {
                        JSONArray dpsContentLinks = collection.getJSONArray("contentLinks");
                        JSONArray contentDetails = new JSONArray();
                        collection.put("contentDetails", (Object)contentDetails);
                        if (dpsContentLinks.length() > 0) {
                            for (int i = 0; i < dpsContentLinks.length(); ++i) {
                                Object next = dpsContentLinks.get(i);
                                if (next instanceof JSONObject) {
                                    JSONObject linkJSON = (JSONObject)next;
                                    String name = linkJSON.getString("name");
                                    String type = linkJSON.getString("type");
                                    if (type.equals("article")) {
                                        DPSArticle dpsChildArticle = this.project.getArticle(name);
                                        if (dpsChildArticle != null) {
                                            contentDetails.put((Object)dpsChildArticle.toJSON());
                                            continue;
                                        }
                                        LOGGER.warn("Article not found " + name);
                                        continue;
                                    }
                                    if (type.equals("banner")) {
                                        DPSBanner dpsChildBanner = this.project.getBanner(name);
                                        if (dpsChildBanner != null) {
                                            contentDetails.put((Object)dpsChildBanner.toJSON());
                                            continue;
                                        }
                                        LOGGER.warn("Banner not found " + name);
                                        continue;
                                    }
                                    if (type.equals("collection")) {
                                        DPSCollection dpsChildCollection = this.project.getCollection(name);
                                        if (dpsChildCollection != null) {
                                            contentDetails.put((Object)dpsChildCollection.toJSON());
                                            continue;
                                        }
                                        LOGGER.warn("Collection not found " + name);
                                        continue;
                                    }
                                    LOGGER.warn("Invalid link type " + type);
                                    continue;
                                }
                                LOGGER.warn("Invalid link entry " + next);
                            }
                        }
                    }
                    this.addToCache(dpsCollection.getName() + "_C", collection);
                }
                ret.put("data", (Object)collection);
            }
            catch (DPSException ex) {
                this.addErrorToDataFeed(ret, ex);
            }
            catch (JSONException ex) {
                this.addErrorToDataFeed(ret, (Exception)ex);
            }
            perfTimer.end();
        }
        return ret;
    }

    @Override
    public JSONObject getCollections(Map searchCriteria) throws DPSException {
        PerfTimer perfTimer = PerfTimer.startTimer(this, "getCollections");
        String cacheKey = (searchCriteria != null ? searchCriteria.toString() : this.project.getId()) + "_C";
        JSONObject collections = dpsCache.get(cacheKey);
        if (collections == null) {
            boolean flatten = true;
            if (searchCriteria != null && searchCriteria.get("flatten") != null && !searchCriteria.get("flatten").equals("true")) {
                flatten = false;
            }
            JSONObject ret = new JSONObject();
            try {
                JSONArray aemCollections = null;
                if (searchCriteria == null || searchCriteria.get("source") == null || searchCriteria.get("source").equals("AEM")) {
                    aemCollections = this.dpsPageManager.getAEMCollections(this.project, flatten);
                    aemCollections = this.filterEntities(aemCollections, searchCriteria);
                    ret.put("data", (Object)aemCollections);
                }
                this.addToCache(cacheKey, ret);
            }
            catch (DPSException ex) {
                this.addErrorToDataFeed(ret, ex);
            }
            catch (JSONException ex) {
                this.addErrorToDataFeed(ret, (Exception)ex);
            }
            collections = ret;
        }
        perfTimer.end();
        return collections;
    }

    @Override
    public JSONObject getBanners(Map searchCriteria) throws DPSException {
        PerfTimer perfTimer = PerfTimer.startTimer(this, "getBanners");
        String cacheKey = (searchCriteria != null ? searchCriteria.toString() : this.project.getId()) + "_B";
        JSONObject projectBanners = dpsCache.get(cacheKey);
        if (projectBanners == null) {
            JSONObject ret = new JSONObject();
            try {
                JSONArray aemBanners = null;
                if (searchCriteria == null || searchCriteria.get("source") == null || searchCriteria.get("source").equals("AEM")) {
                    aemBanners = this.dpsPageManager.getAEMBanners(this.project);
                    aemBanners = this.filterEntities(aemBanners, searchCriteria);
                    ret.put("data", (Object)aemBanners);
                }
                this.addToCache(cacheKey, ret);
            }
            catch (DPSException ex) {
                this.addErrorToDataFeed(ret, ex);
            }
            catch (JSONException ex) {
                this.addErrorToDataFeed(ret, (Exception)ex);
            }
            projectBanners = ret;
        }
        perfTimer.end();
        return projectBanners;
    }

    @Override
    public JSONObject getLayouts(Map searchCriteria) throws DPSException {
        PerfTimer perfTimer = PerfTimer.startTimer(this, "getLayouts");
        String cacheKey = (searchCriteria != null ? searchCriteria.toString() : this.project.getId()) + "_L";
        JSONObject projectLayouts = dpsCache.get(cacheKey);
        if (projectLayouts == null) {
            JSONObject ret = new JSONObject();
            try {
                JSONArray dpsLayouts = this.dpsClient.getDPSLayouts(this.project, false, true);
                ret.put("data", (Object)dpsLayouts);
                this.addToCache(cacheKey, ret);
            }
            catch (DPSException ex) {
                this.addErrorToDataFeed(ret, ex);
            }
            catch (JSONException ex) {
                this.addErrorToDataFeed(ret, (Exception)ex);
            }
            projectLayouts = ret;
        }
        perfTimer.end();
        return projectLayouts;
    }

    @Override
    public Map<String, Object> convertJSONtoMap(JSONArray json) throws DPSException {
        PerfTimer perfTimer = PerfTimer.startTimer(this, "convertJSONtoMap");
        HashMap<String, Object> convertedData = new HashMap<String, Object>();
        try {
            if (json != null) {
                convertedData.put("data", this.jsonMapper.readValue(json.toString(), (TypeReference)new TypeReference<ArrayList<Object>>(){}));
            }
        }
        catch (IOException ioe) {
            throw new DPSException("Failed to convert json to map.", ioe);
        }
        perfTimer.end();
        return convertedData;
    }

    private void addErrorToDataFeed(JSONObject jsonObject, Exception ex) {
        LOGGER.error(ex.getMessage(), (Throwable)ex);
        try {
            JSONArray errorsJSONArray = new JSONArray();
            if (jsonObject.has("errors")) {
                errorsJSONArray = jsonObject.getJSONArray("errors");
            } else {
                jsonObject.put("errors", (Object)errorsJSONArray);
            }
            JSONObject error = new JSONObject();
            error.put("class", ex.getClass());
            error.put("message", (Object)ex.getMessage());
            if (ex.getCause() != null) {
                String cause = ex.getCause().getLocalizedMessage();
                if (StringUtils.isEmpty((CharSequence)cause)) {
                    cause = ex.getCause().getClass().getName();
                }
                if (StringUtils.isNotEmpty((CharSequence)cause)) {
                    error.put("cause", (Object)cause);
                }
            }
            errorsJSONArray.put((Object)error);
        }
        catch (JSONException innerEx) {
            LOGGER.error("Failed to add errors to JSONFeed", (Throwable)ex);
        }
    }

    private JSONArray filterEntities(JSONArray entities, Map searchCriteria) {
        if (entities == null || searchCriteria == null || searchCriteria.isEmpty()) {
            return entities;
        }
        JSONArray filteredList = new JSONArray();
        Set entrySet = searchCriteria.entrySet();
        for (int i = 0; i < entities.length(); ++i) {
            JSONObject nextArticle;
            try {
                nextArticle = entities.getJSONObject(i);
            }
            catch (JSONException jsonEx) {
                LOGGER.warn("Error extracting article at index " + i);
                nextArticle = null;
            }
            if (nextArticle == null) continue;
            boolean matchedAll = true;
            for (Map.Entry<String, String> entry : entrySet) {
                if (this.matchesCriteria(nextArticle, entry)) continue;
                matchedAll = false;
                break;
            }
            if (!matchedAll) continue;
            filteredList.put((Object)nextArticle);
        }
        return filteredList;
    }

    private boolean matchesCriteria(JSONObject entity, Map.Entry<String, String> criteria) {
        boolean matches;
        block10 : {
            matches = false;
            String key = criteria.getKey();
            String value = criteria.getValue();
            try {
                if (key.equals("text")) {
                    Iterator it = entity.keys();
                    while (it.hasNext()) {
                        String nextKey = (String)it.next();
                        if (nextKey == null) continue;
                        try {
                            String nextPropertyValue = entity.getString(nextKey);
                            if (!StringUtils.isNotEmpty((CharSequence)nextPropertyValue) || !(matches = nextPropertyValue.contains(value))) continue;
                            break block10;
                        }
                        catch (Exception ex) {
                            matches = false;
                            continue;
                        }
                    }
                    break block10;
                }
                if (key.equals("rootPath")) {
                    String path;
                    matches = true;
                    if (entity.has("url")) {
                        path = entity.getString("url");
                        boolean bl = matches = path.equals(value) || path.startsWith(value + "/");
                    }
                    if (!matches && entity.has("path")) {
                        path = entity.getString("path");
                        matches = path.equals(value) || path.startsWith(value + "/");
                    }
                } else {
                    matches = true;
                }
            }
            catch (Exception ex) {
                matches = false;
            }
        }
        return matches;
    }

    private void addToCache(String name, JSONObject cacheable) {
    }

    public static void clearCollectionCache(String entityName) {
        dpsCache.remove(entityName);
    }

    class ClearCollectionCache
    extends TimerTask {
        private String entityName;
        final /* synthetic */ PublishDataSourceImpl this$0;

        public ClearCollectionCache(PublishDataSourceImpl publishDataSourceImpl, String entityName) {
            this.this$0 = publishDataSourceImpl;
            this.entityName = entityName;
        }

        private ClearCollectionCache(PublishDataSourceImpl publishDataSourceImpl) {
            this.this$0 = publishDataSourceImpl;
        }

        @Override
        public void run() {
            PublishDataSourceImpl.clearCollectionCache(this.entityName);
        }
    }

}