DurboImportTransformer.java 29.5 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
/*
 * Decompiled with CFR 0_118.
 * 
 * Could not load the following classes:
 *  com.day.durbo.DurboInput
 *  com.day.durbo.DurboInput$Element
 *  com.day.durbo.DurboInput$Node
 *  com.day.durbo.DurboInput$Property
 *  javax.jcr.ItemNotFoundException
 *  javax.jcr.NamespaceException
 *  javax.jcr.NamespaceRegistry
 *  javax.jcr.Node
 *  javax.jcr.NodeIterator
 *  javax.jcr.Property
 *  javax.jcr.PropertyIterator
 *  javax.jcr.PropertyType
 *  javax.jcr.RepositoryException
 *  javax.jcr.Session
 *  javax.jcr.Value
 *  javax.jcr.ValueFactory
 *  javax.jcr.Workspace
 *  javax.jcr.nodetype.ConstraintViolationException
 *  javax.jcr.nodetype.NodeType
 *  javax.jcr.nodetype.NodeTypeManager
 *  javax.jcr.nodetype.PropertyDefinition
 *  org.apache.jackrabbit.util.Text
 *  org.slf4j.Logger
 *  org.slf4j.LoggerFactory
 */
package com.day.cq.replication.impl.content.durbo;

import com.day.cq.replication.ReplicationException;
import com.day.cq.replication.impl.content.durbo.AutoSave;
import com.day.cq.replication.impl.content.durbo.DurboImportConfiguration;
import com.day.cq.replication.impl.content.durbo.DurboUtil;
import com.day.durbo.DurboInput;
import java.io.EOFException;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import javax.jcr.ItemNotFoundException;
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.PropertyType;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.jcr.Workspace;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.nodetype.NodeType;
import javax.jcr.nodetype.NodeTypeManager;
import javax.jcr.nodetype.PropertyDefinition;
import org.apache.jackrabbit.util.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

class DurboImportTransformer {
    public static final String NS_SV_PREFIX = "sv";
    public static final String NS_SV_URI = "http://www.jcp.org/jcr/sv/1.0";
    private static final Logger logger = LoggerFactory.getLogger(DurboImportTransformer.class);
    protected final Session session;
    private final DurboInput input;
    private AutoSave autoSave;
    private final ValueFactory valueFactory;
    private final NodeTypeManager nodeTypeManager;
    private boolean useStableUUIDs = false;
    private Set<String> pathsToUseStableUUIDs = new HashSet<String>();
    private Set<String> nodeTypesToUseStableUUIDs = new HashSet<String>();
    protected final List<String> failedPaths = new LinkedList<String>();
    private DurboImportConfiguration configuration;
    private Set<String> ignoredProperties;

    DurboImportTransformer(DurboImportConfiguration configuration, Session session, DurboInput input) throws RepositoryException {
        this.configuration = configuration;
        this.session = session;
        this.valueFactory = session.getValueFactory();
        this.nodeTypeManager = session.getWorkspace().getNodeTypeManager();
        this.input = input;
        this.autoSave = new AutoSave(configuration.getSaveThreshold());
        this.useStableUUIDs = configuration.isPreserveUUID();
        this.nodeTypesToUseStableUUIDs = configuration.getPreserveUUIDForNodeTypes();
        this.pathsToUseStableUUIDs = configuration.getPreserveUUIDInSubtrees();
        this.ignoredProperties = new HashSet<String>(DurboUtil.IGNORED_PROPERTIES);
        NodeTypeManager nodeTypeManager = session.getWorkspace().getNodeTypeManager();
        for (String nodeType : configuration.getIgnoredNodeTypes()) {
            PropertyDefinition[] declaredProps;
            for (PropertyDefinition propDef : declaredProps = nodeTypeManager.getNodeType(nodeType).getPropertyDefinitions()) {
                this.ignoredProperties.add(propDef.getName());
            }
        }
    }

    public Node transform(Node parent, DurboInput.Node element) throws RepositoryException, IOException, ReplicationException {
        return this.traverse(parent, element, null);
    }

    private Node traverse(Node parent, DurboInput.Node element, Map<String, Boolean> snsInfo) throws ReplicationException, RepositoryException, IOException {
        String nodeName = this.resolveName((DurboInput.Element)element);
        if (logger.isDebugEnabled()) {
            logger.debug("traversing node {}/{}", (Object)parent.getPath(), (Object)nodeName);
        }
        if (DurboUtil.IGNORED_NODES.contains(nodeName) || "rep:policy".equals(nodeName) && !this.configuration.isImportAcl()) {
            if (logger.isInfoEnabled()) {
                logger.info("skipping node {}/{}", (Object)parent.getPath(), (Object)nodeName);
            }
            this.input.skipNode();
            return null;
        }
        DurboInput.Element nextElement = this.input.read();
        HashMap<String, DurboInput.Property> properties = new HashMap<String, DurboInput.Property>();
        while (nextElement != null && nextElement.isProperty()) {
            String name = this.resolveName(nextElement);
            properties.put(name, (DurboInput.Property)nextElement);
            nextElement = this.input.read();
        }
        String primaryNodeType = DurboImportTransformer.getString(properties, "jcr:primaryType");
        if (primaryNodeType == null) {
            throw new ReplicationException("Primary node type property is missing after node start.");
        }
        if (DurboUtil.isAuthorizableNodeType(primaryNodeType, 3)) {
            logger.info("authorizable node {}", (Object)(parent.getPath() + "/" + nodeName + " (" + primaryNodeType + ")"));
            return this.addAuthorizable(parent, nodeName, nextElement, properties);
        }
        if (this.isPolicyNodeType(primaryNodeType)) {
            logger.info("policy node {}", (Object)(parent.getPath() + "/" + nodeName + " (" + primaryNodeType + ")"));
            return this.addPolicy(parent, nodeName, nextElement, properties);
        }
        Set<String> mixinNodeTypes = Collections.emptySet();
        DurboInput.Property property = properties.get("jcr:mixinTypes");
        if (property != null) {
            mixinNodeTypes = new HashSet();
            mixinNodeTypes.addAll(Arrays.asList(Text.explode((String)property.getString(), (int)44)));
        }
        String uuid = DurboImportTransformer.getString(properties, "jcr:uuid");
        Node createdNode = this.createNode(parent, nodeName, primaryNodeType, mixinNodeTypes, uuid, snsInfo);
        for (Map.Entry<String, DurboInput.Property> entry : properties.entrySet()) {
            Value[] values;
            String name = entry.getKey();
            if (this.ignoredProperties.contains(name)) continue;
            property = entry.getValue();
            if (createdNode.hasProperty(name) && createdNode.getProperty(name).getDefinition().isProtected() || (values = property.getJcrValues(this.valueFactory)) == null) continue;
            try {
                if (property.isMultiple()) {
                    createdNode.setProperty(name, values);
                    continue;
                }
                if (values.length <= 0) continue;
                Value value = values[0];
                this.importSingleValue(property, createdNode, name, value);
            }
            catch (ConstraintViolationException re) {
                logger.info("Unable to set (protected) property '" + createdNode.getPath() + "/" + name + "' : " + (Object)re);
            }
        }
        Map<String, Boolean> childSNSInfo = this.prepareForSNS(createdNode);
        while (nextElement != null && !nextElement.isNodeEnd()) {
            String name = this.resolveName(nextElement);
            if (nextElement.isProperty()) {
                logger.warn("Unexpected property after child nodes at {}/{}", (Object)createdNode.getPath(), (Object)name);
            } else {
                this.traverse(createdNode, (DurboInput.Node)nextElement, childSNSInfo);
            }
            if (this.autoSave.needsSave()) {
                this.autoSave.save(this.session);
            }
            nextElement = this.input.read();
        }
        if (nextElement == null) {
            throw new EOFException("Unexpected end of input");
        }
        return createdNode;
    }

    protected void importSingleValue(DurboInput.Property property, Node createdNode, String name, Value value) throws RepositoryException {
        createdNode.setProperty(name, value);
    }

    private Node createNode(Node parent, String name, String primaryNodeType, Set<String> mixinNodeTypes, String uuid, Map<String, Boolean> snsInfo) throws RepositoryException {
        Node createdNode;
        if (parent.hasNode(name) && (snsInfo == null || Boolean.FALSE.equals(snsInfo.get(name)))) {
            NodeIterator nIter;
            Node childNode;
            Node currentChildNode = parent.getNode(name);
            boolean requiresRemoval = !currentChildNode.getPrimaryNodeType().getName().equals(primaryNodeType);
            int isRemovable = 1;
            if (requiresRemoval |= this.reuseUUID(primaryNodeType, parent.getPath()) && uuid != null && currentChildNode.isNodeType("{http://www.jcp.org/jcr/mix/1.0}referenceable") && !currentChildNode.getUUID().equals(uuid)) {
                nIter = currentChildNode.getNodes();
                while (isRemovable != 0 && nIter.hasNext()) {
                    childNode = nIter.nextNode();
                    if (!childNode.isNodeType("{http://www.jcp.org/jcr/nt/1.0}hierarchyNode") && !childNode.isNodeType("rep:Policy")) continue;
                    isRemovable = 0;
                }
            }
            if (requiresRemoval) {
                if (isRemovable != 0) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Node at {} already exists with wrong node type/uuid. Recreating node.", (Object)currentChildNode.getPath());
                    }
                    currentChildNode.remove();
                    createdNode = this.addNode(parent, name, primaryNodeType, mixinNodeTypes, uuid);
                } else {
                    createdNode = currentChildNode;
                    if (logger.isInfoEnabled()) {
                        logger.info("Node at {} already exists with wrong node type/uuid", (Object)createdNode.getPath());
                    }
                }
            } else {
                createdNode = currentChildNode;
                if (logger.isDebugEnabled()) {
                    logger.debug("Node at {} already exists, not creating new one.", (Object)createdNode.getPath());
                }
            }
            nIter = createdNode.getNodes();
            while (nIter.hasNext()) {
                childNode = nIter.nextNode();
                if (childNode.isNodeType("{http://www.jcp.org/jcr/nt/1.0}hierarchyNode") || childNode.isNodeType("rep:Policy")) continue;
                childNode.remove();
            }
            PropertyIterator pIter = createdNode.getProperties();
            while (pIter.hasNext()) {
                Property childProp = pIter.nextProperty();
                if (childProp.getDefinition().isProtected() || childProp.getDefinition().isMandatory()) continue;
                childProp.remove();
            }
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug("Creating new node {} with node type: {}", (Object)(parent.getPath() + '/' + name), (Object)primaryNodeType);
            }
            createdNode = this.addNode(parent, name, primaryNodeType, mixinNodeTypes, uuid);
        }
        if (snsInfo != null) {
            snsInfo.put(name, true);
        }
        HashSet<String> mixins = new HashSet<String>();
        for (NodeType nt : createdNode.getMixinNodeTypes()) {
            String ntName = nt.getName();
            mixins.add(ntName);
            if (mixinNodeTypes.contains(ntName) || DurboUtil.IGNORED_MIXIN_TYPES.contains(ntName) || this.configuration.getIgnoredNodeTypes().contains(ntName)) continue;
            createdNode.removeMixin(ntName);
        }
        for (String nt2 : mixinNodeTypes) {
            if (mixins.contains(nt2) || this.configuration.getIgnoredNodeTypes().contains(nt2)) continue;
            createdNode.addMixin(nt2);
        }
        this.autoSave.modified(1);
        return createdNode;
    }

    private Node addNode(Node parent, String name, String primaryNodeType, Set<String> mixins, String uuid) throws RepositoryException {
        String parentPath = parent.getPath();
        if (uuid == null || !this.reuseUUID(primaryNodeType, parentPath)) {
            return parent.addNode(name, primaryNodeType);
        }
        try {
            String[] prefixes;
            ContentHandler handler = this.session.getImportContentHandler(parentPath, 1);
            handler.startDocument();
            for (String prefix : prefixes = this.session.getNamespacePrefixes()) {
                handler.startPrefixMapping(prefix, this.session.getNamespaceURI(prefix));
            }
            AttributesImpl attrs = new AttributesImpl();
            attrs.addAttribute("http://www.jcp.org/jcr/sv/1.0", "name", "sv:name", "CDATA", name);
            DurboImportTransformer.startElement(handler, "node", attrs);
            DurboImportTransformer.property(handler, "jcr:primaryType", "Name", false, primaryNodeType);
            if (mixins.size() > 0) {
                DurboImportTransformer.property(handler, "jcr:mixinTypes", "Name", true, mixins.toArray(new String[mixins.size()]));
            }
            DurboImportTransformer.property(handler, "jcr:uuid", "String", false, uuid);
            DurboImportTransformer.endElement(handler, "node");
            handler.endDocument();
            return parent.getNode(name);
        }
        catch (SAXException e) {
            Exception root = e.getException();
            if (root instanceof RepositoryException) {
                throw (RepositoryException)root;
            }
            throw new RepositoryException("Error while creating node", (Throwable)root);
        }
    }

    private Node addPolicy(Node parent, String nodeName, DurboInput.Element nextElement, Map<String, DurboInput.Property> properties) throws RepositoryException, IOException, ReplicationException {
        if (nextElement.isProperty()) {
            throw new RepositoryException("element " + nextElement.name() + " should not be a property");
        }
        try {
            String[] prefixes;
            ContentHandler handler = this.session.getImportContentHandler(parent.getPath(), 1);
            handler.startDocument();
            for (String prefix : prefixes = this.session.getNamespacePrefixes()) {
                handler.startPrefixMapping(prefix, this.session.getNamespaceURI(prefix));
            }
            this.traverseSubtree(handler, nextElement, "", nodeName, properties, null);
            handler.endDocument();
            return parent.getNode(nodeName);
        }
        catch (SAXException e) {
            Exception root = e.getException();
            if (root instanceof RepositoryException) {
                throw (RepositoryException)root;
            }
            throw new RepositoryException("Error while creating node", (Throwable)root);
        }
    }

    private Node addAuthorizable(Node parent, String nodeName, DurboInput.Element nextElement, Map<String, DurboInput.Property> properties) throws RepositoryException, IOException, ReplicationException {
        if (nextElement.isProperty()) {
            throw new RepositoryException("element " + nextElement.name() + " should not be a property");
        }
        String uuid = DurboImportTransformer.getString(properties, "jcr:uuid");
        Node existingNode = null;
        try {
            existingNode = this.session.getNodeByIdentifier(uuid);
            if (existingNode != null) {
                nodeName = existingNode.getName();
            }
        }
        catch (ItemNotFoundException var7_7) {
            // empty catch block
        }
        try {
            String[] prefixes;
            ContentHandler handler = this.session.getImportContentHandler(parent.getPath(), this.configuration.isPreserveUserPaths() ? 2 : 1);
            handler.startDocument();
            for (String prefix : prefixes = this.session.getNamespacePrefixes()) {
                handler.startPrefixMapping(prefix, this.session.getNamespaceURI(prefix));
            }
            HashMap<String, DurboInput.Property> binaries = new HashMap<String, DurboInput.Property>();
            HashMap<String, String> tmpPreservedNodePaths = new HashMap<String, String>();
            if (existingNode != null) {
                logger.info("Authorizable '{}' already exists at {}. Preserving sub tree.", (Object)DurboImportTransformer.getString(properties, "rep:principalName"), (Object)existingNode.getPath());
                NodeIterator children = existingNode.getNodes();
                while (children.hasNext()) {
                    Node child = children.nextNode();
                    if (!this.isPreservedNodeName(child.getName()) && !this.hasPreservedNodeType(child)) continue;
                    String tmpNodePath = "/tmp/" + UUID.randomUUID().toString();
                    String originalPath = child.getPath();
                    tmpPreservedNodePaths.put(tmpNodePath, originalPath);
                    this.session.move(originalPath, tmpNodePath);
                    if (!logger.isInfoEnabled()) continue;
                    logger.info("stashing node {} in {}.", (Object)originalPath, (Object)tmpNodePath);
                }
            }
            this.traverseSubtree(handler, nextElement, "", nodeName, properties, binaries);
            handler.endDocument();
            Node n = uuid != null ? this.session.getNodeByIdentifier(uuid) : parent.getNode(nodeName);
            if (!tmpPreservedNodePaths.isEmpty()) {
                for (Map.Entry<String, DurboInput.Property> entry : tmpPreservedNodePaths.entrySet()) {
                    String restoredPath = n.getPath() + "/" + Text.getName((String)((String)entry.getValue()));
                    if (this.session.nodeExists(restoredPath)) {
                        logger.info("saved node at {} was imported. not reverting.", (Object)restoredPath);
                        continue;
                    }
                    String tmpPath = entry.getKey();
                    this.session.move(tmpPath, restoredPath);
                    logger.info("reverting node {} from {}.", (Object)restoredPath, (Object)tmpPath);
                }
            }
            for (Map.Entry<String, DurboInput.Property> entry : binaries.entrySet()) {
                String relPath = entry.getKey();
                if (logger.isDebugEnabled()) {
                    logger.debug("handling binary property {}/{}", (Object)n.getPath(), (Object)relPath);
                }
                Node binaryNode = n.getNode(Text.getRelativeParent((String)relPath, (int)1));
                String name = Text.getName((String)relPath);
                DurboInput.Property binary = entry.getValue();
                Value[] vs = binary.getJcrValues(this.valueFactory);
                if (binary.isMultiple()) {
                    binaryNode.setProperty(name, vs);
                    continue;
                }
                binaryNode.setProperty(name, vs[0]);
            }
            return n;
        }
        catch (SAXException e) {
            Exception root = e.getException();
            if (root instanceof RepositoryException) {
                throw (RepositoryException)root;
            }
            throw new RepositoryException("Error while creating node", (Throwable)root);
        }
    }

    private boolean isPreservedNodeName(String name) throws RepositoryException {
        return ".tokens".equals(name) || this.configuration.getPreservedNodeNames().contains(name);
    }

    private boolean hasPreservedNodeType(Node node) throws RepositoryException {
        boolean preserve = false;
        for (String nt : this.configuration.getPreservedNodeTypes()) {
            if (!node.isNodeType(nt)) continue;
            preserve = true;
            break;
        }
        return preserve;
    }

    private void traverseSubtree(ContentHandler handler, DurboInput.Element nextElement, String relPath, String nodeName, Map<String, DurboInput.Property> properties, Map<String, DurboInput.Property> binaries) throws SAXException, RepositoryException, IOException {
        AttributesImpl attrs = new AttributesImpl();
        attrs.addAttribute("http://www.jcp.org/jcr/sv/1.0", "name", "sv:name", "CDATA", nodeName);
        DurboImportTransformer.startElement(handler, "node", attrs);
        String primaryNodeType = null;
        boolean isUser = false;
        for (Map.Entry<String, DurboInput.Property> entry : properties.entrySet()) {
            String[] strvs;
            String name = entry.getKey();
            if (DurboUtil.IGNORED_SYSVIEW_PROPERTIES.contains(name)) continue;
            DurboInput.Property prop = entry.getValue();
            if (2 == prop.getType()) {
                if (binaries == null) continue;
                logger.debug("binary property -> import postponed.");
                binaries.put(relPath + name, prop);
                continue;
            }
            if (name.equals("jcr:mixinTypes")) {
                strvs = Text.explode((String)prop.getString(), (int)44);
            } else {
                Value[] vs = prop.getJcrValues(this.valueFactory);
                strvs = new String[vs.length];
                for (int i = 0; i < vs.length; ++i) {
                    strvs[i] = vs[i].getString();
                }
            }
            DurboImportTransformer.property(handler, name, PropertyType.nameFromValue((int)prop.getType()), prop.isMultiple(), strvs);
            if (!name.equals("jcr:primaryType")) continue;
            primaryNodeType = prop.getString();
            isUser = DurboUtil.isAuthorizableNodeType(primaryNodeType, 1);
        }
        while (nextElement != null && !nextElement.isNodeEnd()) {
            String name = this.resolveName(nextElement);
            if (nextElement.isProperty()) {
                logger.warn("Unexpected property after child nodes at {}{}", (Object)relPath, (Object)name);
            } else if (DurboUtil.IGNORED_NODES.contains(name)) {
                if (logger.isInfoEnabled()) {
                    logger.info("skipping node {}{}", (Object)relPath, (Object)name);
                }
                this.input.skipNode();
            } else if (isUser && name.equals(".tokens")) {
                if (logger.isInfoEnabled()) {
                    logger.info("skipping .tokens node of user {}{}", (Object)relPath, (Object)nodeName);
                }
                this.input.skipNode();
            } else {
                properties.clear();
                nextElement = this.input.read();
                while (nextElement != null && nextElement.isProperty()) {
                    String propName = this.resolveName(nextElement);
                    properties.put(propName, (DurboInput.Property)nextElement);
                    nextElement = this.input.read();
                }
                if (!this.reuseUUID(primaryNodeType, relPath)) {
                    properties.remove("jcr:uuid");
                }
                this.traverseSubtree(handler, nextElement, relPath + name + "/", name, properties, binaries);
            }
            nextElement = this.input.read();
        }
        if (nextElement == null) {
            throw new EOFException("Unexpected end of input");
        }
        DurboImportTransformer.endElement(handler, "node");
    }

    private static String getString(Map<String, DurboInput.Property> properties, String name) {
        DurboInput.Property property = properties.get(name);
        return property == null ? null : property.getString();
    }

    private Map<String, Boolean> prepareForSNS(Node parentNode) throws RepositoryException {
        HashMap<String, Boolean> info = new HashMap<String, Boolean>();
        NodeIterator iter = parentNode.getNodes();
        while (iter.hasNext()) {
            Node child = iter.nextNode();
            Boolean exists = info.get(child.getName());
            if (exists != null) {
                child.remove();
                continue;
            }
            info.put(child.getName(), false);
        }
        return info;
    }

    private boolean isPolicyNodeType(String ntName) throws RepositoryException {
        return this.nodeTypeManager.getNodeType(ntName).isNodeType("rep:Policy");
    }

    private String resolveName(DurboInput.Element elem) throws RepositoryException {
        String uri = elem.uri();
        String localName = elem.localName();
        if (uri == null) {
            return localName;
        }
        String pfx = elem.prefix();
        try {
            pfx = this.session.getNamespacePrefix(uri);
        }
        catch (NamespaceException e) {
            pfx = this.registerNamespace(pfx, uri);
        }
        return pfx + ":" + localName;
    }

    private String registerNamespace(String pfxHint, String uri) throws RepositoryException {
        int i = 0;
        String pfx = pfxHint;
        NamespaceException error = null;
        while (i < 1000) {
            try {
                this.session.getWorkspace().getNamespaceRegistry().registerNamespace(pfx, uri);
                return pfx;
            }
            catch (NamespaceException e) {
                pfx = pfxHint + i++;
                error = e;
                continue;
            }
        }
        throw new RepositoryException("Giving up automatic namespace registration after 1000 attempts.", (Throwable)error);
    }

    private boolean reuseUUID(String nodeType, String nodePath) {
        boolean reuseUUIDs = false;
        String parentPath = nodePath + "/";
        if (nodeType != null && this.useStableUUIDs && !this.nodeTypesToUseStableUUIDs.isEmpty() && !this.pathsToUseStableUUIDs.isEmpty() && this.nodeTypesToUseStableUUIDs.contains(nodeType)) {
            for (String path : this.pathsToUseStableUUIDs) {
                if (parentPath.startsWith(path)) {
                    reuseUUIDs = true;
                    break;
                }
                reuseUUIDs = false;
            }
        }
        return reuseUUIDs;
    }

    private static /* varargs */ void property(ContentHandler handler, String name, String type, boolean isMultiple, String ... values) throws SAXException {
        AttributesImpl attrs = new AttributesImpl();
        attrs.addAttribute("http://www.jcp.org/jcr/sv/1.0", "name", "sv:name", "CDATA", name);
        attrs.addAttribute("http://www.jcp.org/jcr/sv/1.0", "type", "sv:type", "CDATA", type);
        if (isMultiple) {
            attrs.addAttribute("http://www.jcp.org/jcr/sv/1.0", "multiple", "sv:multiple", "CDATA", "true");
        }
        DurboImportTransformer.startElement(handler, "property", attrs);
        for (String value : values) {
            attrs.clear();
            DurboImportTransformer.startElement(handler, "value", attrs);
            char[] valueChars = value.toCharArray();
            handler.characters(valueChars, 0, valueChars.length);
            DurboImportTransformer.endElement(handler, "value");
        }
        DurboImportTransformer.endElement(handler, "property");
    }

    private static void startElement(ContentHandler handler, String name, Attributes atts) throws SAXException {
        handler.startElement("http://www.jcp.org/jcr/sv/1.0", name, "sv:" + name, atts);
    }

    private static void endElement(ContentHandler handler, String name) throws SAXException {
        handler.endElement("http://www.jcp.org/jcr/sv/1.0", name, "sv:" + name);
    }

    List<String> getFailedPaths() {
        return this.failedPaths;
    }

    public static Node addSimpleAuthorizable(Node parent, String nodeName, String primaryNodeType, Map<String, String> properties) throws RepositoryException {
        try {
            String[] prefixes;
            Session session = parent.getSession();
            ContentHandler handler = session.getImportContentHandler(parent.getPath(), 3);
            handler.startDocument();
            for (String prefix : prefixes = session.getNamespacePrefixes()) {
                handler.startPrefixMapping(prefix, session.getNamespaceURI(prefix));
            }
            AttributesImpl attrs = new AttributesImpl();
            attrs.addAttribute("http://www.jcp.org/jcr/sv/1.0", "name", "sv:name", "CDATA", nodeName);
            DurboImportTransformer.startElement(handler, "node", attrs);
            DurboImportTransformer.property(handler, "jcr:primaryType", "Name", false, primaryNodeType);
            DurboImportTransformer.property(handler, "rep:principalName", "String", false, properties.get("rep:principalName"));
            String authorizableId = properties.get("rep:authorizableId");
            if (authorizableId != null) {
                DurboImportTransformer.property(handler, "rep:authorizableId", "String", false, authorizableId);
            }
            DurboImportTransformer.property(handler, "jcr:uuid", "String", false, properties.get("jcr:uuid"));
            DurboImportTransformer.endElement(handler, "node");
            handler.endDocument();
            Node n = parent.getNode(nodeName);
            return n;
        }
        catch (SAXException e) {
            logger.error("Cannot create authorizable {}", (Object)nodeName, (Object)e);
            return null;
        }
    }
}