/*
(non-Javadoc)

@see
com.impetus.kundera.client.ClientBase#onPersist(com.impetus.kundera.metadata
.model.EntityMetadata, java.lang.Object, java.lang.Object,
java.util.List)
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();
            }
        }
    }
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); }
  }
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);
        }
    }
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);

    }
830059
protected void initIndexPersistableListener() {
        _index.setPersistableListener(new PersistableListener() {
            @Override
            public void beforePersist() {
                try {
                    PersistableListener l = _listener;
                    if(l != null) l.beforePersist();
                } catch (Exception e) {
                    _logger.error("failed on calling beforePersist", e);
                }
                
                try {
                    _bytesDB.persist();
                } catch (Exception e) {
                    _logger.error("failed on calling beforePersist", e);
                }
            }
            
            @Override
            public void afterPersist() {
                try {
                    PersistableListener l = _listener;
                    if(l != null) l.afterPersist();
                } catch(Exception e) {
                    _logger.error("failed on calling afterPersist", e);
                }
            }
        });
    }
1059055
private void onFamilyType(EntityMetadata entityMetadata, final Class clazz, Field f)
    {
        if (entityMetadata.getType() == null || !entityMetadata.getType().equals(Type.SUPER_COLUMN_FAMILY))
        {
            if ((f.isAnnotationPresent(Embedded.class) && f.getType().getAnnotation(Embeddable.class) != null))
            {
                entityMetadata.setType(Type.SUPER_COLUMN_FAMILY);
            }
            else if (f.isAnnotationPresent(ElementCollection.class) && !MetadataUtils.isBasicElementCollectionField(f))
            {
                entityMetadata.setType(Type.SUPER_COLUMN_FAMILY);
            }
            else
            {
                entityMetadata.setType(Type.COLUMN_FAMILY);
            }
        }
    }
476944
@Override
	public void onQuery() {

		final App app = StructrApp.getInstance();
		try (final Tx tx = app.tx()) {

			final Map<String, SharedNodeInterface> nodes = new LinkedHashMap<>();
			for (final SharedNodeInterface node : app.nodeQuery(SharedNodeInterface.class).getAsList()) {
				nodes.put(node.getUuid(), node);
			}

			if (nodes.size() != repository.objectCount()) {

				logger.info("Rebuilding list of shared objects: {} vs. {}", new Object[] { nodes.size(), repository.objectCount() } );

				repository.clear();

				for (final SharedNodeInterface node : nodes.values()) {
					addObjectToRepository(node);
				}
			}

			tx.success();

		} catch (FrameworkException fex) {

			logger.warn("", fex);
		}
	}
882970
@Override
	public void onAfterSave(Object source, DBObject dbo) {
		this.persister.onAfterSave(source, dbo);
	}
225477
function onIceCandidate(id,data)
    {
        if(scope.hasWebRTCSupport())
        {
            getOrCreatePeer(id).onServerMessage(JSON.parse(data));
        }
    }
507817
@Override
    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
    {

        KuduSession session = kuduClient.newSession();
        KuduTable table = null;
        try
        {
            table = kuduClient.openTable(entityMetadata.getTableName());
        }
        catch (Exception e)
        {
            logger.error("Cannot open table : " + entityMetadata.getTableName(), e);
            throw new KunderaException("Cannot open table : " + entityMetadata.getTableName(), e);
        }
        Operation operation = isUpdate ? table.newUpdate() : table.newInsert();
        PartialRow row = operation.getRow();
        populatePartialRow(row, entityMetadata, entity);
        try
        {
            session.apply(operation);
        }
        catch (Exception e)
        {
            logger.error("Cannot insert/update row in table : " + entityMetadata.getTableName(), e);
            throw new KunderaException("Cannot insert/update row in table : " + entityMetadata.getTableName(), e);
        }
        finally
        {
            try
            {
                session.close();
            }
            catch (Exception e)
            {
                logger.error("Cannot close session", e);
                throw new KunderaException("Cannot close session", e);
            }
        }
    }
866180
public <M extends Model> Persister<M> withPersister(String server) {
        Persister<M> persister = _getPersister(server);
        if (persister == null) {
            throw new NotPersisterFindException();
        }
        return persister;
    }
969798
@Override
    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
    {
        // TODO Auto-generated method stub
        // handle persist object
        PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(
                persistenceUnit);
        String clientName = puMetadata.getProperty(DATA_CLIENT).toLowerCase();

        List listEntity = new ArrayList<>();
        listEntity.add(entity);

        SparkDataClient dataClient = SparkDataClientFactory.getDataClient(clientName);

        dataClient.persist(listEntity, entityMetadata, this);
    }
602743
private void onParseRelation(Object entity, final PersistenceDelegator pd, EntityMetadata targetEntityMetadata,
            Object relationEntity, Relation relation, boolean lazilyloaded, Map<Object, Object> relationStack)
    {
        parseRelations(entity, getEntity(relationEntity), getPersistedRelations(relationEntity), pd,
                targetEntityMetadata, lazilyloaded, relationStack);

        // if relation ship is unary, no problem else we need to add
        setRelationToEntity(entity, relationEntity, relation);
    }
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();
			}
		}
	}
108129
private void onRelation(Object entity, Map<String, Object> relationsMap, final Relation relation,
            final EntityMetadata metadata, final PersistenceDelegator pd, boolean lazilyloaded,
            Map<Object, Object> relationStack)
    {
        final Object entityId = PropertyAccessorHelper.getId(entity, metadata);

        // if relation map contains value, then invoke target entity with find
        // by id.
        // else invoke target entity for find by relation, pass it's entityId as
        // a column value and relation.getJoinColumnName as column name.

        Object relationValue = relationsMap != null ? relationsMap.get(relation.getJoinColumnName(kunderaMetadata))
                : null;
        EntityMetadata targetEntityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                relation.getTargetEntity());

        List relationalEntities = fetchRelations(relation, metadata, pd, entityId, relationValue, targetEntityMetadata);

        if (relationalEntities != null)
        {

            for (Object relationEntity : relationalEntities)
            {
                if (relationEntity != null)
                {
                    addToRelationStack(relationStack, relationEntity, targetEntityMetadata);
                }
            }
            for (Object relationEntity : relationalEntities)
            {
                if (relationEntity != null)
                {
                    onParseRelation(entity, pd, targetEntityMetadata, relationEntity, relation, lazilyloaded,
                            relationStack);
                    PersistenceCacheManager.addEntityToPersistenceCache(getEntity(relationEntity), pd,
                            PropertyAccessorHelper.getId(relationEntity, targetEntityMetadata));
                }
            }
        }

    }
289287
@Override
    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
    {
        Connection conn = getConnection();
        try
        {
            // if entity is embeddable...call cql translator to get cql string!
            // use thrift client to execute cql query.

            if (isCql3Enabled(entityMetadata))
            {
                cqlClient.persist(entityMetadata, entity, conn.getClient(), rlHolders,
                        getTtlValues().get(entityMetadata.getTableName()));
            }
            else
            {
                Map<ByteBuffer, Map<String, List<Mutation>>> mutationMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>();
                prepareMutation(entityMetadata, entity, id, rlHolders, mutationMap);
                // Write Mutation map to database
                conn.getClient().batch_mutate(mutationMap, getConsistencyLevel());

                mutationMap.clear();
                mutationMap = null;
            }

        }
        catch (InvalidRequestException e)
        {
            log.error("Error while persisting record, Caused by: .", e);
            throw new KunderaException(e);
        }
        catch (TException e)
        {
            log.error("Error while persisting record, Caused by: .", e);
            throw new KunderaException(e);
        }
        catch (UnsupportedEncodingException e)
        {
            log.error("Error while persisting record, Caused by: .", e);
            throw new KunderaException(e);
        }
        finally
        {
            releaseConnection(conn);

            if (isTtlPerRequest())
            {
                getTtlValues().clear();
            }
        }
    }