Insert property into database if value is not {@code null}, else delete property from
database. Session is not committed but {@link org.sonar.api.config.GlobalPropertyChangeHandler}
are executed.
487977
public PersistentSettings saveProperty(DbSession dbSession, String key, @Nullable String value) {
    savePropertyImpl(dbSession, key, value);
    changeNotifier.onGlobalPropertyChange(key, value);
    return this;
  }
1041207
public int insert(DatabaseType databaseType, DatabaseConnection databaseConnection, T data, ObjectCache objectCache)
			throws SQLException {
		KeyHolder keyHolder = null;
		if (idField != null) {
			boolean assignId;
			if (idField.isAllowGeneratedIdInsert() && !idField.isObjectsFieldValueDefault(data)) {
				assignId = false;
			} else {
				assignId = true;
			}
			if (idField.isSelfGeneratedId() && idField.isGeneratedId()) {
				if (assignId) {
					idField.assignField(connectionSource, data, idField.generateId(), false, objectCache);
				}
			} else if (idField.isGeneratedIdSequence() && databaseType.isSelectSequenceBeforeInsert()) {
				if (assignId) {
					assignSequenceId(databaseConnection, data, objectCache);
				}
			} else if (idField.isGeneratedId()) {
				if (assignId) {
					// get the id back from the database
					keyHolder = new KeyHolder(idField.getColumnName());
				}
			} else {
				// the id should have been set by the caller already
			}
		}

		try {
			// implement {@link DatabaseField#foreignAutoCreate()}, need to do this _before_ getFieldObjects() below
			if (tableInfo.isForeignAutoCreate()) {
				for (FieldType fieldType : tableInfo.getFieldTypes()) {
					if (!fieldType.isForeignAutoCreate()) {
						continue;
					}
					// get the field value
					Object foreignObj = fieldType.extractRawJavaFieldValue(data);
					if (foreignObj != null && fieldType.getForeignIdField().isObjectsFieldValueDefault(foreignObj)) {
						fieldType.createWithForeignDao(foreignObj);
					}
				}
			}

			Object[] args = getFieldObjects(data);
			Object versionDefaultValue = null;
			// implement {@link DatabaseField#version()}
			if (versionFieldTypeIndex >= 0 && args[versionFieldTypeIndex] == null) {
				// if the version is null then we need to initialize it before create
				FieldType versionFieldType = argFieldTypes[versionFieldTypeIndex];
				versionDefaultValue = versionFieldType.moveToNextValue(null);
				args[versionFieldTypeIndex] = versionFieldType.convertJavaFieldToSqlArgValue(versionDefaultValue);
			}

			int rowC;
			try {
				rowC = databaseConnection.insert(statement, args, argFieldTypes, keyHolder);
			} catch (SQLException e) {
				// NOTE: don't log full exception here
				logger.debug("insert data with statement '{}' and {} args, threw exception: {}", statement, args.length,
						e);
				if (args.length > 0) {
					// need to do the (Object) cast to force args to be a single object
					logger.trace("insert arguments: {}", (Object) args);
				}
				throw e;
			}
			logger.debug("insert data with statement '{}' and {} args, changed {} rows", statement, args.length, rowC);
			if (args.length > 0) {
				// need to do the (Object) cast to force args to be a single object
				logger.trace("insert arguments: {}", (Object) args);
			}
			if (rowC > 0) {
				if (versionDefaultValue != null) {
					argFieldTypes[versionFieldTypeIndex].assignField(connectionSource, data, versionDefaultValue, false,
							null);
				}
				if (keyHolder != null) {
					// assign the key returned by the database to the object's id field after it was inserted
					Number key = keyHolder.getKey();
					if (key == null) {
						// may never happen but let's be careful out there
						throw new SQLException(
								"generated-id key was not set by the update call, maybe a schema mismatch between entity and database table?");
					}
					if (key.longValue() == 0L) {
						// sanity check because the generated-key returned is 0 by default, may never happen
						throw new SQLException(
								"generated-id key must not be 0 value, maybe a schema mismatch between entity and database table?");
					}
					assignIdValue(data, key, "keyholder", objectCache);
				}
				/*
				 * If we have a cache and if all of the foreign-collection fields have been assigned then add to cache.
				 * However, if one of the foreign collections has not be assigned then don't add it to the cache.
				 */
				if (objectCache != null && foreignCollectionsAreAssigned(tableInfo.getForeignCollections(), data)) {
					Object id = idField.extractJavaFieldValue(data);
					objectCache.put(clazz, id, data);
				}
			}

			return rowC;
		} catch (SQLException e) {
			throw SqlExceptionUtil.create("Unable to run insert stmt on object " + data + ": " + statement, e);
		}
	}
1031996
public void setSessionProperty(String name, String value)
    {
        requireNonNull(name, "name is null");
        requireNonNull(value, "value is null");
        checkArgument(!name.isEmpty(), "name is empty");

        CharsetEncoder charsetEncoder = US_ASCII.newEncoder();
        checkArgument(name.indexOf('=') < 0, "Session property name must not contain '=': %s", name);
        checkArgument(charsetEncoder.canEncode(name), "Session property name is not US_ASCII: %s", name);
        checkArgument(charsetEncoder.canEncode(value), "Session property value is not US_ASCII: %s", value);

        sessionProperties.put(name, value);
    }
915003
public void setProperty(String key, String value) {
        assertArgumentNotNull("key", key);
        assertArgumentNotNull("value", value);
        session.getProperties().setProperty(key, value);
    }
718500
public static GraqlQueryException insertUnexpectedProperty(String property, Object value, Concept concept) {
        return create("unexpected property `%s %s` for concept `%s`", property, value, concept);
    }
1137986
public T insert(T entity) {

        if (!hasPrimaryKey(entity)) {
            throw new RuntimeException(String.format("Tried to insert entity of type %s with null or zero primary key",
                    entity.getClass().getSimpleName()));
        }

        InsertCreator insert = new InsertCreator(table);

        insert.setValue(idColumn.getColumnName(), getPrimaryKey(entity));

        if (versionColumn != null) {
            insert.setValue(versionColumn.getColumnName(), 0);
        }

        for (Column column : columns) {
            if (!column.isReadOnly()) {
                insert.setValue(column.getColumnName(), getFieldValueAsColumn(entity, column));
            }
        }

        new JdbcTemplate(ormConfig.getDataSource()).update(insert);

        if (versionColumn != null) {
            ReflectionUtils.setFieldValue(entity, versionColumn.getFieldName(), 0);
        }

        return entity;
    }
193602
public void setSessionAttribute(String key, Object newValue)
    {
        Object oldValue = sessionAttributes.put(key, newValue);
        propertyChangeSupport.firePropertyChange(key, oldValue, newValue);
        propertyChangeSupport.firePropertyChange(SESSION_ATTRIBUTES, null, sessionAttributes);
    }
1280165
@SuppressWarnings({ "rawtypes", "unchecked" })
    @FFDCIgnore(Exception.class) //manually logged
    private boolean handlePropertyHits(BackedSession session) {
        final boolean trace = TraceComponent.isAnyTracingEnabled();

        Thread t = Thread.currentThread();

        String id = session.getId();

        try {
            Set<String> propsToWrite = null;

            // we are not synchronized here - were not in old code either
            Hashtable tht = null;
            if (_smc.writeAllProperties()) {
                Map<?, ?> ht = session.getSwappableData();
                propsToWrite = (Set<String>) ht.keySet();
                if (trace && tc.isDebugEnabled()) {
                    Tr.debug(this, tc, "doing app changes for ALL mSwappable Data", ht);
                }
            } else {
                if (session.appDataChanges != null) {
                    if (appDataTablesPerThread) {
                        if ((tht = (Hashtable) session.appDataChanges.get(t)) != null) {
                            if (trace && tc.isDebugEnabled()) {
                                Tr.debug(this, tc, "doing app changes for " + id + " on thread " + t);
                            }
                            propsToWrite = tht.keySet();
                        }
                    } else { // appDataTablesPerSession
                        propsToWrite = session.appDataChanges.keySet();
                        if (trace && tc.isDebugEnabled()) {
                            Tr.debug(this, tc, "doing app changes for TimeBasedWrite");
                        }
                    }
                }
            }

            if (propsToWrite != null) {
                for (String propid : propsToWrite) {
                    long startTime = System.nanoTime();

                    if (id.equals(propid)) {
                        throw new IllegalArgumentException(propid); // internal error, should never occur
                    }

                    String key = createSessionAttributeKey(id, propid);
                    Object value = session.getSwappableData().get(propid);

                    if (value == null) {
                        // Value removed by another thread
                        if (trace && tc.isDebugEnabled())
                            Tr.debug(this, tc, "ignoring " + propid + " because it is no longer found");
                    } else {
                        byte[] objbuf = serialize(value);

                        if (trace && tc.isDebugEnabled()) {
                            @SuppressWarnings("static-access")
                            boolean hideValues = _smc.isHideSessionValues();
                            if (hideValues)
                                tcInvoke(tcSessionAttrCache, "put", key, "byte[" + objbuf.length + "]");
                            else
                                tcInvoke(tcSessionAttrCache, "put", key, objbuf, value);
                        }

                        sessionAttributeCache.put(key, objbuf);

                        if (trace && tc.isDebugEnabled())
                            tcReturn(tcSessionAttrCache, "put");

                        SessionStatistics pmiStats = _iStore.getSessionStatistics();
                        if (pmiStats != null) {
                            pmiStats.writeTimes(objbuf.length, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime));
                        }
                    }
                }

                if (trace && tc.isDebugEnabled())
                    Tr.debug(this, tc, propsToWrite.size() + " property writes are done");

                if (appDataTablesPerThread) {
                    if (session.appDataChanges != null)
                        session.appDataChanges.remove(t);
                    if (trace && tc.isDebugEnabled()) {
                        Tr.debug(this, tc, "remove thread from appDataChanges for thread", t);
                    }
                } else { //appDataTablesPerSession
                    if (session.appDataChanges != null)
                        session.appDataChanges.clear();
                    if (trace && tc.isDebugEnabled()) {
                        Tr.debug(this, tc, "clearing appDataChanges");
                    }
                }
            }

            // see if any properties were REMOVED.
            // if so, process them

            Set<String> propsToRemove = null;

            if (session.appDataRemovals != null) {
                if (!appDataTablesPerThread) { // appDataTablesPerSession
                    propsToRemove = session.appDataRemovals.keySet();
                    if (trace && tc.isDebugEnabled()) {
                        Tr.debug(this, tc, "doing app removals for " + id + " on ALL threads");
                    }
                } else { //appDataTablesPerThread
                    if ((tht = (Hashtable) session.appDataRemovals.get(t)) != null) {
                        if (trace && tc.isDebugEnabled()) {
                            Tr.debug(this, tc, "doing app removals for " + id + " on thread ", t);
                        }
                        propsToRemove = tht.keySet();
                    }
                }

                if (propsToRemove != null && !propsToRemove.isEmpty()) {
                    for (String propid : propsToRemove) {
                        if (trace && tc.isDebugEnabled()) {
                            Tr.debug(this, tc, "deleting prop " + propid + " for session " + id);
                        }
                        String key = createSessionAttributeKey(id, propid);

                        if (trace && tc.isDebugEnabled())
                            tcInvoke(tcSessionAttrCache, "remove", key);

                        boolean removed = sessionAttributeCache.remove(key);

                        if (trace && tc.isDebugEnabled())
                            tcReturn(tcSessionAttrCache, "remove", removed);
                    }
                }

                if (!appDataTablesPerThread) { // appDataTablesPerSession
                    if (session.appDataRemovals != null)
                        session.appDataRemovals.clear();
                    if (trace && tc.isDebugEnabled()) {
                        Tr.debug(this, tc, "clearing appDataRemovals");
                    }
                } else { //appDataTablesPerThread
                    if (session.appDataRemovals != null)
                        session.appDataRemovals.remove(t);
                    if (trace && tc.isDebugEnabled()) {
                        Tr.debug(this, tc, "remove thread from appDataRemovals", t);
                    }
                }
            }

            // Update the session's main cache entry per the identified changes
            if (propsToWrite != null || propsToRemove != null) {
                ArrayList<?> oldValue, newValue;
                long backoff = 20; // allows first two attempts without delay, then a delay of 160-319ms, then a delay of 320-639 ms, ...
                for (boolean replaced = false; !replaced; ) {
                    if (backoff > 500 || (backoff *= 2) > 100)
                        try {
                            TimeUnit.MILLISECONDS.sleep(backoff + (long) Math.random() * backoff);
                        } catch (InterruptedException x) {
                            FFDCFilter.processException(x, getClass().getName(), "324", new Object[] { id, backoff, propsToWrite, propsToRemove });
                            throw x;
                        }
                    if (trace && tc.isDebugEnabled())
                        tcInvoke(tcSessionMetaCache, "get", id);

                    oldValue = sessionMetaCache.get(id);

                    if (trace && tc.isDebugEnabled())
                        tcReturn(tcSessionMetaCache, "get", oldValue);
                    if (oldValue == null) 
                        break; // no need to delete corresponding entries from attributes cache. The code that deleted the session meta info will do so.
                    SessionInfo sessionInfo = new SessionInfo(oldValue).clone();
                    if (propsToWrite != null)
                        sessionInfo.addSessionPropertyIds(propsToWrite);
                    if (propsToRemove != null)
                        sessionInfo.removeSessionPropertyIds(propsToRemove);
                    newValue = sessionInfo.getArrayList();

                    if (trace && tc.isDebugEnabled())
                        tcInvoke(tcSessionMetaCache, "replace", id, oldValue, newValue);

                    replaced = sessionMetaCache.replace(id, oldValue, newValue);

                    if (trace && tc.isDebugEnabled())
                        tcReturn(tcSessionMetaCache, "replace", replaced);
                }
            }
        } catch (Exception ex) {
            FFDCFilter.processException(ex, "com.ibm.ws.session.store.cache.CacheHashMap.handlePropertyHits", "656", this, new Object[] { session });
            Tr.error(tc, "PROP_HIT_ERROR", ex);
            throw new RuntimeException(Tr.formatMessage(tc, "INTERNAL_SERVER_ERROR"));
        }

        return true;
    }
886275
public void executeInsert(ClassDescriptor cld, Object obj) throws PersistenceBrokerException
    {
        if (logger.isDebugEnabled())
        {
            logger.debug("executeInsert: " + obj);
        }
        final StatementManagerIF sm = broker.serviceStatementManager();
        PreparedStatement stmt = null;
        try
        {
            stmt = sm.getInsertStatement(cld);
            if (stmt == null)
            {
                logger.error("getInsertStatement returned a null statement");
                throw new PersistenceBrokerException("getInsertStatement returned a null statement");
            }
            // before bind values perform autoincrement sequence columns
            assignAutoincrementSequences(cld, obj);
            sm.bindInsert(stmt, cld, obj);
            if (logger.isDebugEnabled())
                logger.debug("executeInsert: " + stmt);
            stmt.executeUpdate();
            // after insert read and assign identity columns
            assignAutoincrementIdentityColumns(cld, obj);

            // Harvest any return values.
            harvestReturnValues(cld.getInsertProcedure(), obj, stmt);
        }
        catch (PersistenceBrokerException e)
        {
            logger.error("PersistenceBrokerException during the execution of the insert: " + e.getMessage(), e);
            throw e;
        }
        catch(SequenceManagerException e)
        {
            throw new PersistenceBrokerException("Error while try to assign identity value", e);
        }
        catch (SQLException e)
        {
            final String sql = broker.serviceSqlGenerator().getPreparedInsertStatement(cld).getStatement();
            throw ExceptionHelper.generateException(e, sql, cld, logger, obj);
        }
        finally
        {
            sm.closeResources(stmt, null);
        }
    }
454506
private Instance insertNewProp(final String _key,
                                 final String _value)
    {
        Instance ret = null;
        try {
            final Insert insert = new Insert(DBPropertiesUpdate.TYPE_PROPERTIES);
            insert.add("BundleID", this.bundleInstance);
            insert.add("Key", _key);
            insert.add("Default", _value);
            insert.executeWithoutAccessCheck();
            ret = insert.getInstance();
            insert.close();

        } catch (final EFapsException e) {
            DBPropertiesUpdate.LOG.error("InsertNew(String, String)", e);
        }
        return ret;
    }
536650
public boolean addValue(String property, String value) {
		if (!has()) {
			getOrCreate();
		}
		boolean added = false;
		if (!hasValue(property, value)) {
			TRow row = newRow();
			row.setValue(COLUMN_PROPERTY, property);
			row.setValue(COLUMN_VALUE, value);
			getDao().insert(row);
			added = true;
		}
		return added;
	}
709712
void insertIntoTable(Session session, Result result) {

        PersistentStore store = session.sessionData.getRowStore(this);
        RowSetNavigator nav   = result.initialiseNavigator();

        while (nav.hasNext()) {
            Object[] data = nav.getNext();
            Object[] newData =
                (Object[]) ArrayUtil.resizeArrayIfDifferent(data,
                    getColumnCount());

            insertData(store, newData);
        }
    }
1180047
public void put_property(String name, DbDatum[] properties) throws DevFailed {
		databaseDAO.put_property(this, name, properties);
	}
285552
public void put(Boolean value) {
		if (value == null) {
			this.compiledStatement.bindNull(compiledStatementBindIndex++);
		} else {
			this.compiledStatement.bindLong(compiledStatementBindIndex++, (value == true ? 1 : 0));
		}
	}
679903
public synchronized void insert (Connection conn, T[] objects)
        throws SQLException
    {
        StringBuilder sql = new StringBuilder(
            "insert into " + name + " (" + listOfFields + ") values (?");
        for (int i = 1; i < nColumns; i++) {
            sql.append(",?");
        }
        sql.append(")");
        PreparedStatement insertStmt = conn.prepareStatement(sql.toString());
        for (int i = 0; i < objects.length; i++) {
            bindUpdateVariables(insertStmt, objects[i], null);
            insertStmt.addBatch();
        }
        insertStmt.executeBatch();
        insertStmt.close();
    }
1070988
@Override
    public void nullSafeSet(PreparedStatement preparedStatement, Object value, int i, SharedSessionContractImplementor sessionImplementor) throws HibernateException, SQLException {
        // use JDBC array type, which is fairly new, so tread carefully
        if (value == null) {
			preparedStatement.setNull(i, java.sql.Types.ARRAY);
		} else if(value instanceof Integer[]){
		    Integer[] myArray = (Integer[]) value;
            Array inArray = preparedStatement.getConnection().createArrayOf("integer", myArray);
            preparedStatement.setArray(i, inArray);
		} else if(value instanceof int[]) {
			int[] myArray = (int[]) value;
            Array inArray = preparedStatement.getConnection().createArrayOf("integer", wrap(myArray));
			preparedStatement.setArray(i, inArray);
		} else {
		    throw new IllegalArgumentException("Invalid type of input: " + value.getClass().getName());
		}
951827
public void put_property(Database database, String name, DbDatum[] properties)
            throws DevFailed {
        if (!database.isAccess_checked()) checkAccess(database);

        String[] array = dbdatum2StringArray(name, properties);
        DeviceData argIn = new DeviceData();
        argIn.insert(array);
        command_inout(database, "DbPutProperty", argIn);
    }