Writes an entity into Persistence cache. (Actual database write is done
while flushing)
197356
public void persist(Object e)
    {
        if (e == null)
        {
            throw new IllegalArgumentException(
                    "Entity object is invalid, operation failed. Please check previous log message for details");
        }

        // Create an object graph of the entity object.
        ObjectGraph graph = new GraphGenerator().generateGraph(e, this);
        // Call persist on each node in object graph.
        Node node = graph.getHeadNode();
        try
        {
            // Get write lock before writing object required for transaction.
            lock.writeLock().lock();

            node.setPersistenceDelegator(this);
            node.persist();

            // build flush stack.
            flushManager.buildFlushStack(node, com.impetus.kundera.persistence.context.EventLog.EventType.INSERT);

            // Flushing data.
            flush();

            // Add node to persistence context after successful flush.
            getPersistenceCache().getMainCache().addHeadNode(node);
        }
        finally
        {
            lock.writeLock().unlock();
        }

        // Unlocking object.
        graph.clear();
        graph = null;
        if (log.isDebugEnabled())
        {
            log.debug("Data persisted successfully for entity {}.", e.getClass());
        }
    }
210153
public boolean isPersistent(DbEntity dbEntity) {
    CachedDbEntity cachedDbEntity = getCachedEntity(dbEntity);
    if(cachedDbEntity == null) {
      return false;
    } else {
      return cachedDbEntity.getEntityState() == PERSISTENT;
    }
  }
1199346
def _sync_writes(self):
        '''
        
        '''
        for key in self._wqueue:
            val = self._cache[key]
            self._database[key] = val
        del self._wqueue
        self._wqueue = set()
        self._database.sync()
1355548
public void writeObjects(boolean reuse) throws TransactionAbortedException, LockNotGrantedException
    {
        PersistenceBroker broker = transaction.getBroker();
        ConnectionManagerIF connMan = broker.serviceConnectionManager();
        boolean saveBatchMode = connMan.isBatchMode();

        try
        {
            if(log.isDebugEnabled())
            {
                log.debug(
                        "PB is in internal tx: "
                                + broker.isInTransaction()
                                + "  broker was: "
                                + broker);
            }
            // all neccessary db operations are executed within a PersistenceBroker transaction:
            if(!broker.isInTransaction())
            {
                log.error("PB associated with current odmg-tx is not in tx");
                throw new TransactionAbortedException("Underlying PB is not in tx, was begin call done before commit?");
            }

            // Committing has to be done in two phases. First implicitly upgrade to lock on all related
            // objects of objects in this transaction. Then the list of locked objects has to be
            // reordered to solve referential integrity dependencies, then the objects are
            // written into the database.

            // 0. turn on the batch mode
            connMan.setBatchMode(true);

            // 1. mark objects no longer available in collection
            // for delete and add new found objects
            checkAllEnvelopes(broker);

            // 2. mark all dependend objects for cascading insert/delete
            cascadingDependents();

            // 3. upgrade implicit locks.
            //upgradeImplicitLocksAndCheckIfCommitIsNeeded();
            upgradeLockIfNeeded();

            // 4. Reorder objects
            reorder();
//            System.out.println("## ordering: ");
//            for(int i = 0; i < mvOrderOfIds.size(); i++)
//            {
//                System.out.println("" + mvOrderOfIds.get(i));
//            }
//            System.out.println("## ordering end");

            // 5. write objects.
            writeAllEnvelopes(reuse);

            // 6. execute batch
            connMan.executeBatch();

            // 7. Update all Envelopes to new CleanState
            prepareForReuse(reuse);

            // 6. commit cleanup
            afterWriteCleanup();

        }
        catch(Exception e)
        {
            connMan.clearBatch();
            /*
            arminw:
            log only a warn message, because in top-level methods
            a error log will be done ditto
            */
            if(e instanceof OptimisticLockException)
            {
                // make error log to show the full stack trace one time
                log.error("Optimistic lock exception while write objects", e);
                // PB OptimisticLockException should be clearly signalled to the user
                Object sourceObject = ((OptimisticLockException) e).getSourceObject();
                throw new LockNotGrantedException("Optimistic lock exception occur, source object was (" + sourceObject + ")," +
                        " message was (" + e.getMessage() + ")");
            }
            else if(!(e instanceof RuntimeException))
            {
                log.warn("Error while write objects for tx " + transaction, e);
                throw new ODMGRuntimeException("Unexpected error while write objects: " + e.getMessage());
            }
            else
            {
                log.warn("Error while write objects for tx " + transaction, e);
                throw (RuntimeException) e;
            }
        }
        finally
        {
            needsCommit = false;
            connMan.setBatchMode(saveBatchMode);
        }
    }
139780
def write(self):
        
        io.debug("Storing cache '{0}'".format(self.path))
        with open(self.path, "w") as file:
            json.dump(self._data, file, sort_keys=True, indent=2,
                      separators=(',', ': '))
327990
private void instanceAlreadyLoaded(
		final Tuple resultset,
		final int i,
			//TODO create an interface for this usage
		final OgmEntityPersister persister,
		final org.hibernate.engine.spi.EntityKey key,
		final Object object,
		final LockMode lockMode,
		final SharedSessionContractImplementor session)
	throws HibernateException {
		if ( !persister.isInstance( object ) ) {
			throw new WrongClassException(
					"loaded object was of wrong class " + object.getClass(),
					key.getIdentifier(),
					persister.getEntityName()
				);
		}

		if ( LockMode.NONE != lockMode && upgradeLocks() ) { // no point doing this if NONE was requested

			final boolean isVersionCheckNeeded = persister.isVersioned() &&
					session.getPersistenceContext().getEntry( object )
							.getLockMode().lessThan( lockMode );
			// we don't need to worry about existing version being uninitialized
			// because this block isn't called by a re-entrant load (re-entrant
			// loads _always_ have lock mode NONE)
			if ( isVersionCheckNeeded ) {
				//we only check the version when _upgrading_ lock modes
				Object oldVersion = session.getPersistenceContext().getEntry( object ).getVersion();
				persister.checkVersionAndRaiseSOSE( key.getIdentifier(), oldVersion, session, resultset );
				//we need to upgrade the lock mode to the mode requested
				session.getPersistenceContext().getEntry( object )
						.setLockMode( lockMode );
			}
		}
	}
1130780
public void write(ObjectWriter out, PersistedNodeData nodeData) throws IOException
   {
      // write id
      out.writeInt(SerializationConstants.PERSISTED_NODE_DATA);

      // TransientItemData
      out.writeString(nodeData.getQPath().getAsString());
      out.writeString(nodeData.getIdentifier());

      if (nodeData.getParentIdentifier() != null)
      {
         out.writeByte(SerializationConstants.NOT_NULL_DATA);
         out.writeString(nodeData.getParentIdentifier());
      }
      else
         out.writeByte(SerializationConstants.NULL_DATA);

      out.writeInt(nodeData.getPersistedVersion());
      // -------------------

      out.writeInt(nodeData.getOrderNumber());

      // primary type
      out.writeString(nodeData.getPrimaryTypeName().getAsString());

      // mixins
      InternalQName[] mixinNames = nodeData.getMixinTypeNames();

      if (mixinNames != null)
      {
         out.writeByte(SerializationConstants.NOT_NULL_DATA);
         out.writeInt(mixinNames.length);
         for (int i = 0; i < mixinNames.length; i++)
         {
            out.writeString(mixinNames[i].getAsString());
         }
      }
      else
      {
         out.writeByte(SerializationConstants.NULL_DATA);
      }

      ACLWriter wr = new ACLWriter();

      AccessControlList acl = nodeData.getACL();
      if (acl != null)
      {
         out.writeByte(SerializationConstants.NOT_NULL_DATA);
         wr.write(out, acl);
      }
      else
      {
         out.writeByte(SerializationConstants.NULL_DATA);
      }
   }
133557
void writeCachedLastAccessedTimes(Connection nukerCon) throws Exception {
        if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
            LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[WRITE_CACHED_LAST_ACCESSED_TIMES]);
        }

        // create a copy for the updates, then atomically clear the table
        // the hashtable table clone is shallow, it will not dup the keys/elements
        Hashtable updTab = (Hashtable) cachedLastAccessedTimes.clone();
        cachedLastAccessedTimes.clear();
        Enumeration updEnum = updTab.keys();
        String id = null;
        PreparedStatement ps = null;
        boolean psClose = false;

        while (updEnum.hasMoreElements()) {

            id = (String) updEnum.nextElement();
            Long timeObj = (Long) updTab.get(id);
            long time = timeObj.longValue();
            try {
                ps = nukerCon.prepareStatement(asyncUpdate);
                setPSLong(ps, 1, time);
                ps.setString(2, id);
                ps.setString(3, id);
                ps.setString(4, getIStore().getId());

                ps.executeUpdate();
                ps.close();
                psClose = true;
                if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[WRITE_CACHED_LAST_ACCESSED_TIMES], "handleAsyncUpdates"
                                                                                                                                    + " - Updating LastAccess for " + id);
                }
            } catch (Exception se1) {
                //                if (isStaleConnectionException(se1)) {
                //                    com.ibm.ws.ffdc.FFDCFilter.processException(se1, "com.ibm.ws.session.store.db.DatabaseHashMap.writeCachedLastAccessedTimes", "2102", id);
                //                    if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                //                        LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[WRITE_CACHED_LAST_ACCESSED_TIMES], "StaleConnectionException");
                //                    }
                //                    throw se1;
                //                } else {
                com.ibm.ws.ffdc.FFDCFilter.processException(se1, "com.ibm.ws.session.store.db.DatabaseHashMap.writeCachedLastAccessedTimes", "2109", id);
                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[WRITE_CACHED_LAST_ACCESSED_TIMES], "DatabaseHashMap.handleAsyncError");
                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[WRITE_CACHED_LAST_ACCESSED_TIMES], "CommonMessage.sessionid", id);
                LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[WRITE_CACHED_LAST_ACCESSED_TIMES], "CommonMessage.exception", se1);
                throw se1;
                //                }
            } finally {
                if (!psClose && ps != null) {
                    closeStatement(ps);
                }
            }
        }

    }
535287
public void storeCache() {
        if (cacheOk && cacheRes != null && isDirty) {
            OutputStream out = null;
            try {
                out = cacheRes.putStream();
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, "UTF-8"));
                for (SubsystemFeatureDefinitionImpl entry : cachedFeatures.values()) {
                    ImmutableAttributes imAttrs = entry.getImmutableAttributes();
                    ProvisioningDetails provDetails = entry.getProvisioningDetails();

                    if (imAttrs != null && provDetails != null) {
                        FeatureDefinitionUtils.writeAttributes(imAttrs,
                                                               provDetails,
                                                               writer);
                    } else {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                            Tr.debug(tc, "Unable to write out " + entry.getFeatureName() + " to cache because the provisioning "
                                         + "detail: " + provDetails + " or imAttrs: " + imAttrs + " is null");
                        }
                    }
                }
                writer.write("@=");
                writer.write(toFeatureNameList(installedFeatures));
                writer.write(FeatureDefinitionUtils.NL);
                writer.write("-@");
                writer.write(toFeatureNameList(configuredFeatures));
                writer.write(FeatureDefinitionUtils.NL);
                writer.write("-#");
                writer.write(configurationError ? '1' : '0');
                writer.write(FeatureDefinitionUtils.NL);

                for (Map.Entry<File, BadFeature> entry : knownBadFeatures.entrySet()) {
                    writer.write("XX");
                    writeBadManifestEntry(writer, entry.getKey(), entry.getValue());
                    writer.write(FeatureDefinitionUtils.NL);
                }

                writer.flush();
                writer.close();

                isDirty = false; // mark cache as current after it has been saved
            } catch (IOException e) {
                cacheWarning(e);
            } finally {
                FeatureDefinitionUtils.tryToClose(out);
            }
        }
    }
546413
public function saveEntity($entity, $flush = true)
    {
        $this->preSaveEntity($entity);

        $this->getEntityManager()->persist($entity);

        if ($flush) {
            $this->getEntityManager()->flush($entity);
        }

        // Get updated fields, and include changes so that we have everything.
        $fields  = $entity->getUpdatedFields();
        $changes = [];
        if (method_exists($entity, 'getChanges')) {
            $changes = $entity->getChanges();

            // remove the fields that are part of changes as they were already saved via a setter
            $fields = array_diff_key($fields, $changes);
        }

        // Get Extended Fields to separate from standard Update statement.
        $extendedFields = [];
        $fieldList      = $this->getCustomFieldList('lead');
        foreach ($fields as $alias => $value) {
            if (in_array($fieldList[0][$alias]['object'], ['extendedField', 'extendedFieldSecure'])) {
                // Depends on object added by alteration in organizeFieldsByGroup.
                $extendedFields[$alias]['object'] = $fieldList[0][$alias]['object'];
                $extendedFields[$alias]['id']     = $fieldList[0][$alias]['id'];
                $extendedFields[$alias]['type']   = $fieldList[0][$alias]['type'];
                $extendedFields[$alias]['alias']  = $alias;
                $extendedFields[$alias]['value']  = $value;
                unset($fields[$alias]);
            }
        }

        $this->prepareDbalFieldsForSave($fields);

        // Save standard/core fields (same as core).
        if (!empty($fields)) {
            $table = $this->getEntityManager()->getClassMetadata($this->getClassName())->getTableName();
            $this->getEntityManager()->getConnection()->update($table, $fields, ['id' => $entity->getId()]);
        }

        // Now to update extended fields if there were any to be updated.
        if (!empty($extendedFields)) {
            $insertUpdates = $deletions = [];
            $leadId        = $entity->getId();
            /** @var \Doctrine\DBAL\Connection $connection */
            $connection = $this->getEntityManager()->getConnection();
            foreach ($extendedFields as $extendedField) {
                if (
                    !isset($changes['fields'])
                    || !isset($changes['fields'][$extendedField['alias']])
                ) {
                    // No change to this extended field detected.
                    continue;
                }
                $schema  = $this->leadFieldModel->getSchemaDefinition($extendedField['alias'], $extendedField['type']);
                $columns = [
                    'value' => $extendedField['value'],
                ];
                // Corrects boolean field values, nothing more at this point.
                $this->prepareDbalFieldsForSave($columns);
                $secure    = 'extendedFieldSecure' === $extendedField['object'] ? '_secure' : '';
                $tableName = MAUTIC_TABLE_PREFIX.'lead_fields_leads_'.$schema['type'].$secure.'_xref';

                if (
                    null !== $changes['fields'][$extendedField['alias']][0]
                    && null === $changes['fields'][$extendedField['alias']][1]
                ) {
                    // Removed an existing value.
                    $connection->delete(
                        $tableName,
                        [
                            'lead_id'       => $leadId,
                            'lead_field_id' => $extendedField['id'],
                        ]
                    );
                } else {
                    // Mark for insert/update.
                    if (!isset($insertUpdates[$tableName])) {
                        $insertUpdates[$tableName] = [];
                    }
                    if (!isset($insertUpdates[$tableName][$extendedField['id']])) {
                        $insertUpdates[$tableName][$extendedField['id']] = $columns['value'];
                    }
                }
            }
            // Handle inserts/updates in bulk by table.
            if ($insertUpdates) {
                foreach ($insertUpdates as $tableName => $leadField) {
                    $rows = $params = [];
                    foreach ($leadField as $leadFieldId => $value) {
                        $key          = $tableName.$leadFieldId;
                        $rows[]       = $leadId.', '.$leadFieldId.', :'.$key;
                        $params[$key] = $value;
                    }
                    $sql  = 'INSERT INTO '.$tableName.' (`lead_id`, `lead_field_id`, `value`) '.
                        'VALUES ('.implode('),(', $rows).') '.
                        'ON DUPLICATE KEY UPDATE `value`=VALUES(`value`);';
                    $stmt = $connection->prepare($sql);
                    $stmt->execute($params);
                }
            }
        }

        $this->postSaveEntity($entity);
    }
1075851
private void persistCommitChanges(JPACommit commit, Long timestamp) {
        commit.setTimestamp(timestamp);
        addModifiedObjectsToEntityManager(commit.getJPAObjects(), timestamp);
        commit.setCommitted(true);
        logger.debug("persisting JPACommit");
        entityManager.persist(commit);
        logger.debug("mark the deleted elements as deleted");
        updateDeletedObjectsThroughEntityManager(commit.getDeletions(), timestamp);
    }
688762
@Override
    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> relations)
    {
        String tableName = HBaseUtils.getHTableName(entityMetadata.getSchema(), entityMetadata.getTableName());
        try
        {
            handler.writeData(tableName, entityMetadata, entity, id, relations, showQuery);
        }
        catch (IOException e)
        {
            throw new PersistenceException(e);
        }
    }
981066
final public function save(BaseEntityInterface $entity, $flush = false): self
    {
        $this->_em->persist($entity);

        if (true === $flush) {
            $this->_em->flush();
        }

        return $this;
    }
611796
public function save(AbstractEntity $entity)
    {
        if (empty($entity->getId())) {
            $this->getEntityManager()->persist($entity);
        }
        $this->getEntityManager()->flush($entity);
    }
718129
@Override
    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
    {
        KunderaCoreUtils.printQuery(
                "Persist data into " + entityMetadata.getSchema() + "." + entityMetadata.getTableName() + " for " + id,
                showQuery);
        Row row = createRow(entityMetadata, entity, id, rlHolders);
        // TODO:: handle case for putDate??????

        tableAPI.put(row, null, null);
    }
353281
function Persist(cacheFile, keys, log) {
  var pdata = (cacheFile) ? JSON.parse(fs.readFileSync(cacheFile, 'utf8')) : {}
    , guid = makeGuid(keys);

  pdata[guid] = pdata[guid] || {};

  // this is the only member that needs access to the full object and the file
  this.save = function () {
    if (cacheFile) {
      fs.writeFileSync(cacheFile, JSON.stringify(pdata));
    }
  };

  // members need only know their config object
  this.cfg = pdata[guid];
  this.cfg.opts = this.cfg.opts || {};

  // was a logger passed down?
  this.log = (type.isFunction(log)) ? log : noop;
}
1290492
function flushCacheTimed(stream, onFlush) {
    var nextWrite = lastWrite + settings.time;
    var now = Date.now();

    // we are overdue for a write, so write now
    if (now >= nextWrite) {
      flushCache(stream);
      onFlush();

      return;
    }

    // write after the remainder between now and when
    // the next write should be according to milliseconds
    // and the previous write
    timeout = setTimeout(function () {
      flushCache(stream);
      onFlush();
    }, nextWrite - now);
  }