Save a subset of the changes made within this session.

@param node the node at or below which the changes are to be saved; may not be null
@throws RepositoryException if there is a problem saving the changes
@see AbstractJcrNode#save()
492841
void save( AbstractJcrNode node ) throws RepositoryException {
        // first check the node is valid from a cache perspective
        Set<NodeKey> keysToBeSaved = null;
        try {
            if (node.isNew()) {
                // expected by TCK
                throw new RepositoryException(JcrI18n.unableToSaveNodeThatWasCreatedSincePreviousSave.text(node.getPath(),
                                                                                                           workspaceName()));
            }

            AtomicReference<Set<NodeKey>> refToKeys = new AtomicReference<Set<NodeKey>>();
            if (node.containsChangesWithExternalDependencies(refToKeys)) {
                // expected by TCK
                I18n msg = JcrI18n.unableToSaveBranchBecauseChangesDependOnChangesToNodesOutsideOfBranch;
                throw new ConstraintViolationException(msg.text(node.path(), workspaceName()));
            }
            keysToBeSaved = refToKeys.get();
        } catch (ItemNotFoundException e) {
            throw new InvalidItemStateException(e);
        } catch (NodeNotFoundException e) {
            throw new InvalidItemStateException(e);
        }
        assert keysToBeSaved != null;

        SessionCache sessionCache = cache();
        if (sessionCache.getChangedNodeKeys().size() == keysToBeSaved.size()) {
            // The node is above all the other changes, so go ahead and save the whole session ...
            save();
            return;
        }

        // Perform the save, using 'JcrPreSave' operations ...
        SessionCache systemCache = createSystemCache(false);
        SystemContent systemContent = new SystemContent(systemCache);
        Map<NodeKey, NodeKey> baseVersionKeys = this.baseVersionKeys.get();
        Map<NodeKey, NodeKey> originalVersionKeys = this.originalVersionKeys.get();
        try {
            sessionCache.save(keysToBeSaved, systemContent.cache(), new JcrPreSave(systemContent, baseVersionKeys,
                                                                                   originalVersionKeys, aclChangesCount()));
        } catch (WrappedException e) {
            Throwable cause = e.getCause();
            throw (cause instanceof RepositoryException) ? (RepositoryException)cause : new RepositoryException(e.getCause());
        } catch (DocumentNotFoundException e) {
            throw new InvalidItemStateException(JcrI18n.nodeModifiedBySessionWasRemovedByAnotherSession.text(e.getKey()), e);
        } catch (DocumentAlreadyExistsException e) {
            // Try to figure out which node in this transient state was the problem ...
            NodeKey key = new NodeKey(e.getKey());
            AbstractJcrNode problemNode = node(key, null);
            String path = problemNode.getPath();
            throw new InvalidItemStateException(JcrI18n.nodeCreatedBySessionUsedExistingKey.text(path, key), e);
        } catch (org.modeshape.jcr.cache.ReferentialIntegrityException e) {
            throw new ReferentialIntegrityException(e);
        } catch (Throwable t) {
            throw new RepositoryException(t);
        }

        try {
            // Record the save operation ...
            repository().statistics().increment(ValueMetric.SESSION_SAVES);
        } catch (IllegalStateException e) {
            // The repository has been shutdown ...
        }
    }
1267495
@Override
    protected void saveBeans(List<ProxyActionStatus> addedBeans, List<ProxyActionStatus> modifiedBeans,
            List<ProxyActionStatus> removedBeans) {
        // CRUD operations on Target will be done through repository methods
    }
72662
private void putNodeToStore(final Node<K, V> node) {
		final int nodeid = node.id;
		final int index = (nodeid < 0 ? -nodeid : nodeid);
		final WriteBuffer wbuf = storage.set(index);
		final ByteBuffer buf = wbuf.buf();
		if (node.isDeleted()) { 	// This block is for delete
			if (cleanBlocksOnFree) {
				buf.clear();
				int cx = (blockSize >> 3); // division by 8
				while (cx-- > 0) {
					buf.putLong(0);	// Fill with zeroes
				}
				buf.flip();
			} else {
				node.clean(buf); 	// Generate zeroed minimal buffer
			}
			freeBlocks.set(index); 	// Mark block as free
		} else {
			node.serialize(buf);
		}
		wbuf.save();
		if (enableDirtyCheck) {
			dirtyCheck.clear(index);
		}
		if (enableIOStats) {
			getIOStat(nodeid).incPhysWrite();
		}
	}
338410
public void setNodes(java.util.Collection<Node> nodes) {
        if (nodes == null) {
            this.nodes = null;
            return;
        }

        this.nodes = new java.util.ArrayList<Node>(nodes);
    }
238627
public void doImport() throws RepositoryException, IOException
   {
      try
      {
         uuid = versionableNode.getUUID();
         path = versionableNode.getVersionHistory().getParent().getPath();
         if (LOG.isDebugEnabled())
         {
            LOG.debug("Started: Import version history for node with path=" + path + " and UUID=" + uuid);
         }

         NodeData versionable = (NodeData)versionableNode.getData();
         // ----- VERSIONABLE properties -----
         // jcr:versionHistory
         TransientPropertyData vh =
            TransientPropertyData.createPropertyData(versionable, Constants.JCR_VERSIONHISTORY, PropertyType.REFERENCE,
               false, new TransientValueData(new Identifier(versionHistory)));

         // jcr:baseVersion
         TransientPropertyData bv =
            TransientPropertyData.createPropertyData(versionable, Constants.JCR_BASEVERSION, PropertyType.REFERENCE,
               false, new TransientValueData(new Identifier(baseVersionUuid)));

         // jcr:predecessors
         List<ValueData> values = new ArrayList<ValueData>();
         for (int i = 0; i < predecessors.length; i++)
         {
            values.add(new TransientValueData(new Identifier(predecessors[i])));
         }
         TransientPropertyData pd =
            TransientPropertyData.createPropertyData(versionable, Constants.JCR_PREDECESSORS, PropertyType.REFERENCE,
               true, values);

         PlainChangesLog changesLog = new PlainChangesLogImpl();
         RemoveVisitor rv = new RemoveVisitor();
         rv.visit((NodeData)((NodeImpl)versionableNode.getVersionHistory()).getData());
         changesLog.addAll(rv.getRemovedStates());
         changesLog.add(ItemState.createAddedState(vh));
         changesLog.add(ItemState.createAddedState(bv));
         changesLog.add(ItemState.createAddedState(pd));
         // remove version properties to avoid referential integrety check
         PlainChangesLog changesLogDelete = new PlainChangesLogImpl();

         changesLogDelete.add(ItemState.createDeletedState(((PropertyImpl)versionableNode
            .getProperty("jcr:versionHistory")).getData()));
         changesLogDelete.add(ItemState.createDeletedState(((PropertyImpl)versionableNode
            .getProperty("jcr:baseVersion")).getData()));
         changesLogDelete.add(ItemState.createDeletedState(((PropertyImpl)versionableNode
            .getProperty("jcr:predecessors")).getData()));
         dataKeeper.save(changesLogDelete);
         // remove version history
         dataKeeper.save(changesLog);
         userSession.save();

         // import new version history
         Map<String, Object> context = new HashMap<String, Object>();
         //context.put("versionablenode", versionableNode);
         context.put(ContentImporter.RESPECT_PROPERTY_DEFINITIONS_CONSTRAINTS, true);
         userSession.getWorkspace().importXML(path, versionHistoryStream, 0, context);
         userSession.save();

         if (LOG.isDebugEnabled())
         {
            LOG.debug("Completed: Import version history for node with path=" + path + " and UUID=" + uuid);
         }

         // fetch list of imported child nodes versions
         List<String> versionUuids = (List<String>)context.get(ContentImporter.LIST_OF_IMPORTED_VERSION_HISTORIES);
         if (versionUuids != null && !versionUuids.isEmpty())
         {
            updateVersionedChildNodes(versionUuids);
         }
      }
      catch (RepositoryException exception)
      {
         LOG.error("Failed: Import version history for node with path=" + path + " and UUID=" + uuid, exception);
         throw new RepositoryException(exception);
      }
      catch (IOException exception)
      {
         LOG.error("Failed: Import version history for node with path=" + path + " and UUID=" + uuid, exception);
         IOException newException = new IOException();
         newException.initCause(exception);
         throw newException;
      }
   }
738105
@Override
    public void save() throws IOException {
        // this should be a no-op unless this node instance is the node instance in Jenkins' list of nodes
        // thus where Jenkins.getInstance() == null there is no list of nodes, so we do a no-op
        // Nodes.updateNode(n) will only persist the node record if the node instance is in the list of nodes
        // so either path results in the same behaviour: the node instance is only saved if it is in the list of nodes
        // for all other cases we do not know where to persist the node record and hence we follow the default
        // no-op of a Saveable.NOOP
        final Jenkins jenkins = Jenkins.getInstanceOrNull();
        if (jenkins != null) {
            jenkins.updateNode(this);
        }
    }
388362
public void remove() throws RepositoryException
   {
      NodeData vhnode = (NodeData)dataManager.getItemData(vhID);

      if (vhnode == null)
      {
         ItemState vhState = null;
         List<ItemState> allStates = transientChangesLog.getAllStates();
         for (int i = allStates.size() - 1; i >= 0; i--)
         {
            ItemState state = allStates.get(i);
            if (state.getData().getIdentifier().equals(vhID))
               vhState = state;
         }
         if (vhState != null && vhState.isDeleted())
         {
            return;
         }

         throw new RepositoryException("Version history is not found. UUID: " + vhID
            + ". Context item (ancestor to save) " + ancestorToSave.getAsString());
      }

      // mix:versionable
      // we have to be sure that any versionable node somewhere in repository
      // doesn't refers to a VH of the node being deleted.
      for (String wsName : repository.getWorkspaceNames())
      {
         SessionImpl wsSession = repository.getSystemSession(wsName);
         try
         {
            for (PropertyData sref : wsSession.getTransientNodesManager().getReferencesData(vhID, false))
            {
               // Check if this VH isn't referenced from somewhere in workspace
               // or isn't contained in another one as a child history.
               // Ask ALL references incl. properties from version storage.
               if (sref.getQPath().isDescendantOf(Constants.JCR_VERSION_STORAGE_PATH))
               {
                  if (!sref.getQPath().isDescendantOf(vhnode.getQPath())
                     && (containingHistory != null ? !sref.getQPath().isDescendantOf(containingHistory) : true))
                     // has a reference to the VH in version storage,
                     // it's a REFERENCE property jcr:childVersionHistory of
                     // nt:versionedChild
                     // i.e. this VH is a child history in an another history.
                     // We can't remove this VH now.
                     return;
               }
               else if (!currentWorkspaceName.equals(wsName))
               {
                  // has a reference to the VH in traversed workspace,
                  // it's not a version storage, i.e. it's a property of versionable
                  // node somewhere in ws.
                  // We can't remove this VH now.
                  return;
               } // else -- if we has a references in workspace where the VH is being
               // deleted we can remove VH now.
            }
         }
         finally
         {
            wsSession.logout();
         }
      }

      // remove child versions from VH (if found)
      // ChildVersionRemoveVisitor cvremover = new
      // ChildVersionRemoveVisitor(session,
      // vhnode.getQPath(),
      // ancestorToSave);
      // vhnode.accept(cvremover);

      List<NodeData> childs = dataManager.getChildNodesData(vhnode);
      for (NodeData nodeData : childs)
      {
         if (ntManager.isNodeType(Constants.NT_VERSIONEDCHILD, vhnode.getPrimaryTypeName(), vhnode.getMixinTypeNames()))
         {
            PropertyData property =
               (PropertyData)dataManager.getItemData(nodeData, new QPathEntry(Constants.JCR_CHILDVERSIONHISTORY, 1),
                  ItemType.PROPERTY);

            if (property == null)
               throw new RepositoryException("Property " + Constants.JCR_CHILDVERSIONHISTORY.getAsString()
                  + " for node " + nodeData.getQPath().getAsString() + " not found");

            String childVhID = ValueDataUtil.getString(property.getValues().get(0));
            VersionHistoryRemover historyRemover =
               new VersionHistoryRemover(childVhID, dataManager, ntManager, repository, currentWorkspaceName,
                  containingHistory, ancestorToSave, transientChangesLog, accessManager, userState);
            historyRemover.remove();

         }

      }
      // remove VH
      ItemDataRemoveVisitor visitor = new ItemDataRemoveVisitor(dataManager, ancestorToSave);
      vhnode.accept(visitor);
      transientChangesLog.addAll(visitor.getRemovedStates());
   }
903359
public function save()
    {
        $contents = $this->getForStorage();

        $this->repository->put($this->key, $contents, $this->expire);
    }
615002
public void update(int node) {
        final int prev = prev(node);
        final int next = next(node);
        if ((prev == NIL || compare(prev) > 0) && (next == NIL || compare(next) < 0)) {
            // Update can be done in-place
            copy(node);
            for (int n = node; n != NIL; n = parent(n)) {
                fixAggregates(n);
            }
        } else {
            // TODO: it should be possible to find the new node position without
            // starting from scratch
            remove(node);
            add();
        }
    }
1080377
public synchronized final void initialize() throws RepositoryException {
        if (!initialized) {
            try {
                doInitialize();
                initialized = true;
            } catch (RuntimeException e) {
                throw new RepositoryException(e);
            }
        }
    }
817823
@Override
	public <S extends T> S save(S entity, boolean consistentRead) {
		return operations.createOrUpdate(entity);
	}
544256
public static void assertPrimaryNodeType(final Node node, final String nodeType) throws RepositoryException {
        final NodeType primaryNodeType = node.getPrimaryNodeType();
        assertEquals(nodeType, primaryNodeType.getName());
    }
90476
private void createVersion(Node fileNode, InputStream inputStream, List<String> mixins) throws RepositoryException
   {

      if (!fileNode.isCheckedOut())
      {
         fileNode.checkout();
         fileNode.getSession().save();
      }

      updateContent(fileNode, inputStream, mixins);
      fileNode.getSession().save();
      fileNode.checkin();
      fileNode.getSession().save();
   }
162364
public void addNode(Node node) {

		long nId = node.getId();
		
		if (this.containsNode(nId))
			throw new DuplicatedNodeException(nId);
		int index = nextNodeId++;
		nodeIdMapping.put(nId, index);

		int aliveIndex = index >> 5;
		int aliveSubIndex = index & 31;

		if (aliveIndex >= aliveNodes.size())
			aliveNodes.add(0);

		aliveNodes.set(aliveIndex, aliveNodes.get(aliveIndex) | (byte)(1 << aliveSubIndex));

		adjacency.add(new IntHashSet[] {new IntHashSet(), new IntHashSet()});

		nodes.add(node);
		numberOfNodes++;
	}
428639
private void persistNode(final @Nonnull Node node)  throws IOException {
        // no need for a full save() so we just do the minimum
        if (node instanceof EphemeralNode) {
            Util.deleteRecursive(new File(getNodesDir(), node.getNodeName()));
        } else {
            XmlFile xmlFile = new XmlFile(Jenkins.XSTREAM,
                    new File(new File(getNodesDir(), node.getNodeName()), "config.xml"));
            xmlFile.write(node);
            SaveableListener.fireOnChange(this, xmlFile);
        }
        jenkins.getQueue().scheduleMaintenance();
    }
388642
public Object visit(QueryRootNode node, Object data) throws RepositoryException {
        StringBuilder sb = (StringBuilder) data;
        node.getLocationNode().accept(this, data);
        InternalQName[] selectProps = node.getSelectProperties();
        if (selectProps.length > 0) {
            sb.append('/');
            boolean union = selectProps.length > 1;
            if (union) {
                sb.append('(');
            }
            String pipe = "";
            for (int i = 0; i < selectProps.length; i++) {
                try {
                    sb.append(pipe);
                    sb.append('@');
                    sb.append(resolver.createJCRName(encode(selectProps[i])).getAsString());
                    pipe = "|";
                } catch (NamespaceException e) {
                    exceptions.add(e);
                }
            }
            if (union) {
                sb.append(')');
            }
        }
        if (node.getOrderNode() != null) {
            node.getOrderNode().accept(this, data);
        }
        return data;
    }
812108
protected void entering(NodeData node, int level) throws RepositoryException
   {

      try
      {
         if (node.getQPath().getName().equals(Constants.JCR_XMLTEXT))
         {
            // jcr:xmlcharacters
            List<PropertyData> nodeData = dataManager.getChildPropertiesData(node);
            String strValue = "";
            for (PropertyData propertyData : nodeData)
            {
               if (propertyData.getQPath().getName().equals(Constants.JCR_XMLCHARACTERS))
               {
                  strValue = ValueDataUtil.getString(propertyData.getValues().get(0));
               }
            }
            contentHandler.characters(strValue.toCharArray(), 0, strValue.length());
         }
         else
         {
            List<PropertyData> nodeData = dataManager.getChildPropertiesData(node);
            currentAttr = new AttributesImpl();
            for (PropertyData property : nodeData)
            {

               String strValue = "";

               for (ValueData valueData : property.getValues())
               {
                  String strVal = getValueAsStringForExport(valueData, property.getType());
                  if (strVal.equals(""))
                  {
                     continue;
                  }

                  strValue += //NOSONAR
                     MULTI_VALUE_DELIMITER
                        + (property.getType() == PropertyType.BINARY ? strVal : StringConverter.normalizeString(strVal,
                           true));

               }
               // encode node name
               InternalQName internalPropName = ISO9075.encode(property.getQPath().getName());

               currentAttr.addAttribute(internalPropName.getNamespace(), internalPropName.getName(), getExportName(
                        property, true), "CDATA", !strValue.equals("") ? strValue.substring(1) : strValue);
            }

            if (Constants.ROOT_PATH.equals(node.getQPath()))
               contentHandler.startElement(Constants.NS_JCR_URI, Constants.NS_JCR_PREFIX, JCR_ROOT, currentAttr);

            else
               contentHandler.startElement(node.getQPath().getName().getNamespace(), node.getQPath().getName()
                  .getName(), getExportName(node, true), currentAttr);

         }
      }
      catch (SAXException e)
      {
         throw new RepositoryException(e);
      }
      catch (IllegalStateException e)
      {
         throw new RepositoryException(e);
      }
      catch (IOException e)
      {
         throw new RepositoryException(e);
      }
   }