/*
(non-Javadoc)

@see
com.impetus.kundera.client.ClientBase#onPersist(com.impetus.kundera.metadata
.model.EntityMetadata, java.lang.Object, java.lang.Object,
java.util.List)
507614
@Override
    protected void onPersist(EntityMetadata metadata, Object entity, Object id, List<RelationHolder> relationHolders)
    {
        boolean proxyRemoved = removeKunderaProxies(metadata, entity, relationHolders);

        Transaction tx = null;

        s = getStatelessSession();
        tx = onBegin();
        try
        {
            if (!isUpdate)
            {
                id = s.insert(entity);

                // Update foreign Keys
                updateForeignKeys(metadata, id, relationHolders);
                onCommit(tx);/* tx.commit(); */
            }
            else
            {
                s.update(entity);

                if (proxyRemoved)
                {
                    updateForeignKeys(metadata, id, relationHolders);
                }

                onCommit(tx);
            }
        }
        // TODO: Bad code, get rid of these exceptions, currently necessary for
        // handling many to one case
        catch (org.hibernate.exception.ConstraintViolationException e)
        {
            s.update(entity);
            log.info(e.getMessage());
            onCommit(tx);
            // tx.commit();
        }
        catch (HibernateException e)
        {
            log.error("Error while persisting object of {}, Caused by {}.", metadata.getEntityClazz(), e);
            throw new PersistenceException(e);
        }
    }
562365
byte[] loadPersist() {
    // 00       assert: not written yet
    // 01       assert: load-after-delete
    // 10       expected; read
    // 11       assert: load-after-delete
    assert isPersisted();
    try {
      byte[] res = H2O.getPM().load(backend(), this);
      assert !isDeleted();        // Race in user-land: load-after-delete
      return res;
    } catch( IOException ioe ) { throw Log.throwErr(ioe); }
  }
1340051
protected void onBeforeRender() {
        super.onBeforeRender();
        if (runtimeModel.isEdit()) {
            for (QueryParameter parameter : convertMap.values()) {
                populateDependentParameters(parameter, null);
            }
        }
    }
1370999
public void setUserIdList(java.util.Collection<String> userIdList) {
        if (userIdList == null) {
            this.userIdList = null;
            return;
        }

        this.userIdList = new java.util.ArrayList<String>(userIdList);
    }
388339
private void onIdAttribute(final MetaModelBuilder builder, EntityMetadata entityMetadata, final Class clazz, Field f)
    {
        EntityType entity = (EntityType) builder.getManagedTypes().get(clazz);

        Attribute attrib = entity.getAttribute(f.getName());
        if (!attrib.isCollection() && ((SingularAttribute) attrib).isId())
        {
            entityMetadata.setIdAttribute((SingularAttribute) attrib);
            populateIdAccessorMethods(entityMetadata, clazz, f);
        }
    }
944088
public void setPTableRef(PTable pTable, PhysicalDatabaseParent dbOwner)
    {
        m_pTable = pTable;
        if (pTable == null)
            if (dbOwner != null)
        {
            FieldList record = this.getRecord();
            if (record != null)
            {
                PDatabase pDatabase = dbOwner.getPDatabase(record.getDatabaseName(), ThinPhysicalDatabase.MEMORY_TYPE, true);
                pDatabase.addPDatabaseOwner(this);
                if (pDatabase != null)
                    pTable = pDatabase.getPTable(record, true);
                pTable.addPTableOwner(this);
                m_pTable = pTable;
            }
        }
    }
707024
private void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders,
            Object connection)
    {
        // first open a pipeline
        AttributeWrapper wrapper = wrap(entityMetadata, entity);

        // add relations.

        if (rlHolders != null)
        {
            for (RelationHolder relation : rlHolders)
            {
                String name = relation.getRelationName();
                Object value = relation.getRelationValue();
                byte[] valueInBytes = PropertyAccessorHelper.getBytes(value);
                byte[] nameInBytes = getEncodedBytes(name);
                String valueAsStr = PropertyAccessorHelper.getString(value);
                wrapper.addColumn(nameInBytes, valueInBytes);
                wrapper.addIndex(getHashKey(entityMetadata.getTableName(), name), getDouble(valueAsStr));

                // this index is required to work for UNION/INTERSECT
                // support.

                wrapper.addIndex(getHashKey(entityMetadata.getTableName(), getHashKey(name, valueAsStr)),
                        getDouble(valueAsStr));
            }
        }

        // prepareCompositeKey

        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                entityMetadata.getPersistenceUnit());

        EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());
        String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();
        String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue();

        // No need to check for empty or blank, as considering it as valid name
        // for nosql!
        if (discrColumn != null && discrValue != null)
        {
            byte[] valueInBytes = PropertyAccessorHelper.getBytes(discrValue);
            byte[] nameInBytes = getEncodedBytes(discrColumn);
            wrapper.addColumn(nameInBytes, valueInBytes);
            wrapper.addIndex(getHashKey(entityMetadata.getTableName(), discrColumn), getDouble(discrValue));
            wrapper.addIndex(getHashKey(entityMetadata.getTableName(), getHashKey(discrColumn, discrValue)),
                    getDouble(discrValue));
        }

        String rowKey = null;
        if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType()))
        {
            rowKey = KunderaCoreUtils.prepareCompositeKey(entityMetadata, id);
        }
        else
        {
            ObjectAccessor accessor = new ObjectAccessor();
            rowKey = accessor.toString(id);
            // rowKey = /*PropertyAccessorHelper.getString(entity, (Field)
            // entityMetadata.getIdAttribute().getJavaMember())*/ ;
        }

        String hashKey = getHashKey(entityMetadata.getTableName(), rowKey);

        if (resource != null && resource.isActive())
        {
            ((Transaction) connection).hmset(getEncodedBytes(hashKey), wrapper.getColumns());
        }
        else
        {
            ((Pipeline) connection).hmset(getEncodedBytes(hashKey), wrapper.getColumns());
        }

        // Add inverted indexes for column based search.

        // // Add row key to list(Required for wild search over table).
        //
        // wrapper.addIndex(getHashKey(entityMetadata.getTableName(),
        // ((AbstractAttribute)
        // entityMetadata.getIdAttribute()).getJPAColumnName()),
        // getDouble(rowKey));
        //
        // // Add row-key as inverted index as well needed for multiple clause
        // // search with key and non row key.
        // wrapper.addIndex(getHashKey(
        // entityMetadata.getTableName(),
        // getHashKey(((AbstractAttribute)
        // entityMetadata.getIdAttribute()).getJPAColumnName(), rowKey)),
        // getDouble(rowKey));
        KunderaCoreUtils.printQuery(
                "Persist data into " + entityMetadata.getSchema() + "." + entityMetadata.getTableName()
                        + " for primary key " + rowKey, showQuery);
        addIndex(connection, wrapper, rowKey, entityMetadata);

    }
1369404
@Override
    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
    {
        HttpResponse response = null;
        try
        {
            JsonObject object = CouchDBObjectMapper.getJsonOfEntity(entityMetadata, entity, id, rlHolders,
                    kunderaMetadata);

            String _id = object.get("_id").getAsString();

            URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
                    CouchDBConstants.URL_SEPARATOR + entityMetadata.getSchema().toLowerCase()
                            + CouchDBConstants.URL_SEPARATOR + _id, null, null);

            HttpPut put = new HttpPut(uri);

            StringEntity stringEntity = null;

            if (isUpdate)
            {
                HttpGet get = new HttpGet(uri);
                get.addHeader("Accept", "application/json");
                response = httpClient.execute(httpHost, get, CouchDBUtils.getContext(httpHost));

                try
                {
                    InputStream content = response.getEntity().getContent();
                    Reader reader = new InputStreamReader(content);
                    JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
                    JsonElement rev = jsonObject.get("_rev");
                    object.add("_rev", rev);
                }
                finally
                {
                    closeContent(response);
                }
            }
            object.addProperty("_id", entityMetadata.getTableName() + id);
            stringEntity = new StringEntity(object.toString(), Constants.CHARSET_UTF8);
            stringEntity.setContentType("application/json");
            put.setEntity(stringEntity);

            response = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));

        }
        catch (Exception e)
        {
            log.error("Error while persisting entity with id {}, caused by {}. ", id, e);
            throw new KunderaException(e);
        }
        finally
        {
            closeContent(response);
        }
    }
1321766
@Override
	public void cacheResult(List<CPFriendlyURLEntry> cpFriendlyURLEntries) {
		for (CPFriendlyURLEntry cpFriendlyURLEntry : cpFriendlyURLEntries) {
			if (entityCache.getResult(
						CPFriendlyURLEntryModelImpl.ENTITY_CACHE_ENABLED,
						CPFriendlyURLEntryImpl.class,
						cpFriendlyURLEntry.getPrimaryKey()) == null) {
				cacheResult(cpFriendlyURLEntry);
			}
			else {
				cpFriendlyURLEntry.resetOriginalValues();
			}
		}
	}
5855
@Override
    protected void onPersist(EntityMetadata metadata, Object entity, Object id, List<RelationHolder> rlHolders)
    {

        if (!isOpen())
        {
            throw new PersistenceException("PelopsClient is closed.");
        }

        // check for counter column
        if (isUpdate && metadata.isCounterColumnType())
        {
            throw new UnsupportedOperationException("Invalid operation! Merge is not possible over counter column.");
        }

        String insert_Query = null;
        if (isCql3Enabled(metadata))
        {
            Cassandra.Client client = getRawClient(metadata.getSchema());
            try
            {
                cqlClient.persist(metadata, entity, client, rlHolders, getTtlValues().get(metadata.getTableName()));
            }
            catch (InvalidRequestException e)
            {
                log.error("Error during persist while executing query {}, Caused by: .", insert_Query, e);
                throw new KunderaException(e);
            }
            catch (TException e)
            {
                log.error("Error during persist while executing query {}, Caused by: .", insert_Query, e);
                throw new KunderaException(e);
            }
            catch (UnsupportedEncodingException e)
            {
                log.error("Error during persist while executing query {}, Caused by: .", insert_Query, e);
                throw new KunderaException(e);
            }
        }
        else
        {
            Collection<ThriftRow> tfRows = null;
            try
            {
                String columnFamily = metadata.getTableName();
                tfRows = dataHandler.toThriftRow(entity, id, metadata, columnFamily, getTtlValues().get(columnFamily));
            }
            catch (Exception e)
            {
                log.error("Error during persist, Caused by: .", e);
                throw new KunderaException(e);
            }
            for (ThriftRow tf : tfRows)
            {

                if (tf.getColumnFamilyName().equals(metadata.getTableName()))
                {
                    addRelationsToThriftRow(metadata, tf, rlHolders);
                }
                Mutator mutator = clientFactory.getMutator(pool);
                if (metadata.isCounterColumnType())
                {
                    if (log.isInfoEnabled())
                    {
                        log.info("Persisting counter column family record for row key {}", tf.getId());
                    }
                    List<CounterColumn> thriftCounterColumns = tf.getCounterColumns();
                    List<CounterSuperColumn> thriftCounterSuperColumns = tf.getCounterSuperColumns();
                    if (thriftCounterColumns != null && !thriftCounterColumns.isEmpty())
                    {
                        mutator.writeCounterColumns(tf.getColumnFamilyName(),
                                Bytes.fromByteBuffer(CassandraUtilities.toBytes(tf.getId(), tf.getId().getClass())),
                                Arrays.asList(tf.getCounterColumns().toArray(new CounterColumn[0])));
                    }

                    if (thriftCounterSuperColumns != null && !thriftCounterSuperColumns.isEmpty())
                    {
                        for (CounterSuperColumn sc : thriftCounterSuperColumns)
                        {
                            mutator.writeSubCounterColumns(
                                    tf.getColumnFamilyName(),
                                    Bytes.fromByteBuffer(CassandraUtilities.toBytes(tf.getId(), tf.getId().getClass())),
                                    Bytes.fromByteArray(sc.getName()), sc.getColumns());
                        }
                    }
                }
                else
                {
                    List<Column> thriftColumns = tf.getColumns();
                    List<SuperColumn> thriftSuperColumns = tf.getSuperColumns();
                    if (thriftColumns != null && !thriftColumns.isEmpty())
                    {
                        // Bytes.from
                        mutator.writeColumns(tf.getColumnFamilyName(),
                                Bytes.fromByteBuffer(CassandraUtilities.toBytes(tf.getId(), tf.getId().getClass())),
                                tf.getColumns());
                    }

                    if (thriftSuperColumns != null && !thriftSuperColumns.isEmpty())
                    {
                        for (SuperColumn sc : thriftSuperColumns)
                        {
                            if (log.isInfoEnabled())
                            {
                                log.info("Persisting super column family record for row key {}", tf.getId());
                            }

                            mutator.writeSubColumns(
                                    tf.getColumnFamilyName(),
                                    Bytes.fromByteBuffer(CassandraUtilities.toBytes(tf.getId(), tf.getId().getClass())),
                                    Bytes.fromByteArray(sc.getName()), sc.getColumns());
                        }
                    }
                }
                mutator.execute(getConsistencyLevel());
            }
            tfRows = null;
            if (isTtlPerRequest())
            {
                getTtlValues().clear();
            }
        }
    }
789026
@Override
	public void cacheResult(List<CommerceWishListItem> commerceWishListItems) {
		for (CommerceWishListItem commerceWishListItem : commerceWishListItems) {
			if (entityCache.getResult(
						CommerceWishListItemModelImpl.ENTITY_CACHE_ENABLED,
						CommerceWishListItemImpl.class,
						commerceWishListItem.getPrimaryKey()) == null) {
				cacheResult(commerceWishListItem);
			}
			else {
				commerceWishListItem.resetOriginalValues();
			}
		}
	}
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);
        }
    }
956732
private <T> void doInterceptBeforeUpdate(List<Object> tList, String setSql, List<Object> setSqlArgs) {
		for (DBHelperInterceptor interceptor : interceptors) {
			boolean isContinue = interceptor.beforeUpdate(tList, setSql, setSqlArgs);
			if (!isContinue) {
				throw new NotAllowQueryException("interceptor class:" + interceptor.getClass());
			}
		}
	}
256679
public function postPersist(ClassMetadata $class, $document)
    {
        $class->invokeLifecycleCallbacks(Event::postPersist, $document, [new LifecycleEventArgs($document, $this->dm)]);
        $this->evm->dispatchEvent(Event::postPersist, new LifecycleEventArgs($document, $this->dm));
        $this->cascadePostPersist($class, $document);
    }
614537
public static EntityKey fromPersister(
			final OgmEntityPersister persister,
			final Serializable id,
			SharedSessionContractImplementor session) {
		return fromData(
				persister.getEntityKeyMetadata(),
				persister.getGridIdentifierType(),
				id,
				session );
	}
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);
    }
481382
@Override
	public void cacheResult(List<CommerceTaxFixedRate> commerceTaxFixedRates) {
		for (CommerceTaxFixedRate commerceTaxFixedRate : commerceTaxFixedRates) {
			if (entityCache.getResult(
						CommerceTaxFixedRateModelImpl.ENTITY_CACHE_ENABLED,
						CommerceTaxFixedRateImpl.class,
						commerceTaxFixedRate.getPrimaryKey()) == null) {
				cacheResult(commerceTaxFixedRate);
			}
			else {
				commerceTaxFixedRate.resetOriginalValues();
			}
		}
	}