/*
(non-Javadoc)

@see
com.impetus.kundera.client.Client#persistJoinTable(com.impetus.kundera
.persistence.context.jointable.JoinTableData)
557544
@Override
    public void persistJoinTable(JoinTableData joinTableData)
    {
        String joinTableName = joinTableData.getJoinTableName();
        String joinColumnName = joinTableData.getJoinColumnName();
        String invJoinColumnName = joinTableData.getInverseJoinColumnName();
        Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();

        DBCollection dbCollection = mongoDb.getCollection(joinTableName);
        KunderaCoreUtils.printQuery("Persist join table:" + joinTableName, showQuery);

        for (Object key : joinTableRecords.keySet())
        {
            Set<Object> values = joinTableRecords.get(key);
            Object joinColumnValue = key;

            for (Object childId : values)
            {
                DBObject dbObj = new BasicDBObject();
                dbObj.put("_id", joinColumnValue.toString() + childId);
                dbObj.put(joinColumnName, MongoDBUtils.populateValue(joinColumnValue, joinColumnValue.getClass()));
                dbObj.put(invJoinColumnName, MongoDBUtils.populateValue(childId, childId.getClass()));
                KunderaCoreUtils.printQuery("id:" + joinColumnValue.toString() + childId + "   " + joinColumnName + ":"
                        + joinColumnValue + "   " + invJoinColumnName + ":" + childId, showQuery);

                dbCollection.save(dbObj, getWriteConcern());
            }
        }
    }
993629
public long persist(File persistFile) {
        try {
            FileOutputStream fileStream = new FileOutputStream(persistFile);
            ObjectOutputStream oStream = new ObjectOutputStream((fileStream));

            long persistVersion;
            Map<String, ChangedFile> fileListCopy;
            synchronized (this) {
                fileListCopy = (Map<String, ChangedFile>) fileList.clone();
                fileListCopy.putAll(reservedFiles);
                persistVersion = listVersion;
            }

            oStream.writeObject(fileListCopy);
            oStream.close();
            return persistVersion;
        } catch (IOException e) {
            throw new RuntimeException("Unable to persist File Changed List:" +
                                       e.getMessage(), e);
        }
    }
808367
public void persist(Node node)
    {
        Object entity = node.getData();
        Object id = node.getEntityId();
        EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, node.getDataClass());
        isUpdate = node.isUpdate();
        List<RelationHolder> relationHolders = getRelationHolders(node);
        onPersist(metadata, entity, id, relationHolders);
        id = PropertyAccessorHelper.getId(entity, metadata);
        node.setEntityId(id);
        indexNode(node, metadata);
    }
845644
void persist(final String key, final String value, final boolean enableDisableMode, final boolean disable, final File file) throws IOException, StartException {
        persist(key, value, enableDisableMode, disable, file, null);
    }
817823
@Override
	public <S extends T> S save(S entity, boolean consistentRead) {
		return operations.createOrUpdate(entity);
	}
1311873
protected function linkJoinTable()
    {
        // Join to the many-many join table
        $dataClassIDColumn = DataObject::getSchema()->sqlColumnForField($this->dataClass(), 'ID');
        $this->dataQuery->innerJoin(
            $this->joinTable,
            "\"{$this->joinTable}\".\"{$this->localKey}\" = {$dataClassIDColumn}"
        );

        // Add the extra fields to the query
        if ($this->extraFields) {
            $this->appendExtraFieldsToQuery();
        }
    }
1209582
private void addJoinTable(List<Relation> relations)
    {
        for (Relation relation : relations)
        {
            if (relation.getType().equals(ForeignKey.MANY_TO_MANY) && relation.isRelatedViaJoinTable())
            {
                String joinTableName = relation.getJoinTableMetadata().getJoinTableName();
                String hTableName = HBaseUtils.getHTableName(databaseName, joinTableName);
                HTableDescriptor tableDescriptor = new HTableDescriptor(TableName.valueOf(hTableName));
                tableDescriptor.addFamily(new HColumnDescriptor(joinTableName));
                createOrUpdateTable(hTableName, tableDescriptor);
            }
        }
    }
642703
private void populateCollectionFromJoinTable(Object entity, EntityMetadata entityMetadata,
            PersistenceDelegator delegator, Relation relation)
    {
        JoinTableMetadata jtMetadata = relation.getJoinTableMetadata();
        Client pClient = delegator.getClient(entityMetadata);

        String schema = entityMetadata.getSchema();

        EntityMetadata owningEntityMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),
                relation.getTargetEntity());
        Class columnJavaType = owningEntityMetadata.getIdAttribute().getJavaType();
        if (jtMetadata == null)
        {
            columnJavaType = entityMetadata.getIdAttribute().getJavaType();
            Relation owningEntityMetadataRelation = owningEntityMetadata.getRelation(relation.getMappedBy());
            jtMetadata = owningEntityMetadataRelation.getJoinTableMetadata();
            pClient = delegator.getClient(owningEntityMetadata);
            schema = owningEntityMetadata.getSchema();
        }

        String joinTableName = jtMetadata.getJoinTableName();

        Set<String> joinColumns = jtMetadata.getJoinColumns();
        Set<String> inverseJoinColumns = jtMetadata.getInverseJoinColumns();

        String joinColumnName = (String) joinColumns.toArray()[0];
        String inverseJoinColumnName = (String) inverseJoinColumns.toArray()[0];

        Object entityId = PropertyAccessorHelper.getId(entity, entityMetadata);
        List<?> foreignKeys = pClient.getColumnsById(schema, joinTableName, joinColumnName, inverseJoinColumnName,
                entityId, columnJavaType);

        List childrenEntities = new ArrayList();

        if (foreignKeys != null)
        {
            for (Object foreignKey : foreignKeys)
            {
                EntityMetadata childMetadata = KunderaMetadataManager.getEntityMetadata(delegator.getKunderaMetadata(),
                        relation.getTargetEntity());

                Object child = delegator.find(relation.getTargetEntity(), foreignKey);
                Object obj = child instanceof EnhanceEntity && child != null ? ((EnhanceEntity) child).getEntity()
                        : child;

                // If child has any bidirectional relationship, process them
                // here
                Field biDirectionalField = relation.getBiDirectionalField();
                boolean isBidirectionalRelation = (biDirectionalField != null);

                if (isBidirectionalRelation && obj != null)
                {
                    Object columnValue = PropertyAccessorHelper.getId(obj, childMetadata);
                    Object[] pKeys = pClient.findIdsByColumn(entityMetadata.getSchema(), joinTableName, joinColumnName,
                            inverseJoinColumnName, columnValue, entityMetadata.getEntityClazz());
                    List parents = delegator.find(entity.getClass(), pKeys);
                    PropertyAccessorHelper.set(obj, biDirectionalField,
                            ObjectUtils.getFieldInstance(parents, biDirectionalField));
                    PersistenceCacheManager.addEntityToPersistenceCache(obj, delegator, columnValue);
                }

                childrenEntities.add(obj);
            }
        }
        Field childField = relation.getProperty();

        try
        {
            PropertyAccessorHelper.set(
                    entity,
                    childField,
                    PropertyAccessorHelper.isCollection(childField.getType()) ? ObjectUtils.getFieldInstance(
                            childrenEntities, childField) : childrenEntities.get(0));
            PersistenceCacheManager.addEntityToPersistenceCache(entity, delegator, entityId);
        }
        catch (PropertyAccessException ex)
        {
            throw new EntityReaderException(ex);
        }
    }
970817
@SuppressWarnings("unchecked")
	public <T> T save(T entity) {
		if (entity == null) {
			throw new ApitraryOrmException("Cannot persist null entity");
		}
		log.debug("Saving " + entity.getClass());

		PostRequest request = new PostRequest();
		request.setEntity(resolveApitraryEntity(entity));

		String payload = marshall(entity);

		request.setRequestPayload(payload);

		PostResponse response = resolveApitraryClient().send(request);

		if (HttpStatus.Created.ordinal() == response.getStatusCode()) {
			return (T) new PostResponseUnmarshaller().unMarshall(response, entity);
		} else {
			throw new ApitraryOrmException(response.getResult());
		}
	}
1178052
private void processEmbeddable(Object entity, HBaseDataWrapper hbaseData, EntityMetadata m,
            MetamodelImpl metaModel, int count, String prefix, Attribute attribute, Class javaType)
    {
        Set<Attribute> attribEmbeddables = metaModel.embeddable(javaType).getAttributes();
        Object embeddedField = KunderaCoreUtils.createNewInstance(javaType);
        if (!attribute.isCollection())
        {
            String newPrefix = prefix != "" ? prefix + ((AbstractAttribute) attribute).getJPAColumnName()
                    + HBaseUtils.DOT : ((AbstractAttribute) attribute).getJPAColumnName() + HBaseUtils.DOT;
            writeValuesToEntity(embeddedField, hbaseData, m, metaModel, attribEmbeddables, null, null, count, newPrefix);
            PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), embeddedField);
        }
        else
        {
            int newCount = count + 1;
            String newPrefix = prefix != "" ? prefix + ((AbstractAttribute) attribute).getJPAColumnName()
                    + HBaseUtils.DELIM : ((AbstractAttribute) attribute).getJPAColumnName() + HBaseUtils.DELIM;
            List embeddedCollection = new ArrayList();
            byte[] columnValue = hbaseData.getColumnValue(HBaseUtils.getColumnDataKey(m.getTableName(), newPrefix
                    + HBaseUtils.SIZE));
            int size = 0;
            if (columnValue != null)
            {
                size = Bytes.toInt(columnValue);
            }
            while (size != newCount)
            {
                embeddedField = KunderaCoreUtils.createNewInstance(javaType);
                writeValuesToEntity(embeddedField, hbaseData, m, metaModel, attribEmbeddables, null, null, newCount++,
                        newPrefix);
                embeddedCollection.add(embeddedField);
            }
            PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), embeddedCollection);
        }
    }
1035343
public function save(Persistable $persistable) : void
    {
        $data = $this->serializer->serialize($persistable);

        $success = $this->connector->set($this->key, $data);

        if (!$success) {
            throw new RuntimeException('Failed to save persistable'
                . ' to the database.');
        }
    }
837685
static void joinExtendedPC(JPAExPcBindingContext bindingContext, AbstractJPAComponent jpaComponent) {
        final boolean isTraceOn = TraceComponent.isAnyTracingEnabled();
        if (isTraceOn && tc.isEntryEnabled())
            Tr.entry(tc, "enlistExtendedPC: " + bindingContext.thisToString());

        if (bindingContext.isBmt()) {
            if (isTraceOn && tc.isEntryEnabled())
                Tr.exit(tc, "enlistExtendedPC: incorrectly called with BMT context");
            throw new IllegalArgumentException();
        }

        UOWCoordinator uowCoord = jpaComponent.getUOWCurrent().getUOWCoord();
        if (!uowCoord.isGlobal()) {
            if (isTraceOn && tc.isEntryEnabled())
                Tr.exit(tc, "enlistExtendedPC: incorrectly called outside global tx");
            throw new IllegalStateException();
        }

        SynchronizationRegistryUOWScope uowSyncRegistry = getSynchronizationRegistryUOWScope(uowCoord);

        // New this binding key only once and update the puid in the loop
        ExPcBindingKey bindingKey = new ExPcBindingKey(bindingContext.getBindId(), null);
        for (JPAPuId puId : bindingContext.getExPcPuIds()) {
            bindingKey.puId = puId;
            ExPcBindingInfo exPcBindingInfo = getExPcBindingInfo(bindingKey);
            boolean txUnsynchronized = exPcBindingInfo.isTxUnsynchronized();

            if (exPcBindingInfo.em == null) {
                if (isTraceOn && tc.isDebugEnabled())
                    Tr.debug(tc, "not joining unused lazy persistence context");

                // Per spec, we should associate an invocation with the
                // transaction to either give an error now if an incompatible
                // EM is already associated with the transaction, to give an
                // error if a subsequent SFSB is enlisted with a different ExPC,
                // or to ensure that this ExPC is used by all EMs (ExPC or
                // otherwise) that access the PU from this transaction.  We have
                // never done this eager enlistment (and instead done lazy
                // enlistment and lazy EM acquisition), so we can't change now
                // without risking a change in behavior.
            } else {
                JPAExEmInvocation invocationEm = getInvocation(uowSyncRegistry, exPcBindingInfo.txKeyPuId);
                if (invocationEm == null) {
                    if (isTraceOn && tc.isDebugEnabled())
                        Tr.debug(tc, "joining " + exPcBindingInfo.txKeyPuId);

                    invocationEm = jpaComponent.getJPARuntime().createExEmInvocation(uowCoord, exPcBindingInfo.em, txUnsynchronized);
                    setInvocation(uowSyncRegistry, exPcBindingInfo.txKeyPuId, invocationEm);

                    // JPA 5.9.1 Container Responsibilities
                    //
                    // For stateful session beans with extended persistence contexts:
                    // ** When a business method of the stateful session bean is invoked, if the stateful
                    //    session bean uses container managed transaction demarcation, and the entity
                    //    manager is not already associated with the current JTA transaction, the
                    //    container associates the entity manager with the current JTA transaction and
                    //    calls EntityManager.joinTransaction.

                    // Verify that the tx synchronizations are compatible
                    if (txUnsynchronized != invocationEm.ivUnsynchronized) {
                        Tr.error(tc, "JPATXSYNC_ILLEGAL_PROPAGATION_CWWJP0046E");
                        String msgTxt = "CWWJP0046E: An UNSYNCHRONIZED JPA persistence context cannot be propagated into a SYNCHRONIZED EntityManager.";
                        throw new IllegalStateException(msgTxt);
                    }
                    if (!txUnsynchronized) {
                        exPcBindingInfo.em.joinTransaction();
                    }
                } else {
                    // JPA 5.9.1 Container Responsibilities
                    //
                    // For stateful session beans with extended persistence contexts:
                    // ** If there is a different persistence context already associated with the JTA
                    //    transaction, the container throws the EJBException.
                    if (invocationEm.ivEm != exPcBindingInfo.em) {
                        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
                            Tr.exit(tc, "enlistExtendedPC : Different persistence context already associate with a JTA tx.");
                        throw jpaComponent.getExPcBindingContext().newEJBException
                                        ("5.9.1 A persistence context is associated to the current JTA transaction " +
                                         "and it is different than the extend-scoped persistence context bound to this SFSB.");
                    }

                    // Verify that the tx synchronizations are compatible
                    if (txUnsynchronized != invocationEm.ivUnsynchronized) {
                        Tr.error(tc, "JPATXSYNC_INCOMPATIBLE_PROPAGATION_CWWJP0047E",
                                 exPcBindingInfo.txKeyPuId,
                                 (invocationEm.ivUnsynchronized ? "UNSYNCHRONIZED" : "SYNCHRONIZED"),
                                 bindingContext.getName());

                        StringBuilder sb = new StringBuilder();
                        sb.append("CWWJP0047E: The persistence context associated with persistence unit '");
                        sb.append(exPcBindingInfo.txKeyPuId);
                        sb.append("' has SynchronizationType of type ");
                        sb.append((invocationEm.ivUnsynchronized ? "UNSYNCHRONIZED" : "SYNCHRONIZED"));
                        sb.append(", which is incompatible with the extended persistence context ");
                        sb.append("declared by ");
                        sb.append(bindingContext.getName());
                        throw new IllegalStateException(new String(sb));
                    }
                }
            }
        }

        if (isTraceOn && tc.isEntryEnabled())
            Tr.exit(tc, "enlistExtendedPC");
    }
805559
public void ensureDataAvailable() throws PersistentDataEncodingException, SevereMessageStoreException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "ensureDataAvailable");

        // Check whether the item is still in the store
        AbstractItem item = getItem();
        if ((item == null) || !item.isInStore())
        {
            throw new NotInMessageStore();
        }

        // This is an unconditional caching or copy of the data, compared with a conditional
        // copy of the data which is taken by copyDataIfVulnerable
        if (_cachedPersistable == null)
        {
            _cachedPersistable = new CachedPersistable(_masterPersistable, true);
        }
        else
        {
            _cachedPersistable.cacheMemberData();
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "ensureDataAvailable");
    }
842508
@Override
    public TableIdx getJoinTableIdx(final SQLSelect _sqlSelect)
        throws CacheReloadException
    {
        final String tableName = ((SQLTable) getTable()).getSqlTable();
        return _sqlSelect.getIndexer().getTableIdx(tableName, this.attribute.getName(),
                        this.startType.getMainTable().getSqlTable());
    }
917810
@Override
  public PersistentDependency createDepend()
  {
    ArrayList<PathImpl> pathList = ((MergePath) _root)._pathList;

    if (pathList.size() == 1)
      return (PersistentDependency) pathList.get(0).createDepend();

    DependencyList dependList = new DependencyList();

    for (int i = 0; i < pathList.size(); i++) {
      PathImpl path = pathList.get(i);

      PathImpl realPath = path.lookup(_pathname);

      dependList.add((PersistentDependency) realPath.createDepend());
    }

    return dependList;
  }
304736
@Override
    public void merge(JMSConnectionFactoryDefinition annotation, Class<?> instanceClass, Member member) throws InjectionException {

        if (member != null) {
            // ConnectionFactoryDefinition is a class-level annotation only.
            throw new IllegalArgumentException(member.toString());
        }

        interfaceName = mergeAnnotationValue(interfaceName, isXmlInterfaceNameSet, annotation.interfaceName(), JMSConnectionFactoryProperties.INTERFACE_NAME.getAnnotationKey(),
                                             JMSResourceDefinitionConstants.JMS_CONNECTION_FACTORY_INTERFACE);
        className = mergeAnnotationValue(className, isXmlClassNameSet, annotation.className(), JMSConnectionFactoryProperties.CLASS_NAME.getAnnotationKey(), "");
        resourceAdapter = mergeAnnotationValue(resourceAdapter, isXmlResourceAdapterSet, annotation.resourceAdapter(),
                                               JMSConnectionFactoryProperties.RESOURCE_ADAPTER.getAnnotationKey(),
                                               JMSResourceDefinitionConstants.DEFAULT_JMS_RESOURCE_ADAPTER);
        user = mergeAnnotationValue(user, isXMLUserSet, annotation.user(), JMSConnectionFactoryProperties.USER.getAnnotationKey(), "");
        password = mergeAnnotationValue(password, isXmlPasswordSet, annotation.password(), JMSConnectionFactoryProperties.PASSWORD.getAnnotationKey(), "");
        clientId = mergeAnnotationValue(clientId, isXmlClientIdSet, annotation.clientId(), JMSConnectionFactoryProperties.CLIENT_ID.getAnnotationKey(), "");
        properties = mergeAnnotationProperties(properties, xmlProperties, annotation.properties());
        transactional = mergeAnnotationBoolean(transactional, isXmlTransactionalSet, annotation.transactional(), JMSConnectionFactoryProperties.TRANSACTIONAL.getAnnotationKey(),
                                               JMSResourceDefinitionConstants.DEFAULT_TRANSACTIONAL_VALUE);
        description = mergeAnnotationValue(description, isXmlDescriptionSet, annotation.description(), JMSConnectionFactoryProperties.DESCRIPTION.getAnnotationKey(), ""); // d662109
        maxPoolSize = mergeAnnotationInteger(maxPoolSize, isXmlMaxPoolSizeSet, annotation.maxPoolSize(), JMSConnectionFactoryProperties.MAX_POOL_SIZE.getAnnotationKey(), -1, null);
        minPoolSize = mergeAnnotationInteger(minPoolSize, isXmlMinPoolSizeSet, annotation.minPoolSize(), JMSConnectionFactoryProperties.MIN_POOL_SIZE.getAnnotationKey(), -1, null);

    }
245558
@Override
    public void persistJoinTable(JoinTableData joinTableData)
    {
        String tableName = joinTableData.getJoinTableName();
        String inverseJoinColumn = joinTableData.getInverseJoinColumnName();
        String joinColumn = joinTableData.getJoinColumnName();

        Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();
        Object connection = null;
        Pipeline pipeline = null;
        /**
         * Example: join table : PERSON_ADDRESS join column : PERSON_ID (1_p)
         * inverse join column : ADDRESS_ID (1_a) store in REDIS:
         * PERSON_ADDRESS:1_p_1_a PERSON_ID 1_p ADDRESS_ID 1_a
         */
        // String rowKey =
        try
        {
            connection = getConnection();
            if (isBoundTransaction())
            {
                pipeline = ((Jedis) connection).pipelined();
            }
            Set<Object> joinKeys = joinTableRecords.keySet();

            for (Object joinKey : joinKeys)
            {
                String joinKeyAsStr = PropertyAccessorHelper.getString(joinKey);

                Set<Object> inverseKeys = joinTableRecords.get(joinKey);

                for (Object inverseKey : inverseKeys)
                {
                    Map<byte[], byte[]> redisFields = new HashMap<byte[], byte[]>(1);
                    String inverseJoinKeyAsStr = PropertyAccessorHelper.getString(inverseKey);
                    String redisKey = getHashKey(tableName, joinKeyAsStr + "_" + inverseJoinKeyAsStr);
                    redisFields.put(getEncodedBytes(joinColumn), getEncodedBytes(joinKeyAsStr)); // put
                                                                                                 // join
                                                                                                 // column
                                                                                                 // field.
                    redisFields.put(getEncodedBytes(inverseJoinColumn), getEncodedBytes(inverseJoinKeyAsStr)); // put
                                                                                                               // inverse
                                                                                                               // join
                                                                                                               // column
                                                                                                               // field

                    // add to hash table.

                    if (resource != null && resource.isActive())
                    {
                        ((Transaction) connection).hmset(getEncodedBytes(redisKey), redisFields);
                        // add index
                        ((Transaction) connection).zadd(getHashKey(tableName, inverseJoinKeyAsStr),
                                getDouble(inverseJoinKeyAsStr), redisKey);
                        ((Transaction) connection).zadd(getHashKey(tableName, joinKeyAsStr), getDouble(joinKeyAsStr),
                                redisKey);

                    }
                    else
                    {
                        ((Jedis) connection).hmset(getEncodedBytes(redisKey), redisFields);
                        // add index
                        ((Jedis) connection).zadd(getHashKey(tableName, inverseJoinKeyAsStr),
                                getDouble(inverseJoinKeyAsStr), redisKey);
                        ((Jedis) connection).zadd(getHashKey(tableName, joinKeyAsStr), getDouble(joinKeyAsStr),
                                redisKey);

                    }
                    redisFields.clear();
                }

            }
            KunderaCoreUtils.printQuery("Persist Join Table:" + tableName, showQuery);
        }
        finally
        {
            if (pipeline != null)
            {
                pipeline.sync();
            }
            onCleanup(connection);
        }

    }