ReferenceSearch.java 15.9 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.cq.commons.predicate.AbstractResourcePredicate
 *  com.day.cq.wcm.api.Page
 *  com.day.cq.wcm.api.PageManager
 *  com.day.cq.wcm.api.WCMException
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.Property
 *  javax.jcr.PropertyIterator
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.Value
 *  javax.jcr.ValueFactory
 *  org.apache.jackrabbit.util.Text
 *  org.apache.sling.api.SlingException
 *  org.apache.sling.api.resource.PersistenceException
 *  org.apache.sling.api.resource.Resource
 *  org.apache.sling.api.resource.ResourceResolver
 *  org.apache.sling.api.resource.ResourceUtil
 *  org.apache.sling.jcr.api.SlingRepository
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.wcm.commons;

import com.day.cq.commons.predicate.AbstractResourcePredicate;
import com.day.cq.wcm.api.Page;
import com.day.cq.wcm.api.PageManager;
import com.day.cq.wcm.api.WCMException;
import com.day.cq.wcm.commons.UGCUtil;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import org.apache.jackrabbit.util.Text;
import org.apache.sling.api.SlingException;
import org.apache.sling.api.resource.PersistenceException;
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.jcr.api.SlingRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ReferenceSearch {
    private SlingRepository repository;
    private static final Logger log = LoggerFactory.getLogger(ReferenceSearch.class);
    private String searchRoot = "/";
    private boolean exact = false;
    private boolean hollow = false;
    private int maxReferencesPerPage = -1;
    private AbstractResourcePredicate resourcePredicate = null;

    public ReferenceSearch setRepository(SlingRepository repository) {
        this.repository = repository;
        return this;
    }

    public String getSearchRoot() {
        return this.searchRoot;
    }

    public ReferenceSearch setSearchRoot(String searchRoot) {
        this.searchRoot = searchRoot == null || searchRoot.equals("") ? "/" : searchRoot;
        return this;
    }

    public boolean isExact() {
        return this.exact;
    }

    public ReferenceSearch setExact(boolean exact) {
        this.exact = exact;
        return this;
    }

    public boolean isHollow() {
        return this.hollow;
    }

    public ReferenceSearch setHollow(boolean hollow) {
        this.hollow = hollow;
        return this;
    }

    public int getMaxReferencesPerPage() {
        return this.maxReferencesPerPage;
    }

    public ReferenceSearch setMaxReferencesPerPage(int maxReferencesPerPage) {
        this.maxReferencesPerPage = maxReferencesPerPage;
        return this;
    }

    public ReferenceSearch setPredicate(AbstractResourcePredicate resourcePredicate) {
        this.resourcePredicate = resourcePredicate;
        return this;
    }

    public Map<String, Info> search(ResourceResolver resolver, String path) {
        if (path == null) {
            return Collections.emptyMap();
        }
        String root = this.searchRoot.equals("/") ? "" : this.searchRoot;
        PageManager manager = (PageManager)resolver.adaptTo(PageManager.class);
        HashMap<String, Info> infos = new HashMap<String, Info>();
        Pattern pattern = this.getSearchPattern(path);
        String qPath = ReferenceSearch.escapeIllegalXpathSearchChars(path);
        String query = String.format("%s//*[jcr:contains(., '\"%s\"')]", root, qPath);
        this.search(resolver, manager, infos, pattern, query);
        String escPath = Text.escapePath((String)path);
        if (!escPath.equals(path)) {
            Pattern escPattern = this.getSearchPattern(escPath);
            String qEscPath = ReferenceSearch.escapeIllegalXpathSearchChars(escPath);
            query = String.format("%s//*[jcr:contains(., '%s')]", root, qEscPath);
            this.search(resolver, manager, infos, escPattern, query);
        }
        Iterator<Map.Entry<String, Info>> entries = infos.entrySet().iterator();
        while (entries.hasNext()) {
            Resource pageResource;
            Map.Entry<String, Info> entry = entries.next();
            if (entry.getValue().getProperties().isEmpty()) {
                entries.remove();
                continue;
            }
            if (this.resourcePredicate == null || entry.getValue().page == null || (pageResource = (Resource)entry.getValue().page.adaptTo(Resource.class)) == null || this.resourcePredicate.evaluate(pageResource)) continue;
            entries.remove();
        }
        return infos;
    }

    private void search(ResourceResolver resolver, PageManager manager, Map<String, Info> infos, Pattern pattern, String query) {
        log.debug("Searching for references using: {}", (Object)query);
        Iterator iter = null;
        try {
            iter = resolver.findResources(query, "xpath");
        }
        catch (SlingException e) {
            log.warn("error finding resources", (Throwable)e);
            return;
        }
        while (iter.hasNext()) {
            Resource res = (Resource)iter.next();
            Page page = manager.getContainingPage(res);
            if (page == null) continue;
            Info info = infos.get(page.getPath());
            if (info == null) {
                info = new Info(page, this.hollow);
                infos.put(page.getPath(), info);
            }
            try {
                Node node = (Node)res.adaptTo(Node.class);
                PropertyIterator pIter = node.getProperties();
                block5 : while (pIter.hasNext() && (this.getMaxReferencesPerPage() < 0 || info.getProperties().size() < this.getMaxReferencesPerPage())) {
                    Property p = pIter.nextProperty();
                    if (p.getType() != 1 && p.getType() != 7) continue;
                    if (p.isMultiple()) {
                        for (Value v : p.getValues()) {
                            String value = v.getString();
                            if (!pattern.matcher(value).find()) continue;
                            info.addProperty(p.getPath());
                            continue block5;
                        }
                        continue;
                    }
                    String value = p.getString();
                    if (!pattern.matcher(value).find()) continue;
                    info.addProperty(p.getPath());
                }
                continue;
            }
            catch (RepositoryException e) {
                log.error("Error while accessing " + res.getPath(), (Throwable)e);
                continue;
            }
        }
    }

    public Collection<String> adjustReferences(ResourceResolver resolver, String path, String destination, String[] refPaths) {
        if (refPaths == null) {
            return Collections.emptyList();
        }
        HashSet<String> adjusted = new HashSet<String>();
        for (String p : refPaths) {
            Resource content;
            Resource r = resolver.getResource(p);
            if (r == null) {
                log.warn("Given path does not address a resource: {}", (Object)p);
                continue;
            }
            Page page = (Page)r.adaptTo(Page.class);
            if (page == null) {
                log.warn("Given path does not address a page: {}", (Object)p);
            }
            Resource resource = content = page != null ? page.getContentResource() : null;
            if (content == null) {
                log.warn("Given page does not have content: {}", (Object)p);
            }
            try {
                Node node = content != null ? (Node)content.adaptTo(Node.class) : (Node)r.adaptTo(Node.class);
                adjusted.addAll(this.adjustReferences(node, path, destination));
            }
            catch (RepositoryException e) {
                log.error("Error while adjusting references on " + r.getPath(), (Throwable)e);
            }
            try {
                String adjustedUGCPath = this.adjustUserGeneratedContentReference(r, path, destination);
                if (adjustedUGCPath == null) continue;
                adjusted.add(adjustedUGCPath);
                log.info("Adjusted user generated content path {}.", (Object)adjustedUGCPath);
                continue;
            }
            catch (Exception e) {
                log.error("Error while adjusting user generated references on " + r.getPath(), (Throwable)e);
            }
        }
        PageManager pm = (PageManager)resolver.adaptTo(PageManager.class);
        for (String pathOfAdjusted : adjusted) {
            Page adjustedPage;
            Resource adjustedResource = resolver.getResource(pathOfAdjusted);
            if (null == adjustedResource || null == (adjustedPage = pm.getContainingPage(adjustedResource))) continue;
            try {
                pm.touch((Node)adjustedPage.adaptTo(Node.class), true, Calendar.getInstance(), false);
            }
            catch (WCMException e) {
                log.error("could not update last modified on adjusted page [{}]: ", (Object)adjustedPage.getPath(), (Object)e);
            }
        }
        try {
            resolver.commit();
        }
        catch (PersistenceException e) {
            log.error("Error while adjusting references.", (Throwable)e);
        }
        return adjusted;
    }

    public Collection<String> adjustReferences(Node node, String path, String destination) throws RepositoryException {
        return this.adjustReferences(node, path, destination, false, Collections.<String>emptySet());
    }

    public Collection<String> adjustReferences(Node node, String path, String destination, boolean shallow, Set<String> excludedProperties) throws RepositoryException {
        HashSet<String> adjusted = new HashSet<String>();
        Pattern pattern = this.getReplacementPattern(path);
        String escDest = Text.escapePath((String)destination);
        PropertyIterator iter = node.getProperties();
        while (iter.hasNext()) {
            Property p = iter.nextProperty();
            if ((excludedProperties.contains(p.getName()) || p.getType() != 1) && p.getType() != 7) continue;
            if (p.isMultiple()) {
                Value[] values = p.getValues();
                boolean modified = false;
                for (int i = 0; i < values.length; ++i) {
                    String value = this.rewrite(values[i].getString(), path, pattern, destination, escDest);
                    if (value == null) continue;
                    values[i] = node.getSession().getValueFactory().createValue(value, p.getType());
                    modified = true;
                }
                if (!modified) continue;
                p.setValue(values);
                adjusted.add(p.getPath());
                log.info("Adjusted property {}.", (Object)p.getPath());
                continue;
            }
            String value = this.rewrite(p.getString(), path, pattern, destination, escDest);
            if (value == null) continue;
            p.setValue(value);
            adjusted.add(p.getPath());
            log.info("Adjusted property {}.", (Object)p.getPath());
        }
        if (!shallow) {
            iter = node.getNodes();
            while (iter.hasNext()) {
                adjusted.addAll(this.adjustReferences(iter.nextNode(), path, destination, shallow, excludedProperties));
            }
        }
        return adjusted;
    }

    private String adjustUserGeneratedContentReference(Resource resource, String path, String destination) throws RepositoryException, WCMException {
        String ugcPath = resource.getPath();
        if (ugcPath.startsWith("/content/usergenerated" + path)) {
            String newUgcPath = ugcPath.replaceFirst(path, destination);
            ResourceResolver resolver = resource.getResourceResolver();
            Resource newUgcResource = resolver.resolve(newUgcPath);
            if (ResourceUtil.isNonExistingResource((Resource)newUgcResource)) {
                PageManager pageManager = (PageManager)resolver.adaptTo(PageManager.class);
                String newUgcParentPath = Text.getRelativeParent((String)UGCUtil.UGCToResourcePath(newUgcResource), (int)1);
                UGCUtil.prepareUserGeneratedContent(resolver, newUgcParentPath);
                pageManager.move(resource, newUgcPath, Text.getName((String)resource.getPath()), true, true, new String[0]);
                return newUgcPath;
            }
        }
        return null;
    }

    protected Pattern getSearchPattern(String path) {
        if (this.exact) {
            return Pattern.compile("([\"']|^)(" + Pattern.quote(path) + ")([;.?#\"']|$)");
        }
        return Pattern.compile("([\"']|^)(" + Pattern.quote(path) + ")([;.?#\"'/](.*)|$)");
    }

    protected Pattern getReplacementPattern(String path) {
        String escPath = Text.escapePath((String)path);
        String literal = Pattern.quote(path);
        if (!escPath.equals(path)) {
            literal = literal + "|" + Pattern.quote(escPath);
        }
        if (this.exact) {
            return Pattern.compile("([\"'])(" + literal + ")([;.?#\"'])");
        }
        return Pattern.compile("([\"'])(" + literal + ")([;.?#\"'/])");
    }

    protected String rewrite(String value, String from, Pattern p, String to, String escTo) {
        if (value.equals(from)) {
            return to;
        }
        if (value.startsWith(from + "#") || value.startsWith(from + ".html")) {
            return to + value.substring(from.length());
        }
        if (!this.exact && value.startsWith(from + "/")) {
            return to + value.substring(from.length());
        }
        Matcher m = p.matcher(value);
        StringBuffer ret = null;
        String repl = "$1" + escTo + "$3";
        while (m.find()) {
            if (ret == null) {
                ret = new StringBuffer();
            }
            m.appendReplacement(ret, repl);
        }
        if (ret == null) {
            return null;
        }
        m.appendTail(ret);
        return ret.toString();
    }

    public static String escapeIllegalXpathSearchChars(String s) {
        StringBuffer sb = new StringBuffer();
        for (char c : s.toCharArray()) {
            if (c == '!' || c == '(' || c == ')' || c == ':' || c == '^' || c == '[' || c == ']' || c == '{' || c == '}' || c == '?' || c == '\"' || c == '\\' || c == ' ' || c == '~') {
                sb.append('\\');
            } else if (c == '\'') {
                sb.append(c);
            }
            sb.append(c);
        }
        return sb.toString();
    }

    public static final class Info {
        private final Page page;
        private final String pageTitle;
        private final String pagePath;
        private final Set<String> properties = new HashSet<String>();

        public Info(Page page) {
            this.page = page;
            this.pageTitle = page.getTitle();
            this.pagePath = page.getPath();
        }

        public Info(Page page, boolean hollow) {
            this.page = !hollow ? page : null;
            this.pageTitle = page.getTitle();
            this.pagePath = page.getPath();
        }

        private void addProperty(String path) {
            this.properties.add(path);
        }

        public Page getPage() {
            return this.page;
        }

        public Set<String> getProperties() {
            return this.properties;
        }

        public String getPageTitle() {
            return this.pageTitle;
        }

        public String getPagePath() {
            return this.pagePath;
        }
    }

}