ListServlet.java 19.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.adobe.granite.xss.XSSAPI
 *  com.day.jcr.vault.fs.io.AccessControlHandling
 *  com.day.jcr.vault.packaging.Dependency
 *  com.day.jcr.vault.packaging.JcrPackage
 *  com.day.jcr.vault.packaging.JcrPackageDefinition
 *  com.day.jcr.vault.packaging.JcrPackageManager
 *  com.day.jcr.vault.packaging.PackageId
 *  com.day.jcr.vault.packaging.PackagingService
 *  com.day.jcr.vault.packaging.Version
 *  javax.jcr.Item
 *  javax.jcr.ItemNotFoundException
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.PathNotFoundException
 *  javax.jcr.Property
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.Value
 *  javax.jcr.Workspace
 *  javax.jcr.query.Query
 *  javax.jcr.query.QueryManager
 *  javax.jcr.query.QueryResult
 *  javax.servlet.ServletException
 *  javax.servlet.http.HttpServletRequest
 *  javax.servlet.http.HttpServletResponse
 *  org.apache.commons.lang3.StringUtils
 *  org.apache.jackrabbit.commons.iterator.NodeIteratorAdapter
 *  org.apache.jackrabbit.util.ISO9075
 *  org.apache.jackrabbit.util.Text
 *  org.apache.sling.commons.json.JSONException
 *  org.apache.sling.commons.json.io.JSONWriter
 *  org.osgi.framework.BundleContext
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.crx.packmgr.impl.servlets;

import com.adobe.granite.xss.XSSAPI;
import com.day.crx.packmgr.impl.AbstractServlet;
import com.day.crx.packmgr.impl.support.RequestData;
import com.day.jcr.vault.fs.io.AccessControlHandling;
import com.day.jcr.vault.packaging.Dependency;
import com.day.jcr.vault.packaging.JcrPackage;
import com.day.jcr.vault.packaging.JcrPackageDefinition;
import com.day.jcr.vault.packaging.JcrPackageManager;
import com.day.jcr.vault.packaging.PackageId;
import com.day.jcr.vault.packaging.PackagingService;
import com.day.jcr.vault.packaging.Version;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import javax.jcr.Item;
import javax.jcr.ItemNotFoundException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.Workspace;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.jackrabbit.commons.iterator.NodeIteratorAdapter;
import org.apache.jackrabbit.util.ISO9075;
import org.apache.jackrabbit.util.Text;
import org.apache.sling.commons.json.JSONException;
import org.apache.sling.commons.json.io.JSONWriter;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ListServlet
extends AbstractServlet {
    private static final Logger log = LoggerFactory.getLogger(ListServlet.class);
    private XSSAPI xssAPI;

    public ListServlet(BundleContext bc, XSSAPI xssAPI) {
        super(bc);
        this.xssAPI = xssAPI;
    }

    @Override
    protected void doService(HttpServletRequest request, HttpServletResponse res, Session session) throws ServletException, IOException {
        res.setContentType("application/json");
        res.setCharacterEncoding("UTF-8");
        try {
            JcrPackageManager packMgr = PackagingService.getPackageManager((Session)session);
            RequestData req = new RequestData(request);
            String path = req.getParameter("path");
            String query = req.getParameter("q");
            List packs = path != null ? ListServlet.getByPath(packMgr, request, session, path) : (StringUtils.isBlank((CharSequence)query) ? packMgr.listPackages() : ListServlet.query(packMgr, request, session, query));
            Printer p = new Printer(packMgr, res.getWriter(), request, this.xssAPI);
            p.print(packs);
        }
        catch (Exception e) {
            this.logger.error("Error while retrieving infos: {}", (Object)e.toString());
            res.sendError(500);
        }
    }

    private static List<JcrPackage> getByPath(JcrPackageManager packMgr, HttpServletRequest req, Session session, String path) throws UnsupportedEncodingException {
        List packs = new ArrayList<JcrPackage>();
        try {
            boolean versions = "true".equals(req.getParameter("includeVersions"));
            if (session.nodeExists(path)) {
                JcrPackage pack = packMgr.open(session.getNode(path));
                if (pack != null) {
                    if (versions) {
                        String group = pack.getDefinition().getId().getGroup();
                        String name = pack.getDefinition().getId().getName();
                        packs = ListServlet.find(packMgr, session, group, name);
                    } else {
                        packs.add(pack);
                    }
                }
            } else if (versions) {
                packs = ListServlet.findSimilar(packMgr, session, path);
            }
        }
        catch (RepositoryException e) {
            // empty catch block
        }
        return packs;
    }

    private static List<JcrPackage> findSimilar(JcrPackageManager packMgr, Session session, String path) throws RepositoryException {
        ArrayList<JcrPackage> packs = new ArrayList<JcrPackage>();
        if (path == null) {
            return packs;
        }
        if (!path.startsWith(packMgr.getPackageRoot().getPath())) {
            return packs;
        }
        int i = path.lastIndexOf("/");
        if (i < 0) {
            return packs;
        }
        String group = path.substring(packMgr.getPackageRoot().getPath().length() + 1, i);
        String name = path.substring(i + 1);
        name = name.substring(0, name.indexOf("-"));
        return ListServlet.find(packMgr, session, group, name);
    }

    private static List<JcrPackage> find(JcrPackageManager packMgr, Session session, String group, String name) throws RepositoryException {
        ArrayList<JcrPackage> packs = new ArrayList<JcrPackage>();
        NodeIterator nodes = packMgr.getPackageRoot().getNode(group).getNodes();
        while (nodes.hasNext()) {
            JcrPackage pack;
            Node n = nodes.nextNode();
            if (ListServlet.isSnapshot(n) || (pack = packMgr.open(n)) == null || !pack.getDefinition().getId().getName().equals(name)) continue;
            packs.add(pack);
        }
        return packs;
    }

    private static Collection<JcrPackage> query(JcrPackageManager packMgr, HttpServletRequest req, Session session, String q) throws RepositoryException, UnsupportedEncodingException {
        NodeIterator nodes;
        TreeSet<JcrPackage> packs = new TreeSet<JcrPackage>(new Comparator<JcrPackage>(){

            @Override
            public int compare(JcrPackage o1, JcrPackage o2) {
                try {
                    return o1.getDefinition().getId().compareTo(o2.getDefinition().getId());
                }
                catch (RepositoryException e) {
                    throw new RuntimeException((Throwable)e);
                }
            }
        });
        String packRoot = ISO9075.encodePath((String)packMgr.getPackageRoot().getPath());
        String term = Text.escapeIllegalXpathSearchChars((String)q).replaceAll("'", "''");
        String query = "/jcr:root" + packRoot + "//element(*, nt:file)[jcr:contains(., '" + term + "')]";
        QueryManager qm = session.getWorkspace().getQueryManager();
        try {
            nodes = qm.createQuery(query, "xpath").execute().getNodes();
        }
        catch (RepositoryException e) {
            nodes = NodeIteratorAdapter.EMPTY;
        }
        while (nodes.hasNext()) {
            JcrPackage pack;
            Node packNode = nodes.nextNode();
            while (packNode != null && !packNode.isNodeType("{http://www.jcp.org/jcr/nt/1.0}file")) {
                packNode = ListServlet.getParentNode((Item)packNode);
            }
            if (packNode == null || ListServlet.isSnapshot(packNode) || (pack = packMgr.open(packNode)) == null) continue;
            boolean versions = "true".equals(req.getParameter("includeVersions"));
            if (versions) {
                String group = pack.getDefinition().getId().getGroup();
                String name = pack.getDefinition().getId().getName();
                packs.addAll(ListServlet.find(packMgr, session, group, name));
                continue;
            }
            packs.add(pack);
        }
        return packs;
    }

    private static Node getParentNode(Item item) throws RepositoryException {
        try {
            return item.getParent();
        }
        catch (ItemNotFoundException e) {
            return null;
        }
    }

    private static boolean isSnapshot(Node node) throws RepositoryException {
        return node.getPath().contains("/.snapshot");
    }

    private static class Printer {
        private final JcrPackageManager packMgr;
        private final JSONWriter w;
        private HttpServletRequest request;
        private XSSAPI xssAPI;

        public Printer(JcrPackageManager packMgr, Writer writer, HttpServletRequest request, XSSAPI xssAPI) {
            this.packMgr = packMgr;
            this.w = new JSONWriter(writer);
            this.request = request;
            this.xssAPI = xssAPI;
        }

        public void print(Collection<JcrPackage> packs) throws JSONException, RepositoryException {
            this.w.object();
            this.w.key("results").array();
            Node packRoot = null;
            for (JcrPackage pack : packs) {
                if (packRoot == null) {
                    packRoot = this.packMgr.getPackageRoot();
                }
                JcrPackageDefinition def = pack.getDefinition();
                PackageId id = def.getId();
                String path = pack.getNode().getPath();
                Node defNode = def.getNode();
                this.w.object();
                this.w.key("pid").value((Object)id);
                this.w.key("path").value((Object)path);
                this.w.key("name").value((Object)id.getName());
                this.w.key("downloadName").value((Object)id.getDownloadName());
                String group = id.getGroup();
                this.w.key("group").value((Object)group);
                this.w.key("groupTitle").value((Object)this.getGroupTitle(packRoot, group));
                this.w.key("version").value((Object)id.getVersion());
                if (def.getDescription() != null) {
                    this.w.key("description").value((Object)this.xssAPI.filterHTML(def.getDescription()));
                }
                this.w.key("thumbnail").value((Object)this.getThumbnailUrl(defNode, path));
                this.w.key("buildCount").value(def.getBuildCount());
                if (def.getLastModified() != null) {
                    this.w.key("lastModified").value(def.getLastModified().getTimeInMillis());
                    this.w.key("lastModifiedBy").value((Object)def.getLastModifiedBy());
                }
                if (def.getCreated() != null) {
                    this.w.key("created").value(def.getCreated().getTimeInMillis());
                    this.w.key("createdBy").value((Object)def.getCreatedBy());
                }
                if (def.getLastUnpacked() != null) {
                    this.w.key("lastUnpacked").value(def.getLastUnpacked().getTimeInMillis());
                    this.w.key("lastUnpackedBy").value((Object)def.getLastUnpackedBy());
                }
                if (def.getLastWrapped() != null) {
                    this.w.key("lastWrapped").value(def.getLastWrapped().getTimeInMillis());
                    this.w.key("lastWrappedBy").value((Object)def.getLastWrappedBy());
                }
                if (def.getLastUnwrapped() != null) {
                    this.w.key("lastUnwrapped").value(def.getLastUnwrapped().getTimeInMillis());
                    if (def.getLastUnwrappedBy() != null) {
                        this.w.key("lastUnwrappedBy").value((Object)def.getLastUnwrappedBy());
                    }
                }
                this.w.key("size").value(pack.getSize());
                this.w.key("hasSnapshot").value(pack.getSnapshot() != null);
                this.w.key("needsRewrap").value(this.needsRewrap(pack, id, packRoot));
                if (defNode.hasProperty("builtWith")) {
                    this.writeProp("builtWith", defNode, "builtWith");
                } else if (defNode.hasProperty("cqVersion")) {
                    String v = "CQ-" + defNode.getProperty("cqVersion").getString();
                    this.w.key("builtWith").value((Object)v);
                }
                this.writeProp("testedWith", defNode, "testedWith");
                this.writeProp("fixedBugs", defNode, "fixedBugs");
                this.w.key("requiresRoot").value(def.requiresRoot());
                this.w.key("requiresRestart").value(def.requiresRestart());
                AccessControlHandling ac = def.getAccessControlHandling();
                this.w.key("acHandling").value((Object)(ac == null ? "" : ac.name().toLowerCase()));
                boolean resolved = this.printDependencies(def.getDependencies());
                this.w.key("resolved").value(resolved);
                this.writeMultiProp("replaces", defNode, "replaces");
                this.writeProp("providerName", defNode, "providerName");
                this.writeProp("providerUrl", defNode, "providerUrl");
                this.writeProp("providerLink", defNode, "providerLink");
                this.w.key("filter").array();
                if (defNode.hasNode("filter")) {
                    NodeIterator filters = defNode.getNode("filter").getNodes();
                    while (filters.hasNext()) {
                        this.printFilter(filters.nextNode());
                    }
                }
                this.w.endArray();
                this.w.key("screenshots").array();
                if (defNode.hasNode("screenshots")) {
                    NodeIterator it = defNode.getNode("screenshots").getNodes();
                    while (it.hasNext()) {
                        this.w.value((Object)it.nextNode().getPath());
                    }
                }
                this.w.endArray();
                this.w.endObject();
            }
            this.w.endArray();
            this.w.key("total").value((long)packs.size());
            this.w.endObject();
        }

        private boolean printDependencies(Dependency[] dependencies) throws JSONException {
            boolean resolved = true;
            this.w.key("dependencies").array();
            for (Dependency d : dependencies) {
                try {
                    PackageId id = this.packMgr.resolve(d, false);
                    this.w.object();
                    this.w.key("name").value((Object)d.toString());
                    this.w.key("id").value((Object)(id == null ? "" : id));
                    this.w.endObject();
                    if (id != null) continue;
                    resolved = false;
                    continue;
                }
                catch (RepositoryException e) {
                    log.error("unable to resolve dependencies", (Throwable)e);
                }
            }
            this.w.endArray();
            return resolved;
        }

        private boolean needsRewrap(JcrPackage pack, PackageId id, Node packRoot) throws RepositoryException {
            String groupPath = "".equals(id.getGroup()) ? id.getGroup() : "/" + id.getGroup();
            return !pack.getNode().getParent().getPath().equals(packRoot.getPath() + groupPath);
        }

        private String getThumbnailUrl(Node defNode, String path) throws RepositoryException {
            long ck = System.currentTimeMillis();
            try {
                ck = defNode.getProperty("thumbnail.png/jcr:content/jcr:lastModified").getLong();
            }
            catch (PathNotFoundException e) {
                // empty catch block
            }
            return this.request.getContextPath() + this.request.getServletPath() + "/thumbnail.jsp?_charset_=utf-8&path=" + Text.escape((String)path) + "&ck=" + ck;
        }

        private String getGroupTitle(Node packRoot, String group) throws RepositoryException {
            Node groupNode;
            if (group.contains("/")) {
                group = group.substring(0, group.indexOf("/"));
            }
            String groupTitle = group;
            if (!"".equals(group) && packRoot.hasNode(group) && (groupNode = packRoot.getNode(group)).hasProperty("jcr:title")) {
                groupTitle = groupNode.getProperty("jcr:title").getString();
            }
            return groupTitle;
        }

        private void printFilter(Node filter) throws JSONException, RepositoryException {
            this.w.object();
            if (filter.hasProperty("root")) {
                this.w.key("root").value((Object)filter.getProperty("root").getString());
            }
            if (filter.hasProperty("rules")) {
                Property rules = filter.getProperty("rules");
                Value[] ruleValues = rules.isMultiple() ? rules.getValues() : new Value[]{rules.getValue()};
                this.w.key("rules").array();
                for (Value rule : ruleValues) {
                    this.printRule(rule);
                }
                this.w.endArray();
            }
            this.w.endObject();
        }

        private void printRule(Value rule) throws JSONException, RepositoryException {
            this.w.object();
            String v = rule.getString();
            String modifier = v.substring(0, v.indexOf(":"));
            this.w.key("modifier").value((Object)modifier);
            String pattern = v.substring(v.indexOf(":") + 1);
            this.w.key("pattern").value((Object)pattern);
            this.w.endObject();
        }

        private void writeProp(String key, Node node, String prop) throws RepositoryException, JSONException {
            this.writeProp(key, node, prop, false);
        }

        private void writeMultiProp(String key, Node node, String prop) throws RepositoryException, JSONException {
            this.writeProp(key, node, prop, true);
        }

        private void writeProp(String key, Node node, String prop, boolean multi) throws RepositoryException, JSONException {
            if (node.hasProperty(prop)) {
                this.w.key(key);
                Property p = node.getProperty(prop);
                if (multi || p.isMultiple()) {
                    this.w.array();
                    if (p.isMultiple()) {
                        for (Value v : p.getValues()) {
                            this.w.value((Object)v.getString());
                        }
                    } else {
                        this.w.value((Object)p.getString());
                    }
                    this.w.endArray();
                } else {
                    this.w.value((Object)p.getString());
                }
            }
        }
    }

}