WidgetExtensionProviderImpl.java 14.8 KB
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.Workspace
 *  javax.jcr.query.Query
 *  javax.jcr.query.QueryManager
 *  javax.jcr.query.QueryResult
 *  org.apache.felix.scr.annotations.Activate
 *  org.apache.felix.scr.annotations.Component
 *  org.apache.felix.scr.annotations.Property
 *  org.apache.felix.scr.annotations.Reference
 *  org.apache.felix.scr.annotations.Service
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceUtil
 *  org.apache.sling.api.resource.ValueMap
 *  org.apache.sling.commons.json.JSONArray
 *  org.apache.sling.commons.json.JSONException
 *  org.apache.sling.commons.json.JSONObject
 *  org.apache.sling.commons.osgi.PropertiesUtil
 *  org.apache.sling.jcr.resource.JcrResourceResolverFactory
 *  org.osgi.service.component.ComponentContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.widget.impl;

import com.day.cq.widget.WidgetExtensionProvider;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Dictionary;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Workspace;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.commons.json.JSONArray;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.JSONObject;
import org.apache.sling.commons.osgi.PropertiesUtil;
import org.apache.sling.jcr.resource.JcrResourceResolverFactory;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/*
 * This class specifies class file version 49.0 but uses Java 6 signatures.  Assumed Java 6.
 */
@Component(label="%widgetextensionprovider.name", description="%widgetextensionprovider.description", metatype=1)
@Service(value={WidgetExtensionProvider.class})
public class WidgetExtensionProviderImpl
implements WidgetExtensionProvider {
    protected final Logger log;
    @Reference
    protected JcrResourceResolverFactory resourceManagerFactory;
    @Property(value={"contentfinder"}, cardinality=Integer.MAX_VALUE)
    protected static final String EXTENDABLE_WIDGETS = "extendable.widgets";
    @Property(boolValue={0})
    protected static final String DEBUG = "widgetextensionprovider.debug";
    private static final String EXTENDABLE_PREFIX = "_extension";
    private static final String EXTENSION_GROUP = "extensionGroup";
    private static final String EXTENSION_ORDER = "extensionOrder";
    private static final String EXTENSION_TYPE = "extensionType";
    public static final String ECMA_DATE_FORMAT = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z";
    public static final Locale DATE_FORMAT_LOCALE = Locale.US;
    private String[] extendableWidgets;
    private boolean debug;
    private static DateFormat calendarFormat;

    public WidgetExtensionProviderImpl() {
        this.log = LoggerFactory.getLogger(this.getClass());
        this.debug = false;
    }

    @Override
    public List<Resource> getExtensions(String xtype, Session session) {
        ArrayList<Resource> extensions = new ArrayList<Resource>();
        if (this.isExtendable(xtype)) {
            String key = xtype + "_extension";
            try {
                Query query = session.getWorkspace().getQueryManager().createQuery("//*[@extensionType='" + key + "'] order by @" + "extensionGroup" + " descending", "xpath");
                QueryResult result = query.execute();
                NodeIterator iter = result.getNodes();
                while (iter.hasNext()) {
                    String path = iter.nextNode().getPath();
                    extensions.add(this.resourceManagerFactory.getResourceResolver(session).getResource(path));
                }
            }
            catch (RepositoryException re) {
                this.log.error("Error occurred while search for extensions for: " + key, (Throwable)re);
            }
        }
        return extensions;
    }

    @Override
    public JSONObject getJson(String key, Session session) {
        List<Resource> extensions = this.getExtensions(key, session);
        JSONObject obj = new JSONObject();
        for (Resource res : extensions) {
            String group = (String)((ValueMap)res.adaptTo(ValueMap.class)).get("extensionGroup", (Object)"unknown");
            try {
                JSONArray a;
                if (obj.has(group)) {
                    a = (JSONArray)obj.get(group);
                } else {
                    obj.put(group, (Object)new JSONArray());
                    a = (JSONArray)obj.get(group);
                }
                Iterator itr = res.getResourceResolver().listChildren(res);
                while (itr.hasNext()) {
                    Resource kid = (Resource)itr.next();
                    InputStream ins = (InputStream)kid.adaptTo(InputStream.class);
                    if (ins == null) continue;
                    if (!this.hasOverlay(kid)) {
                        a.put((Object)("@file:" + kid.getPath()));
                    }
                    try {
                        ins.close();
                    }
                    catch (IOException ignore) {}
                }
                continue;
            }
            catch (JSONException e) {
                continue;
            }
        }
        return obj;
    }

    @Override
    public String getJsonString(String key, Session session) {
        String str;
        try {
            str = this.debug ? this.getJson(key, session).toString(4) : this.getJson(key, session).toString();
        }
        catch (JSONException e) {
            str = this.getJson(key, session).toString();
        }
        str = this.addJsCode(str, session);
        return str;
    }

    private String addJsCode(String str, Session session) {
        int pos = str.indexOf("@file:");
        if (pos >= 0) {
            int pathEnd = pos + "@file:".length();
            String path = str.substring(pathEnd, str.indexOf("\"", pathEnd));
            Resource content = this.resourceManagerFactory.getResourceResolver(session).getResource(path);
            InputStream is = (InputStream)content.adaptTo(InputStream.class);
            String jsCode = this.getString(is);
            String preFix = str.substring(0, pos - 1);
            String postFix = str.substring(str.indexOf("\"", pathEnd) + 1);
            str = preFix + jsCode + postFix;
            if (str.indexOf("@file:") >= 0) {
                str = this.addJsCode(str, session);
            }
        }
        return str;
    }

    @Activate
    protected void activate(ComponentContext context) throws RepositoryException {
        this.extendableWidgets = PropertiesUtil.toStringArray(context.getProperties().get("extendable.widgets"));
        this.debug = PropertiesUtil.toBoolean(context.getProperties().get("widgetextensionprovider.debug"), (boolean)false);
    }

    private boolean isExtendable(String xtype) {
        for (String type : this.extendableWidgets) {
            if (!xtype.equals(type)) continue;
            return true;
        }
        return false;
    }

    public void dump(Resource resource, JSONObject obj, int maxRecursionLevels) throws JSONException {
        this.dump(resource, obj, 0, maxRecursionLevels);
    }

    protected void dump(Resource resource, JSONObject obj, int currentRecursionLevel, int maxRecursionLevels) throws JSONException {
        ValueMap valueMap = (ValueMap)resource.adaptTo(ValueMap.class);
        Object propertyMap = valueMap;
        if (propertyMap == null) {
            propertyMap = (Map)resource.adaptTo(Map.class);
        }
        if (propertyMap == null) {
            String value = (String)resource.adaptTo(String.class);
            if (value != null) {
                obj.put(ResourceUtil.getName((Resource)resource), (Object)value);
            }
            return;
        }
        for (Map.Entry prop : propertyMap.entrySet()) {
            this.writeProperty(obj, valueMap, prop.getKey().toString(), prop.getValue());
        }
        if (this.recursionLevelActive(currentRecursionLevel, maxRecursionLevels)) {
            Iterator children = ResourceUtil.listChildren((Resource)resource);
            while (children.hasNext()) {
                Resource n = (Resource)children.next();
                this.dumpSingleResource(n, obj, currentRecursionLevel, maxRecursionLevels);
            }
        }
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     * Loose catch block
     * Enabled aggressive block sorting
     * Enabled unnecessary exception pruning
     * Enabled aggressive exception aggregation
     * Lifted jumps to return sites
     */
    private String getString(InputStream is) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
            if (!this.debug) continue;
            sb.append("\n");
        }
        try {
            is.close();
            return sb.toString();
        }
        catch (IOException e) {
            return sb.toString();
        }
        catch (IOException e) {
            try {
                is.close();
                return sb.toString();
            }
            catch (IOException e) {
                return sb.toString();
            }
            catch (Throwable throwable) {
                try {
                    is.close();
                    throw throwable;
                }
                catch (IOException e) {
                    // empty catch block
                }
                throw throwable;
            }
        }
    }

    protected void dumpSingleResource(Resource n, JSONObject obj, int currentRecursionLevel, int maxRecursionLevels) throws JSONException {
        if (this.recursionLevelActive(currentRecursionLevel, maxRecursionLevels)) {
            JSONObject jsonObj = new JSONObject();
            this.dump(n, jsonObj, currentRecursionLevel + 1, maxRecursionLevels);
            obj.put(ResourceUtil.getName((Resource)n), (Object)jsonObj);
        }
    }

    protected boolean recursionLevelActive(int currentRecursionLevel, int maxRecursionLevels) {
        return maxRecursionLevels < 0 || currentRecursionLevel < maxRecursionLevels;
    }

    protected void writeProperty(JSONObject obj, ValueMap valueMap, String key, Object value) throws JSONException {
        Object[] values = null;
        if (value.getClass().isArray() && (values = (Object[])value).length == 0) {
            obj.put(key, (Object)new JSONArray());
            return;
        }
        if (value instanceof InputStream || values != null && values[0] instanceof InputStream) {
            return;
        }
        if (!value.getClass().isArray()) {
            this.dumpValue(obj, value, key);
        } else {
            JSONArray a = new JSONArray();
            for (Object v : values) {
                this.dumpValue(a, v);
            }
            obj.put(key, (Object)a);
        }
    }

    protected void dumpValue(JSONObject obj, Object value, String key) throws JSONException {
        if (value instanceof InputStream) {
            obj.put(key, 0);
        } else if (value instanceof Calendar) {
            obj.put(key, (Object)WidgetExtensionProviderImpl.format((Calendar)value));
        } else if (value instanceof Boolean) {
            obj.put(key, ((Boolean)value).booleanValue());
        } else if (value instanceof Long) {
            obj.put(key, ((Long)value).longValue());
        } else if (value instanceof Integer) {
            obj.put(key, ((Integer)value).longValue());
        } else if (value instanceof Double) {
            obj.put(key, ((Double)value).doubleValue());
        } else {
            obj.put(key, (Object)value.toString());
        }
    }

    protected void dumpValue(JSONArray a, Object value) throws JSONException {
        if (value instanceof InputStream) {
            a.put(0);
        } else if (value instanceof Calendar) {
            a.put((Object)WidgetExtensionProviderImpl.format((Calendar)value));
        } else if (value instanceof Boolean) {
            a.put(((Boolean)value).booleanValue());
        } else if (value instanceof Long) {
            a.put(((Long)value).longValue());
        } else if (value instanceof Integer) {
            a.put(((Integer)value).longValue());
        } else if (value instanceof Double) {
            a.put(((Double)value).doubleValue());
        } else {
            a.put((Object)value.toString());
        }
    }

    public static synchronized String format(Calendar date) {
        if (calendarFormat == null) {
            calendarFormat = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z", DATE_FORMAT_LOCALE);
        }
        return calendarFormat.format(date.getTime());
    }

    private boolean hasOverlay(Resource resource) {
        int idx;
        ResourceResolver resolver = resource.getResourceResolver();
        String[] searchPath = resource.getResourceResolver().getSearchPath();
        String resourcePath = resource.getPath();
        for (idx = 0; idx < searchPath.length && !resourcePath.startsWith(searchPath[idx]); ++idx) {
        }
        if (idx == 0 || idx >= searchPath.length) {
            return false;
        }
        String relPath = resourcePath.substring(searchPath[idx].length());
        for (int idx2 = 0; idx2 < idx; ++idx2) {
            if (resolver.getResource(searchPath[idx2] + relPath) == null) continue;
            return true;
        }
        return false;
    }

    protected void bindResourceManagerFactory(JcrResourceResolverFactory jcrResourceResolverFactory) {
        this.resourceManagerFactory = jcrResourceResolverFactory;
    }

    protected void unbindResourceManagerFactory(JcrResourceResolverFactory jcrResourceResolverFactory) {
        if (this.resourceManagerFactory == jcrResourceResolverFactory) {
            this.resourceManagerFactory = null;
        }
    }
}