List.java 24 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 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.commons.Filter
 *  com.day.cq.commons.RangeIterator
 *  com.day.cq.search.Predicate
 *  com.day.cq.search.Query
 *  com.day.cq.search.QueryBuilder
 *  com.day.cq.search.SimpleSearch
 *  com.day.cq.search.result.Hit
 *  com.day.cq.search.result.SearchResult
 *  com.day.cq.tagging.TagManager
 *  com.day.cq.wcm.api.Page
 *  com.day.cq.wcm.api.PageFilter
 *  com.day.cq.wcm.api.PageManager
 *  com.day.text.Text
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.Session
 *  javax.jcr.Workspace
 *  javax.jcr.query.Query
 *  javax.jcr.query.QueryManager
 *  javax.jcr.query.QueryResult
 *  org.apache.commons.collections.iterators.EmptyIterator
 *  org.apache.sling.api.SlingHttpServletRequest
 *  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.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.wcm.foundation;

import com.day.cq.commons.Filter;
import com.day.cq.commons.RangeIterator;
import com.day.cq.search.Predicate;
import com.day.cq.search.QueryBuilder;
import com.day.cq.search.SimpleSearch;
import com.day.cq.search.result.Hit;
import com.day.cq.search.result.SearchResult;
import com.day.cq.tagging.TagManager;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageFilter;
import com.day.cq.wcm.api.PageManager;
import com.day.text.Text;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.NoSuchElementException;
import java.util.Set;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
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.commons.collections.iterators.EmptyIterator;
import org.apache.sling.api.SlingHttpServletRequest;
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.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class List {
    public static final Logger log = LoggerFactory.getLogger(List.class);
    public static final String DEFAULT_QUERY = "";
    public static final String URL_EXTENSION = ".html";
    public static final String TYPE_PROPERTY_NAME = "displayAs";
    public static final String SOURCE_PROPERTY_NAME = "listFrom";
    public static final String SOURCE_CHILDREN = "children";
    public static final String SOURCE_DESCENDANTS = "descendants";
    public static final String SOURCE_STATIC = "static";
    public static final String SOURCE_SEARCH = "search";
    public static final String SOURCE_QUERYBUILDER = "querybuilder";
    public static final String SOURCE_TAGS = "tags";
    public static final String TYPE_DEFAULT = "default";
    public static final String PARENT_PAGE_PROPERTY_NAME = "parentPage";
    public static final String ANCESTOR_PAGE_PROPERTY_NAME = "ancestorPage";
    public static final String TAGS_SEARCH_ROOT_PROPERTY_NAME = "tagsSearchRoot";
    public static final String TAGS_PROPERTY_NAME = "tags";
    public static final String TAGS_MATCH_PROPERTY_NAME = "tagsMatch";
    public static final String PAGES_PROPERTY_NAME = "pages";
    public static final String QUERY_PROPERTY_NAME = "query";
    public static final String SEARCH_IN_PROPERTY_NAME = "searchIn";
    public static final String LIMIT_PROPERTY_NAME = "limit";
    public static final String PAGE_MAX_PROPERTY_NAME = "pageMax";
    public static final String ORDER_BY_PROPERTY_NAME = "orderBy";
    public static final String ORDERED_PROPERTY_NAME = "ordered";
    public static final String SAVEDQUERY_PROPERTY_NAME = "savedquery";
    public static final String PAGE_START_PARAM_NAME = "start";
    public static final String PAGE_MAX_PARAM_NAME = "max";
    public static final String ALLOW_DUPLICATES_PROPERTY_NAME = "allowDuplicates";
    private String id;
    private SlingHttpServletRequest request;
    private java.util.List<Resource> resources;
    private java.util.List<Page> pages;
    private Iterator<Page> pageIterator;
    private Iterator<Node> nodeIterator;
    private boolean inited;
    private boolean ordered;
    private String source;
    private String query;
    private String queryType;
    private String startIn;
    private String type;
    private String orderBy;
    private Comparator<Page> orderComparator;
    private int limit = -1;
    private int pageMaximum = -1;
    private int pageStart = 0;
    private Resource resource;
    private ValueMap properties;
    private PageFilter pageFilter;

    public List(SlingHttpServletRequest request) {
        this(request, null);
    }

    public List(SlingHttpServletRequest request, PageFilter pageFilter) {
        this.request = request;
        this.pageFilter = pageFilter;
        this.resource = request.getResource();
        this.generateId();
    }

    private void initConfig() {
        this.properties = ResourceUtil.getValueMap((Resource)this.resource);
        if (this.source == null) {
            this.source = (String)this.properties.get("listFrom", (Object)"static");
        }
        if (this.query == null) {
            this.query = (String)this.properties.get("query", (Object)"");
        }
        if (this.startIn == null) {
            this.startIn = (String)this.properties.get("searchIn", (Object)Text.getAbsoluteParent((String)this.resource.getPath(), (int)1));
        }
        if (this.type == null) {
            this.type = (String)this.properties.get("displayAs", (Object)"default");
        }
        if (this.orderBy == null) {
            this.orderBy = (String)this.properties.get("orderBy", null);
        }
        if (this.limit < 0) {
            this.limit = (Integer)this.properties.get("limit", (Object)100);
        }
        if (this.pageMaximum < 0) {
            this.pageMaximum = (Integer)this.properties.get("pageMax", (Object)-1);
        }
        this.ordered = (Boolean)this.properties.get("ordered", (Object)this.ordered);
        if (this.getParameter("start") != null) {
            try {
                this.pageStart = Integer.parseInt(this.getParameter("start"));
            }
            catch (Throwable t) {
                // empty catch block
            }
        }
        if (this.getParameter("max") != null) {
            try {
                this.pageMaximum = Integer.parseInt(this.getParameter("max"));
            }
            catch (Throwable t) {
                // empty catch block
            }
        }
    }

    private boolean init() {
        if (!this.inited) {
            block33 : {
                this.initConfig();
                if (this.pageIterator == null) {
                    ResourceResolver resolver = this.request.getResourceResolver();
                    PageManager pm = (PageManager)resolver.adaptTo(PageManager.class);
                    boolean allowDuplicates = (Boolean)this.properties.get("allowDuplicates", (Object)false);
                    try {
                        String parentPath;
                        Session session = (Session)resolver.adaptTo(Session.class);
                        if ("querybuilder".equals(this.source)) {
                            QueryBuilder queryBuilder = (QueryBuilder)resolver.adaptTo(QueryBuilder.class);
                            if (session == null || queryBuilder == null) break block33;
                            try {
                                com.day.cq.search.Query query = queryBuilder.loadQuery(this.resource.getPath() + "/" + "savedquery", session);
                                if (query != null) {
                                    SearchResult result = query.getResult();
                                    this.pageIterator = new HitBasedPageIterator(pm, result.getHits().iterator(), !allowDuplicates, this.pageFilter);
                                    this.nodeIterator = result.getNodes();
                                }
                                break block33;
                            }
                            catch (Exception e) {
                                log.error("error loading stored querybuilder query from " + this.resource.getPath(), (Throwable)e);
                            }
                            break block33;
                        }
                        if ("search".equals(this.source)) {
                            if ("".equals(this.query)) {
                                this.pageIterator = EmptyIterator.INSTANCE;
                            }
                            if (this.queryType != null) {
                                Query jcrQuery = session.getWorkspace().getQueryManager().createQuery(this.query, this.queryType);
                                QueryResult result = jcrQuery.execute();
                                this.pageIterator = new NodeBasedPageIterator(pm, result.getNodes(), !allowDuplicates, this.pageFilter);
                            } else {
                                SimpleSearch search = this.getSearch(this.resource.getPath());
                                search.setQuery(this.query);
                                search.setSearchIn(this.startIn);
                                search.addPredicate(new Predicate("type", "type").set("type", "cq:Page"));
                                search.setHitsPerPage(100000);
                                SearchResult result = search.getResult();
                                this.pageIterator = new HitBasedPageIterator(pm, result.getHits().iterator(), !allowDuplicates, this.pageFilter);
                            }
                        } else if ("children".equals(this.source) || "descendants".equals(this.source)) {
                            parentPath = null;
                            boolean deep = false;
                            if ("children".equals(this.source)) {
                                parentPath = (String)this.properties.get("parentPage", (Object)this.resource.getPath());
                            } else if ("descendants".equals(this.source)) {
                                deep = true;
                                parentPath = (String)this.properties.get("ancestorPage", (Object)this.resource.getPath());
                            }
                            Page startPage = pm.getContainingPage(parentPath);
                            if (startPage != null) {
                                PageFilter pageFilter = this.pageFilter != null ? this.pageFilter : new PageFilter();
                                this.pageIterator = startPage.listChildren((Filter)pageFilter, deep);
                            } else {
                                this.pageIterator = EmptyIterator.INSTANCE;
                            }
                        } else if ("tags".equals(this.source)) {
                            parentPath = (String)this.properties.get("tagsSearchRoot", (Object)this.resource.getPath());
                            String[] tags = (String[])this.properties.get("tags", (Object)new String[0]);
                            boolean matchAny = ((String)this.properties.get("tagsMatch", (Object)"any")).equals("any");
                            Page startPage = pm.getContainingPage(parentPath);
                            if (startPage != null && tags.length > 0) {
                                TagManager tagManager = (TagManager)this.request.getResourceResolver().adaptTo(TagManager.class);
                                RangeIterator results = tagManager.find(startPage.getPath(), tags, matchAny);
                                LinkedHashMap<String, Page> pages = new LinkedHashMap<String, Page>();
                                while (results.hasNext()) {
                                    Resource r = (Resource)results.next();
                                    Page page = pm.getContainingPage(r);
                                    if (page == null || this.pageFilter != null && !this.pageFilter.includes(page)) continue;
                                    pages.put(page.getPath(), page);
                                }
                                this.pageIterator = pages.values().iterator();
                            } else {
                                this.pageIterator = EmptyIterator.INSTANCE;
                            }
                        } else {
                            String[] statics;
                            ArrayList<Page> staticPages = new ArrayList<Page>();
                            for (String path : statics = (String[])this.properties.get("pages", (Object)new String[0])) {
                                Page p = pm.getContainingPage(path);
                                if (p == null || this.pageFilter != null && !this.pageFilter.includes(p)) continue;
                                staticPages.add(p);
                            }
                            this.pageIterator = staticPages.iterator();
                        }
                    }
                    catch (Exception e) {
                        log.error("error creating page iterator", (Throwable)e);
                    }
                }
            }
            this.pages = new ArrayList<Page>();
            this.resources = new ArrayList<Resource>();
            if (this.pageIterator == null) {
                return false;
            }
            while (this.pageIterator.hasNext()) {
                Page page = this.pageIterator.next();
                this.pages.add(page);
            }
            if (this.orderComparator != null) {
                Collections.sort(this.pages, this.orderComparator);
            } else if (this.orderBy != null) {
                Collections.sort(this.pages, new PageComparator(this.orderBy));
            }
            if (this.pages.size() > this.limit) {
                this.pages = this.pages.subList(0, this.limit);
            }
            for (Page p : this.pages) {
                this.resources.add(p.getContentResource());
            }
            this.inited = true;
        }
        return true;
    }

    private void generateId() {
        String rootMarker;
        String path = this.resource.getPath();
        int root = path.indexOf(rootMarker = "jcr:content/");
        if (root >= 0) {
            path = path.substring(root + rootMarker.length());
        }
        this.id = path.replace('/', '_');
    }

    private SimpleSearch getSearch(String path) {
        try {
            Resource res = this.request.getResourceResolver().getResource(path);
            SimpleSearch search = (SimpleSearch)res.adaptTo(SimpleSearch.class);
            if (search != null) {
                return search;
            }
        }
        catch (Exception e) {
            // empty catch block
        }
        if (path.lastIndexOf("/") > 0) {
            return this.getSearch(Text.getRelativeParent((String)path, (int)1));
        }
        return null;
    }

    private String getParameter(String name) {
        return this.request.getParameter(this.id + "_" + name);
    }

    public Iterator<Resource> getResources() {
        return this.init() && this.resources.size() > 0 ? this.resources.iterator() : null;
    }

    public Iterator<Page> getPages() {
        if (this.init() && this.pages.size() > 0) {
            ArrayList<Page> plist = new ArrayList<Page>();
            int c = 0;
            for (int i = 0; i < this.pages.size(); ++i) {
                if (i < this.pageStart) continue;
                plist.add(this.pages.get(i));
                if (this.pageMaximum > 0 && ++c == this.pageMaximum) break;
            }
            return plist.iterator();
        }
        return null;
    }

    public Iterator<Node> getNodes() {
        return this.init() ? this.nodeIterator : null;
    }

    public boolean isOrdered() {
        return this.ordered;
    }

    public boolean isEmpty() {
        return !this.init() || this.resources.isEmpty();
    }

    public int size() {
        return this.init() ? this.resources.size() : 0;
    }

    public boolean isPaginating() {
        return this.pageStart > 0 || this.pageMaximum > 0 && this.size() > this.pageMaximum;
    }

    public int getPageStart() {
        return this.pageStart;
    }

    public int getPageMaximum() {
        return this.pageMaximum;
    }

    public String getNextPageLink() {
        if (this.isPaginating() && this.pageMaximum > 0 && this.pageStart + this.pageMaximum < this.size()) {
            int start = this.pageStart + this.pageMaximum;
            PageLink link = new PageLink(this.request);
            link.setParameter("start", start);
            return link.toString();
        }
        return null;
    }

    public String getPreviousPageLink() {
        if (this.isPaginating() && this.pageStart > 0) {
            int start = this.pageMaximum > 0 && this.pageStart > this.pageMaximum ? this.pageStart - this.pageMaximum : 0;
            PageLink link = new PageLink(this.request);
            link.setParameter("start", start);
            return link.toString();
        }
        return null;
    }

    public void setSource(String src) {
        this.source = src;
    }

    public void setQuery(String q) {
        this.setQuery(q, null);
    }

    public void setQuery(String q, String type) {
        this.query = q;
        this.queryType = type;
    }

    public void setStartIn(String start) {
        this.startIn = start;
    }

    public String getType() {
        return this.type;
    }

    public void setType(String t) {
        this.type = t;
    }

    public void setOrderComparator(Comparator<Page> obc) {
        this.orderComparator = obc;
    }

    public void setOrderBy(String ob) {
        this.orderBy = ob;
    }

    public void setOrdered(boolean o) {
        this.ordered = o;
    }

    public void setLimit(int l) {
        this.limit = l;
    }

    public void setPageMaximum(int pm) {
        this.pageMaximum = pm;
    }

    public void setPageStart(int psi) {
        this.pageStart = psi;
    }

    public void setPageIterator(Iterator<Page> iter) {
        this.pageIterator = iter;
        this.setSource("static");
    }

    private class HitBasedPageIterator
    extends AbstractPageIterator {
        private Iterator<Hit> hits;

        public HitBasedPageIterator(PageManager pm, Iterator<Hit> hits, boolean avoidDuplicates, PageFilter pageFilter) {
            super();
            this.pm = pm;
            this.hits = hits;
            if (avoidDuplicates) {
                this.seen = new HashSet();
            }
            this.pageFilter = pageFilter;
            this.nextPage = this.seek();
        }

        @Override
        protected Page seek() {
            while (this.hits != null && this.hits.hasNext()) {
                try {
                    Page page = this.pm.getContainingPage(this.hits.next().getResource());
                    if (page == null || this.seen != null && !this.seen.add(page.getPath()) || this.pageFilter != null && !this.pageFilter.includes(page)) continue;
                    return page;
                }
                catch (Exception e) {
                    List.log.error("Could not get page behind search result hit", (Throwable)e);
                    continue;
                }
            }
            return null;
        }
    }

    private class NodeBasedPageIterator
    extends AbstractPageIterator {
        private NodeIterator nodes;

        public NodeBasedPageIterator(PageManager pm, NodeIterator nodes, boolean avoidDuplicates, PageFilter pageFilter) {
            super();
            this.pm = pm;
            this.nodes = nodes;
            if (avoidDuplicates) {
                this.seen = new HashSet();
            }
            this.pageFilter = pageFilter;
            this.nextPage = this.seek();
        }

        @Override
        protected Page seek() {
            while (this.nodes != null && this.nodes.hasNext()) {
                try {
                    Page page = this.pm.getContainingPage(this.nodes.nextNode().getPath());
                    if (page == null || this.seen != null && !this.seen.add(page.getPath()) || this.pageFilter != null && !this.pageFilter.includes(page)) continue;
                    return page;
                }
                catch (Exception e) {
                    List.log.error("Could not get page behind result node", (Throwable)e);
                    continue;
                }
            }
            return null;
        }
    }

    private abstract class AbstractPageIterator
    implements Iterator<Page> {
        protected PageManager pm;
        protected Page nextPage;
        protected Set<String> seen;
        protected PageFilter pageFilter;

        private AbstractPageIterator() {
        }

        @Override
        public boolean hasNext() {
            return this.nextPage != null;
        }

        @Override
        public Page next() {
            if (!this.hasNext()) {
                throw new NoSuchElementException();
            }
            Page page = this.nextPage;
            this.nextPage = this.seek();
            return page;
        }

        protected abstract Page seek();

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }

    private class PageLink {
        private String path;
        private HashMap<String, Object> params;

        public PageLink(SlingHttpServletRequest request) {
            this.path = request.getPathInfo();
            PageManager pm = (PageManager)request.getResourceResolver().adaptTo(PageManager.class);
            Page page = pm.getContainingPage(this.path);
            if (page != null) {
                this.path = page.getPath() + ".html";
            }
            this.initParams(request.getQueryString());
        }

        public void addParameter(String name, Object value) {
            name = this.prefixName(name);
            this.params.put(name, value);
        }

        public void setParameter(String name, Object value) {
            if (this.params.containsKey(name = this.prefixName(name))) {
                this.params.remove(name);
            }
            this.addParameter(name, value);
        }

        public String toString() {
            String url = this.path;
            for (String param : this.params.keySet()) {
                url = this.appendParam(url, param, this.params.get(param));
            }
            return url;
        }

        private String prefixName(String name) {
            if (!name.startsWith(List.this.id + "_")) {
                name = List.this.id + "_" + name;
            }
            return name;
        }

        private void initParams(String query) {
            String[] pairs;
            this.params = new HashMap();
            for (String pair : pairs = Text.explode((String)query, (int)38)) {
                String[] param = Text.explode((String)pair, (int)61, (boolean)true);
                this.params.put(param[0], param[1]);
            }
        }

        private String appendParam(String url, String name, Object value) {
            char delim = url.indexOf(63) > 0 ? '&' : '?';
            return new StringBuffer(url).append(delim).append(name).append('=').append(value).toString();
        }
    }

    public class PageComparator<P extends Page>
    implements Comparator<P> {
        private String property;
        private boolean isDateProperty;

        public PageComparator(String prop) {
            this.property = prop;
            this.isDateProperty = this.isDate(prop);
        }

        @Override
        public int compare(P p1, P p2) {
            int comp = this.getKey(p1).compareTo(this.getKey(p2));
            return comp != 0 && this.isDateProperty ? - comp : comp;
        }

        private String getKey(P p) {
            return (String)p.getProperties().get(this.property, (Object)"");
        }

        private boolean isDate(String prop) {
            return prop.matches("jcr:created") || prop.matches("cq:lastModified") || prop.matches("cq:lastPublished");
        }
    }

}