Package org.modeshape.jcr.value

Examples of org.modeshape.jcr.value.Name


    protected MutableCachedNode createNamespace( SessionCache session,
                                                 MutableCachedNode parent,
                                                 String prefix,
                                                 String uri ) {
        Name nodeName = prefix.length() != 0 ? session.getContext().getValueFactories().getNameFactory().create(prefix) : ModeShapeLexicon.NAMESPACE;
        return createNode(session,
                          parent,
                          "mode:namespaces-" + uri,
                          nodeName,
                          ModeShapeLexicon.NAMESPACE,
View Full Code Here


        public void process( MutableCachedNode node,
                             SaveContext context ) throws Exception {
            // Most nodes do not need any extra processing, so the first thing to do is figure out whether this
            // node has a primary type or mixin types that need extra processing. Unfortunately, this means we always have
            // to get the primary type and mixin types.
            final Name primaryType = node.getPrimaryType(cache);
            final Set<Name> mixinTypes = node.getMixinTypes(cache);

            if (nodeTypeCapabilities.isFullyDefinedType(primaryType, mixinTypes)) {
                // There is nothing to do for this node ...
                return;
            }

            if (!initialized) {
                // We're gonna need a few more objects, so create them now ...
                initialized = true;
                versionManager = versionManager();
                propertyFactory = propertyFactory();
                referenceFactory = referenceFactory();
            }

            AbstractJcrNode jcrNode = null;

            // -----------
            // mix:created
            // -----------
            boolean initializeVersionHistory = false;
            if (node.isNew()) {
                if (nodeTypeCapabilities.isCreated(primaryType, mixinTypes)) {
                    // Set the created by and time information if not changed explicitly
                    node.setPropertyIfUnchanged(cache, propertyFactory.create(JcrLexicon.CREATED, context.getTime()));
                    node.setPropertyIfUnchanged(cache, propertyFactory.create(JcrLexicon.CREATED_BY, context.getUserId()));
                }
                initializeVersionHistory = nodeTypeCapabilities.isVersionable(primaryType, mixinTypes);
            } else {
                // Changed nodes can only be made versionable if the primary type or mixins changed ...
                if (node.hasChangedPrimaryType() || !node.getAddedMixins(cache).isEmpty()) {
                    initializeVersionHistory = nodeTypeCapabilities.isVersionable(primaryType, mixinTypes);
                }
            }

            // ----------------
            // mix:lastModified
            // ----------------
            if (nodeTypeCapabilities.isLastModified(primaryType, mixinTypes)) {
                // Set the last modified by and time information if it has not been changed explicitly
                node.setPropertyIfUnchanged(cache, propertyFactory.create(JcrLexicon.LAST_MODIFIED, context.getTime()));
                node.setPropertyIfUnchanged(cache, propertyFactory.create(JcrLexicon.LAST_MODIFIED_BY, context.getUserId()));
            }

            // ---------------
            // mix:versionable
            // ---------------
            if (initializeVersionHistory) {
                // See if there is a version history for the node ...
                NodeKey versionableKey = node.getKey();
                if (!systemContent.hasVersionHistory(versionableKey)) {
                    // Initialize the version history ...
                    NodeKey historyKey = systemContent.versionHistoryNodeKeyFor(versionableKey);
                    NodeKey baseVersionKey = baseVersionKeys == null ? null : baseVersionKeys.get(versionableKey);
                    // it may happen during an import, that a node with version history & base version is assigned a new key and
                    // therefore
                    // the base version points to an existing version while no version history is found initially
                    boolean shouldCreateNewVersionHistory = true;
                    if (baseVersionKey != null) {
                        CachedNode baseVersionNode = systemCache.getNode(baseVersionKey);
                        if (baseVersionNode != null) {
                            historyKey = baseVersionNode.getParentKey(systemCache);
                            shouldCreateNewVersionHistory = (historyKey == null);
                        }
                    }
                    if (shouldCreateNewVersionHistory) {
                        // a new version history should be initialized
                        assert historyKey != null;
                        if (baseVersionKey == null) baseVersionKey = historyKey.withRandomId();
                        NodeKey originalVersionKey = originalVersionKeys != null ? originalVersionKeys.get(versionableKey) : null;
                        Path versionHistoryPath = versionManager.versionHistoryPathFor(versionableKey);
                        systemContent.initializeVersionStorage(versionableKey, historyKey, baseVersionKey, primaryType,
                                                               mixinTypes, versionHistoryPath, originalVersionKey,
                                                               context.getTime());
                    }

                    // Now update the node as if it's checked in (with the exception of the predecessors...)
                    Reference historyRef = referenceFactory.create(historyKey, true);
                    Reference baseVersionRef = referenceFactory.create(baseVersionKey, true);
                    node.setProperty(cache, propertyFactory.create(JcrLexicon.IS_CHECKED_OUT, Boolean.TRUE));
                    node.setReference(cache, propertyFactory.create(JcrLexicon.VERSION_HISTORY, historyRef), systemCache);
                    node.setReference(cache, propertyFactory.create(JcrLexicon.BASE_VERSION, baseVersionRef), systemCache);
                    // JSR 283 - 15.1
                    node.setReference(cache, propertyFactory.create(JcrLexicon.PREDECESSORS, new Object[] {baseVersionRef}),
                                      systemCache);
                } else {
                    // we're dealing with node which has a version history, check if there any versionable properties present
                    boolean hasVersioningProperties = node.hasProperty(JcrLexicon.IS_CHECKED_OUT, cache)
                                                      || node.hasProperty(JcrLexicon.VERSION_HISTORY, cache)
                                                      || node.hasProperty(JcrLexicon.BASE_VERSION, cache)
                                                      || node.hasProperty(JcrLexicon.PREDECESSORS, cache);

                    if (!hasVersioningProperties) {
                        // the node doesn't have any versionable properties, so this is a case of mix:versionable removed at some
                        // point and then re-added. If it had any versioning properties, we might've been dealing with something
                        // else
                        // e.g. a restore

                        // Re-link the versionable properties, based on the existing version history
                        node.setProperty(cache, propertyFactory.create(JcrLexicon.IS_CHECKED_OUT, Boolean.TRUE));

                        JcrVersionHistoryNode versionHistoryNode = versionManager().getVersionHistory(node(node.getKey(), null));
                        Reference historyRef = referenceFactory.create(versionHistoryNode.key(), true);
                        node.setReference(cache, propertyFactory.create(JcrLexicon.VERSION_HISTORY, historyRef), systemCache);

                        // set the base version to the last existing version
                        JcrVersionNode baseVersion = null;
                        for (VersionIterator versionIterator = versionHistoryNode.getAllVersions(); versionIterator.hasNext();) {
                            JcrVersionNode version = (JcrVersionNode)versionIterator.nextVersion();
                            if (baseVersion == null || version.isLinearSuccessorOf(baseVersion)) {
                                baseVersion = version;
                            }
                        }
                        assert baseVersion != null;
                        Reference baseVersionRef = referenceFactory.create(baseVersion.key(), true);
                        node.setReference(cache, propertyFactory.create(JcrLexicon.BASE_VERSION, baseVersionRef), systemCache);

                        // set the predecessors to the same list as the base version's predecessors
                        Version[] baseVersionPredecessors = baseVersion.getPredecessors();
                        Reference[] predecessors = new Reference[baseVersionPredecessors.length];
                        for (int i = 0; i < baseVersionPredecessors.length; i++) {
                            predecessors[i] = referenceFactory.create(((JcrVersionNode)baseVersionPredecessors[i]).key(), true);
                        }
                        node.setReference(cache, propertyFactory.create(JcrLexicon.PREDECESSORS, predecessors), systemCache);
                    }
                }
            }

            // -----------
            // nt:resource
            // -----------
            if (nodeTypeCapabilities.isNtResource(primaryType)) {
                // If there is no "jcr:mimeType" property ...
                if (!node.hasProperty(JcrLexicon.MIMETYPE, cache)) {
                    // Try to get the MIME type for the binary value ...
                    org.modeshape.jcr.value.Property dataProp = node.getProperty(JcrLexicon.DATA, cache);
                    if (dataProp != null) {
                        Object dataValue = dataProp.getFirstValue();
                        if (dataValue instanceof Binary) {
                            Binary binaryValue = (Binary)dataValue;
                            // Get the name of this node's parent ...
                            String fileName = null;
                            NodeKey parentKey = node.getParentKey(cache);
                            if (parentKey != null) {
                                CachedNode parent = cache.getNode(parentKey);
                                Name parentName = parent.getName(cache);
                                fileName = stringFactory().create(parentName);
                            }
                            String mimeType = binaryValue.getMimeType(fileName);
                            if (mimeType != null) {
                                node.setProperty(cache, propertyFactory.create(JcrLexicon.MIMETYPE, mimeType));
                            }
                        }
                    }
                }
            }

            // --------------------
            // Mandatory properties
            // --------------------
            // Some of the version history properties are mandatory, so we need to initialize the version history first ...
            Collection<JcrPropertyDefinition> mandatoryPropDefns = null;
            mandatoryPropDefns = nodeTypeCapabilities.getMandatoryPropertyDefinitions(primaryType, mixinTypes);
            if (!mandatoryPropDefns.isEmpty()) {
                // There is at least one mandatory property on this node, so go through all of the mandatory property
                // definitions and see if any do not correspond to existing properties ...
                for (JcrPropertyDefinition defn : mandatoryPropDefns) {
                    Name propName = defn.getInternalName();
                    if (!node.hasProperty(propName, cache)) {
                        // There is no mandatory property ...
                        if (defn.hasDefaultValues()) {
                            // This may or may not be auto-created; we don't care ...
                            if (jcrNode == null) jcrNode = node(node, (Type)null, null);
                            JcrValue[] defaultValues = defn.getDefaultValues();
                            if (defn.isMultiple()) {
                                jcrNode.setProperty(propName, defaultValues, defn.getRequiredType(), false);
                            } else {
                                // don't skip constraint checks or protected checks
                                jcrNode.setProperty(propName, defaultValues[0], false, false, false, false);
                            }
                        } else {
                            // There is no default for this mandatory property, so this is a constraint violation ...
                            String pName = defn.getName();
                            String typeName = defn.getDeclaringNodeType().getName();
                            String loc = readableLocation(node);
                            throw new ConstraintViolationException(JcrI18n.missingMandatoryProperty.text(pName, typeName, loc));
                        }
                    } else {
                        // There is a property with the same name as the mandatory property, so verify that the
                        // existing property does indeed use this property definition. Use the JCR property
                        // since it may already cache the property definition ID or will know how to find it ...
                        if (jcrNode == null) jcrNode = node(node, (Type)null, null);
                        AbstractJcrProperty jcrProperty = jcrNode.getProperty(propName);
                        PropertyDefinitionId defnId = jcrProperty.propertyDefinitionId();
                        if (defn.getId().equals(defnId)) {
                            // This existing property does use the auto-created definition ...
                            continue;
                        }
                        // The existing property does not use the property definition, but we can't auto-create the property
                        // because there is already an existing one with the same name. First see if we can forcibly
                        // recompute the property definition ...
                        jcrProperty.releasePropertyDefinitionId();
                        defnId = jcrProperty.propertyDefinitionId();
                        if (defn.getId().equals(defnId)) {
                            // This existing property does use the auto-created definition ...
                            continue;
                        }

                        // Still didn't match, so this is a constraint violation of the existing property ...
                        String pName = defn.getName();
                        String typeName = defn.getDeclaringNodeType().getName();
                        String loc = readableLocation(node);
                        I18n msg = JcrI18n.propertyNoLongerSatisfiesConstraints;
                        throw new ConstraintViolationException(msg.text(pName, loc, defn.getName(), typeName));
                    }
                }
            }

            // ---------------------
            // Mandatory child nodes
            // ---------------------
            Collection<JcrNodeDefinition> mandatoryChildDefns = null;
            mandatoryChildDefns = nodeTypeCapabilities.getMandatoryChildNodeDefinitions(primaryType, mixinTypes);
            if (!mandatoryChildDefns.isEmpty()) {
                Set<Name> childrenNames = new HashSet<Name>();
                for (ChildReference childRef : node.getChildReferences(cache())) {
                    childrenNames.add(childRef.getName());
                }

                for (JcrNodeDefinition defn : mandatoryChildDefns) {
                    Name childName = defn.getInternalName();
                    if (!childrenNames.contains(childName)) {
                        throw new ConstraintViolationException(
                                                               JcrI18n.propertyNoLongerSatisfiesConstraints.text(childName,
                                                                                                                 readableLocation(node),
                                                                                                                 defn.getName(),
View Full Code Here

        @Override
        public void processAfterLocking( MutableCachedNode modifiedNode,
                                         SaveContext context,
                                         NodeCache persistentNodeCache ) throws RepositoryException {
            // We actually can avoid this altogether if certain conditions are met ...
            final Name primaryType = modifiedNode.getPrimaryType(cache);
            final Set<Name> mixinTypes = modifiedNode.getMixinTypes(cache);
            if (!nodeTypeCapabilities.disallowsSameNameSiblings(primaryType, mixinTypes)) return;

            MutableCachedNode.NodeChanges changes = modifiedNode.getNodeChanges();
            Map<NodeKey, Name> appendedChildren = changes.appendedChildren();
            Map<NodeKey, Name> renamedChildren = changes.renamedChildren();
            Set<NodeKey> removedChildren = changes.removedChildren();
            if (!appendedChildren.isEmpty() || !renamedChildren.isEmpty()) {

                Multimap<Name, NodeKey> appendedOrRenamedChildrenByName = LinkedListMultimap.create();
                for (Map.Entry<NodeKey, Name> appended : appendedChildren.entrySet()) {
                    appendedOrRenamedChildrenByName.put(appended.getValue(), appended.getKey());
                }
                for (Map.Entry<NodeKey, Name> renamed : renamedChildren.entrySet()) {
                    appendedOrRenamedChildrenByName.put(renamed.getValue(), renamed.getKey());
                }

                assert appendedOrRenamedChildrenByName.isEmpty() == false;

                // look at the information that was already persisted to determine whether some other thread has already
                // created a child with the same name
                CachedNode persistentNode = persistentNodeCache.getNode(modifiedNode.getKey());
                final ChildReferences persistedChildReferences = persistentNode.getChildReferences(persistentNodeCache);
                final SiblingCounter siblingCounter = SiblingCounter.create(persistedChildReferences);

                // process appended/renamed children
                for (Name childName : appendedOrRenamedChildrenByName.keySet()) {
                    int existingChildrenWithSameName = persistedChildReferences.getChildCount(childName);
                    if (existingChildrenWithSameName == 0) {
                        continue;
                    }
                    if (existingChildrenWithSameName == 1) {
                        // See if the existing same-name sibling is removed ...
                        NodeKey persistedChildKey = persistedChildReferences.getChild(childName).getKey();
                        if (removedChildren.contains(persistedChildKey)) {
                            // the sole existing child with this name is being removed, so we can ignore it ...
                            // existingChildrenWithSameName = 0;
                            continue;
                        }
                    }

                    // There is at least one persisted child with the same name, and we're adding a new child
                    // or renaming an existing child to this name. Therefore, we have to find a child node definition
                    // that allows SNS. Look for one ignoring the child node type (this is faster than finding the
                    // child node primary types) ...
                    NodeDefinitionSet childDefns = nodeTypeCapabilities.findChildNodeDefinitions(primaryType, mixinTypes);
                    JcrNodeDefinition childNodeDefinition = childDefns.findBestDefinitionForChild(childName, null, true,
                                                                                                  siblingCounter);
                    if (childNodeDefinition != null) {
                        // found the one child node definition that applies, so it's okay ...
                        continue;
                    }

                    // We were NOT able to find a definition that allows SNS for this name, but we need to make sure that
                    // the node that already exists (persisted) isn't the one that's being changed
                    NodeKey persistedChildKey = persistedChildReferences.getChild(childName).getKey();
                    if (appendedChildren.containsKey(persistedChildKey) || renamedChildren.containsKey(persistedChildKey)) {
                        // The persisted node is being changed, so it's okay ...
                        continue;
                    }

                    // We still were NOT able to find a definition that allows SNS for this name WITHOUT considering the
                    // specific child node type. This likely means there is either 0 or more than 1 (possibly residual)
                    // child node definitions. We need to find all of the added/renamed child nodes and use their specific
                    // primary types. The first to fail will result in an exception ...
                    final SessionCache session = cache();
                    for (NodeKey appendedOrRenamedKey : appendedOrRenamedChildrenByName.get(childName)) {
                        MutableCachedNode appendedOrRenamedChild = session.mutable(appendedOrRenamedKey);
                        if (appendedOrRenamedChild == null) continue;
                        Name childPrimaryType = appendedOrRenamedChild.getPrimaryType(session);
                        childDefns = nodeTypeCapabilities.findChildNodeDefinitions(primaryType, mixinTypes);
                        childNodeDefinition = childDefns.findBestDefinitionForChild(childName, childPrimaryType, true,
                                                                                    siblingCounter);
                        if (childNodeDefinition == null) {
                            // Could not find a valid child node definition that allows SNS given the child's primary type and
View Full Code Here

        AbstractJcrNode node = jcrNodes.get(nodeKey);
        boolean mightBeShared = true;
        if (node == null) {

            if (expectedType == null) {
                Name primaryType = cachedNode.getPrimaryType(cache);
                expectedType = Type.typeForPrimaryType(primaryType);
                if (expectedType == null) {
                    // If this node from the system workspace, then the default is Type.SYSTEM rather than Type.NODE ...
                    if (repository().systemWorkspaceKey().equals(nodeKey.getWorkspaceKey())) {
                        expectedType = Type.SYSTEM;
View Full Code Here

        // Check whether external nodes are involved
        validateMoveForExternalNodes(srcPath, destPath);

        // check whether the parent definition allows children which match the source
        final Name newChildName = destPath.getLastSegment().getName();
        destParentNode.validateChildNodeDefinition(newChildName, srcNode.getPrimaryTypeName(), true);

        // We already checked whether the supplied destination path is below the supplied source path, but this isn't
        // sufficient if any of the ancestors are shared nodes. Therefore, check whether the destination node
        // is actually underneath the source node by walking up the destination path to see if there are any
View Full Code Here

    @Override
    public void removeVersionLabel( String label ) throws VersionException, RepositoryException {
        AbstractJcrNode versionLabels = versionLabels();

        Name propName = null;
        try {
            // This throws a PNFE if the named property doesn't already exist
            propName = versionLabels.getProperty(label).name();
        } catch (PathNotFoundException pnfe) {
            // This gets thrown if the label doesn't already exist
View Full Code Here

        private JcrVersionNode nextVersionIfPossible() {
            while (nodeIterator.hasNext()) {
                AbstractJcrNode node = (AbstractJcrNode)nodeIterator.nextNode();

                Name nodeName;
                try {
                    nodeName = node.segment().getName();
                } catch (RepositoryException re) {
                    throw new IllegalStateException(re);
                }
View Full Code Here

        if (getDefinition().isProtected()) {
            throw new ConstraintViolationException(JcrI18n.cannotRemoveFromProtectedNode.text(getPath()));
        }

        NodeTypes nodeTypes = session.nodeTypes();
        Name removedMixinName = nameFrom(mixinName);
        if (!isNodeType(mixinName)) {
            throw new NoSuchNodeTypeException(JcrI18n.invalidMixinTypeForNode.text(mixinName, location()));
        }

        if (JcrMixLexicon.SHAREABLE.equals(removedMixinName) && isShareable()) {
            // Can only remove the shareable mixin if there are no other shared nodes
            NodeIterator shared = getSharedSet();
            long numShared = shared.getSize();
            if (numShared > 1L) {
                // This is not possible, so build up a useful error message ...
                StringBuilder paths = new StringBuilder();
                if (shared.hasNext()) {
                    Node sharedNode = shared.nextNode();
                    paths.append(sharedNode.getPath());
                }
                while (shared.hasNext()) {
                    paths.append(", ");
                    Node sharedNode = shared.nextNode();
                    paths.append(sharedNode.getPath());
                }
                String msg = JcrI18n.cannotRemoveShareableMixinThatIsShared.text(location(), numShared, paths);
                throw new ConstraintViolationException(msg);
            }
        }

        // Get the information from the node ...
        SessionCache cache = sessionCache();
        CachedNode cachedNode = node();
        Name primaryTypeName = cachedNode.getPrimaryType(cache);

        // Build up the list of new mixin types ...
        Set<Name> newMixinNames = new HashSet<Name>(cachedNode.getMixinTypes(cache));
        if (!newMixinNames.remove(removedMixinName)) {
            // Nothing to remove ...
View Full Code Here

        if (!mixinType.isMixin()) return false;
        if (isLocked()) return false;
        if (!isCheckedOut()) return false;
        if (getDefinition().isProtected()) return false;
        if (mixinType.isAbstract()) return false;
        final Name mixinNameObj = mixinType.getInternalName();
        if (isNodeType(mixinNameObj)) return true;

        // do not allow versionable mixin on external nodes
        if (isExternal() && session().nodeTypes().isVersionable(mixinNameObj)) {
            return false;
        }

        // ------------------------------------------------------------------------------
        // Check for any existing properties based on residual definitions that conflict
        // ------------------------------------------------------------------------------
        if (mixinType.hasPropertyDefinitions()) {
            for (JcrPropertyDefinition propDefn : mixinType.allPropertyDefinitions()) {
                Name propName = propDefn.getInternalName();
                AbstractJcrProperty existingProp = getProperty(propName);
                if (existingProp == null) continue;
                if (propDefn.isMultiple()) {
                    if (!propDefn.canCastToTypeAndSatisfyConstraints(existingProp.getValues(), session())) {
                        return false;
                    }
                } else {
                    if (!propDefn.canCastToTypeAndSatisfyConstraints(existingProp.getValue(), session())) {
                        return false;
                    }
                }
            }
        }

        // ------------------------------------------------------------------------------
        // Check for any existing child nodes based on residual definitions that conflict
        // ------------------------------------------------------------------------------
        if (mixinType.hasChildNodeDefinitions()) {
            // There is at least one child node definition (unusual for mixins!) ....
            Set<Name> mixinChildNodeNames = new HashSet<Name>();
            for (JcrNodeDefinition nodeDefinition : mixinType.allChildNodeDefinitions()) {
                mixinChildNodeNames.add(nodeDefinition.getInternalName());
            }

            CachedNode node = node();
            NodeCache cache = cache();
            NodeTypes nodeTypes = session.nodeTypes();
            // Need to figure out if the child node requires an SNS definition
            ChildReferences refs = node.getChildReferences(cache());
            // Create a sibling counter that reduces the count by 1, since we're always dealing with existing children
            // but the 'findBestDefinitionForChild' logic is looking to *add* a child ...
            SiblingCounter siblingCounter = SiblingCounter.alter(SiblingCounter.create(refs), -1);
            for (Name nodeName : mixinChildNodeNames) {
                int snsCount = siblingCounter.countSiblingsNamed(nodeName);
                if (snsCount == 0) continue;
                Iterator<ChildReference> iter = refs.iterator(nodeName);
                while (iter.hasNext()) {
                    ChildReference ref = iter.next();
                    CachedNode child = cache.getNode(ref);
                    Name childPrimaryType = child.getPrimaryType(cache);
                    boolean skipProtected = true;
                    NodeDefinitionSet childDefns = nodeTypes.findChildNodeDefinitions(mixinType.getInternalName(), null);
                    JcrNodeDefinition childDefn = childDefns.findBestDefinitionForChild(nodeName, childPrimaryType,
                                                                                        skipProtected, siblingCounter);
                    if (childDefn == null) {
View Full Code Here

        if (defn == null || nodeTypes.getVersion() > defn.nodeTypesVersion) {
            assert !this.isRoot();
            // Determine the node type based upon this node's type information ...
            CachedNode parent = getParent().node();
            SessionCache cache = sessionCache();
            Name nodeName = name();
            Name primaryType = node().getPrimaryType(cache);
            Name parentPrimaryType = parent.getPrimaryType(cache);
            Set<Name> parentMixins = parent.getMixinTypes(cache);
            SiblingCounter siblingCounter = SiblingCounter.create(parent, cache);
            boolean skipProtected = true;
            NodeDefinitionSet childDefns = nodeTypes.findChildNodeDefinitions(parentPrimaryType, parentMixins);
            JcrNodeDefinition childDefn = childDefns.findBestDefinitionForChild(nodeName, primaryType, skipProtected,
View Full Code Here

TOP

Related Classes of org.modeshape.jcr.value.Name

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.