RepositoryCopier.java 20.8 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  javax.jcr.Credentials
 *  javax.jcr.NamespaceException
 *  javax.jcr.NamespaceRegistry
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.Property
 *  javax.jcr.PropertyIterator
 *  javax.jcr.Repository
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.Value
 *  javax.jcr.Workspace
 *  javax.jcr.nodetype.NodeDefinition
 *  javax.jcr.nodetype.NodeType
 *  javax.jcr.nodetype.PropertyDefinition
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.jcr.vault.util;

import com.day.jcr.vault.fs.api.ProgressTrackerListener;
import com.day.jcr.vault.fs.api.RepositoryAddress;
import com.day.jcr.vault.fs.api.WorkspaceFilter;
import com.day.jcr.vault.util.RepositoryProvider;
import com.day.jcr.vault.util.Text;
import java.util.Calendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import javax.jcr.Credentials;
import javax.jcr.NamespaceException;
import javax.jcr.NamespaceRegistry;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.Workspace;
import javax.jcr.nodetype.NodeDefinition;
import javax.jcr.nodetype.NodeType;
import javax.jcr.nodetype.PropertyDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

public class RepositoryCopier {
    private static final Logger log = LoggerFactory.getLogger(RepositoryCopier.class);
    protected ProgressTrackerListener tracker;
    private int numNodes = 0;
    private int totalNodes = 0;
    private long totalSize = 0;
    private long currentSize = 0;
    private int batchSize = 1024;
    private long throttle = 0;
    private long start = 0;
    private String lastKnownGood;
    private String currentPath;
    private String resumeFrom;
    private WorkspaceFilter srcFilter;
    private Map<String, String> prefixMapping = new HashMap<String, String>();
    private boolean onlyNewer;
    private boolean update;
    private boolean noOrdering;
    private Session srcSession;
    private Session dstSession;
    private String cqLastModified;
    private volatile boolean abort;

    public void setTracker(ProgressTrackerListener tracker) {
        this.tracker = tracker;
    }

    public int getBatchSize() {
        return this.batchSize;
    }

    public void setBatchSize(int batchSize) {
        this.batchSize = batchSize;
    }

    public long getThrottle() {
        return this.throttle;
    }

    public void setThrottle(long throttle) {
        this.throttle = throttle;
    }

    public void setSourceFilter(WorkspaceFilter srcFilter) {
        this.srcFilter = srcFilter;
    }

    public void setOnlyNewer(boolean onlyNewer) {
        this.onlyNewer = onlyNewer;
    }

    public void setUpdate(boolean update) {
        this.update = update;
    }

    public boolean isNoOrdering() {
        return this.noOrdering;
    }

    public void setNoOrdering(boolean noOrdering) {
        this.noOrdering = noOrdering;
    }

    public boolean isOnlyNewer() {
        return this.onlyNewer;
    }

    public boolean isUpdate() {
        return this.update;
    }

    public WorkspaceFilter getSrcFilter() {
        return this.srcFilter;
    }

    public String getResumeFrom() {
        return this.resumeFrom;
    }

    public void setResumeFrom(String resumeFrom) {
        this.resumeFrom = resumeFrom;
    }

    public String getLastKnownGood() {
        return this.lastKnownGood;
    }

    public String getCurrentPath() {
        return this.currentPath;
    }

    public int getCurrentNumNodes() {
        return this.numNodes;
    }

    public int getTotalNodes() {
        return this.totalNodes;
    }

    public long getTotalSize() {
        return this.totalSize;
    }

    public long getCurrentSize() {
        return this.currentSize;
    }

    public void abort() {
        this.abort = true;
    }

    /*
     * WARNING - Removed try catching itself - possible behaviour change.
     */
    public void copy(RepositoryAddress src, RepositoryAddress dst, boolean recursive) {
        Object[] arrobject = new Object[3];
        arrobject[0] = src;
        arrobject[1] = dst;
        arrobject[2] = recursive ? "" : "non-";
        this.track("", "Copy %s to %s (%srecursive)", arrobject);
        Session srcSession = null;
        Session dstSession = null;
        try {
            Repository dstRepo;
            Repository srcRepo;
            RepositoryProvider repProvider = new RepositoryProvider();
            try {
                srcRepo = repProvider.getRepository(src);
            }
            catch (RepositoryException e) {
                log.error("Error while retrieving src repository {}: {}", (Object)src, (Object)e.toString());
                if (srcSession != null) {
                    srcSession.logout();
                }
                if (dstSession != null) {
                    dstSession.logout();
                }
                return;
            }
            try {
                dstRepo = repProvider.getRepository(dst);
            }
            catch (RepositoryException e) {
                log.error("Error while retrieving dst repository {}: {}", (Object)dst, (Object)e.toString());
                if (srcSession != null) {
                    srcSession.logout();
                }
                if (dstSession != null) {
                    dstSession.logout();
                }
                return;
            }
            try {
                Credentials srcCreds = src.getCredentials();
                srcSession = srcRepo.login(srcCreds, src.getWorkspace());
            }
            catch (RepositoryException e) {
                log.error("Error while logging in src repository {}: {}", (Object)src, (Object)e.toString());
                if (srcSession != null) {
                    srcSession.logout();
                }
                if (dstSession != null) {
                    dstSession.logout();
                }
                return;
            }
            try {
                Credentials dstCreds = dst.getCredentials();
                dstSession = dstRepo.login(dstCreds, dst.getWorkspace());
            }
            catch (RepositoryException e) {
                log.error("Error while logging in dst repository {}: {}", (Object)dst, (Object)e.toString());
                if (srcSession != null) {
                    srcSession.logout();
                }
                if (dstSession != null) {
                    dstSession.logout();
                }
                return;
            }
            this.copy(srcSession, src.getPath(), dstSession, dst.getPath(), recursive);
        }
        finally {
            if (srcSession != null) {
                srcSession.logout();
            }
            if (dstSession != null) {
                dstSession.logout();
            }
        }
    }

    public void copy(Session srcSession, String srcPath, Session dstSession, String dstPath, boolean recursive) {
        Node dstRoot;
        Node srcRoot;
        if (srcSession == null || dstSession == null) {
            throw new IllegalArgumentException("no src or dst session provided");
        }
        this.srcSession = srcSession;
        this.dstSession = dstSession;
        String dstParent = Text.getRelativeParent(dstPath, 1);
        String dstName = this.checkNameSpace(Text.getName(dstPath));
        try {
            srcRoot = srcSession.getNode(srcPath);
        }
        catch (RepositoryException e) {
            log.error("Error while retrieving src node {}: {}", (Object)srcPath, (Object)e.toString());
            return;
        }
        try {
            dstRoot = dstSession.getNode(dstParent);
        }
        catch (RepositoryException e) {
            log.error("Error while retrieving dst parent node {}: {}", (Object)dstParent, (Object)e.toString());
            return;
        }
        try {
            this.cqLastModified = srcSession.getNamespacePrefix("http://www.day.com/jcr/cq/1.0") + ":lastModified";
        }
        catch (RepositoryException e) {
            // empty catch block
        }
        try {
            this.numNodes = 0;
            this.totalNodes = 0;
            this.currentSize = 0;
            this.totalSize = 0;
            this.start = System.currentTimeMillis();
            this.copy(srcRoot, dstRoot, dstName, recursive);
            if (this.numNodes > 0) {
                this.track("", "Saving %d nodes...", this.numNodes);
                dstSession.save();
                this.track("", "Done.", new Object[0]);
            }
            long end = System.currentTimeMillis();
            this.track("", "Copy completed. %d nodes in %dms. %d bytes", this.totalNodes, end - this.start, this.totalSize);
        }
        catch (RepositoryException e) {
            log.error("Error during copy: {}", (Object)e.toString());
        }
    }

    private void copy(Node src, Node dstParent, String dstName, boolean recursive) throws RepositoryException {
        String path;
        Node dst;
        if (this.abort) {
            return;
        }
        this.currentPath = path = src.getPath();
        String dstPath = dstParent.getPath() + "/" + dstName;
        if (this.srcFilter != null && !this.srcFilter.contains(path)) {
            this.track(path, "------ I", new Object[0]);
            return;
        }
        boolean skip = false;
        if (this.resumeFrom != null) {
            if (path.equals(this.resumeFrom)) {
                this.resumeFrom = null;
            } else {
                skip = true;
            }
        }
        boolean useSysView = src.getDefinition().isProtected();
        boolean isNew = false;
        boolean overwrite = this.update;
        if (dstParent.hasNode(dstName)) {
            dst = dstParent.getNode(dstName);
            if (skip) {
                this.track(path, "------ S", new Object[0]);
            } else if (overwrite) {
                if (this.onlyNewer && dstName.equals("jcr:content")) {
                    if (this.isNewer(src, dst)) {
                        Object[] arrobject = new Object[]{++this.totalNodes};
                        this.track(dstPath, "%06d U", arrobject);
                    } else {
                        overwrite = false;
                        recursive = false;
                        Object[] arrobject = new Object[]{++this.totalNodes};
                        this.track(dstPath, "%06d -", arrobject);
                    }
                } else {
                    Object[] arrobject = new Object[]{++this.totalNodes};
                    this.track(dstPath, "%06d U", arrobject);
                }
                if (useSysView) {
                    dst = this.sysCopy(src, dstParent, dstName);
                }
            } else {
                Object[] arrobject = new Object[]{++this.totalNodes};
                this.track(dstPath, "%06d -", arrobject);
            }
        } else {
            try {
                if (skip) {
                    this.track(path, "------ S", new Object[0]);
                    dst = null;
                } else {
                    dst = useSysView ? this.sysCopy(src, dstParent, dstName) : dstParent.addNode(dstName, src.getPrimaryNodeType().getName());
                }
                Object[] arrobject = new Object[]{++this.totalNodes};
                this.track(dstPath, "%06d A", arrobject);
                isNew = true;
            }
            catch (RepositoryException e) {
                log.warn("Error while adding node {} (ignored): {}", (Object)dstPath, (Object)e.toString());
                return;
            }
        }
        if (useSysView) {
            if (!skip) {
                this.trackTree(dst, isNew);
            }
        } else {
            HashSet<String> names = new HashSet<String>();
            if (!skip && (overwrite || isNew)) {
                PropertyIterator iter;
                if (!isNew) {
                    for (NodeType nt2 : dst.getMixinNodeTypes()) {
                        names.add(nt2.getName());
                    }
                    for (NodeType nt2 : src.getMixinNodeTypes()) {
                        String mixName = this.checkNameSpace(nt2.getName());
                        if (names.remove(mixName)) continue;
                        dst.addMixin(nt2.getName());
                    }
                    for (String mix : names) {
                        dst.removeMixin(mix);
                    }
                } else {
                    for (NodeType nt2 : src.getMixinNodeTypes()) {
                        dst.addMixin(this.checkNameSpace(nt2.getName()));
                    }
                }
                names.clear();
                if (!isNew) {
                    iter = dst.getProperties();
                    while (iter.hasNext()) {
                        names.add(this.checkNameSpace(iter.nextProperty().getName()));
                    }
                }
                iter = src.getProperties();
                while (iter.hasNext()) {
                    Property p = iter.nextProperty();
                    String pName = this.checkNameSpace(p.getName());
                    names.remove(pName);
                    if (p.getDefinition().isProtected()) continue;
                    if (dst.hasProperty(pName)) {
                        dst.getProperty(pName).remove();
                    }
                    if (p.getDefinition().isMultiple()) {
                        Value[] vs = p.getValues();
                        dst.setProperty(pName, vs);
                        for (long s : p.getLengths()) {
                            this.totalSize += s;
                            this.currentSize += s;
                        }
                        continue;
                    }
                    Value v = p.getValue();
                    dst.setProperty(pName, v);
                    long s = p.getLength();
                    this.totalSize += s;
                    this.currentSize += s;
                }
                for (String pName : names) {
                    try {
                        dst.getProperty(pName).remove();
                    }
                    catch (RepositoryException e) {}
                }
            }
            if (recursive && dst != null) {
                Node child;
                NodeIterator niter;
                names.clear();
                if (overwrite && !isNew) {
                    niter = dst.getNodes();
                    while (niter.hasNext()) {
                        names.add(this.checkNameSpace(niter.nextNode().getName()));
                    }
                }
                niter = src.getNodes();
                while (niter.hasNext()) {
                    child = niter.nextNode();
                    String cName = this.checkNameSpace(child.getName());
                    names.remove(cName);
                    this.copy(child, dst, cName, true);
                }
                if (this.resumeFrom == null) {
                    if (overwrite && !isNew && !this.noOrdering && src.getPrimaryNodeType().hasOrderableChildNodes()) {
                        niter = src.getNodes();
                        while (niter.hasNext()) {
                            child = niter.nextNode();
                            String name = child.getName();
                            if (!dst.hasNode(name)) continue;
                            dst.orderBefore(name, null);
                        }
                    }
                    for (String name : names) {
                        try {
                            Node cNode = dst.getNode(name);
                            this.track(cNode.getPath(), "%06d D", ++this.totalNodes);
                            cNode.remove();
                        }
                        catch (RepositoryException e) {}
                    }
                }
            }
        }
        if (!skip) {
            ++this.numNodes;
        }
        if (this.numNodes >= this.batchSize) {
            try {
                this.track("", "Intermediate saving %d nodes (%d kB)...", this.numNodes, this.currentSize / 1000);
                long now = System.currentTimeMillis();
                this.dstSession.save();
                long end = System.currentTimeMillis();
                this.track("", "Done in %d ms. Total time: %d, total nodes %d, %d kB", end - now, end - this.start, this.totalNodes, this.totalSize / 1000);
                this.lastKnownGood = this.currentPath;
                this.numNodes = 0;
                this.currentSize = 0;
                if (this.throttle > 0) {
                    Object[] arrobject = new Object[2];
                    arrobject[0] = this.throttle;
                    arrobject[1] = this.throttle == 1 ? "" : "s";
                    this.track("", "Throttling enabled. Waiting %d second%s...", arrobject);
                    try {
                        Thread.sleep(this.throttle * 1000);
                    }
                    catch (InterruptedException e) {}
                }
            }
            catch (RepositoryException e) {
                log.error("Error during intermediate save ({}); try again later: {}", (Object)this.numNodes, (Object)e.toString());
            }
        }
    }

    private Node sysCopy(Node src, Node dstParent, String dstName) throws RepositoryException {
        try {
            ContentHandler handler = dstParent.getSession().getImportContentHandler(dstParent.getPath(), 0);
            src.getSession().exportSystemView(src.getPath(), handler, true, false);
            return dstParent.getNode(dstName);
        }
        catch (SAXException e) {
            throw new RepositoryException("Unable to perform sysview copy", (Throwable)e);
        }
    }

    private void trackTree(Node node, boolean isNew) throws RepositoryException {
        NodeIterator iter = node.getNodes();
        while (iter.hasNext()) {
            Node child = iter.nextNode();
            if (isNew) {
                this.track(child.getPath(), "%06d A", ++this.totalNodes);
            } else {
                this.track(child.getPath(), "%06d U", ++this.totalNodes);
            }
            this.trackTree(child, isNew);
        }
    }

    private boolean isNewer(Node src, Node dst) {
        try {
            Calendar srcDate = null;
            Calendar dstDate = null;
            if (this.cqLastModified != null && src.hasProperty(this.cqLastModified) && dst.hasProperty(this.cqLastModified)) {
                srcDate = src.getProperty(this.cqLastModified).getDate();
                dstDate = dst.getProperty(this.cqLastModified).getDate();
            } else if (src.hasProperty("jcr:lastModified") && dst.hasProperty("jcr:lastModified")) {
                srcDate = src.getProperty("jcr:lastModified").getDate();
                dstDate = dst.getProperty("jcr:lastModified").getDate();
            }
            return srcDate == null || dstDate == null || srcDate.after(dstDate);
        }
        catch (RepositoryException e) {
            log.error("Unable to compare dates: {}", (Object)e.toString());
            return true;
        }
    }

    private String checkNameSpace(String name) {
        block9 : {
            try {
                int idx = name.indexOf(58);
                if (idx <= 0) break block9;
                String prefix = name.substring(0, idx);
                String mapped = this.prefixMapping.get(prefix);
                if (mapped == null) {
                    String uri = this.srcSession.getNamespaceURI(prefix);
                    try {
                        mapped = this.dstSession.getNamespacePrefix(uri);
                    }
                    catch (NamespaceException e) {
                        mapped = prefix;
                        int i = 0;
                        while (i >= 0) {
                            try {
                                this.dstSession.getWorkspace().getNamespaceRegistry().registerNamespace(mapped, uri);
                                i = -1;
                            }
                            catch (NamespaceException e1) {
                                mapped = prefix + i++;
                            }
                        }
                    }
                    this.prefixMapping.put(prefix, mapped);
                }
                if (mapped.equals(prefix)) {
                    return name;
                }
                return mapped + prefix.substring(idx);
            }
            catch (RepositoryException e) {
                log.error("Error processing namespace for {}: {}", (Object)name, (Object)e.toString());
            }
        }
        return name;
    }

    private /* varargs */ void track(String path, String fmt, Object ... args) {
        if (this.tracker != null) {
            this.tracker.onMessage(ProgressTrackerListener.Mode.TEXT, String.format(fmt, args), path);
        }
    }
}