_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q164000
HBaseDataHandler.returnSpecificFieldList
train
private List returnSpecificFieldList(EntityMetadata m, List<Map<String, Object>> columnsToOutput, List<HBaseDataWrapper> results, List outputResults) { for (HBaseDataWrapper data : results) { List result = new ArrayList(); Map<String, byte[]> columns = data.getColumns(); for (Map<String, Object> map : columnsToOutput) { Object obj; String colDataKey = HBaseUtils.getColumnDataKey((String) map.get(Constants.COL_FAMILY), (String) map.get(Constants.DB_COL_NAME)); if ((boolean) map.get(Constants.IS_EMBEDDABLE)) { Class embedClazz = (Class) map.get(Constants.FIELD_CLAZZ); String prefix = (String) map.get(Constants.DB_COL_NAME) + HBaseUtils.DOT; obj = populateEmbeddableObject(data, KunderaCoreUtils.createNewInstance(embedClazz), m, embedClazz, prefix); } else if (isIdCol(m, (String) map.get(Constants.DB_COL_NAME))) { obj = HBaseUtils.fromBytes(data.getRowKey(), (Class) map.get(Constants.FIELD_CLAZZ)); } else { obj = HBaseUtils.fromBytes(columns.get(colDataKey), (Class) map.get(Constants.FIELD_CLAZZ)); } result.add(obj); } if (columnsToOutput.size() == 1) outputResults.addAll(result); else outputResults.add(result); } return outputResults; }
java
{ "resource": "" }
q164001
HBaseDataHandler.isIdCol
train
private boolean isIdCol(EntityMetadata m, String colName) { return ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName().equals(colName); }
java
{ "resource": "" }
q164002
HBaseDataHandler.populateEmbeddableObject
train
private Object populateEmbeddableObject(HBaseDataWrapper data, Object obj, EntityMetadata m, Class clazz, String prefix) { MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel( m.getPersistenceUnit()); Set<Attribute> attributes = metaModel.embeddable(clazz).getAttributes(); writeValuesToEntity(obj, data, m, metaModel, attributes, null, null, -1, prefix); return obj; }
java
{ "resource": "" }
q164003
HBaseDataHandler.getObjectFromByteArray
train
private Object getObjectFromByteArray(EntityType entityType, byte[] value, String jpaColumnName, EntityMetadata m) { if (jpaColumnName != null) { String fieldName = m.getFieldName(jpaColumnName); if (fieldName != null) { Attribute attribute = fieldName != null ? entityType.getAttribute(fieldName) : null; EntityMetadata relationMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, attribute.getJavaType()); Object colValue = PropertyAccessorHelper.getObject(relationMetadata.getIdAttribute().getJavaType(), value); return colValue; } } logger.warn("No value found for column {}, returning null.", jpaColumnName); return null; }
java
{ "resource": "" }
q164004
HBaseDataHandler.getHandle
train
public HBaseDataHandler getHandle() { HBaseDataHandler handler = new HBaseDataHandler(this.kunderaMetadata, this.connection); handler.filter = this.filter; handler.filters = this.filters; return handler; }
java
{ "resource": "" }
q164005
HibernateClient.onBegin
train
private Transaction onBegin() { Transaction tx; if (((StatelessSessionImpl) s).getTransactionCoordinator().isTransactionActive()) { tx = ((StatelessSessionImpl) s).getTransaction(); } else { tx = s.beginTransaction(); } return tx; }
java
{ "resource": "" }
q164006
HibernateClient.persistJoinTable
train
@Override public void persistJoinTable(JoinTableData joinTableData) { String schemaName = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, joinTableData.getEntityClass()) .getSchema(); 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); insertRecordInJoinTable(schemaName, joinTableName, joinColumnName, invJoinColumnName, key, values); } }
java
{ "resource": "" }
q164007
HibernateClient.insertRecordInJoinTable
train
private void insertRecordInJoinTable(String schemaName, String joinTableName, String joinColumnName, String inverseJoinColumnName, Object parentId, Set<Object> childrenIds) { s = getStatelessSession(); Transaction tx = onBegin(); for (Object childId : childrenIds) { StringBuffer query = new StringBuffer(); // write an update query Object[] existingRowIds = findIdsByColumn(schemaName, joinTableName, joinColumnName, inverseJoinColumnName, (String) childId, null); boolean joinTableRecordsExists = false; if (existingRowIds != null && existingRowIds.length > 0) { for (Object o : existingRowIds) { if (o.toString().equals(parentId.toString())) { joinTableRecordsExists = true; break; } } } if (!joinTableRecordsExists) { query.append("INSERT INTO ").append(getFromClause(schemaName, joinTableName)).append("(") .append(joinColumnName).append(",").append(inverseJoinColumnName).append(")") .append(" VALUES('").append(parentId).append("','").append(childId).append("')"); s.createSQLQuery(query.toString()).executeUpdate(); } } onCommit(tx); // tx.commit(); }
java
{ "resource": "" }
q164008
HibernateClient.onNativeUpdate
train
public int onNativeUpdate(String query, Map<Parameter, Object> parameterMap) { s = getStatelessSession(); Query q = s.createSQLQuery(query); setParameters(parameterMap, q); // Transaction tx = s.getTransaction() == null ? s.beginTransaction(): // s.getTransaction(); // tx.begin(); int i = q.executeUpdate(); // tx.commit(); return i; }
java
{ "resource": "" }
q164009
HibernateClient.getDataType
train
private Object[] getDataType(EntityMetadata entityMetadata, Object... arg1) throws PropertyAccessException { Field idField = (Field) entityMetadata.getIdAttribute().getJavaMember(); PropertyAccessor<?> accessor = PropertyAccessorFactory.getPropertyAccessor(idField); Object[] pKeys = new Object[arg1.length]; int cnt = 0; for (Object r : arg1) { pKeys[cnt++] = accessor.fromString(idField.getClass(), r.toString()); } return pKeys; }
java
{ "resource": "" }
q164010
HibernateClient.getFromClause
train
private String getFromClause(String schemaName, String tableName) { String clause = tableName; if (schemaName != null && !schemaName.isEmpty()) { clause = schemaName + "." + tableName; } return clause; }
java
{ "resource": "" }
q164011
HibernateClient.updateForeignKeys
train
private void updateForeignKeys(EntityMetadata metadata, Object id, List<RelationHolder> relationHolders) { for (RelationHolder rh : relationHolders) { String linkName = rh.getRelationName(); Object linkValue = rh.getRelationValue(); if (linkName != null && linkValue != null) { // String fieldName = metadata.getFieldName(linkName); String clause = getFromClause(metadata.getSchema(), metadata.getTableName()); // String updateSql = "Update " + // metadata.getEntityClazz().getSimpleName() + " SET " + // fieldName + "= '" + linkValue + "' WHERE " // + ((AbstractAttribute) metadata.getIdAttribute()).getName() + // " = '" + id + "'"; String updateSql = "Update " + clause + " SET " + linkName + "= '" + linkValue + "' WHERE " + ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName() + " = '" + id + "'"; onNativeUpdate(updateSql, null); } } }
java
{ "resource": "" }
q164012
HibernateClient.removeKunderaProxies
train
private boolean removeKunderaProxies(EntityMetadata metadata, Object entity, List<RelationHolder> relationHolders) { boolean proxyRemoved = false; for (Relation relation : metadata.getRelations()) { if (relation != null && relation.isUnary()) { Object relationObject = PropertyAccessorHelper.getObject(entity, relation.getProperty()); if (relationObject != null && ProxyHelper.isKunderaProxy(relationObject)) { EntityMetadata relMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, relation.getTargetEntity()); Method idAccessorMethod = relMetadata.getReadIdentifierMethod(); Object foreignKey = null; try { foreignKey = idAccessorMethod.invoke(relationObject, new Object[] {}); } catch (IllegalArgumentException e) { log.error("Error while Fetching relationship value of {}, Caused by {}.", metadata.getEntityClazz(), e); } catch (IllegalAccessException e) { log.error("Error while Fetching relationship value of {}, Caused by {}.", metadata.getEntityClazz(), e); } catch (InvocationTargetException e) { log.error("Error while Fetching relationship value of {}, Caused by {}.", metadata.getEntityClazz(), e); } if (foreignKey != null) { relationObject = null; PropertyAccessorHelper.set(entity, relation.getProperty(), relationObject); relationHolders .add(new RelationHolder(relation.getJoinColumnName(kunderaMetadata), foreignKey)); proxyRemoved = true; } } } } return proxyRemoved; }
java
{ "resource": "" }
q164013
HibernateClient.setParameters
train
private void setParameters(Map<Parameter, Object> parameterMap, Query q) { if (parameterMap != null && !parameterMap.isEmpty()) { for (Parameter parameter : parameterMap.keySet()) { Object paramObject = parameterMap.get(parameter); if (parameter.getName() != null) { if (paramObject instanceof Collection) { q.setParameterList(parameter.getName(), (Collection) paramObject); } else { q.setParameter(parameter.getName(), paramObject); } } else if (parameter.getPosition() != null) { if (paramObject instanceof Collection) { q.setParameterList(Integer.toString(parameter.getPosition()), (Collection) paramObject); } else { q.setParameter(Integer.toString(parameter.getPosition()), paramObject); } } } } }
java
{ "resource": "" }
q164014
CassandraSchemaManager.dropSchema
train
public void dropSchema() { if (operation != null && operation.equalsIgnoreCase("create-drop")) { try { dropKeyspaceOrCFs(); } catch (Exception ex) { log.error("Error during dropping schema in cassandra, Caused by: .", ex); throw new SchemaGenerationException(ex, "Cassandra"); } } cassandra_client = null; }
java
{ "resource": "" }
q164015
CassandraSchemaManager.dropKeyspaceOrCFs
train
private void dropKeyspaceOrCFs() throws InvalidRequestException, SchemaDisagreementException, TException, Exception { if (createdKeyspaces.contains(databaseName))// drop if created during // create-drop call. { cassandra_client.system_drop_keyspace(databaseName); } else { cassandra_client.set_keyspace(databaseName); for (TableInfo tableInfo : tableInfos) { dropColumnFamily(tableInfo); } } }
java
{ "resource": "" }
q164016
CassandraSchemaManager.dropColumnFamily
train
private void dropColumnFamily(TableInfo tableInfo) throws Exception { if (isCql3Enabled(tableInfo)) { dropTableUsingCql(tableInfo); } else { cassandra_client.system_drop_column_family(tableInfo.getTableName()); } }
java
{ "resource": "" }
q164017
CassandraSchemaManager.onCreateKeyspace
train
private KsDef onCreateKeyspace() throws Exception { try { createdKeyspaces.add(databaseName); createKeyspace(); } catch (InvalidRequestException irex) { // Ignore and add a log.debug // keyspace already exists. // remove from list if already created. createdKeyspaces.remove(databaseName); } cassandra_client.set_keyspace(databaseName); return cassandra_client.describe_keyspace(databaseName); }
java
{ "resource": "" }
q164018
CassandraSchemaManager.createKeyspace
train
private void createKeyspace() throws Exception { if (cql_version != null && cql_version.equals(CassandraConstants.CQL_VERSION_3_0)) { onCql3CreateKeyspace(); } else { Map<String, String> strategy_options = new HashMap<String, String>(); List<CfDef> cfDefs = new ArrayList<CfDef>(); KsDef ksDef = new KsDef(databaseName, csmd.getPlacement_strategy(databaseName), cfDefs); setProperties(ksDef, strategy_options); ksDef.setStrategy_options(strategy_options); cassandra_client.system_add_keyspace(ksDef); } }
java
{ "resource": "" }
q164019
CassandraSchemaManager.onCql3CreateKeyspace
train
private void onCql3CreateKeyspace() throws InvalidRequestException, UnavailableException, TimedOutException, SchemaDisagreementException, TException, UnsupportedEncodingException { String createKeyspace = CQLTranslator.CREATE_KEYSPACE; String placement_strategy = csmd.getPlacement_strategy(databaseName); String replication_conf = CQLTranslator.SIMPLE_REPLICATION; createKeyspace = createKeyspace.replace("$KEYSPACE", Constants.ESCAPE_QUOTE + databaseName + Constants.ESCAPE_QUOTE); Schema schema = CassandraPropertyReader.csmd.getSchema(databaseName); if (schema != null && schema.getName() != null && schema.getName().equalsIgnoreCase(databaseName) && schema.getSchemaProperties() != null) { Properties schemaProperties = schema.getSchemaProperties(); if (placement_strategy.equalsIgnoreCase(SimpleStrategy.class.getSimpleName()) || placement_strategy.equalsIgnoreCase(SimpleStrategy.class.getName())) { String replicationFactor = schemaProperties.getProperty(CassandraConstants.REPLICATION_FACTOR, CassandraConstants.DEFAULT_REPLICATION_FACTOR); replication_conf = replication_conf.replace("$REPLICATION_FACTOR", replicationFactor); createKeyspace = createKeyspace.replace("$CLASS", placement_strategy); } else if (placement_strategy.equalsIgnoreCase(NetworkTopologyStrategy.class.getSimpleName()) || placement_strategy.equalsIgnoreCase(NetworkTopologyStrategy.class.getName())) { if (schema.getDataCenters() != null && !schema.getDataCenters().isEmpty()) { StringBuilder builder = new StringBuilder(); for (DataCenter dc : schema.getDataCenters()) { builder.append(CQLTranslator.QUOTE_STR); builder.append(dc.getName()); builder.append(CQLTranslator.QUOTE_STR); builder.append(":"); builder.append(dc.getValue()); builder.append(CQLTranslator.COMMA_STR); } builder.delete(builder.lastIndexOf(CQLTranslator.COMMA_STR), builder.length()); replication_conf = builder.toString(); } } createKeyspace = createKeyspace.replace("$CLASS", placement_strategy); createKeyspace = createKeyspace.replace("$REPLICATION", replication_conf); boolean isDurableWrites = Boolean.parseBoolean(schemaProperties.getProperty( CassandraConstants.DURABLE_WRITES, "true")); createKeyspace = createKeyspace.replace("$DURABLE_WRITES", isDurableWrites + ""); } else { createKeyspace = createKeyspace.replace("$CLASS", placement_strategy); replication_conf = replication_conf.replace("$REPLICATION_FACTOR", (CharSequence) externalProperties.getOrDefault(CassandraConstants.REPLICATION_FACTOR, CassandraConstants.DEFAULT_REPLICATION_FACTOR)); createKeyspace = createKeyspace.replace("$REPLICATION", replication_conf); createKeyspace = createKeyspace.replace("$DURABLE_WRITES", "true"); } cassandra_client.execute_cql3_query(ByteBuffer.wrap(createKeyspace.getBytes(Constants.CHARSET_UTF8)), Compression.NONE, ConsistencyLevel.ONE); KunderaCoreUtils.printQuery(createKeyspace, showQuery); }
java
{ "resource": "" }
q164020
CassandraSchemaManager.createColumnFamilies
train
private void createColumnFamilies(List<TableInfo> tableInfos, KsDef ksDef) throws Exception { for (TableInfo tableInfo : tableInfos) { if (isCql3Enabled(tableInfo)) { createOrUpdateUsingCQL3(tableInfo, ksDef); createIndexUsingCql(tableInfo); } else { createOrUpdateColumnFamily(tableInfo, ksDef); } // Create Inverted Indexed Table if required. createInvertedIndexTable(tableInfo, ksDef); } }
java
{ "resource": "" }
q164021
CassandraSchemaManager.createOrUpdateColumnFamily
train
private void createOrUpdateColumnFamily(TableInfo tableInfo, KsDef ksDef) throws Exception { MetaDataHandler handler = new MetaDataHandler(); if (containsCompositeKey(tableInfo)) { validateCompoundKey(tableInfo); createOrUpdateUsingCQL3(tableInfo, ksDef); // After successful schema operation, perform index creation. createIndexUsingCql(tableInfo); } else if (containsCollectionColumns(tableInfo) || isCql3Enabled(tableInfo)) { createOrUpdateUsingCQL3(tableInfo, ksDef); createIndexUsingCql(tableInfo); } else { CfDef cf_def = handler.getTableMetadata(tableInfo); try { cassandra_client.system_add_column_family(cf_def); } catch (InvalidRequestException irex) { updateExistingColumnFamily(tableInfo, ksDef, irex); } } }
java
{ "resource": "" }
q164022
CassandraSchemaManager.containsCompositeKey
train
private boolean containsCompositeKey(TableInfo tableInfo) { return tableInfo.getTableIdType() != null && tableInfo.getTableIdType().isAnnotationPresent(Embeddable.class); }
java
{ "resource": "" }
q164023
CassandraSchemaManager.updateExistingColumnFamily
train
private void updateExistingColumnFamily(TableInfo tableInfo, KsDef ksDef, InvalidRequestException irex) throws Exception { StringBuilder builder = new StringBuilder("^Cannot add already existing (?:column family|table) .*$"); if (irex.getWhy() != null && irex.getWhy().matches(builder.toString())) { SchemaOperationType operationType = SchemaOperationType.getInstance(operation); switch (operationType) { case create: handleCreate(tableInfo, ksDef); break; case createdrop: handleCreate(tableInfo, ksDef); break; case update: if (isCql3Enabled(tableInfo)) { for (ColumnInfo column : tableInfo.getColumnMetadatas()) { addColumnToTable(tableInfo, column); } createIndexUsingCql(tableInfo); } else { updateTable(ksDef, tableInfo); } break; default: break; } } else { log.error("Error occurred while creating table {}, Caused by: {}.", tableInfo.getTableName(), irex); throw new SchemaGenerationException("Error occurred while creating table " + tableInfo.getTableName(), irex, "Cassandra", databaseName); } }
java
{ "resource": "" }
q164024
CassandraSchemaManager.handleCreate
train
private void handleCreate(TableInfo tableInfo, KsDef ksDef) throws Exception { if (containsCompositeKey(tableInfo)) { validateCompoundKey(tableInfo); // First drop existing column family. dropTableUsingCql(tableInfo); } else { onDrop(tableInfo); } createOrUpdateColumnFamily(tableInfo, ksDef); }
java
{ "resource": "" }
q164025
CassandraSchemaManager.update
train
protected void update(List<TableInfo> tableInfos) { try { createOrUpdateKeyspace(tableInfos); } catch (Exception ex) { log.error("Error occurred while creating {}, Caused by: .", databaseName, ex); throw new SchemaGenerationException(ex); } }
java
{ "resource": "" }
q164026
CassandraSchemaManager.getCompositeIdEmbeddables
train
private void getCompositeIdEmbeddables(EmbeddableType embeddable, List compositeEmbeddables, MetamodelImpl metaModel) { compositeEmbeddables.add(embeddable.getJavaType().getSimpleName()); for (Object column : embeddable.getAttributes()) { Attribute columnAttribute = (Attribute) column; Field f = (Field) columnAttribute.getJavaMember(); if (columnAttribute.getJavaType().isAnnotationPresent(Embeddable.class)) { getCompositeIdEmbeddables(metaModel.embeddable(columnAttribute.getJavaType()), compositeEmbeddables, metaModel); } } }
java
{ "resource": "" }
q164027
CassandraSchemaManager.onEmbeddedColumns
train
private void onEmbeddedColumns(CQLTranslator translator, TableInfo tableInfo, StringBuilder queryBuilder, List compositeEmbeddables) { List<EmbeddedColumnInfo> embeddedColumns = tableInfo.getEmbeddedColumnMetadatas(); for (EmbeddedColumnInfo embColInfo : embeddedColumns) { if (!compositeEmbeddables.contains(embColInfo.getEmbeddable().getJavaType().getSimpleName())) { String cqlType = CQLTranslator.FROZEN + Constants.STR_LT + Constants.ESCAPE_QUOTE + embColInfo.getEmbeddable().getJavaType().getSimpleName() + Constants.ESCAPE_QUOTE + Constants.STR_GT + translator.COMMA_STR; translator.appendColumnName(queryBuilder, embColInfo.getEmbeddedColumnName(), cqlType); } } }
java
{ "resource": "" }
q164028
CassandraSchemaManager.postProcessEmbedded
train
private void postProcessEmbedded(Map<String, String> embNametoUDTQuery, Map<String, List<String>> embNametoDependentList) { for (Map.Entry<String, List<String>> entry : embNametoDependentList.entrySet()) { checkRelationAndExecuteQuery(entry.getKey(), embNametoDependentList, embNametoUDTQuery); } }
java
{ "resource": "" }
q164029
CassandraSchemaManager.checkRelationAndExecuteQuery
train
private void checkRelationAndExecuteQuery(String embeddableKey, Map<String, List<String>> embeddableToDependentEmbeddables, Map<String, String> queries) { List<String> dependentEmbeddables = embeddableToDependentEmbeddables.get(embeddableKey); if (!dependentEmbeddables.isEmpty()) { for (String dependentEmbeddable : dependentEmbeddables) { checkRelationAndExecuteQuery(dependentEmbeddable, embeddableToDependentEmbeddables, queries); } } KunderaCoreUtils.printQuery(queries.get(embeddableKey), showQuery); try { cassandra_client.execute_cql3_query( ByteBuffer.wrap(queries.get(embeddableKey).getBytes(Constants.CHARSET_UTF8)), Compression.NONE, ConsistencyLevel.ONE); } catch (Exception e) { throw new KunderaException("Error while creating type: " + queries.get(embeddableKey), e); } }
java
{ "resource": "" }
q164030
CassandraSchemaManager.appendPrimaryKey
train
private void appendPrimaryKey(CQLTranslator translator, EmbeddableType compoEmbeddableType, Field[] fields, StringBuilder queryBuilder) { for (Field f : fields) { if (!ReflectUtils.isTransientOrStatic(f)) { if (f.getType().isAnnotationPresent(Embeddable.class)) { // compound partition key MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel( puMetadata.getPersistenceUnitName()); queryBuilder.append(translator.OPEN_BRACKET); queryBuilder.append(translator.SPACE_STRING); appendPrimaryKey(translator, (EmbeddableType) metaModel.embeddable(f.getType()), f.getType() .getDeclaredFields(), queryBuilder); queryBuilder.deleteCharAt(queryBuilder.length() - 1); queryBuilder.append(translator.CLOSE_BRACKET); queryBuilder.append(Constants.SPACE_COMMA); } else { Attribute attribute = compoEmbeddableType.getAttribute(f.getName()); translator.appendColumnName(queryBuilder, ((AbstractAttribute) attribute).getJPAColumnName()); queryBuilder.append(Constants.SPACE_COMMA); } } } }
java
{ "resource": "" }
q164031
CassandraSchemaManager.appendClusteringOrder
train
private void appendClusteringOrder(CQLTranslator translator, List<ColumnInfo> compositeColumns, StringBuilder clusterKeyOrderingBuilder, StringBuilder primaryKeyBuilder) { // to retrieve the order in which cluster key is formed String[] primaryKeys = primaryKeyBuilder.toString().split("\\s*,\\s*"); for (String primaryKey : primaryKeys) { // to compare the objects without enclosing quotes primaryKey = primaryKey.trim().substring(1, primaryKey.trim().length() - 1); for (ColumnInfo colInfo : compositeColumns) { if (primaryKey.equals(colInfo.getColumnName())) { if (colInfo.getOrderBy() != null) { translator.appendColumnName(clusterKeyOrderingBuilder, colInfo.getColumnName()); clusterKeyOrderingBuilder.append(translator.SPACE_STRING); clusterKeyOrderingBuilder.append(colInfo.getOrderBy()); clusterKeyOrderingBuilder.append(translator.COMMA_STR); } } } } if (clusterKeyOrderingBuilder.length() != 0) { clusterKeyOrderingBuilder.deleteCharAt(clusterKeyOrderingBuilder.toString().lastIndexOf(",")); clusterKeyOrderingBuilder.append(translator.CLOSE_BRACKET); } }
java
{ "resource": "" }
q164032
CassandraSchemaManager.replaceColumnsAndStripLastChar
train
private StringBuilder replaceColumnsAndStripLastChar(String columnFamilyQuery, StringBuilder queryBuilder) { // strip last ",". if (queryBuilder.length() > 0) { queryBuilder.deleteCharAt(queryBuilder.length() - 1); columnFamilyQuery = StringUtils.replace(columnFamilyQuery, CQLTranslator.COLUMNS, queryBuilder.toString()); queryBuilder = new StringBuilder(columnFamilyQuery); } return queryBuilder; }
java
{ "resource": "" }
q164033
CassandraSchemaManager.createIndexUsingThrift
train
private void createIndexUsingThrift(TableInfo tableInfo, CfDef cfDef) throws Exception { for (IndexInfo indexInfo : tableInfo.getColumnsToBeIndexed()) { for (ColumnDef columnDef : cfDef.getColumn_metadata()) { if (new String(columnDef.getName(), Constants.ENCODING).equals(indexInfo.getColumnName())) { columnDef.setIndex_type(CassandraIndexHelper.getIndexType(indexInfo.getIndexType())); // columnDef.setIndex_name(indexInfo.getIndexName()); } } } cassandra_client.system_update_column_family(cfDef); }
java
{ "resource": "" }
q164034
CassandraSchemaManager.createIndexUsingCql
train
private void createIndexUsingCql(TableInfo tableInfo) throws Exception { List<String> embeddedIndexes = new ArrayList<String>(); for (EmbeddedColumnInfo embeddedColumnInfo : tableInfo.getEmbeddedColumnMetadatas()) { for (ColumnInfo columnInfo : embeddedColumnInfo.getColumns()) { if (columnInfo.isIndexable()) { embeddedIndexes.add(columnInfo.getColumnName()); } } } StringBuilder indexQueryBuilder = new StringBuilder("create index if not exists on \""); indexQueryBuilder.append(tableInfo.getTableName()); indexQueryBuilder.append("\"(\"$COLUMN_NAME\")"); tableInfo.getColumnsToBeIndexed(); for (IndexInfo indexInfo : tableInfo.getColumnsToBeIndexed()) { ColumnInfo columnInfo = new ColumnInfo(); columnInfo.setColumnName(indexInfo.getColumnName()); // indexes on embeddables not supported in cql3 if (!embeddedIndexes.contains(indexInfo.getColumnName())) { String replacedWithindexName = StringUtils.replace(indexQueryBuilder.toString(), "$COLUMN_NAME", indexInfo.getColumnName()); try { KunderaCoreUtils.printQuery(replacedWithindexName, showQuery); cassandra_client.execute_cql3_query(ByteBuffer.wrap(replacedWithindexName.getBytes()), Compression.NONE, ConsistencyLevel.ONE); } catch (InvalidRequestException ire) { if (ire.getWhy() != null && !ire.getWhy().equals("Index already exists") && operation.equalsIgnoreCase(SchemaOperationType.update.name())) { log.error("Error occurred while creating indexes on column{} of table {}, , Caused by: .", indexInfo.getColumnName(), tableInfo.getTableName(), ire); throw new SchemaGenerationException("Error occurred while creating indexes on column " + indexInfo.getColumnName() + " of table " + tableInfo.getTableName(), ire, "Cassandra", databaseName); } } } } }
java
{ "resource": "" }
q164035
CassandraSchemaManager.dropTableUsingCql
train
private void dropTableUsingCql(TableInfo tableInfo) throws Exception { CQLTranslator translator = new CQLTranslator(); StringBuilder dropQuery = new StringBuilder("drop table "); translator.ensureCase(dropQuery, tableInfo.getTableName(), false); KunderaCoreUtils.printQuery(dropQuery.toString(), showQuery); cassandra_client.execute_cql3_query(ByteBuffer.wrap(dropQuery.toString().getBytes()), Compression.NONE, ConsistencyLevel.ONE); }
java
{ "resource": "" }
q164036
CassandraSchemaManager.addColumnToTable
train
private void addColumnToTable(TableInfo tableInfo, ColumnInfo column) throws Exception { CQLTranslator translator = new CQLTranslator(); StringBuilder addColumnQuery = new StringBuilder("ALTER TABLE "); translator.ensureCase(addColumnQuery, tableInfo.getTableName(), false); addColumnQuery.append(" ADD "); translator.ensureCase(addColumnQuery, column.getColumnName(), false); addColumnQuery.append(" " + translator.getCQLType(CassandraValidationClassMapper.getValidationClass(column.getType(), isCql3Enabled(tableInfo)))); try { KunderaCoreUtils.printQuery(addColumnQuery.toString(), showQuery); cassandra_client.execute_cql3_query(ByteBuffer.wrap(addColumnQuery.toString().getBytes()), Compression.NONE, ConsistencyLevel.ONE); } catch (InvalidRequestException ireforAddColumn) { StringBuilder ireforAddColumnbBuilder = new StringBuilder("Invalid column name "); ireforAddColumnbBuilder.append(column.getColumnName() + " because it conflicts with an existing column"); if (ireforAddColumn.getWhy() != null && ireforAddColumn.getWhy().equals(ireforAddColumnbBuilder.toString())) { // alterColumnType(tableInfo, translator, column); } else { log.error("Error occurred while altering column type of table {}, Caused by: .", tableInfo.getTableName(), ireforAddColumn); throw new SchemaGenerationException("Error occurred while adding column into table " + tableInfo.getTableName(), ireforAddColumn, "Cassandra", databaseName); } } }
java
{ "resource": "" }
q164037
CassandraSchemaManager.alterColumnType
train
private void alterColumnType(TableInfo tableInfo, CQLTranslator translator, ColumnInfo column) throws Exception { StringBuilder alterColumnTypeQuery = new StringBuilder("ALTER TABLE "); translator.ensureCase(alterColumnTypeQuery, tableInfo.getTableName(), false); alterColumnTypeQuery.append(" ALTER "); translator.ensureCase(alterColumnTypeQuery, column.getColumnName(), false); alterColumnTypeQuery.append(" TYPE " + translator.getCQLType(CassandraValidationClassMapper.getValidationClass(column.getType(), isCql3Enabled(tableInfo)))); cassandra_client.execute_cql3_query(ByteBuffer.wrap(alterColumnTypeQuery.toString().getBytes()), Compression.NONE, ConsistencyLevel.ONE); KunderaCoreUtils.printQuery(alterColumnTypeQuery.toString(), showQuery); }
java
{ "resource": "" }
q164038
CassandraSchemaManager.onCompositeColumns
train
private void onCompositeColumns(CQLTranslator translator, List<ColumnInfo> compositeColumns, StringBuilder queryBuilder, List<ColumnInfo> columns, boolean isCounterColumnFamily) { MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel( puMetadata.getPersistenceUnitName()); for (ColumnInfo colInfo : compositeColumns) { if (columns == null || (columns != null && !columns.contains(colInfo))) { String cqlType = null; if (isCounterColumnFamily) { cqlType = "counter"; translator.appendColumnName(queryBuilder, colInfo.getColumnName(), cqlType); queryBuilder.append(Constants.SPACE_COMMA); } // check for composite partition keys #734 else if (colInfo.getType().isAnnotationPresent(Embeddable.class)) { EmbeddableType embeddedObject = (EmbeddableType) metaModel.embeddable(colInfo.getType()); for (Field embeddedColumn : colInfo.getType().getDeclaredFields()) { if (!ReflectUtils.isTransientOrStatic(embeddedColumn)) { validateAndAppendColumnName(translator, queryBuilder, ((AbstractAttribute) embeddedObject.getAttribute(embeddedColumn.getName())) .getJPAColumnName(), embeddedColumn.getType()); } } } else { validateAndAppendColumnName(translator, queryBuilder, colInfo.getColumnName(), colInfo.getType()); } } } }
java
{ "resource": "" }
q164039
CassandraSchemaManager.validateAndAppendColumnName
train
private void validateAndAppendColumnName(CQLTranslator translator, StringBuilder queryBuilder, String b, Class<?> clazz) { String dataType = CassandraValidationClassMapper.getValidationClass(clazz, true); translator.appendColumnName(queryBuilder, b, translator.getCQLType(dataType)); queryBuilder.append(Constants.SPACE_COMMA); }
java
{ "resource": "" }
q164040
CassandraSchemaManager.onCollectionColumns
train
private void onCollectionColumns(CQLTranslator translator, List<CollectionColumnInfo> collectionColumnInfos, StringBuilder queryBuilder) { for (CollectionColumnInfo cci : collectionColumnInfos) { String dataType = CassandraValidationClassMapper.getValidationClass(cci.getType(), true); // CQL Type of collection column String collectionCqlType = translator.getCQLType(dataType); // Collection Column Name String collectionColumnName = new String(cci.getCollectionColumnName()); // Generic Type list StringBuilder genericTypesBuilder = null; List<Class<?>> genericClasses = cci.getGenericClasses(); if (!genericClasses.isEmpty()) { genericTypesBuilder = new StringBuilder(); if (MapType.class.getSimpleName().equals(dataType) && genericClasses.size() == 2) { genericTypesBuilder.append(Constants.STR_LT); String keyDataType = CassandraValidationClassMapper.getValidationClass(genericClasses.get(0), true); genericTypesBuilder.append(translator.getCQLType(keyDataType)); genericTypesBuilder.append(Constants.SPACE_COMMA); String valueDataType = CassandraValidationClassMapper.getValidationClass(genericClasses.get(1), true); genericTypesBuilder.append(translator.getCQLType(valueDataType)); genericTypesBuilder.append(Constants.STR_GT); } else if ((ListType.class.getSimpleName().equals(dataType) || SetType.class.getSimpleName().equals( dataType)) && genericClasses.size() == 1) { genericTypesBuilder.append(Constants.STR_LT); String valueDataType = CassandraValidationClassMapper.getValidationClass(genericClasses.get(0), true); genericTypesBuilder.append(translator.getCQLType(valueDataType)); genericTypesBuilder.append(Constants.STR_GT); } else { throw new SchemaGenerationException("Incorrect collection field definition for " + cci.getCollectionColumnName() + ". Generic Types must be defined correctly."); } } if (genericTypesBuilder != null) { collectionCqlType += genericTypesBuilder.toString(); } translator.appendColumnName(queryBuilder, collectionColumnName, collectionCqlType); queryBuilder.append(Constants.SPACE_COMMA); } }
java
{ "resource": "" }
q164041
CassandraSchemaManager.createInvertedIndexTable
train
private void createInvertedIndexTable(TableInfo tableInfo, KsDef ksDef) throws Exception { CfDef cfDef = getInvertedIndexCF(tableInfo); if (cfDef != null) { try { cassandra_client.system_add_column_family(cfDef); } catch (InvalidRequestException irex) { updateExistingColumnFamily(tableInfo, ksDef, irex); } } }
java
{ "resource": "" }
q164042
CassandraSchemaManager.getInvertedIndexCF
train
private CfDef getInvertedIndexCF(TableInfo tableInfo) throws InvalidRequestException, SchemaDisagreementException, TException { boolean indexTableRequired = CassandraPropertyReader.csmd.isInvertedIndexingEnabled(databaseName) && !tableInfo.getEmbeddedColumnMetadatas().isEmpty(); if (indexTableRequired) { CfDef cfDef = new CfDef(); cfDef.setKeyspace(databaseName); cfDef.setColumn_type("Super"); cfDef.setName(tableInfo.getTableName() + Constants.INDEX_TABLE_SUFFIX); cfDef.setKey_validation_class(UTF8Type.class.getSimpleName()); return cfDef; } return null; }
java
{ "resource": "" }
q164043
CassandraSchemaManager.dropInvertedIndexTable
train
private void dropInvertedIndexTable(TableInfo tableInfo) { boolean indexTableRequired = CassandraPropertyReader.csmd.isInvertedIndexingEnabled(databaseName)/* ) */ && !tableInfo.getEmbeddedColumnMetadatas().isEmpty(); if (indexTableRequired) { try { cassandra_client.system_drop_column_family(tableInfo.getTableName() + Constants.INDEX_TABLE_SUFFIX); } catch (Exception ex) { if (log.isWarnEnabled()) { log.warn("Error while dropping inverted index table, Caused by: ", ex); } } } }
java
{ "resource": "" }
q164044
CassandraSchemaManager.onValidateTable
train
private void onValidateTable(KsDef ksDef, TableInfo tableInfo) throws Exception { boolean tablefound = false; for (CfDef cfDef : ksDef.getCf_defs()) { if (cfDef.getName().equals(tableInfo.getTableName())/* * && (cfDef. * getColumn_type * ().equals( * ColumnFamilyType * . * getInstanceOf * ( * tableInfo.getType * ()).name())) */) { if (cfDef.getColumn_type().equals(ColumnFamilyType.Standard.name())) { for (ColumnInfo columnInfo : tableInfo.getColumnMetadatas()) { onValidateColumn(tableInfo, cfDef, columnInfo); } tablefound = true; break; } else if (cfDef.getColumn_type().equals(ColumnFamilyType.Super.name())) { tablefound = true; } } } if (!tablefound) { throw new SchemaGenerationException("Column family " + tableInfo.getTableName() + " does not exist in keyspace " + databaseName + "", "Cassandra", databaseName, tableInfo.getTableName()); } }
java
{ "resource": "" }
q164045
CassandraSchemaManager.onValidateColumn
train
private void onValidateColumn(TableInfo tableInfo, CfDef cfDef, ColumnInfo columnInfo) throws Exception { boolean columnfound = false; boolean isCounterColumnType = isCounterColumnType(tableInfo, null); for (ColumnDef columnDef : cfDef.getColumn_metadata()) { if (isMetadataSame(columnDef, columnInfo, isCql3Enabled(tableInfo), isCounterColumnType)) { columnfound = true; break; } } if (!columnfound) { throw new SchemaGenerationException("Column " + columnInfo.getColumnName() + " does not exist in column family " + tableInfo.getTableName() + "", "Cassandra", databaseName, tableInfo.getTableName()); } }
java
{ "resource": "" }
q164046
CassandraSchemaManager.isMetadataSame
train
private boolean isMetadataSame(ColumnDef columnDef, ColumnInfo columnInfo, boolean isCql3Enabled, boolean isCounterColumnType) throws Exception { return isIndexPresent(columnInfo, columnDef, isCql3Enabled, isCounterColumnType); }
java
{ "resource": "" }
q164047
CassandraSchemaManager.updateTable
train
private void updateTable(KsDef ksDef, TableInfo tableInfo) throws Exception { for (CfDef cfDef : ksDef.getCf_defs()) { if (cfDef.getName().equals(tableInfo.getTableName()) && cfDef.getColumn_type().equals(ColumnFamilyType.getInstanceOf(tableInfo.getType()).name())) { boolean toUpdate = false; if (cfDef.getColumn_type().equals(STANDARDCOLUMNFAMILY)) { for (ColumnInfo columnInfo : tableInfo.getColumnMetadatas()) { toUpdate = isCfDefUpdated(columnInfo, cfDef, isCql3Enabled(tableInfo), isCounterColumnType(tableInfo, null), tableInfo) ? true : toUpdate; } } if (toUpdate) { cassandra_client.system_update_column_family(cfDef); } createIndexUsingThrift(tableInfo, cfDef); break; } } }
java
{ "resource": "" }
q164048
CassandraSchemaManager.isCfDefUpdated
train
private boolean isCfDefUpdated(ColumnInfo columnInfo, CfDef cfDef, boolean isCql3Enabled, boolean isCounterColumnType, TableInfo tableInfo) throws Exception { boolean columnPresent = false; boolean isUpdated = false; for (ColumnDef columnDef : cfDef.getColumn_metadata()) { if (isColumnPresent(columnInfo, columnDef, isCql3Enabled)) { if (!isValidationClassSame(columnInfo, columnDef, isCql3Enabled, isCounterColumnType)) { columnDef.setValidation_class(CassandraValidationClassMapper.getValidationClass( columnInfo.getType(), isCql3Enabled)); // if (columnInfo.isIndexable() && // !columnDef.isSetIndex_type()) // { // IndexInfo indexInfo = // tableInfo.getColumnToBeIndexed(columnInfo.getColumnName()); // columnDef.setIndex_type(CassandraIndexHelper.getIndexType(indexInfo.getIndexType())); // columnDef.isSetIndex_type(); // columnDef.setIndex_typeIsSet(true); // columnDef.setIndex_nameIsSet(true); // } // else // { columnDef.setIndex_nameIsSet(false); columnDef.setIndex_typeIsSet(false); // } isUpdated = true; } columnPresent = true; break; } } if (!columnPresent) { cfDef.addToColumn_metadata(getColumnMetadata(columnInfo, tableInfo)); isUpdated = true; } return isUpdated; }
java
{ "resource": "" }
q164049
CassandraSchemaManager.getColumnMetadata
train
private ColumnDef getColumnMetadata(ColumnInfo columnInfo, TableInfo tableInfo) { ColumnDef columnDef = new ColumnDef(); columnDef.setName(columnInfo.getColumnName().getBytes()); columnDef.setValidation_class(CassandraValidationClassMapper.getValidationClass(columnInfo.getType(), isCql3Enabled(tableInfo))); if (columnInfo.isIndexable()) { IndexInfo indexInfo = tableInfo.getColumnToBeIndexed(columnInfo.getColumnName()); columnDef.setIndex_type(CassandraIndexHelper.getIndexType(indexInfo.getIndexType())); // if (!indexInfo.getIndexName().equals(indexInfo.getColumnName())) // { // columnDef.setIndex_name(indexInfo.getIndexName()); // } } return columnDef; }
java
{ "resource": "" }
q164050
CassandraSchemaManager.setProperties
train
private void setProperties(KsDef ksDef, Map<String, String> strategy_options) { Schema schema = CassandraPropertyReader.csmd.getSchema(databaseName); if (schema != null && schema.getName() != null && schema.getName().equalsIgnoreCase(databaseName) && schema.getSchemaProperties() != null) { setKeyspaceProperties(ksDef, schema.getSchemaProperties(), strategy_options, schema.getDataCenters()); } else { setDefaultReplicationFactor(strategy_options); } }
java
{ "resource": "" }
q164051
CassandraSchemaManager.setKeyspaceProperties
train
private void setKeyspaceProperties(KsDef ksDef, Properties schemaProperties, Map<String, String> strategyOptions, List<DataCenter> dcs) { String placementStrategy = schemaProperties.getProperty(CassandraConstants.PLACEMENT_STRATEGY, SimpleStrategy.class.getSimpleName()); if (placementStrategy.equalsIgnoreCase(SimpleStrategy.class.getSimpleName()) || placementStrategy.equalsIgnoreCase(SimpleStrategy.class.getName())) { String replicationFactor = schemaProperties.getProperty(CassandraConstants.REPLICATION_FACTOR, CassandraConstants.DEFAULT_REPLICATION_FACTOR); strategyOptions.put("replication_factor", replicationFactor); } else if (placementStrategy.equalsIgnoreCase(NetworkTopologyStrategy.class.getSimpleName()) || placementStrategy.equalsIgnoreCase(NetworkTopologyStrategy.class.getName())) { if (dcs != null && !dcs.isEmpty()) { for (DataCenter dc : dcs) { strategyOptions.put(dc.getName(), dc.getValue()); } } } else { strategyOptions.put("replication_factor", CassandraConstants.DEFAULT_REPLICATION_FACTOR); } ksDef.setStrategy_class(placementStrategy); ksDef.setDurable_writes(Boolean.parseBoolean(schemaProperties.getProperty(CassandraConstants.DURABLE_WRITES))); }
java
{ "resource": "" }
q164052
CassandraSchemaManager.getColumnFamilyProperties
train
private Properties getColumnFamilyProperties(TableInfo tableInfo) { if (tables != null) { for (Table table : tables) { if (table != null && table.getName() != null && table.getName().equalsIgnoreCase(tableInfo.getTableName())) { return table.getProperties(); } } } return null; }
java
{ "resource": "" }
q164053
CassandraSchemaManager.validateEntity
train
@Override public boolean validateEntity(Class clazz) { EntityValidatorAgainstCounterColumn entityValidatorAgainstSchema = new EntityValidatorAgainstCounterColumn(); return entityValidatorAgainstSchema.validateEntity(clazz); }
java
{ "resource": "" }
q164054
CassandraSchemaManager.setColumnFamilyProperties
train
private void setColumnFamilyProperties(CfDef cfDef, Properties cfProperties, StringBuilder builder) { if ((cfDef != null && cfProperties != null) || (builder != null && cfProperties != null)) { if (builder != null) { builder.append(CQLTranslator.WITH_CLAUSE); } onSetKeyValidation(cfDef, cfProperties, builder); onSetCompactionStrategy(cfDef, cfProperties, builder); onSetComparatorType(cfDef, cfProperties, builder); onSetSubComparator(cfDef, cfProperties, builder); // onSetReplicateOnWrite(cfDef, cfProperties, builder); onSetCompactionThreshold(cfDef, cfProperties, builder); onSetComment(cfDef, cfProperties, builder); onSetTableId(cfDef, cfProperties, builder); onSetGcGrace(cfDef, cfProperties, builder); onSetCaching(cfDef, cfProperties, builder); onSetBloomFilter(cfDef, cfProperties, builder); onSetRepairChance(cfDef, cfProperties, builder); onSetReadRepairChance(cfDef, cfProperties, builder); // Strip last AND clause. if (builder != null && StringUtils.contains(builder.toString(), CQLTranslator.AND_CLAUSE)) { builder.delete(builder.lastIndexOf(CQLTranslator.AND_CLAUSE), builder.length()); // builder.deleteCharAt(builder.length() - 2); } // Strip last WITH clause. if (builder != null && StringUtils.contains(builder.toString(), CQLTranslator.WITH_CLAUSE)) { builder.delete(builder.lastIndexOf(CQLTranslator.WITH_CLAUSE), builder.length()); // builder.deleteCharAt(builder.length() - 2); } } }
java
{ "resource": "" }
q164055
CassandraSchemaManager.onSetReadRepairChance
train
private void onSetReadRepairChance(CfDef cfDef, Properties cfProperties, StringBuilder builder) { String dclocalReadRepairChance = cfProperties.getProperty(CassandraConstants.DCLOCAL_READ_REPAIR_CHANCE); if (dclocalReadRepairChance != null) { try { if (builder != null) { appendPropertyToBuilder(builder, dclocalReadRepairChance, CassandraConstants.DCLOCAL_READ_REPAIR_CHANCE); } else { cfDef.setDclocal_read_repair_chance(Double.parseDouble(dclocalReadRepairChance)); } } catch (NumberFormatException nfe) { log.error("READ_REPAIR_CHANCE should be double type, Caused by: {}.", nfe); throw new SchemaGenerationException(nfe); } } }
java
{ "resource": "" }
q164056
CassandraSchemaManager.onSetRepairChance
train
private void onSetRepairChance(CfDef cfDef, Properties cfProperties, StringBuilder builder) { String readRepairChance = cfProperties.getProperty(CassandraConstants.READ_REPAIR_CHANCE); if (readRepairChance != null) { try { if (builder != null) { appendPropertyToBuilder(builder, readRepairChance, CassandraConstants.READ_REPAIR_CHANCE); } else { cfDef.setRead_repair_chance(Double.parseDouble(readRepairChance)); } } catch (NumberFormatException nfe) { log.error("READ_REPAIR_CHANCE should be double type, Caused by: .", nfe); throw new SchemaGenerationException(nfe); } } }
java
{ "resource": "" }
q164057
CassandraSchemaManager.onSetBloomFilter
train
private void onSetBloomFilter(CfDef cfDef, Properties cfProperties, StringBuilder builder) { String bloomFilterFpChance = cfProperties.getProperty(CassandraConstants.BLOOM_FILTER_FP_CHANCE); if (bloomFilterFpChance != null) { try { if (builder != null) { appendPropertyToBuilder(builder, bloomFilterFpChance, CassandraConstants.BLOOM_FILTER_FP_CHANCE); } else { cfDef.setBloom_filter_fp_chance(Double.parseDouble(bloomFilterFpChance)); } } catch (NumberFormatException nfe) { log.error("BLOOM_FILTER_FP_CHANCE should be double type, Caused by: .", nfe); throw new SchemaGenerationException(nfe); } } }
java
{ "resource": "" }
q164058
CassandraSchemaManager.onSetCaching
train
private void onSetCaching(CfDef cfDef, Properties cfProperties, StringBuilder builder) { String caching = cfProperties.getProperty(CassandraConstants.CACHING); if (caching != null) { if (builder != null) { appendPropertyToBuilder(builder, caching, CassandraConstants.CACHING); } else { cfDef.setCaching(caching); } } }
java
{ "resource": "" }
q164059
CassandraSchemaManager.onSetGcGrace
train
private void onSetGcGrace(CfDef cfDef, Properties cfProperties, StringBuilder builder) { String gcGraceSeconds = cfProperties.getProperty(CassandraConstants.GC_GRACE_SECONDS); if (gcGraceSeconds != null) { try { if (builder != null) { appendPropertyToBuilder(builder, gcGraceSeconds, CassandraConstants.GC_GRACE_SECONDS); } else { cfDef.setGc_grace_seconds(Integer.parseInt(gcGraceSeconds)); } } catch (NumberFormatException nfe) { log.error("GC_GRACE_SECONDS should be numeric type, Caused by: .", nfe); throw new SchemaGenerationException(nfe); } } }
java
{ "resource": "" }
q164060
CassandraSchemaManager.onSetTableId
train
private void onSetTableId(CfDef cfDef, Properties cfProperties, StringBuilder builder) { String id = cfProperties.getProperty(CassandraConstants.ID); if (id != null) { try { if (builder != null) { // TODO::::not available with composite key? } else { cfDef.setId(Integer.parseInt(id)); } } catch (NumberFormatException nfe) { log.error("Id should be numeric type, Caused by: ", nfe); throw new SchemaGenerationException(nfe); } } }
java
{ "resource": "" }
q164061
CassandraSchemaManager.onSetComment
train
private void onSetComment(CfDef cfDef, Properties cfProperties, StringBuilder builder) { String comment = cfProperties.getProperty(CassandraConstants.COMMENT); if (comment != null) { if (builder != null) { String comment_Str = CQLTranslator.getKeyword(CassandraConstants.COMMENT); builder.append(comment_Str); builder.append(CQLTranslator.EQ_CLAUSE); builder.append(CQLTranslator.QUOTE_STR); builder.append(comment); builder.append(CQLTranslator.QUOTE_STR); builder.append(CQLTranslator.AND_CLAUSE); } else { cfDef.setComment(comment); } } }
java
{ "resource": "" }
q164062
CassandraSchemaManager.onSetReplicateOnWrite
train
private void onSetReplicateOnWrite(CfDef cfDef, Properties cfProperties, StringBuilder builder) { String replicateOnWrite = cfProperties.getProperty(CassandraConstants.REPLICATE_ON_WRITE); if (builder != null) { String replicateOn_Write = CQLTranslator.getKeyword(CassandraConstants.REPLICATE_ON_WRITE); builder.append(replicateOn_Write); builder.append(CQLTranslator.EQ_CLAUSE); builder.append(Boolean.parseBoolean(replicateOnWrite)); builder.append(CQLTranslator.AND_CLAUSE); } else if (cfDef != null) { cfDef.setReplicate_on_write(false); } }
java
{ "resource": "" }
q164063
CassandraSchemaManager.onSetCompactionThreshold
train
private void onSetCompactionThreshold(CfDef cfDef, Properties cfProperties, StringBuilder builder) { String maxCompactionThreshold = cfProperties.getProperty(CassandraConstants.MAX_COMPACTION_THRESHOLD); if (maxCompactionThreshold != null) { try { if (builder != null) { // Somehow these are not working for cassandra 1.1 // though they claim it should work. // appendPropertyToBuilder(builder, // maxCompactionThreshold, // CassandraConstants.MAX_COMPACTION_THRESHOLD); } else { cfDef.setMax_compaction_threshold(Integer.parseInt(maxCompactionThreshold)); } } catch (NumberFormatException nfe) { log.error("Max_Compaction_Threshold should be numeric type, Caused by: .", nfe); throw new SchemaGenerationException(nfe); } } String minCompactionThreshold = cfProperties.getProperty(CassandraConstants.MIN_COMPACTION_THRESHOLD); if (minCompactionThreshold != null) { try { if (builder != null) { // Somehow these are not working for cassandra 1.1 // though they claim it should work. // appendPropertyToBuilder(builder, // minCompactionThreshold, // CassandraConstants.MIN_COMPACTION_THRESHOLD); } else { cfDef.setMin_compaction_threshold(Integer.parseInt(minCompactionThreshold)); } } catch (NumberFormatException nfe) { log.error("Min_Compaction_Threshold should be numeric type, Caused by: . ", nfe); throw new SchemaGenerationException(nfe); } } }
java
{ "resource": "" }
q164064
CassandraSchemaManager.onSetSubComparator
train
private void onSetSubComparator(CfDef cfDef, Properties cfProperties, StringBuilder builder) { String subComparatorType = cfProperties.getProperty(CassandraConstants.SUBCOMPARATOR_TYPE); if (subComparatorType != null && ColumnFamilyType.valueOf(cfDef.getColumn_type()) == ColumnFamilyType.Super) { if (builder != null) { // super column are not supported for composite key as of // now, leaving blank place holder.. } else { cfDef.setSubcomparator_type(subComparatorType); } } }
java
{ "resource": "" }
q164065
CassandraSchemaManager.onSetComparatorType
train
private void onSetComparatorType(CfDef cfDef, Properties cfProperties, StringBuilder builder) { String comparatorType = cfProperties.getProperty(CassandraConstants.COMPARATOR_TYPE); if (comparatorType != null) { if (builder != null) { // TODO:::nothing available. } else { cfDef.setComparator_type(comparatorType); } } }
java
{ "resource": "" }
q164066
CassandraSchemaManager.onSetCompactionStrategy
train
private void onSetCompactionStrategy(CfDef cfDef, Properties cfProperties, StringBuilder builder) { String compactionStrategy = cfProperties.getProperty(CassandraConstants.COMPACTION_STRATEGY); if (compactionStrategy != null) { if (builder != null) { String strategy_class = CQLTranslator.getKeyword(CassandraConstants.COMPACTION_STRATEGY); builder.append(strategy_class); builder.append(CQLTranslator.EQ_CLAUSE); builder.append(CQLTranslator.QUOTE_STR); builder.append(compactionStrategy); builder.append(CQLTranslator.QUOTE_STR); builder.append(CQLTranslator.AND_CLAUSE); } else { cfDef.setCompaction_strategy(compactionStrategy); } } }
java
{ "resource": "" }
q164067
CassandraSchemaManager.onSetKeyValidation
train
private void onSetKeyValidation(CfDef cfDef, Properties cfProperties, StringBuilder builder) { String keyValidationClass = cfProperties.getProperty(CassandraConstants.KEY_VALIDATION_CLASS); if (keyValidationClass != null) { if (builder != null) { // nothing available. } else { cfDef.setKey_validation_class(keyValidationClass); } } }
java
{ "resource": "" }
q164068
CassandraSchemaManager.isCql3Enabled
train
private boolean isCql3Enabled(TableInfo tableInfo) { Properties cfProperties = getColumnFamilyProperties(tableInfo); String defaultValidationClass = cfProperties != null ? cfProperties .getProperty(CassandraConstants.DEFAULT_VALIDATION_CLASS) : null; // For normal columns boolean isCounterColumnType = isCounterColumnType(tableInfo, defaultValidationClass); return containsCompositeKey(tableInfo) || containsCollectionColumns(tableInfo) || ((cql_version != null && cql_version.equals(CassandraConstants.CQL_VERSION_3_0)) && (containsEmbeddedColumns(tableInfo) || containsElementCollectionColumns(tableInfo))) && !isCounterColumnType || ((cql_version != null && cql_version.equals(CassandraConstants.CQL_VERSION_3_0)) && !tableInfo .getType().equals(Type.SUPER_COLUMN_FAMILY.name())); }
java
{ "resource": "" }
q164069
CassandraSchemaManager.appendPropertyToBuilder
train
private void appendPropertyToBuilder(StringBuilder builder, String replicateOnWrite, String keyword) { String replicateOn_Write = CQLTranslator.getKeyword(keyword); builder.append(replicateOn_Write); builder.append(CQLTranslator.EQ_CLAUSE); builder.append(replicateOnWrite); builder.append(CQLTranslator.AND_CLAUSE); }
java
{ "resource": "" }
q164070
CassandraSchemaManager.validateCompoundKey
train
private void validateCompoundKey(TableInfo tableInfo) { if (tableInfo.getType() != null && tableInfo.getType().equals(Type.SUPER_COLUMN_FAMILY.name())) { throw new SchemaGenerationException( "Composite/Compound columns are not yet supported over Super column family by Cassandra", "cassandra", databaseName); } }
java
{ "resource": "" }
q164071
CassandraSchemaManager.onLog
train
private void onLog(TableInfo tableInfo, CqlMetadata metadata, Map<ByteBuffer, String> value_types, CqlMetadata originalMetadata) throws CharacterCodingException { System.out.format("Persisted Schema for " + tableInfo.getTableName()); System.out.format("\n"); System.out.format("Column Name: \t\t Column name type"); System.out.format("\n"); printInfo(originalMetadata); System.out.format("\n"); System.out.format("Mapped schema for " + tableInfo.getTableName()); System.out.format("\n"); System.out.format("Column Name: \t\t Column name type"); System.out.format("\n"); printInfo(metadata); }
java
{ "resource": "" }
q164072
CassandraSchemaManager.isCounterColumnType
train
private boolean isCounterColumnType(TableInfo tableInfo, String defaultValidationClass) { return (csmd != null && csmd.isCounterColumn(databaseName, tableInfo.getTableName())) || (defaultValidationClass != null && (defaultValidationClass.equalsIgnoreCase(CounterColumnType.class.getSimpleName()) || defaultValidationClass .equalsIgnoreCase(CounterColumnType.class.getName())) || (tableInfo.getType() .equals(CounterColumnType.class.getSimpleName()))); }
java
{ "resource": "" }
q164073
RedisClient.fetch
train
private Object fetch(Class clazz, Object key, Object connection, byte[][] fields) throws InstantiationException, IllegalAccessException { Object result = null; EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz); MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel( entityMetadata.getPersistenceUnit()); String rowKey = null; if (metaModel.isEmbeddable(entityMetadata.getIdAttribute().getBindableJavaType())) { if(key instanceof String && ((String) key).indexOf(COMPOSITE_KEY_SEPERATOR)>0){ rowKey = (String) key; } else{ rowKey = KunderaCoreUtils.prepareCompositeKey(entityMetadata, key); } } else { ObjectAccessor accessor = new ObjectAccessor(); rowKey = accessor.toString(key); } String hashKey = getHashKey(entityMetadata.getTableName(), rowKey); KunderaCoreUtils .printQuery("Fetch data from " + entityMetadata.getTableName() + " for PK " + rowKey, showQuery); try { Map<byte[], byte[]> columns = new HashMap<byte[], byte[]>(); // IF it is for selective columns if (fields != null) { List<byte[]> fieldValues = null; if (resource != null && resource.isActive()) { Response response = ((Transaction) connection).hmget(getEncodedBytes(hashKey), fields); // ((Transaction) connection).exec(); ((RedisTransaction) resource).onExecute(((Transaction) connection)); fieldValues = (List<byte[]>) response.get(); connection = getConnection(); } else { fieldValues = ((Jedis) connection).hmget(getEncodedBytes(hashKey), fields); } if (fieldValues != null && !fieldValues.isEmpty()) { for (int i = 0; i < fields.length; i++) { if (fieldValues.get(i) != null) { columns.put(fields[i], fieldValues.get(i)); } } } } else { columns = getColumns(connection, hashKey, columns); } // Map<byte[], byte[]> result = unwrap(entityMetadata, columns, key); } catch (JedisConnectionException jedex) { // Jedis is throwing runtime exception in case of no result // found!!!! return null; } return result; }
java
{ "resource": "" }
q164074
RedisClient.deleteRelation
train
private void deleteRelation(Object connection, EntityMetadata entityMetadata, String rowKey) { List<String> relations = entityMetadata.getRelationNames(); if (relations != null) { for (String relation : relations) { if (resource != null && resource.isActive()) { ((Transaction) connection).hdel(getHashKey(entityMetadata.getTableName(), rowKey), relation); } else { ((Pipeline) connection).hdel(getHashKey(entityMetadata.getTableName(), rowKey), relation); } } } /* * Response<Map<String, String>> fields = null; if (resource != null && * resource.isActive()) { fields = ((Transaction) * connection).hgetAll(getHashKey(entityMetadata.getTableName(), * rowKey)); if (connection != null) { ((Pipeline) connection).sync(); } * for (String field : fields.get().keySet()) { ((Transaction) * connection).hdel(getHashKey(entityMetadata.getTableName(), rowKey), * field); } } else { fields = ((Pipeline) * connection).hgetAll(getHashKey(entityMetadata.getTableName(), * rowKey)); if (connection != null) { ((Pipeline) connection).sync(); } * for (String field : fields.get().keySet()) { ((Pipeline) * connection).hdel(getHashKey(entityMetadata.getTableName(), rowKey), * field); } } */ }
java
{ "resource": "" }
q164075
RedisClient.fetchColumn
train
private List fetchColumn(String columnName, Object connection, List results, Set<String> resultKeys) { for (String hashKey : resultKeys) { List columnValues = null; if (resource != null && resource.isActive()) { Response response = ((Transaction) connection).hmget(hashKey, columnName); // ((Transaction) connection).exec(); ((RedisTransaction) resource).onExecute(((Transaction) connection)); columnValues = (List) response.get(); } else { columnValues = ((Jedis) connection).hmget(hashKey, columnName); } if (columnValues != null && !columnValues.isEmpty()) { results.addAll(columnValues); // Currently returning list of // string as known issue // with // joint table concept! } } return results; }
java
{ "resource": "" }
q164076
RedisClient.findIdsByColumn
train
private Object[] findIdsByColumn(String tableName, String columnName, Object columnValue) { Object connection = null; try { connection = getConnection(); String valueAsStr = PropertyAccessorHelper.getString(columnValue); Set<String> results = null; if (resource != null && resource.isActive()) { Response response = ((Transaction) connection).zrangeByScore(getHashKey(tableName, columnName), getDouble(valueAsStr), getDouble(valueAsStr)); // ((Transaction) connection).exec(); ((RedisTransaction) resource).onExecute(((Transaction) connection)); results = (Set<String>) response.get(); } else { results = ((Jedis) connection).zrangeByScore(getHashKey(tableName, columnName), getDouble(valueAsStr), getDouble(valueAsStr)); } if (results != null) { return results.toArray(new Object[0]); } } finally { onCleanup(connection); } return null; }
java
{ "resource": "" }
q164077
RedisClient.getHashKey
train
private String getHashKey(final String tableName, final String rowKey) { StringBuilder builder = new StringBuilder(tableName); builder.append(":"); builder.append(rowKey); return builder.toString(); }
java
{ "resource": "" }
q164078
RedisClient.getEncodedBytes
train
byte[] getEncodedBytes(final String name) { try { if (name != null) { return name.getBytes(Constants.CHARSET_UTF8); } } catch (UnsupportedEncodingException e) { logger.error("Error during persist, Caused by:", e); throw new PersistenceException(e); } return null; }
java
{ "resource": "" }
q164079
RedisClient.addIndex
train
private void addIndex(final Object connection, final AttributeWrapper wrapper, final String rowKey, final EntityMetadata metadata) { Indexer indexer = indexManager.getIndexer(); if (indexer != null && indexer.getClass().getSimpleName().equals("RedisIndexer")) { // Add row key to list(Required for wild search over table). wrapper.addIndex( getHashKey(metadata.getTableName(), ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName()), getDouble(rowKey)); // Add row-key as inverted index as well needed for multiple clause // search with key and non row key. wrapper.addIndex( getHashKey(metadata.getTableName(), getHashKey(((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName(), rowKey)), getDouble(rowKey)); indexer.index(metadata.getEntityClazz(), metadata, wrapper.getIndexes(), rowKey, null); } }
java
{ "resource": "" }
q164080
RedisClient.unIndex
train
private void unIndex(final Object connection, final AttributeWrapper wrapper, final String member) { Set<String> keys = wrapper.getIndexes().keySet(); for (String key : keys) { if (resource != null && resource.isActive()) { ((Transaction) connection).zrem(key, member); } else { ((Pipeline) connection).zrem(key, member); } } }
java
{ "resource": "" }
q164081
RedisClient.onCleanup
train
private void onCleanup(Object connection) { // if not running within transaction boundary if (this.connection != null) { if (settings != null) { ((Jedis) connection).configResetStat(); } factory.releaseConnection((Jedis) this.connection); } this.connection = null; }
java
{ "resource": "" }
q164082
RedisClient.addToWrapper
train
private void addToWrapper(EntityMetadata entityMetadata, AttributeWrapper wrapper, Object resultedObject, Attribute attrib) { addToWrapper(entityMetadata, wrapper, resultedObject, attrib, null); }
java
{ "resource": "" }
q164083
RedisClient.reInitialize
train
private Object reInitialize(Object connection, Set<String> rowKeys) { /* * if(!rowKeys.isEmpty()) { */ connection = getConnection(); // } return connection; }
java
{ "resource": "" }
q164084
RedisClient.findAllColumns
train
private <E> List<E> findAllColumns(Class<E> entityClass, byte[][] columns, Object... keys) { Object connection = getConnection(); // connection.co List results = new ArrayList(); try { for (Object key : keys) { Object result = fetch(entityClass, key, connection, columns); if (result != null) { results.add(result); } } } catch (InstantiationException e) { logger.error("Error during find by key:", e); throw new PersistenceException(e); } catch (IllegalAccessException e) { logger.error("Error during find by key:", e); throw new PersistenceException(e); } return results; }
java
{ "resource": "" }
q164085
RedisClient.getConnection
train
private Object getConnection() { /* * Jedis connection = factory.getConnection(); * * // If resource is not null means a transaction in progress. * * if (settings != null) { for (String key : settings.keySet()) { * connection.configSet(key, settings.get(key).toString()); } } * * if (resource != null && resource.isActive()) { return * ((RedisTransaction) resource).bindResource(connection); } else { * return connection; } if (resource == null || (resource != null && * !resource.isActive())) */ // means either transaction resource is not bound or it is not active, // but connection has already by initialized if (isBoundTransaction() && this.connection != null) { return this.connection; } // if running within transaction boundary. if (resource != null && resource.isActive()) { // no need to get a connection from pool, as nested MULTI is not yet // supported. if (((RedisTransaction) resource).isResourceBound()) { return ((RedisTransaction) resource).getResource(); } else { Jedis conn = getAndSetConnection(); return ((RedisTransaction) resource).bindResource(conn); } } else { Jedis conn = getAndSetConnection(); return conn; } }
java
{ "resource": "" }
q164086
RedisClient.getAndSetConnection
train
private Jedis getAndSetConnection() { Jedis conn = factory.getConnection(); this.connection = conn; // If resource is not null means a transaction in progress. if (settings != null) { for (String key : settings.keySet()) { conn.configSet(key, settings.get(key).toString()); } } return conn; }
java
{ "resource": "" }
q164087
RedisClient.initializeIndexer
train
private void initializeIndexer() { if (this.indexManager.getIndexer() != null && this.indexManager.getIndexer().getClass().getSimpleName().equals("RedisIndexer")) { ((RedisIndexer) this.indexManager.getIndexer()).assignConnection(getConnection()); } }
java
{ "resource": "" }
q164088
CglibLazyInitializer.getProxy
train
public static KunderaProxy getProxy(final String entityName, final Class<?> persistentClass, final Class<?>[] interfaces, final Method getIdentifierMethod, final Method setIdentifierMethod, final Object id, final PersistenceDelegator pd) throws PersistenceException { final CglibLazyInitializer instance = new CglibLazyInitializer(entityName, persistentClass, interfaces, id, getIdentifierMethod, setIdentifierMethod, pd); final KunderaProxy proxy; Class factory = getProxyFactory(persistentClass, interfaces); proxy = getProxyInstance(factory, instance); instance.constructed = true; return proxy; }
java
{ "resource": "" }
q164089
CglibLazyInitializer.getProxyInstance
train
private static KunderaProxy getProxyInstance(Class factory, CglibLazyInitializer instance) { KunderaProxy proxy; try { Enhancer.registerCallbacks(factory, new Callback[] { instance, null }); proxy = (KunderaProxy) factory.newInstance(); } catch (IllegalAccessException e) { throw new LazyInitializationException(e); } catch (InstantiationException e) { throw new LazyInitializationException(e); } finally { Enhancer.registerCallbacks(factory, null); } return proxy; }
java
{ "resource": "" }
q164090
CglibLazyInitializer.getProxyFactory
train
public static Class getProxyFactory(Class persistentClass, Class[] interfaces) throws PersistenceException { Enhancer e = new Enhancer(); e.setSuperclass(interfaces.length == 1 ? persistentClass : null); e.setInterfaces(interfaces); e.setCallbackTypes(new Class[] { InvocationHandler.class, NoOp.class, }); e.setCallbackFilter(FINALIZE_FILTER); e.setUseFactory(false); e.setInterceptDuringConstruction(false); return e.createClass(); }
java
{ "resource": "" }
q164091
HBaseUtils.isFindKeyOnly
train
public static boolean isFindKeyOnly(EntityMetadata metadata, List<Map<String, Object>> colToOutput) { if (colToOutput != null && colToOutput.size() == 1) { String idCol = ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName(); return idCol.equals(colToOutput.get(0).get(Constants.DB_COL_NAME)) && !(boolean) colToOutput.get(0).get(Constants.IS_EMBEDDABLE); } else { return false; } }
java
{ "resource": "" }
q164092
MongoDBClient.findGFSEntity
train
private Object findGFSEntity(EntityMetadata entityMetadata, Class entityClass, Object key) { GridFSDBFile outputFile = findGridFSDBFile(entityMetadata, key); return outputFile != null ? handler.getEntityFromGFSDBFile(entityMetadata.getEntityClazz(), instantiateEntity(entityClass, null), entityMetadata, outputFile, kunderaMetadata) : null; }
java
{ "resource": "" }
q164093
MongoDBClient.findGridFSDBFile
train
private GridFSDBFile findGridFSDBFile(EntityMetadata entityMetadata, Object key) { String id = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName(); DBObject query = new BasicDBObject("metadata." + id, key); KunderaGridFS gfs = new KunderaGridFS(mongoDb, entityMetadata.getTableName()); return gfs.findOne(query); }
java
{ "resource": "" }
q164094
MongoDBClient.loadQueryDataGFS
train
private <E> List<E> loadQueryDataGFS(EntityMetadata entityMetadata, BasicDBObject mongoQuery, BasicDBObject orderBy, int maxResult, int firstResult, boolean isCountQuery) { List<GridFSDBFile> gfsDBfiles = getGFSDBFiles(mongoQuery, orderBy, entityMetadata.getTableName(), maxResult, firstResult); if (isCountQuery) { return (List<E>) Collections.singletonList(gfsDBfiles.size()); } List entities = new ArrayList<E>(); for (GridFSDBFile file : gfsDBfiles) { populateGFSEntity(entityMetadata, entities, file); } return entities; }
java
{ "resource": "" }
q164095
MongoDBClient.loadQueryData
train
private <E> List<E> loadQueryData(EntityMetadata entityMetadata, BasicDBObject mongoQuery, BasicDBObject orderBy, int maxResult, int firstResult, boolean isCountQuery, BasicDBObject keys, String... results) throws InstantiationException, IllegalAccessException { String documentName = entityMetadata.getTableName(); List entities = new ArrayList<E>(); Object object = getDBCursorInstance(mongoQuery, orderBy, maxResult, firstResult, keys, documentName, isCountQuery); DBCursor cursor = null; if (object instanceof Long) { List<Long> lst = new ArrayList<Long>(); lst.add((Long) object); return (List<E>) lst; } else { cursor = (DBCursor) object; } if (results != null && results.length > 0) { DBCollection dbCollection = mongoDb.getCollection(documentName); KunderaCoreUtils.printQuery("Find document: " + mongoQuery, showQuery); for (int i = 1; i < results.length; i++) { String result = results[i]; // If User wants search on a column within a particular super // column, // fetch that embedded object collection only // otherwise retrieve whole entity // TODO: improve code if (result != null && result.indexOf(".") >= 0) { // TODO i need to discuss with Amresh before modifying it. entities.addAll(handler.getEmbeddedObjectList(dbCollection, entityMetadata, documentName, mongoQuery, result, orderBy, maxResult, firstResult, keys, kunderaMetadata)); return entities; } } } log.debug("Fetching data from " + documentName + " for Filter " + mongoQuery.toString()); while (cursor.hasNext()) { DBObject fetchedDocument = cursor.next(); populateEntity(entityMetadata, entities, fetchedDocument); } return entities; }
java
{ "resource": "" }
q164096
MongoDBClient.populateGFSEntity
train
private void populateGFSEntity(EntityMetadata entityMetadata, List entities, GridFSDBFile gfsDBFile) { Object entity = instantiateEntity(entityMetadata.getEntityClazz(), null); handler.getEntityFromGFSDBFile(entityMetadata.getEntityClazz(), entity, entityMetadata, gfsDBFile, kunderaMetadata); entities.add(entity); }
java
{ "resource": "" }
q164097
MongoDBClient.getDBCursorInstance
train
public Object getDBCursorInstance(BasicDBObject mongoQuery, BasicDBObject orderBy, int maxResult, int firstResult, BasicDBObject keys, String documentName, boolean isCountQuery) { DBCollection dbCollection = mongoDb.getCollection(documentName); DBCursor cursor = null; if (isCountQuery) return dbCollection.count(mongoQuery); else cursor = orderBy != null ? dbCollection.find(mongoQuery, keys).sort(orderBy).limit(maxResult) .skip(firstResult) : dbCollection.find(mongoQuery, keys).limit(maxResult).skip(firstResult); return cursor; }
java
{ "resource": "" }
q164098
MongoDBClient.getGFSDBFiles
train
private List<GridFSDBFile> getGFSDBFiles(BasicDBObject mongoQuery, BasicDBObject sort, String collectionName, int maxResult, int firstResult) { KunderaGridFS gfs = new KunderaGridFS(mongoDb, collectionName); return gfs.find(mongoQuery, sort, firstResult, maxResult); }
java
{ "resource": "" }
q164099
MongoDBClient.findByRelation
train
public List<Object> findByRelation(String colName, Object colValue, Class entityClazz) { EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz); // you got column name and column value. DBCollection dbCollection = mongoDb.getCollection(m.getTableName()); BasicDBObject query = new BasicDBObject(); query.put(colName, MongoDBUtils.populateValue(colValue, colValue.getClass())); KunderaCoreUtils.printQuery("Find by relation:" + query, showQuery); DBCursor cursor = dbCollection.find(query); DBObject fetchedDocument = null; List<Object> results = new ArrayList<Object>(); while (cursor.hasNext()) { fetchedDocument = cursor.next(); populateEntity(m, results, fetchedDocument); } return results.isEmpty() ? null : results; }
java
{ "resource": "" }