************************************************************
CRUD Operations on Persistable Objects
************************************************************
496639
function (key) {
        let parent = readPersistable(__private.local, key, true);
        if (!parent) {
            const parentKey = key.substring(0, key.lastIndexOf('['));
            createParentIfNotExisting(parentKey);
            // If a parent does not exist locally, but exists remotely, then, it should be
            // created locally. If a parent exists, it could be either an object or an array
            // and there is no easy way of figuring that out based on just the key. So, we
            // make an assumption that objects would not generally have keys that start with
            // numbers.
            const itemKey = key.substring(key.lastIndexOf('[') + 1, key.length - 1);
            const isArray = !isNaN(parseInt(itemKey, 10));
            createOrUpdatePersistable(parentKey, new Persistable(parentKey, isArray ? [] : {}));
        }
    }
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);
        }
    }
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;
            }
        });
    }
335479
function(persist) {
          /**
          * is Persistant or not
          * @property {boolean} isPersisted Persistant property
          * @memberof AbstractLocalStorage
          */
          this.isPersisted = persist;

          this.myStore = null;
          /**
          * Is storage supported
          * @method isSupported
          * @memberof AbstractLocalStorage
          * @returns {boolean} Returns true if supported
          */
          this.isSupported = function() {
            return (typeof (Storage) !== "undefined");
          };

          // true = localStorage, false = sessionStorage
          if (this.isSupported()) {
            //logger.debug("AUGMENTED: localStorage exists");

            if (this.isPersisted) {
              this.myStore = localStorage;
            } else {
              this.myStore = sessionStorage;
            }
          } else {
            logger.warn("AUGMENTED: No localStorage.");
          }

          /**
          * Gets an item from storage
          * @method getItem
          * @memberof AbstractLocalStorage
          * @param {string} key The key in storage
          * @returns {object} Returns object from storage
          */
          this.getItem = function(itemKey) {
            var item = this.myStore.getItem(itemKey);
            if (item) {
              return JSON.parse(item);
            }
            return null;
          };

          /**
          * Sets an item to storage
          * @method setItem
          * @memberof AbstractLocalStorage
          * @param {string} key The key in storage
          * @param {object} object The data to set
          */
          this.setItem = function(itemKey, object) {
            this.myStore.setItem(itemKey, JSON.stringify(object));
          };

          /**
          * Removes an item from storage
          * @method removeItem
          * @memberof AbstractLocalStorage
          * @param {string} key The key in storage
          */
          this.removeItem = function(itemKey) {
            this.myStore.removeItem(itemKey);
          };

          /**
          * Clears storage - <b>Warning: Destructive in non-namespaced instances!</b>
          * @method clear
          * @memberof AbstractLocalStorage
          */
          this.clear = function() {
            this.myStore.clear();
          };

          /**
          * Gets the key from storage for index
          * @method key
          * @memberof AbstractLocalStorage
          * @param {number} i The index in storage
          * @returns {string} Returns the key from storage
          */
          this.key = function(i) {
            return this.myStore.key(i);
          };

          /**
          * The length of storage by keys
          * @method length
          * @memberof AbstractLocalStorage
          * @returns {number} Returns the length of storage by keys
          */
          this.length = function() {
            return this.myStore.length;
          };
        }
989215
@Override
    public synchronized void persistableOperationBegun() throws SevereMessageStoreException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(this, tc, "persistableOperationBegun");

        _persistableOperationBegunCounter++;

        if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
            SibTr.event(this, tc, "persistableOperationBegunCounter: " + _persistableOperationBegunCounter);

        if (_link != null)
        {
            if (_persistableOperationBegunCounter - _persistableOperationCompletedCounter == 1)
            {
                _link.persistentRepresentationIsUnstable();
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(this, tc, "persistableOperationBegun");
    }
441761
function save(callback) {
            var model, request;

            model = this;

            this.constructor.dispatch('beforeSave', {
                data : {
                    model : this
                }
            });
            this.dispatch('beforeSave');

            this.isValid(function (isValid) {
                if (isValid) {
                    if (model.hasOwnProperty('id') && model.id !== '') {
                        request = {
                            action : 'update',
                            data : model,
                            model : model.constructor
                        };
                        model.constructor.storage.update(request, function updateCallback(data) {
                            model.constructor.dispatch('afterSave', {
                                data : {
                                    model : model
                                }
                            });

                            model.dispatch('afterSave');
                            if (callback) {
                                callback(data);
                            }
                        });
                    }
                    else {
                        request = {
                            action : 'create',
                            data : model,
                            model : model.constructor
                        };
                        model.constructor.storage.create(request, function createCallback(data) {
                            model.constructor.dispatch('afterSave', {
                                data : {
                                    model : model
                                }
                            });

                            model.dispatch('afterSave');
                            if (callback) {
                                callback(data);
                            }
                        });
                    }
                } else {
                    if (callback) {
                        callback(data);
                    }
                }
            });

        }
202448
@Override
    public void persistJoinTable(JoinTableData joinTableData)
    {
        String joinTableName = joinTableData.getJoinTableName();
        String invJoinColumnName = joinTableData.getInverseJoinColumnName();
        Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();
        String tableName = HBaseUtils.getHTableName(joinTableData.getSchemaName(), joinTableName);
        for (Object key : joinTableRecords.keySet())
        {
            Set<Object> values = joinTableRecords.get(key);
            Object joinColumnValue = key;
            Map<String, Object> columns = new HashMap<String, Object>();
            for (Object childValue : values)
            {
                columns.put(invJoinColumnName + "_" + childValue, childValue);
            }
            if (columns != null && !columns.isEmpty())
            {
                try
                {
                    handler.writeJoinTableData(tableName, joinColumnValue, columns, joinTableName);
                    KunderaCoreUtils.printQuery("Persist Join Table:" + joinTableName, showQuery);
                }
                catch (IOException e)
                {
                    throw new PersistenceException(e);
                }
            }
        }
    }
99314
public void executeUpdate(ClassDescriptor cld, Object obj) throws PersistenceBrokerException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("executeUpdate: " + obj);
        }

        // obj with nothing but key fields is not updated
        if (cld.getNonPkRwFields().length == 0)
        {
            return;
        }

        final StatementManagerIF sm = broker.serviceStatementManager();
        PreparedStatement stmt = null;
        // BRJ: preserve current locking values
        // locking values will be restored in case of exception
        ValueContainer[] oldLockingValues;
        oldLockingValues = cld.getCurrentLockingValues(obj);
        try
        {
            stmt = sm.getUpdateStatement(cld);
            if (stmt == null)
            {
                logger.error("getUpdateStatement returned a null statement");
                throw new PersistenceBrokerException("getUpdateStatement returned a null statement");
            }

            sm.bindUpdate(stmt, cld, obj);
            if (logger.isDebugEnabled())
                logger.debug("executeUpdate: " + stmt);

            if ((stmt.executeUpdate() == 0) && cld.isLocking()) //BRJ
            {
                /**
                 * Kuali Foundation modification -- 6/19/2009
                 */
            	String objToString = "";
            	try {
            		objToString = obj.toString();
            	} catch (Exception ex) {}
                throw new OptimisticLockException("Object has been modified by someone else: " + objToString, obj);
                /**
                 * End of Kuali Foundation modification
                 */
            }

            // Harvest any return values.
            harvestReturnValues(cld.getUpdateProcedure(), obj, stmt);
        }
        catch (OptimisticLockException e)
        {
            // Don't log as error
            if (logger.isDebugEnabled())
                logger.debug(
                    "OptimisticLockException during the execution of update: " + e.getMessage(),
                    e);
            throw e;
        }
        catch (PersistenceBrokerException e)
        {
            // BRJ: restore old locking values
            setLockingValues(cld, obj, oldLockingValues);

            logger.error(
                "PersistenceBrokerException during the execution of the update: " + e.getMessage(),
                e);
            throw e;
        }
        catch (SQLException e)
        {
            final String sql = broker.serviceSqlGenerator().getPreparedUpdateStatement(cld).getStatement();
            throw ExceptionHelper.generateException(e, sql, cld, logger, obj);
        }
        finally
        {
            sm.closeResources(stmt, null);
        }
    }
830046
private final void prepareObject(ZooPC obj, long oid, boolean hollow, 
    		ZooClassDef classDef) {
//        obj.jdoNewInstance(sm); //?
        
        if (hollow) {
        	cache.addToCache(obj, classDef, oid, ObjectState.HOLLOW_PERSISTENT_NONTRANSACTIONAL);
        } else {
        	cache.addToCache(obj, classDef, oid, ObjectState.PERSISTENT_CLEAN);
        }
    }
101809
@Override
    // TODO: what happens if pushAll and key already exists?
    public Object put(Object key, Object value) {
        verifyOperation($set);

        return updates.put(getKeyForUpdate(key), DBObjectUtil.toDBObject(value));
    }
922087
@Override
    public void write(ByteBuffer buffer) {
//        if (obj instanceof Persistable)
//            ((Persistable) obj).write(buffer);
//        else {
        if (obj != null)
            buffer.put(getSerialized());
        tmpBuffer = null;
//        }
    }
1232835
function persist(client, next) {
    var single = isModel(item)
      , data;

    switch (method) {
      case 'create':
        data = single ? [ item.clone() ] : item.clone().models;
        client.insert(pluck(data), config, function inserted(error, results) {
          if (error) return next(error);

          //
          // Set the _stored property for each model to true.
          //
          results.forEach(function each(model) {
            if (single) return item.stored = model._id;
            item.id(model._id).stored = model._id;
          });

          next(null, results);
        });
      break;

      case 'read':
        //
        // Models will be read by Model _id if no query was passed or if
        // the Model already exists in the database. This would otherwise
        // result in data ambiguity.
        //
        query = query || {};
        if (single && item.id) query._id = item.id;

        //
        // No query and Model has no ObjectId reference, return early.
        //
        if (single && !Object.keys(query).length) return next(null, null);

        //
        // Read the documents from the MongoDB database and process
        // the results, depending on the item being a Model or Collection.
        //
        client.find(query, config).toArray(function found(error, results) {
          if (error) return next(error);
          if (single) results = results[0];

          //
          // If the item is a model, parse first. After merge the results
          // of the read operation in the current item.
          //
          if (single && options.parse) results = item.parse(results, options);
          item.set(results);

          next(null, results);
        });
      break;

      case 'update':
      case 'patch':
        data = single ? [ item ] : item.models;
        async.reduce(data, 0, function loopModels(memo, model, fn) {
          model = model.clone();
          var update = { $set: pluck(model) };
          if (config.upsert) update = pluck(model);

          client.update({ _id: model.id }, update, config, function updated(error, results) {
            if (error) return next(error);

            model.stored = model.id;
            fn(null, memo + results);
          });
        }, next);
      break;

      case 'delete':
        data = single ? [ item ] : item.models;
        async.reduce(data, 0, function loopModels(memo, model, fn) {
          client.remove({ _id: model.id }, config, function updated(error, results) {
            if (error) return fn(error);

            //
            // Update the stored state properties to false.
            //
            model.stored = false;
            fn(null, memo + results);
          });
        }, next);
      break;
    }
  }
983705
public void persistAttributes()
    {
        String attrName = getScopedName( STORED_ATTRS_ATTR );
        getSession().setAttribute( attrName, _scopedContainer.getSerializableAttrs() );
    }
389105
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)
            || (tranState == TransactionState.STATE_COMMITTING_2PC))
        {
            batchingContext.delete(getPersistable());
        }
        else if ((tranState == TransactionState.STATE_PREPARED)
                 || (tranState == TransactionState.STATE_PREPARING))
        {
            Persistable tuple = getPersistable();
            tuple.setLogicallyDeleted(true);
            batchingContext.updateLogicalDeleteAndXID(tuple);
        }
        else if ((tranState == TransactionState.STATE_ROLLEDBACK)
                 || (tranState == TransactionState.STATE_ROLLINGBACK))
        {
            Persistable tuple = getPersistable();
            tuple.setLogicallyDeleted(false);
            batchingContext.updateLogicalDeleteAndXID(tuple);
        }
        else
        {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "persist");
            throw new IllegalStateException(nls.getFormattedMessage("INVALID_TASK_OPERATION_SIMS1520", new Object[] {tranState}, null));
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "persist");
    }
179717
@Override
    public void persistJoinTable(JoinTableData joinTableData)
    {
        String joinTableName = joinTableData.getJoinTableName();
        String invJoinColumnName = joinTableData.getInverseJoinColumnName();
        Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();

        EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
                joinTableData.getEntityClass());

        Connection conn = null;
        try
        {

            conn = getConnection();

            if (isCql3Enabled(entityMetadata))
            {
                persistJoinTableByCql(joinTableData, conn.getClient());
            }
            else
            {
                KunderaCoreUtils.printQuery("Persist join table:" + joinTableName, showQuery);
                for (Object key : joinTableRecords.keySet())
                {
                    PropertyAccessor accessor = PropertyAccessorFactory.getPropertyAccessor((Field) entityMetadata
                            .getIdAttribute().getJavaMember());
                    byte[] rowKey = accessor.toBytes(key);

                    Set<Object> values = joinTableRecords.get(key);
                    List<Column> columns = new ArrayList<Column>();

                    // Create Insertion List
                    List<Mutation> insertionList = new ArrayList<Mutation>();
                    Class columnType = null;
                    for (Object value : values)
                    {
                        Column column = new Column();
                        column.setName(PropertyAccessorFactory.STRING.toBytes(invJoinColumnName
                                + Constants.JOIN_COLUMN_NAME_SEPARATOR + value));
                        column.setValue(PropertyAccessorHelper.getBytes(value));

                        column.setTimestamp(generator.getTimestamp());
                        columnType = value.getClass();
                        columns.add(column);

                        Mutation mut = new Mutation();
                        mut.setColumn_or_supercolumn(new ColumnOrSuperColumn().setColumn(column));
                        insertionList.add(mut);
                    }
                    createIndexesOnColumns(entityMetadata, joinTableName, columns, columnType);
                    // Create Mutation Map
                    Map<String, List<Mutation>> columnFamilyValues = new HashMap<String, List<Mutation>>();
                    columnFamilyValues.put(joinTableName, insertionList);
                    Map<ByteBuffer, Map<String, List<Mutation>>> mulationMap = new HashMap<ByteBuffer, Map<String, List<Mutation>>>();
                    mulationMap.put(ByteBuffer.wrap(rowKey), columnFamilyValues);

                    // Write Mutation map to database

                    conn.getClient().set_keyspace(entityMetadata.getSchema());

                    conn.getClient().batch_mutate(mulationMap, getConsistencyLevel());
                }
            }
        }
        catch (InvalidRequestException e)
        {
            log.error("Error while inserting record into join table, Caused by: .", e);
            throw new PersistenceException(e);
        }
        catch (TException e)
        {
            log.error("Error while inserting record into join table, Caused by: .", e);
            throw new PersistenceException(e);
        }
        finally
        {
            releaseConnection(conn);
        }
    }
172206
private void persistDecorator(XMLExtendedStreamWriter writer, ModelNode model) throws XMLStreamException {
       if (shouldWriteDecoratorAndElements(model)) {
           writer.writeStartElement(decoratorElement);
           persistChildren(writer, model);
           writer.writeEndElement();
       }
    }
479065
@Override
  public Deferred<Object> persist() {
    final byte[] q = Arrays.copyOfRange(batched_qualifier, 0, qualifier_index);
    final byte[] v = Arrays.copyOfRange(batched_value, 0, value_index);
    final byte[] r = Arrays.copyOfRange(row_key, 0, row_key.length);
    final long base_time = this.base_time; // shadow fixes issue #1436
    System.out.println(Arrays.toString(q) + "  " + Arrays.toString(v) + "  " + Arrays.toString(r));
    reset();
    return tsdb.put(r, q, v, base_time);
  }