Worker method for updating the given entity with optimistic locking.

@param entity
the entity to update
@param versionMetadata
the metadata for optimistic locking
@return the updated entity
506504
@SuppressWarnings("unchecked")
  protected <E> E updateWithOptimisticLockingInternal(E entity, PropertyMetadata versionMetadata) {
    Transaction transaction = null;
    try {
      entityManager.executeEntityListeners(CallbackType.PRE_UPDATE, entity);
      Entity nativeEntity = (Entity) Marshaller.marshal(entityManager, entity, Intent.UPDATE);
      transaction = datastore.newTransaction();
      Entity storedNativeEntity = transaction.get(nativeEntity.getKey());
      if (storedNativeEntity == null) {
        throw new OptimisticLockException(
            String.format("Entity does not exist: %s", nativeEntity.getKey()));
      }
      String versionPropertyName = versionMetadata.getMappedName();
      long version = nativeEntity.getLong(versionPropertyName) - 1;
      long storedVersion = storedNativeEntity.getLong(versionPropertyName);
      if (version != storedVersion) {
        throw new OptimisticLockException(
            String.format("Expecting version %d, but found %d", version, storedVersion));
      }
      transaction.update(nativeEntity);
      transaction.commit();
      E updatedEntity = (E) Unmarshaller.unmarshal(nativeEntity, entity.getClass());
      entityManager.executeEntityListeners(CallbackType.POST_UPDATE, updatedEntity);
      return updatedEntity;
    } catch (DatastoreException exp) {
      throw DatastoreUtils.wrap(exp);
    } finally {
      rollbackIfActive(transaction);
    }
  }
1231948
@PUT
    @Consumes({Servlets.JSON_MEDIA_TYPE, MediaType.APPLICATION_JSON})
    @Produces(Servlets.JSON_MEDIA_TYPE)
    public Response updateEntities(@Context HttpServletRequest request) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("==> EntityResource.updateEntities()");
        }

        String entityJson = null;
        AtlasPerfTracer perf = null;
        try {
            if (AtlasPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
                perf = AtlasPerfTracer.getPerfTracer(PERF_LOG, "EntityResource.updateEntities()");
            }

            final String entities = Servlets.getRequestPayload(request);

            entityJson = AtlasClient.toString(new JSONArray(entities));

            if (LOG.isDebugEnabled()) {
                LOG.info("updating entities {} ", entityJson);
            }

            AtlasEntitiesWithExtInfo   entitiesInfo     = restAdapters.toAtlasEntities(entities);
            EntityMutationResponse     mutationResponse = entityREST.createOrUpdate(entitiesInfo);
            CreateUpdateEntitiesResult result           = restAdapters.toCreateUpdateEntitiesResult(mutationResponse);

            if (LOG.isDebugEnabled()) {
                LOG.debug("Updated entities: {}", result.getEntityResult());
            }

            JSONObject response = getResponse(result);
            return Response.ok(response).build();
        } catch (AtlasBaseException e) {
            LOG.error("Unable to persist entity instance entityDef={}", entityJson, e);
            throw toWebApplicationException(e);
        } catch(EntityExistsException e) {
            LOG.error("Unique constraint violation for entityDef={}", entityJson, e);
            throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.CONFLICT));
        } catch (ValueConversionException ve) {
            LOG.error("Unable to persist entity instance due to a deserialization error entityDef={}", entityJson, ve);
            throw new WebApplicationException(Servlets.getErrorResponse(ve.getCause(), Response.Status.BAD_REQUEST));
        } catch (AtlasException | IllegalArgumentException e) {
            LOG.error("Unable to persist entity instance entityDef={}", entityJson, e);
            throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.BAD_REQUEST));
        } catch (WebApplicationException e) {
            LOG.error("Unable to persist entity instance entityDef={}", entityJson, e);
            throw e;
        } catch (Throwable e) {
            LOG.error("Unable to persist entity instance entityDef={}", entityJson, e);
            throw new WebApplicationException(Servlets.getErrorResponse(e, Response.Status.INTERNAL_SERVER_ERROR));
        } finally {
            AtlasPerfTracer.log(perf);

            if (LOG.isDebugEnabled()) {
                LOG.debug("<== EntityResource.updateEntities()");
            }
        }
    }
1062832
public final void write(EntityMetadata metadata, Object entity)
    {
        if (indexer != null)
        {
            MetamodelImpl metamodel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                    metadata.getPersistenceUnit());
            ((com.impetus.kundera.index.lucene.Indexer) indexer).index(metadata, metamodel, entity);
        }
    }
90319
public static void updateMetadata(CacheEntry entry, Metadata providedMetadata) {
      if (entry != null && providedMetadata != null) {
         Metadata mergedMetadata;
         if (entry.getMetadata() == null) {
            mergedMetadata = providedMetadata;
         } else {
            mergedMetadata = applyVersion(entry.getMetadata(), providedMetadata);
         }
         entry.setMetadata(mergedMetadata);
      }
   }
708747
@Override
	public int update(MetadataReference metadataReference) throws SQLException {

		UpdateBuilder<MetadataReference, Void> ub = updateBuilder();
		ub.updateColumnValue(MetadataReference.COLUMN_REFERENCE_SCOPE,
				metadataReference.getReferenceScope().getValue());
		ub.updateColumnValue(MetadataReference.COLUMN_TABLE_NAME,
				metadataReference.getTableName());
		ub.updateColumnValue(MetadataReference.COLUMN_COLUMN_NAME,
				metadataReference.getColumnName());
		ub.updateColumnValue(MetadataReference.COLUMN_ROW_ID_VALUE,
				metadataReference.getRowIdValue());
		ub.updateColumnValue(MetadataReference.COLUMN_TIMESTAMP,
				metadataReference.getTimestamp());

		setFkWhere(ub.where(), metadataReference.getFileId(),
				metadataReference.getParentId());

		PreparedUpdate<MetadataReference> update = ub.prepare();
		int updated = update(update);

		return updated;
	}
815967
@Override
	public void update(
			final Serializable id,
			final Object[] fields,
			final int[] dirtyFields,
			final boolean hasDirtyCollection,
			final Object[] oldFields,
			final Object oldVersion,
			final Object object,
			final Object rowId,
			final SharedSessionContractImplementor session) throws HibernateException {

		//note: dirtyFields==null means we had no snapshot, and we couldn't get one using select-before-update
		//	  oldFields==null just means we had no snapshot to begin with (we might have used select-before-update to get the dirtyFields)

		//TODO support "multi table" entities
		final boolean[] tableUpdateNeeded = getTableUpdateNeeded( dirtyFields, hasDirtyCollection );
		final int span = getTableSpan();

		final boolean[] propsToUpdate;
		EntityEntry entry = session.getPersistenceContext().getEntry( object );

		// Ensure that an immutable or non-modifiable entity is not being updated unless it is
		// in the process of being deleted.
		if ( entry == null && ! isMutable() ) {
			throw new IllegalStateException( "Updating immutable entity that is not in session yet!" );
		}
		//we always use a dynamicUpdate model for Infinispan
		if ( (
				//getEntityMetamodel().isDynamicUpdate() &&
				dirtyFields != null ) ) {

			propsToUpdate = getPropertiesToUpdate( dirtyFields, hasDirtyCollection );
			// don't need to check laziness (dirty checking algorithm handles that)
		}
		else if ( ! isModifiableEntity( entry ) ) {
			//TODO does that apply to OGM?
			// We need to generate UPDATE SQL when a non-modifiable entity (e.g., read-only or immutable)
			// needs:
			// - to have references to transient entities set to null before being deleted
			// - to have version incremented do to a "dirty" association
			// If dirtyFields == null, then that means that there are no dirty properties to
			// to be updated; an empty array for the dirty fields needs to be passed to
			// getPropertiesToUpdate() instead of null.
			propsToUpdate = getPropertiesToUpdate(
					( dirtyFields == null ? ArrayHelper.EMPTY_INT_ARRAY : dirtyFields ),
					hasDirtyCollection
			);
			// don't need to check laziness (dirty checking algorithm handles that)
		}
		else {
			// For the case of dynamic-update="false", or no snapshot, we update all properties
			//TODO handle lazy
			propsToUpdate = getPropertyUpdateability( object );
		}

		final SessionFactoryImplementor factory = getFactory();
		if ( log.isTraceEnabled() ) {
			log.trace( "Updating entity: " + MessageHelper.infoString( this, id, factory ) );
			if ( isVersioned() ) {
				log.trace( "Existing version: " + oldVersion + " -> New version: " + fields[getVersionProperty()] );
			}
		}


		for ( int j = 0; j < span; j++ ) {
			// Now update only the tables with dirty properties (and the table with the version number)
			if ( tableUpdateNeeded[j] ) {
				final EntityKey key = EntityKeyBuilder.fromPersister( this, id, session );

				final boolean useVersion = j == 0 && isVersioned();

				if ( usesNonAtomicOptimisticLocking ) {
					final Tuple tupleInDatastore = getFreshTuple( key, session );
					final EntityMetamodel entityMetamodel = getEntityMetamodel();

					// Write any appropriate versioning conditional parameters
					if ( useVersion && entityMetamodel.getOptimisticLockStyle() == OptimisticLockStyle.VERSION ) {
						if ( checkVersion( propsToUpdate ) ) {
							checkVersionAndRaiseSOSE( id, oldVersion, session, tupleInDatastore );
						}
					}
					else if ( isAllOrDirtyOptLocking() && oldFields != null ) {
						boolean[] versionability = getPropertyVersionability(); //TODO: is this really necessary????
						boolean[] includeOldField = entityMetamodel.getOptimisticLockStyle() == OptimisticLockStyle.ALL
								? getPropertyUpdateability()
										: propsToUpdate;

						//TODO do a diff on the properties value from resultset and the dirty value
						GridType[] types = gridPropertyTypes;

						for ( int i = 0; i < entityMetamodel.getPropertySpan(); i++ ) {
							boolean include = includeOldField[i] &&
									isPropertyOfTable( i, j ) &&
									versionability[i]; //TODO: is this really necessary????
							if ( include ) {
								final GridType type = types[i];
								//FIXME what do do with settable?
								boolean[] settable = type.toColumnNullness( oldFields[i], factory );
								final Object snapshotValue = type.nullSafeGet(
										tupleInDatastore, getPropertyColumnNames( i ), session, object
										);

								if ( !type.isEqual( oldFields[i], snapshotValue, factory ) ) {
									raiseStaleObjectStateException( id );
								}
							}
						}
					}
				}

				TuplePointer tuplePointer = getSharedTuplePointer( key, object, session );
				Tuple resultset = tuplePointer.getTuple();
				resultset = createNewResultSetIfNull( key, resultset, id, session );
				resultset.setSnapshotType( SnapshotType.UPDATE );
				saveSharedTuple( object, resultset, session );

				if ( mightManageInverseAssociations ) {
					removeFromInverseAssociations( resultset, j, id, session );
				}
				dehydrate( resultset, fields, propsToUpdate, j, id, session );

				// TODO OGM-616 Also use this facet for "all columns" optimistic locking strategy
				if ( isVersioned() && optimisticLockingAwareGridDialect != null ) {
					Tuple oldVersionTuple = new Tuple();
					oldVersionTuple.put( getVersionColumnName(), oldVersion );

					boolean success = optimisticLockingAwareGridDialect.updateTupleWithOptimisticLock( key, oldVersionTuple, resultset, getTupleContext( session ) );

					// If there is an error handler registered, pass the applied/failed operation to it as needed
					if ( success ) {
						if ( invocationCollectingGridDialect != null ) {
							invocationCollectingGridDialect.onUpdateTupleWithOptimisticLockSuccess( key, oldVersionTuple, resultset );
						}
					}
					else {
						if ( invocationCollectingGridDialect != null ) {
							try {
								raiseStaleObjectStateException( id );
							}
							catch (Exception e) {
								invocationCollectingGridDialect.onUpdateTupleWithOptimisticLockFailure( key, oldVersionTuple, resultset, e );
							}
						}
						else {
							raiseStaleObjectStateException( id );
						}
					}
				}
				else {
					insertOrUpdateTuple( key, tuplePointer, hasUpdateGeneratedProperties(), session );
				}

				if ( mightManageInverseAssociations ) {
					addToInverseAssociations( resultset, j, id, session );
				}
			}
		}
	}
1046116
def update_entity(self, entity, agent=None, metadata=None):
        
        self._entity_manager.update_entity(entity, agent=agent,
                metadata=metadata)
167707
public synchronized void storeEventForCurrentAppVersion(double timestamp, int versionCode, String versionName, String eventLabel) {
		EventRecord eventRecord = events.get(eventLabel);
		if (eventRecord == null) {
			eventRecord = new EventRecord();
			events.put(eventLabel, eventRecord);
		}
		eventRecord.update(timestamp, versionName, versionCode);
		notifyDataChanged();
	}
155876
LogMetadata withUpdateVersion(int value) {
        Preconditions.checkArgument(value >= this.updateVersion.get(), "versions must increase");
        this.updateVersion.set(value);
        return this;
    }
26627
public static Map<String, AttributeValueUpdate> toUpdateItem(final Object entity) {
        return toUpdateItem(entity, NamingPolicy.LOWER_CAMEL_CASE);
    }
1200347
private void addModifiedObjectsToEntityManager(List<JPAObject> modified, Long timestamp) {
        for (JPAObject update : modified) {
            update.setTimestamp(timestamp);
            entityManager.persist(update);
        }
    }
530434
@Override
	public void update(Object entity) {
		if (entity == null) {
			throw new IllegalArgumentException("'entity' must not be [" + entity + "]");
		}
		
		assertTransactional();
		((AppEngineGlobalTransaction) transaction.get()).coordinator().update(entity);
	}
48196
public int addOrUpdate(Entity entity) throws SQLException {
		return null == entity.get(primaryKeyField) ? add(entity) : update(entity);
	}
642452
@Override
	public boolean update(T entity) {
		if(entity == null) {
			return false;
		}
		
		X primaryID = getPrimaryID(entity);
		if(primaryID == null) {
			return false;
		}
		
		if(!allowEmptyOrZeroID() && AssertUtils.isEmpty(primaryID)) {
			return false;
		}
		
		this.mongoTemplate.save(entity);
		return true;
	}
834704
public boolean updateEntity(Entity entity) {
        String entityName = entity.getName();
        checkEntityIsEmpty(entityName);
        QueryPart<Entity> queryPart = new Query<Entity>("entities")
                .path(entityName, true);
        return httpClientManager.updateMetaData(queryPart, patch(entity));
    }
231859
public function lock($entity, $lockMode, $lockVersion = null)
    {
        if ($entity === null) {
            throw new \InvalidArgumentException("No entity passed to UnitOfWork#lock().");
        }

        if ($this->getEntityState($entity, self::STATE_DETACHED) != self::STATE_MANAGED) {
            throw ORMInvalidArgumentException::entityNotManaged($entity);
        }

        $class = $this->em->getClassMetadata(get_class($entity));

        switch (true) {
            case LockMode::OPTIMISTIC === $lockMode:
                if ( ! $class->isVersioned) {
                    throw OptimisticLockException::notVersioned($class->name);
                }

                if ($lockVersion === null) {
                    return;
                }

                if ($entity instanceof Proxy && !$entity->__isInitialized__) {
                    $entity->__load();
                }

                $entityVersion = $class->reflFields[$class->versionField]->getValue($entity);

                if ($entityVersion != $lockVersion) {
                    throw OptimisticLockException::lockFailedVersionMismatch($entity, $lockVersion, $entityVersion);
                }

                break;

            case LockMode::NONE === $lockMode:
            case LockMode::PESSIMISTIC_READ === $lockMode:
            case LockMode::PESSIMISTIC_WRITE === $lockMode:
                if (!$this->em->getConnection()->isTransactionActive()) {
                    throw TransactionRequiredException::transactionRequired();
                }

                $oid = spl_object_hash($entity);

                $this->getEntityPersister($class->name)->lock(
                    array_combine($class->getIdentifierFieldNames(), $this->entityIdentifiers[$oid]),
                    $lockMode
                );
                break;

            default:
                // Do nothing
        }
    }
1343703
public static AuditEntryBean apiVersionUpdated(ApiVersionBean bean, EntityUpdatedData data,
            ISecurityContext securityContext) {
        if (data.getChanges().isEmpty()) {
            return null;
        }
        AuditEntryBean entry = newEntry(bean.getApi().getOrganization().getId(), AuditEntityType.Api, securityContext);
        entry.setEntityId(bean.getApi().getId());
        entry.setEntityVersion(bean.getVersion());
        entry.setWhat(AuditEntryType.Update);
        entry.setData(toJSON(data));
        return entry;
    }