/*
(non-Javadoc)

@see com.impetus.kundera.client.ClientBase#onPersist(com.impetus.kundera.
metadata.model.EntityMetadata, java.lang.Object, java.lang.Object,
java.util.List)
199892
@Override
    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
    {
        JsonDocument doc = handler.getDocumentFromEntity(entityMetadata, entity, kunderaMetadata);

        if (!isUpdate)
        {
            bucket.insert(doc);
            LOGGER.debug("Inserted document with ID : " + doc.id() + " in the " + bucket.name() + " Bucket");
        }
        else
        {
            bucket.upsert(doc);
            LOGGER.debug("Updated document with ID : " + doc.id() + " in the " + bucket.name() + " Bucket");
        }
    }
865009
public void addListener(SettingsEntityListener settingsEntityListener) {
    RunAsSystemAspect.runAsSystem(
        () ->
            entityListenersService.addEntityListener(
                entityTypeId,
                new EntityListener() {
                  @Override
                  public void postUpdate(Entity entity) {
                    settingsEntityListener.postUpdate(entity);
                  }

                  @Override
                  public Object getEntityId() {
                    return getEntityType().getId();
                  }
                }));
  }
755739
@Override
    protected List<Object> populateEntities(EntityMetadata m, Client client)
    {
        return onQuery(m, client);
    }
1035822
public void refresh(Object entity)
    {
        if (contains(entity))
        {
            MainCache mainCache = (MainCache) getPersistenceCache().getMainCache();
            Node node = mainCache.getNodeFromCache(entity, getMetadata(entity.getClass()), this);
            // Locking as it might read from persistence context.

            try
            {
                lock.readLock().lock();
                node.setPersistenceDelegator(this);
                node.refresh();
            }
            finally
            {
                lock.readLock().unlock();
            }
        }
        else
        {
            throw new IllegalArgumentException("This is not a valid or managed entity, can't be refreshed");
        }
    }
274923
private void parseMaxPersist(Map<Object, Object> props) {
        // -1 means unlimited
        // 0..1 means 1
        // X means X
        Object value = props.get(HttpConfigConstants.PROPNAME_MAX_PERSIST);
        if (null != value) {
            try {
                this.maxPersistRequest = minLimit(convertInteger(value), HttpConfigConstants.MIN_PERSIST_REQ);
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                    Tr.event(tc, "Config: Max persistent requests is " + getMaximumPersistentRequests());
                }
            } catch (NumberFormatException nfe) {
                FFDCFilter.processException(nfe, getClass().getName() + ".parseMaxPersist", "1");
                if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
                    Tr.event(tc, "Config: Invalid max persistent requests; " + value);
                }
            }
        }
    }
723075
private void onPersistGFS(Object entity, Object entityId, EntityMetadata entityMetadata, boolean isUpdate)
    {
        KunderaGridFS gfs = new KunderaGridFS(mongoDb, entityMetadata.getTableName());
        if (!isUpdate)
        {
            GridFSInputFile gfsInputFile = handler.getGFSInputFileFromEntity(gfs, entityMetadata, entity,
                    kunderaMetadata, isUpdate);
            saveGridFSFile(gfsInputFile, entityMetadata);
        }
        else
        {
            Object val = handler.getLobFromGFSEntity(gfs, entityMetadata, entity, kunderaMetadata);
            String md5 = MongoDBUtils.calculateMD5(val);
            GridFSDBFile outputFile = findGridFSDBFile(entityMetadata, entityId);

            // checking MD5 of the file to be updated with the file saved in DB
            if (md5.equals(outputFile.getMD5()))
            {
                DBObject metadata = handler.getMetadataFromGFSEntity(gfs, entityMetadata, entity, kunderaMetadata);
                outputFile.setMetaData(metadata);
                outputFile.save();
            }
            else
            {
                // GFSInput file is created corresponding to the entity to be
                // merged with a new ObjectID()
                GridFSInputFile gfsInputFile = handler.getGFSInputFileFromEntity(gfs, entityMetadata, entity,
                        kunderaMetadata, isUpdate);
                ObjectId updatedId = (ObjectId) gfsInputFile.getId();
                DBObject metadata = gfsInputFile.getMetaData();

                // updated file is saved in DB
                saveGridFSFile(gfsInputFile, entityMetadata);

                // last version of file is deleted
                DBObject query = new BasicDBObject("_id", outputFile.getId());
                gfs.remove(query);

                // newly added file is found using its _id
                outputFile = gfs.findOne(updatedId);

                // Id of entity (which is saved in metadata) is updated to its
                // actual Id
                metadata.put(((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName(), entityId);
                outputFile.setMetaData(metadata);

                // output file is updated
                outputFile.save();
            }
        }
    }
200775
@Override
    public void getUserLists(final long listOwnerUserId) {
        getDispatcher().invokeLater(new AsyncTask(USER_LISTS, listeners) {
            @Override
            public void invoke(List<TwitterListener> listeners) throws TwitterException {
                ResponseList<UserList> lists = twitter.getUserLists(listOwnerUserId);
                for (TwitterListener listener : listeners) {
                    try {
                        listener.gotUserLists(lists);
                    } catch (Exception e) {
                        logger.warn("Exception at getUserLists", e);
                    }
                }
            }
        });
    }
1299927
protected void onDeleteOrUpdate(List results)
    {

        if (results != null)
        {
            if (!kunderaQuery.isUpdateClause())
            {
                // then case of delete
                for (Object result : results)
                {
                    PersistenceCacheManager.addEntityToPersistenceCache(result, persistenceDelegeator,
                            PropertyAccessorHelper.getId(result, this.getEntityMetadata()));

                    persistenceDelegeator.remove(result);
                }
            }
            else
            {
                EntityMetadata entityMetadata = getEntityMetadata();
                for (Object result : results)
                {
                    PersistenceCacheManager.addEntityToPersistenceCache(result, persistenceDelegeator,
                            PropertyAccessorHelper.getId(result, this.getEntityMetadata()));

                    for (UpdateClause c : kunderaQuery.getUpdateClauseQueue())
                    {
                        String columnName = c.getProperty();
                        try
                        {

                            DefaultEntityType entityType = (DefaultEntityType) kunderaMetadata.getApplicationMetadata()
                                    .getMetamodel(entityMetadata.getPersistenceUnit())
                                    .entity(entityMetadata.getEntityClazz());

                            // That will always be attribute name.

                            Attribute attribute = entityType.getAttribute(columnName);

                            // TODO : catch column name.

                            if (c.getValue() instanceof String)
                            {
                                PropertyAccessorHelper.set(result, (Field) attribute.getJavaMember(), c.getValue()
                                        .toString());
                            }
                            else
                            {
                                PropertyAccessorHelper.set(result, (Field) attribute.getJavaMember(), c.getValue());
                            }
                            persistenceDelegeator.merge(result);
                        }
                        catch (IllegalArgumentException iax)
                        {
                            log.error("Invalid column name: " + columnName + " for class : "
                                    + entityMetadata.getEntityClazz());
                            throw new QueryHandlerException("Error while executing query: " + iax);
                        }
                    }
                }
            }
        }
    }
1110406
@Override
    protected void onPersist(EntityMetadata entityMetadata, Object entity, Object id, List<RelationHolder> rlHolders)
    {
        if (!isUpdate)
        {
            r.db(entityMetadata.getSchema()).table(entityMetadata.getTableName())
                    .insert(populateRmap(entityMetadata, entity)).run(connection);
        }
        else
        {
            r.db(entityMetadata.getSchema()).table(entityMetadata.getTableName())
                    .update(populateRmap(entityMetadata, entity)).run(connection);
        }
    }
1151017
@Override
	protected boolean onSingleTapUpHelper(final int index, final Item item, final MapView mapView) {
		if (this.mFocusItemsOnTap) {
			this.mFocusedItemIndex = index;
			mapView.postInvalidate();
		}
		return this.mOnItemGestureListener.onItemSingleTapUp(index, item);
	}
868450
public synchronized void onAddedToList(ObservableList list, Object value) {
        if (!configuration.isUseGc()) {
            return;
        }
        if (value != null && DolphinUtils.isDolphinBean(value.getClass())) {
            Instance instance = getInstance(value);
            Reference reference = new ListReference(listToParent.get(list), list, instance);
            if (reference.hasCircularReference()) {
                throw new CircularDependencyException("Circular dependency detected!");
            }
            instance.getReferences().add(reference);
            removeFromGC(instance);
        }
    }
469425
public static synchronized EntityManagerProvider instance(String unitName, Map<String,String> overridingPersistenceProps) {
        overridingProperties = overridingPersistenceProps;
        return instance(unitName);
    }
670068
private void scheduleBatchLoadIfNeeded(Serializable id, SharedSessionContractImplementor session) throws MappingException {
		//cannot batch fetch by unique key (property-ref associations)
		if ( StringHelper.isEmpty( delegate.getRHSUniqueKeyPropertyName() ) && id != null ) {
			EntityPersister persister = session.getFactory().getMetamodel().entityPersister( delegate.getAssociatedEntityName() );
			EntityKey entityKey = session.generateEntityKey( id, persister );
			if ( !session.getPersistenceContext().containsEntity( entityKey ) ) {
				session.getPersistenceContext().getBatchFetchQueue().addBatchLoadableEntityKey( entityKey );
			}
		}
	}
185644
static void onPersist(final EntityManager em, final User user) 
	{
		logger.info("");
		logger.info("");
		logger.info("#######################Persisting##########################################");
		logger.info("");
		logger.info(user.toString());
		persist(user, em);
		logger.info("");
		System.out.println("#######################Persisting##########################################");
		logger.info("");
		logger.info("");
	}
136747
public static void registerDataPersisters(DataPersister... dataPersisters) {
		// we build the map and replace it to lower the chance of concurrency issues
		List<DataPersister> newList = new ArrayList<DataPersister>();
		if (registeredPersisters != null) {
			newList.addAll(registeredPersisters);
		}
		for (DataPersister persister : dataPersisters) {
			newList.add(persister);
		}
		registeredPersisters = newList;
	}
1084573
public final void update(EntityMetadata metadata, Object entity, Object parentId, Class<?> clazz)
    {
        try
        {
            if (indexer != null)
            {
                if (indexer.getClass().getName().equals(IndexingConstants.LUCENE_INDEXER))
                {
                    MetamodelImpl metamodel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                            metadata.getPersistenceUnit());
                    Object id = PropertyAccessorHelper.getId(entity, metadata);
                    boolean isEmbeddedId = metamodel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType());

                    boolean documentExistsInIndex = ((com.impetus.kundera.index.lucene.Indexer) indexer)
                            .documentExistsInIndex(metadata, id, kunderaMetadata, isEmbeddedId, clazz);

                    if (documentExistsInIndex)
                    {
                        ((com.impetus.kundera.index.lucene.Indexer) indexer).update(metadata, metamodel, entity, id,
                                parentId != null ? parentId.toString() : null);
                    }
                    else
                    {

                        boolean documentExists = ((com.impetus.kundera.index.lucene.Indexer) indexer)
                                .entityExistsInIndex(entity.getClass(), kunderaMetadata, metadata);
                        if (documentExists)
                        {
                            ((com.impetus.kundera.index.lucene.Indexer) indexer).unindex(metadata, id, kunderaMetadata,
                                    clazz);
                            ((com.impetus.kundera.index.lucene.Indexer) indexer).flush();
                        }
                        ((com.impetus.kundera.index.lucene.Indexer) indexer).index(metadata, metamodel, entity,
                                parentId != null ? parentId.toString() : null, clazz);
                    }
                }
                else
                {
                    MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                            metadata.getPersistenceUnit());

                    Map<String, PropertyIndex> indexProperties = metadata.getIndexProperties();
                    Map<String, Object> indexCollection = new HashMap<String, Object>();
                    Object id = PropertyAccessorHelper.getId(entity, metadata);
                    for (String columnName : indexProperties.keySet())
                    {
                        PropertyIndex index = indexProperties.get(columnName);
                        Field property = index.getProperty();
                        // String propertyName = index.getName();
                        Object obj = PropertyAccessorHelper.getObject(entity, property);
                        indexCollection.put(columnName, obj);
                    }

                    indexCollection.put(((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName(), id);

                    EntityMetadata parentMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);
                    if (parentId != null)
                        indexCollection.put(((AbstractAttribute) parentMetadata.getIdAttribute()).getJPAColumnName(),
                                parentId);

                    onEmbeddable(entity, metadata.getEntityClazz(), metaModel, indexCollection);
                    indexer.index(metadata.getEntityClazz(), metadata, indexCollection, parentId, clazz);
                }
            }
        }
        catch (PropertyAccessException e)
        {
            throw new IndexingException("Can't access ID from entity class " + metadata.getEntityClazz(), e);
        }
    }
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);
        }
    }