/*
(non-Javadoc)

@see
com.impetus.client.hbase.Writer#writeForeignKeys(org.apache.hadoop.hbase
.client.HTable, java.lang.String, java.util.Map)
173860
@Override
    public void writeForeignKeys(HTableInterface hTable, String rowKey, Map<String, Set<String>> foreignKeyMap)
            throws IOException
    {
        Put p = new Put(Bytes.toBytes(rowKey));

        // Checking if foreign key column family exists
        Get g = new Get(Bytes.toBytes(rowKey));
        Result r = hTable.get(g);

        boolean isPresent = false;

        for (Map.Entry<String, Set<String>> entry : foreignKeyMap.entrySet())
        {
            String property = entry.getKey(); // Foreign key name
            Set<String> foreignKeys = entry.getValue();
            String keys = MetadataUtils.serializeKeys(foreignKeys);

            // Check if there was any existing foreign key value, if yes, append
            // it
            byte[] value = r.getValue(Bytes.toBytes(Constants.FOREIGN_KEY_EMBEDDED_COLUMN_NAME),
                    Bytes.toBytes(property));
            String existingForeignKey = Bytes.toString(value);

            if (existingForeignKey == null || existingForeignKey.isEmpty())
            {
                p.add(Bytes.toBytes(Constants.FOREIGN_KEY_EMBEDDED_COLUMN_NAME), Bytes.toBytes(property),
                        Bytes.toBytes(keys));
                isPresent = true;
            }
            else
            {
                p.add(Bytes.toBytes(Constants.FOREIGN_KEY_EMBEDDED_COLUMN_NAME), Bytes.toBytes(property),
                        Bytes.toBytes(existingForeignKey + Constants.FOREIGN_KEY_SEPARATOR + keys));
                isPresent = true;
            }
        }
        if (isPresent)
        {
            hTable.put(p);
        }
    }
101091
private static void writeMap(Map<?, ?> map, CharBuf buffer) {
        if (!map.isEmpty()) {
            buffer.addChar('{');
            boolean firstItem = true;
            for (Map.Entry<?, ?> entry : map.entrySet()) {
                if (entry.getKey() == null) {
                    throw new IllegalArgumentException("Maps with null keys can\'t be converted to JSON");
                }

                if (!firstItem) {
                    buffer.addChar(',');
                } else {
                    firstItem = false;
                }

                buffer.addJsonFieldName(entry.getKey().toString());
                writeObject(entry.getValue(), buffer);
            }
            buffer.addChar('}');
        } else {
            buffer.addChars(EMPTY_MAP_CHARS);
        }
    }
1099829
public TableWriteItems withHashOnlyKeysToDelete(String hashKeyName,
            Object... hashKeyValues) {
        if (hashKeyName == null)
            throw new IllegalArgumentException();
        PrimaryKey[] primaryKeys = new PrimaryKey[hashKeyValues.length];
        for (int i=0; i < hashKeyValues.length; i++)
            primaryKeys[i] = new PrimaryKey(hashKeyName, hashKeyValues[i]);
        return withPrimaryKeysToDelete(primaryKeys);
    }
1354413
public void setTagKeys(java.util.Collection<String> tagKeys) {
        if (tagKeys == null) {
            this.tagKeys = null;
            return;
        }

        this.tagKeys = new com.ibm.cloud.objectstorage.internal.SdkInternalList<String>(tagKeys);
    }
257236
@Override
  public String getOrCreateForKey(String key) {
    return uuidsByKey.computeIfAbsent(key, k -> Uuids.create());
  }
719632
protected void writeMap(Map<?, ?> map, CharBuf buffer) {
        if (map.isEmpty()) {
            buffer.addChars(EMPTY_MAP_CHARS);
            return;
        }
        buffer.addChar(OPEN_BRACE);
        for (Map.Entry<?, ?> entry : map.entrySet()) {
            if (entry.getKey() == null) {
                throw new IllegalArgumentException("Maps with null keys can\'t be converted to JSON");
            }
            String key = entry.getKey().toString();
            Object value = entry.getValue();
            if (isExcludingValues(value) || isExcludingFieldsNamed(key)) {
                continue;
            }
            writeMapEntry(key, value, buffer);
            buffer.addChar(COMMA);
        }
        buffer.removeLastChar(COMMA); // dangling comma
        buffer.addChar(CLOSE_BRACE);
    }
140069
public void doWrite(FieldTable table, KeyAreaInfo keyArea, BaseBuffer bufferNew) throws DBException
    {
        BaseBuffer bufferSeek = this.doSeek("==", table, keyArea);
        if (bufferSeek != null) // if (this.GetUniqueKeyCode() == DBConstants.UNIQUE) // Success means this one already exists
            throw new DBException(Constants.DUPLICATE_KEY);
        this.insertCurrent(table, keyArea, bufferNew, +1);  // Point to next HIGHER key
    }
1063506
function( keys ) {
		var lookupString = keys.toString();
		var id = this.plainObjectSignatureLookup[lookupString];			
		if (id === undefined) {

			// Create new signature buffer
			var sigbuf = [];
			sigbuf.push( pack2b( keys.length, false ) );
			for (var i=0, l=keys.length; i<l; ++i) {
				sigbuf.push( pack2b( this.stringID(keys[i]), false ) );
			}

			// Keep on table
			this.plainObjectSignatureTable.push( Buffer.concat( sigbuf ) );
			this.plainObjectSignatureLookup[lookupString] 
				= id = this.plainObjectSignatureTable.length - 1;

		}
		return id;
	}
548537
private static void getForeignKeys(DatabaseMetaData md, DatabaseRelationDefinition relation, DBMetadata metadata) throws SQLException {

		QuotedIDFactory idfac = metadata.getQuotedIDFactory();

		RelationID relationId = relation.getID();
		try (ResultSet rs = md.getImportedKeys(null, relationId.getSchemaName(), relationId.getTableName())) {
            extractForeignKeys(relation, metadata, idfac, rs);
        }
        catch (Exception ex) {
            try (ResultSet rs = md.getImportedKeys(relationId.getSchemaName(),null, relationId.getTableName())) {
                extractForeignKeys(relation, metadata, idfac, rs);
            }
        }
	}
952883
@Override
    public void writeRelations(HTableInterface htable, Object rowKey, boolean containsEmbeddedObjectsOnly,
            List<RelationHolder> relations, String columnFamilyName) throws IOException
    {
        Put p = new Put(HBaseUtils.getBytes(rowKey));

        boolean isPresent = false;
        for (RelationHolder r : relations)
        {
            if (r != null)
            {
                if (containsEmbeddedObjectsOnly)
                {
                    p.add(Bytes.toBytes(r.getRelationName()), Bytes.toBytes(r.getRelationName()),
                            PropertyAccessorHelper.getBytes(r.getRelationValue()));
                    isPresent = true;
                }
                else
                {
                    p.add(columnFamilyName.getBytes(), Bytes.toBytes(r.getRelationName()), System.currentTimeMillis(),
                            PropertyAccessorHelper.getBytes(r.getRelationValue()));
                    isPresent = true;
                }
            }
        }

        if (isPresent)
        {
            htable.put(p);
        }
    }
493611
private void writeProperties(JsonGenerator jsonGenerator, ResultSet rs) throws IOException, SQLException {
        if (columnCountProperties != -1) {
            jsonGenerator.writeObjectFieldStart("properties");
            for (Map.Entry<String, Integer> entry : cachedColumnNames.entrySet()) {
                String string = entry.getKey();
                string = string.toLowerCase();
                Integer fieldId = entry.getValue();
                if (rs.getObject(fieldId) instanceof Object[]) {
                    Object[] array = (Object[]) rs.getObject(fieldId);
                    jsonGenerator.writeArrayFieldStart(string);
                    writeArray(jsonGenerator, array, true);
                    jsonGenerator.writeEndArray();
                } else if (rs.getObject(fieldId) != null && rs.getObject(fieldId).equals("{}")){
                    jsonGenerator.writeObjectFieldStart(string);
                    jsonGenerator.writeEndObject();
                } else if (rs.getObject(fieldId) == "null") {
                    jsonGenerator.writeFieldName(string);
                    jsonGenerator.writeNull();
                } else {
                    jsonGenerator.writeObjectField(string, rs.getObject(fieldId));
                }
            }
            jsonGenerator.writeEndObject();
        }
    }
1085286
public void writeKeyOffsets(CodeType codeType)
    { // Now, write all the key offsets out
        Record recClassInfo = this.getMainRecord();
        try   {
            //String previousKey;
            String strKeyName = "";
            String strRecordClass;
            String uniqueKeyFields[] = new String[10];
            String uniqueKeySeq[] = new String[10];
            int uniqueKeyCount = 0;
            strRecordClass = recClassInfo.getField(ClassInfo.CLASS_NAME).getString();
            
            Record recKeyInfo = this.getRecord(KeyInfo.KEY_INFO_FILE);
            recKeyInfo.close();
            int count = 0;
            while (recKeyInfo.hasNext())
            {
                recKeyInfo.next();
                count++;
                strKeyName = recKeyInfo.getField(KeyInfo.KEY_NAME).getString();
                if (strKeyName.length() == 0)
                    strKeyName = recKeyInfo.getField(KeyInfo.KEY_FIELD_1).getString();
                if (strKeyName.equalsIgnoreCase(DBConstants.PRIMARY_KEY))
                    strKeyName = strRecordClass + "Primary";    // To avoid re-defining kPrimaryKey

                if (!((IncludeScopeField)recKeyInfo.getField(KeyInfo.INCLUDE_SCOPE)).includeThis(codeType, true))
                    continue;
                if (keyInBase(recClassInfo, recKeyInfo))
                    continue;
                if (!strKeyName.equalsIgnoreCase(DBConstants.PRIMARY_KEY))
                    if (count == 1)
                        if (recKeyInfo.getField(KeyInfo.KEY_NUMBER).isNull())
                            count++;   // Special case, no sequence, first key is not the primary key... first key must be primary key
                if (count > 1)
                    m_StreamOut.writeit("\npublic static final String " + this.convertNameToConstant(strKeyName + "Key") + " = \"" + strKeyName +"\";\n");

                    // This logic here checks to see if this is a unique key with one field, if yes adds field to array
                String keyTypeStr, strKeyFieldName;
                keyTypeStr = recKeyInfo.getField(KeyInfo.KEY_TYPE).getString();
                if (keyTypeStr.length() == 0)
                    keyTypeStr = KeyTypeField.UNIQUE; // Unique key if no selection
                strKeyFieldName = recKeyInfo.getField(KeyInfo.KEY_FIELD_2).getString();
                if (((keyTypeStr.charAt(0) == KeyTypeField.UNIQUE.charAt(0)) || (keyTypeStr.charAt(0) == 'Y')) && (strKeyFieldName.length() == 0))
                    { // Unique key with one field, default logic... always try to read
                    strKeyFieldName = recKeyInfo.getField(KeyInfo.KEY_FIELD_1).getString();
                    uniqueKeyFields[uniqueKeyCount] = strKeyFieldName;
                    uniqueKeySeq[uniqueKeyCount] = strKeyName;
                    uniqueKeyCount++;
                }
            }
            recKeyInfo.close();
        } catch (DBException ex)   {
            ex.printStackTrace();
        }
    }
1235122
@Override
    public void writeData(String tableName, EntityMetadata m, Object entity, Object rowId,
            List<RelationHolder> relations, boolean showQuery) throws IOException
    {
        HTableInterface hTable = gethTable(tableName);

        MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
                m.getPersistenceUnit());

        EntityType entityType = metaModel.entity(m.getEntityClazz());

        Set<Attribute> attributes = entityType.getAttributes();

        if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))
        {
            rowId = KunderaCoreUtils.prepareCompositeKey(m, rowId);
        }

        HBaseDataWrapper columnWrapper = new HBaseDataWrapper(rowId, new java.util.HashMap<String, Attribute>(),
                entity, null);
        List<HBaseDataWrapper> persistentData = new ArrayList<HBaseDataHandler.HBaseDataWrapper>(attributes.size());

        Map<String, HBaseDataWrapper> columnWrappers = preparePersistentData(tableName, m.getTableName(), entity,
                rowId, metaModel, attributes, columnWrapper, persistentData, showQuery);

        writeColumnData(hTable, entity, columnWrappers);

        for (HBaseDataWrapper wrapper : persistentData)
        {
            hbaseWriter.writeColumns(hTable, wrapper.getColumnFamily(), wrapper.getRowKey(), wrapper.getColumns(),
                    wrapper.getValues(), wrapper.getEntity());
        }

        // Persist relationships as a column in newly created Column family by
        // Kundera
        boolean containsEmbeddedObjectsOnly = columnWrapper.getColumns().isEmpty() && persistentData.isEmpty();

        if (relations != null && !relations.isEmpty())
        {
            hbaseWriter.writeRelations(hTable, rowId, containsEmbeddedObjectsOnly, relations, m.getTableName());
        }

        // add discriminator column
        String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();
        String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue();

        // No need to check for empty or blank, as considering it as valid name
        // for nosql!
        if (discrColumn != null && discrValue != null)
        {
            List<RelationHolder> discriminator = new ArrayList<RelationHolder>(1);
            discriminator.add(new RelationHolder(discrColumn, discrValue));
            hbaseWriter.writeRelations(hTable, rowId, containsEmbeddedObjectsOnly, discriminator, m.getTableName());
        }

        puthTable(hTable);
    }
149802
public void setKeys(java.util.Collection<java.util.Map<String, AttributeValue>> keys) {
        if (keys == null) {
            this.keys = null;
            return;
        }

        this.keys = new java.util.ArrayList<java.util.Map<String, AttributeValue>>(keys);
    }
178076
public static String generateSign(Map<String, String> map,String paternerKey){
		return generateSign(map, null, paternerKey);
	}
503168
public static Map<Integer, PrimaryKey> constructPrimaryKeyMap(Collection<PrimaryKey> aPrimaryKeys)
	{
		if (aPrimaryKeys == null)
			return null;

		Map<Integer, PrimaryKey> map = new HashMap<Integer, PrimaryKey>(aPrimaryKeys.size());
		PrimaryKey primaryKey = null;
		for (Iterator<PrimaryKey> i = aPrimaryKeys.iterator(); i.hasNext();)
		{
			primaryKey = (PrimaryKey) i.next();
			map.put(Integer.valueOf(primaryKey.getPrimaryKey()), primaryKey);
		}
		return map;
	}
1029073
private static void makeAllColumnsPrimaryKeysIfNoPrimaryKeysFound(Table table) {
        if ((table != null) && (table.getPrimaryKeyColumns() != null) && (table.getPrimaryKeyColumns().length == 0)) {
            Column[] allCoumns = table.getColumns();

            for (Column column : allCoumns) {
                column.setPrimaryKey(true);
            }
        }
    }