/*
(non-Javadoc)

@see
com.impetus.kundera.client.Client#persistJoinTable(com.impetus.kundera
.persistence.context.jointable.JoinTableData)
553082
@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();

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

            for (Object childId : values)
            {
                Map<String, Object> obj = new HashMap<String, Object>();
                String id = joinTableName + "#" + joinColumnValue.toString() + "#" + childId;
                obj.put("_id", id);
                obj.put(joinColumnName, joinColumnValue);
                obj.put(invJoinColumnName, childId);
                JsonObject object = gson.toJsonTree(obj).getAsJsonObject();
                HttpResponse response = null;
                try
                {
                    URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
                            CouchDBConstants.URL_SEPARATOR + joinTableData.getSchemaName().toLowerCase()
                                    + CouchDBConstants.URL_SEPARATOR + id, null, null);

                    HttpPut put = new HttpPut(uri);
                    StringEntity stringEntity = null;
                    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 joinTable data, coused by {}.", e);
                    throw new KunderaException(e);
                }
                finally
                {
                    closeContent(response);
                }
            }
        }
    }
334439
@Override
    public boolean persistIfPossible(Command command) {
        if(!(command instanceof CommandJdo)) {
            // ought not to be the case, since this service created the object in the #create() method
            return false;
        }
        final CommandJdo commandJdo = (CommandJdo)command;
        repositoryService.persist(commandJdo);
        return true;
    }
689232
@Override
    public Iterable<T> save(final Iterable<T> entities) {
        return inTransaction(new Callable<Iterable<T>>() {
            @Override
            public Iterable<T> call() throws Exception {
                for (T object : entities) {
                    entityManager.persist(object);
                }
                return entities;
            }
        });
    }
932401
private static void onEmbeddable(EntityType entityType, Attribute column, Object entity,
            EmbeddableType embeddableType, JsonObject jsonObject)
    {
        Object embeddedObject = PropertyAccessorHelper.getObject(entity, (Field) column.getJavaMember());
        String embeddedColumnName = ((AbstractAttribute) column).getJPAColumnName();
        Set<Attribute> embeddableAttributes = embeddableType.getAttributes();
        jsonObject.add(embeddedColumnName, getJsonObject(embeddableAttributes, embeddedObject));
    }
249401
public void persist() throws Exception {
		if (!mapping.equals(initialMapping)) {
			state.clear();
			for (Map.Entry<W, W> window : mapping.entrySet()) {
				state.add(new Tuple2<>(window.getKey(), window.getValue()));
			}
		}
	}
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());
            }
        }
    }
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);
    }
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());
		}
	}
691379
static boolean mergeKeepUpdate(Session session, HashMappedList rowSet,
                                   int[] cols, Type[] colTypes, Row row,
                                   Object[] newData) {

        Object[] data = (Object[]) rowSet.get(row);

        if (data != null) {
            if (IndexAVL
                    .compareRows(row
                        .getData(), newData, cols, colTypes) != 0 && IndexAVL
                            .compareRows(newData, data, cols, colTypes) != 0) {
                return false;
            }

            for (int j = 0; j < cols.length; j++) {
                newData[cols[j]] = data[cols[j]];
            }

            rowSet.put(row, newData);
        } else {
            rowSet.add(row, newData);
        }

        return true;
    }
185600
@Override
    public List<Object> findParentEntityFromJoinTable(EntityMetadata parentMetadata, String joinTableName,
            String joinColumnName, String inverseJoinColumnName, Object childId)
    {
        throw new PersistenceException("Not applicable for HBase");
    }
497611
public final void persist(BatchingContext batchingContext, TransactionState tranState)
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "persist", new Object[] { batchingContext, tranState});

        if ((tranState == TransactionState.STATE_COMMITTED) || (tranState == TransactionState.STATE_COMMITTING_1PC))
        {
            batchingContext.updateRedeliveredCountOnly(getPersistable());
        }
        else
        {
            throw new IllegalStateException(nls.getFormattedMessage("INVALID_TASK_OPERATION_SIMS1520", new Object[] {tranState}, null));
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "persist");
    }
284485
protected void persistProperties() throws Exception {
		if (isNewState()) {
			return;
		}

		if (Database.DB_TYPE_HSQLDB.equals(model.getDb().getType())) {
			configuration.save(new File(fileName));
		}
		model.getDb().getTableSession().update(getSessionId(), getSessionName());
	}
1126160
@Override
    public PersistenceUnitUtil getPersistenceUnitUtil()
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
            Tr.debug(tc, "getPersistenceUnitUtil : " + this);
        throw new UnsupportedOperationException("This operation is not supported on a pooling EntityManagerFactory.");
    }
1196434
private void flushJoinTableData()
    {
        if (applyFlush())
        {
            for (JoinTableData jtData : flushManager.getJoinTableData())
            {
                if (!jtData.isProcessed())
                {
                    EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                            jtData.getEntityClass());
                    Client client = getClient(m);
                    if (OPERATION.INSERT.equals(jtData.getOperation()))
                    {
                        client.persistJoinTable(jtData);
                        jtData.setProcessed(true);
                    }
                    else if (OPERATION.DELETE.equals(jtData.getOperation()))
                    {
                        for (Object pk : jtData.getJoinTableRecords().keySet())
                        {
                            client.deleteByColumn(m.getSchema(), jtData.getJoinTableName(),
                                    jtData.getJoinColumnName(), pk);
                        }
                        jtData.setProcessed(true);
                    }
                }

            }
        }
    }
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);
            }
        }
    }
207146
private static void processJoinTables(final List<TableModel> result, final Map<String, Map<Table, List<String>>> joinTableMetadata) {
        joinTableMetadata.entrySet().forEach(entry -> {
            LOG.debug("Processing join tables for {}. Found {} join tables to process", entry.getKey(), entry.getValue().size());
            final TableModel model = getModelBySQLName(result, entry.getKey());
            if (model == null) {
                LOG.error("Could not find table {} in the already generated models! This should not happen!", entry.getKey());
                throw new NullPointerException("Table model not found");
            }
            entry.getValue().entrySet().forEach(tableListEntry -> {
                LOG.debug("Processing join table {}", tableListEntry.getKey().getFullName());
                final TableModel joinTable = getModelBySQLName(result, tableListEntry.getKey().getFullName());
                if (joinTable == null) {
                    LOG.error("Could not find join table {} in the already generated models! This should not happen!", entry.getKey());
                    throw new NullPointerException("Table model not found");
                }
                JoinTableSimplifierModel jtsModel = new JoinTableSimplifierModel();
                jtsModel.setName(joinTable.getName());
                for (ForeignKeyModel fKModel : joinTable.getForeignKeys()) {
                    if (fKModel.getJavaTypeName().equals(model.getClassName())) {
                        jtsModel.getConstructorParams().add("this");
                    } else {
                        jtsModel.getConstructorParams().add(fKModel.getName());
                        jtsModel.getMethodParams().put(fKModel.getJavaTypeName(), fKModel.getName());
                    }
                }

                model.getJoinTableSimplifierData().put(joinTable.getClassName(), jtsModel);
            });
        });
    }
937017
public function createJoinTable()
    {
        if ($this->joinTableExists() === true) {
            return;
        }

        $q = 'CREATE TABLE \''.$this->joinTable().'\' (
            target_type VARCHAR(255),
            target_id VARCHAR(255),
            target_property VARCHAR(255),
            attachment_type VARCHAR(255),
            attachment_id VARCHAR(255),
            created DATETIME
        )';
        $this->logger->debug($q);
        $this->source()->db()->query($q);
    }