_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q164100 | MongoDBClient.saveGridFSFile | train | private void saveGridFSFile(GridFSInputFile gfsInputFile, EntityMetadata m)
{
try
{
DBCollection coll = mongoDb.getCollection(m.getTableName() + MongoDBUtils.FILES);
createUniqueIndexGFS(coll, ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName());
gfsInputFile.save();
log.info("Input GridFS file: " + gfsInputFile.getFilename() + " is saved successfully in "
+ m.getTableName() + MongoDBUtils.CHUNKS + " and metadata in " + m.getTableName()
+ MongoDBUtils.FILES);
}
catch (MongoException e)
{
log.error("Error in saving GridFS file in " + m.getTableName() + MongoDBUtils.FILES + " or "
+ m.getTableName() + MongoDBUtils.CHUNKS + " collections.");
throw new KunderaException("Error in saving GridFS file in " + m.getTableName() + MongoDBUtils.FILES
+ " or " + m.getTableName() + MongoDBUtils.CHUNKS + " collections. Caused By: ", e);
}
try
{
gfsInputFile.validate();
log.info("Input GridFS file: " + gfsInputFile.getFilename() + " is validated.");
}
catch (MongoException e)
{
log.error("Error in validating GridFS file in " + m.getTableName() + MongoDBUtils.FILES + " collection.");
throw new KunderaException("Error in validating GridFS file in " + m.getTableName() + MongoDBUtils.FILES
+ " collection. Caused By: ", e);
}
} | java | {
"resource": ""
} |
q164101 | MongoDBClient.onPersistGFS | train | private void onPersistGFS(Object entity, Object entityId, EntityMetadata entityMetadata, boolean isUpdate)
{
KunderaGridFS gfs = new KunderaGridFS(mongoDb, entityMetadata.getTableName());
if (!isUpdate)
{
GridFSInputFile gfsInputFile = handler.getGFSInputFileFromEntity(gfs, entityMetadata, entity,
kunderaMetadata, isUpdate);
saveGridFSFile(gfsInputFile, entityMetadata);
}
else
{
Object val = handler.getLobFromGFSEntity(gfs, entityMetadata, entity, kunderaMetadata);
String md5 = MongoDBUtils.calculateMD5(val);
GridFSDBFile outputFile = findGridFSDBFile(entityMetadata, entityId);
// checking MD5 of the file to be updated with the file saved in DB
if (md5.equals(outputFile.getMD5()))
{
DBObject metadata = handler.getMetadataFromGFSEntity(gfs, entityMetadata, entity, kunderaMetadata);
outputFile.setMetaData(metadata);
outputFile.save();
}
else
{
// GFSInput file is created corresponding to the entity to be
// merged with a new ObjectID()
GridFSInputFile gfsInputFile = handler.getGFSInputFileFromEntity(gfs, entityMetadata, entity,
kunderaMetadata, isUpdate);
ObjectId updatedId = (ObjectId) gfsInputFile.getId();
DBObject metadata = gfsInputFile.getMetaData();
// updated file is saved in DB
saveGridFSFile(gfsInputFile, entityMetadata);
// last version of file is deleted
DBObject query = new BasicDBObject("_id", outputFile.getId());
gfs.remove(query);
// newly added file is found using its _id
outputFile = gfs.findOne(updatedId);
// Id of entity (which is saved in metadata) is updated to its
// actual Id
metadata.put(((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName(), entityId);
outputFile.setMetaData(metadata);
// output file is updated
outputFile.save();
}
}
} | java | {
"resource": ""
} |
q164102 | MongoDBClient.onFlushBatch | train | private void onFlushBatch(Map<String, BulkWriteOperation> bulkWriteOperationMap)
{
if (!bulkWriteOperationMap.isEmpty())
{
for (BulkWriteOperation builder : bulkWriteOperationMap.values())
{
try
{
builder.execute(getWriteConcern());
}
catch (BulkWriteException bwex)
{
log.error("Batch insertion is not performed due to error in write command. Caused By: ", bwex);
throw new KunderaException(
"Batch insertion is not performed due to error in write command. Caused By: ", bwex);
}
catch (MongoException mex)
{
log.error("Batch insertion is not performed. Caused By: ", mex);
throw new KunderaException("Batch insertion is not performed. Caused By: ", mex);
}
}
}
} | java | {
"resource": ""
} |
q164103 | MongoDBClient.onFlushCollection | train | private void onFlushCollection(Map<String, List<DBObject>> collections)
{
for (String tableName : collections.keySet())
{
DBCollection dbCollection = mongoDb.getCollection(tableName);
KunderaCoreUtils.printQuery("Persist collection:" + tableName, showQuery);
try
{
dbCollection.insert(collections.get(tableName).toArray(new DBObject[0]), getWriteConcern(), encoder);
}
catch (MongoException ex)
{
throw new KunderaException("document is not inserted in " + dbCollection.getFullName()
+ " collection. Caused By:", ex);
}
}
} | java | {
"resource": ""
} |
q164104 | MongoDBClient.onPersist | train | private Map<String, List<DBObject>> onPersist(Map<String, List<DBObject>> collections, Object entity, Object id,
EntityMetadata metadata, List<RelationHolder> relationHolders, boolean isUpdate)
{
persistenceUnit = metadata.getPersistenceUnit();
Map<String, DBObject> documents = handler.getDocumentFromEntity(metadata, entity, relationHolders,
kunderaMetadata);
if (isUpdate)
{
for (String documentName : documents.keySet())
{
BasicDBObject query = new BasicDBObject();
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
metadata.getPersistenceUnit());
if (metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType()))
{
MongoDBUtils.populateCompoundKey(query, metadata, metaModel, id);
}
else
{
query.put("_id", MongoDBUtils.populateValue(id, id.getClass()));
}
DBCollection dbCollection = mongoDb.getCollection(documentName);
KunderaCoreUtils.printQuery("Persist collection:" + documentName, showQuery);
dbCollection.save(documents.get(documentName), getWriteConcern());
}
}
else
{
for (String documentName : documents.keySet())
{
// a db collection can have multiple records..
// and we can have a collection of records as well.
List<DBObject> dbStatements = null;
if (collections.containsKey(documentName))
{
dbStatements = collections.get(documentName);
dbStatements.add(documents.get(documentName));
}
else
{
dbStatements = new ArrayList<DBObject>();
dbStatements.add(documents.get(documentName));
collections.put(documentName, dbStatements);
}
}
}
return collections;
} | java | {
"resource": ""
} |
q164105 | MongoDBClient.executeScript | train | @Override
public Object executeScript(String script)
{
Object result = mongoDb.eval(script);
KunderaCoreUtils.printQuery("Execute mongo jscripts:" + script, showQuery);
return result;
} | java | {
"resource": ""
} |
q164106 | MongoDBClient.parseMapReduceCommand | train | private MapReduceCommand parseMapReduceCommand(String jsonClause)
{
String collectionName = jsonClause.replaceFirst("(?ms).*?\\.\\s*(.+?)\\s*\\.\\s*mapReduce\\s*\\(.*", "$1");
if (collectionName.contains("getCollection"))
{
collectionName = collectionName
.replaceFirst(".*getCollection\\s*\\(\\s*(['\"])([^'\"]+)\\1\\s*\\).*", "$2");
}
DBCollection collection = mongoDb.getCollection(collectionName);
String body = jsonClause.replaceFirst("^(?ms).*?mapReduce\\s*\\(\\s*(.*)\\s*\\)\\s*;?\\s*$", "$1");
String mapFunction = findCommaSeparatedArgument(body, 0).trim();
String reduceFunction = findCommaSeparatedArgument(body, 1).trim();
String query = findCommaSeparatedArgument(body, 2).trim();
DBObject parameters = (DBObject) JSON.parse(query);
DBObject mongoQuery;
if (parameters.containsField("query"))
{
mongoQuery = (DBObject) parameters.get("query");
}
else
{
mongoQuery = new BasicDBObject();
}
return new MapReduceCommand(collection, mapFunction, reduceFunction, null, MapReduceCommand.OutputType.INLINE,
mongoQuery);
} | java | {
"resource": ""
} |
q164107 | MongoDBClient.findCommaSeparatedArgument | train | private String findCommaSeparatedArgument(String functionBody, int index)
{
int start = 0;
int found = -1;
int brackets = 0;
int pos = 0;
int length = functionBody.length();
while (found < index && pos < length)
{
char ch = functionBody.charAt(pos);
switch (ch)
{
case ',':
if (brackets == 0)
{
found++;
if (found < index)
{
start = pos + 1;
}
}
break;
case '(':
case '[':
case '{':
brackets++;
break;
case ')':
case ']':
case '}':
brackets--;
break;
}
pos++;
}
if (found == index)
{
return functionBody.substring(start, pos - 1);
}
else if (pos == length)
{
return functionBody.substring(start);
}
else
{
return "";
}
} | java | {
"resource": ""
} |
q164108 | MongoDBClient.parseAndScroll | train | private DBCursor parseAndScroll(String jsonClause, String collectionName) throws JSONParseException
{
BasicDBObject clause = (BasicDBObject) JSON.parse(jsonClause);
DBCursor cursor = mongoDb.getCollection(collectionName).find(clause);
return cursor;
} | java | {
"resource": ""
} |
q164109 | MongoDBClient.handleUpdateFunctions | train | public int handleUpdateFunctions(BasicDBObject query, BasicDBObject update, String collName)
{
DBCollection collection = mongoDb.getCollection(collName);
KunderaCoreUtils.printQuery("Update collection:" + query, showQuery);
WriteResult result = null;
try
{
result = collection.update(query, update);
}
catch (MongoException ex)
{
return -1;
}
if (result.getN() <= 0)
return -1;
return result.getN();
} | java | {
"resource": ""
} |
q164110 | MongoDBClient.createUniqueIndexGFS | train | private void createUniqueIndexGFS(DBCollection coll, String id)
{
try
{
coll.createIndex(new BasicDBObject("metadata." + id, 1), new BasicDBObject("unique", true));
}
catch (MongoException ex)
{
throw new KunderaException("Error in creating unique indexes in " + coll.getFullName() + " collection on "
+ id + " field");
}
} | java | {
"resource": ""
} |
q164111 | CouchbaseBucketUtils.openBucket | train | public static Bucket openBucket(CouchbaseCluster cluster, String name, String password)
{
if (cluster == null)
{
throw new KunderaException("CouchbaseCluster object can't be null");
}
try
{
Bucket bucket;
if (password != null && !password.trim().isEmpty())
{
bucket = cluster.openBucket(name, password);
}
else
{
bucket = cluster.openBucket(name);
}
LOGGER.debug("Bucket [" + name + "] is opened!");
return bucket;
}
catch (CouchbaseException ex)
{
LOGGER.error("Not able to open bucket [" + name + "].", ex);
throw new KunderaException("Not able to open bucket [" + name + "].", ex);
}
} | java | {
"resource": ""
} |
q164112 | CouchbaseBucketUtils.closeBucket | train | public static void closeBucket(Bucket bucket)
{
if (bucket != null)
{
if (!bucket.close())
{
LOGGER.error("Not able to close bucket [" + bucket.name() + "].");
throw new KunderaException("Not able to close bucket [" + bucket.name() + "].");
}
else
{
LOGGER.debug("Bucket [" + bucket.name() + "] is closed!");
}
}
} | java | {
"resource": ""
} |
q164113 | DSClient.find | train | @Override
public Object find(Class entityClass, Object rowId) {
EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);
StringBuilder builder = createSelectQuery(rowId, metadata, metadata.getTableName());
ResultSet rSet = this.execute(builder.toString(), null);
List results = iterateAndReturn(rSet, metadata);
return results.isEmpty() ? null : results.get(0);
} | java | {
"resource": ""
} |
q164114 | DSClient.createSelectQuery | train | private StringBuilder createSelectQuery(Object rowId, EntityMetadata metadata, String tableName) {
MetamodelImpl metaModel =
(MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(metadata.getPersistenceUnit());
CQLTranslator translator = new CQLTranslator();
String select_Query = translator.SELECTALL_QUERY;
select_Query = StringUtils.replace(select_Query, CQLTranslator.COLUMN_FAMILY,
translator.ensureCase(new StringBuilder(), tableName, false).toString());
StringBuilder builder = new StringBuilder(select_Query);
builder.append(CQLTranslator.ADD_WHERE_CLAUSE);
onWhereClause(metadata, rowId, translator, builder, metaModel, metadata.getIdAttribute());
builder.delete(builder.lastIndexOf(CQLTranslator.AND_CLAUSE), builder.length());
return builder;
} | java | {
"resource": ""
} |
q164115 | DSClient.populateSecondaryTableData | train | private void populateSecondaryTableData(Object rowId, Object entity, MetamodelImpl metaModel,
EntityMetadata metadata) {
AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(metadata.getEntityClazz());
List<String> secondaryTables =
((DefaultEntityAnnotationProcessor) managedType.getEntityAnnotation()).getSecondaryTablesName();
for (String tableName : secondaryTables) {
StringBuilder builder = createSelectQuery(rowId, metadata, tableName);
ResultSet rSet = this.execute(builder.toString(), null);
Iterator<Row> rowIter = rSet.iterator();
Row row = rowIter.next();
ColumnDefinitions columnDefs = row.getColumnDefinitions();
Iterator<Definition> columnDefIter = columnDefs.iterator();
entity = iteratorColumns(metadata, metaModel, metaModel.entity(metadata.getEntityClazz()),
new HashMap<String, Object>(), entity, row, columnDefIter);
}
} | java | {
"resource": ""
} |
q164116 | DSClient.iteratorColumns | train | private Object iteratorColumns(EntityMetadata metadata, MetamodelImpl metamodel, EntityType entityType,
Map<String, Object> relationalValues, Object entity, Row row, Iterator<Definition> columnDefIter) {
while (columnDefIter.hasNext()) {
Definition columnDef = columnDefIter.next();
final String columnName = columnDef.getName(); // column name
DataType dataType = columnDef.getType(); // data type
if (metadata.getRelationNames() != null && metadata.getRelationNames().contains(columnName)
&& !columnName.equals(((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName())) {
Object relationalValue = DSClientUtilities.assign(row, null, metadata, dataType.getName(), entityType,
columnName, null, metamodel);
relationalValues.put(columnName, relationalValue);
} else {
String fieldName = columnName.equals(((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName())
? metadata.getIdAttribute().getName() : metadata.getFieldName(columnName);
Attribute attribute = fieldName != null ? entityType.getAttribute(fieldName) : null;
if (attribute != null) {
if (!attribute.isAssociation()) {
entity = DSClientUtilities.assign(row, entity, metadata, dataType.getName(), entityType,
columnName, null, metamodel);
}
} else if (metamodel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType())) {
entity = populateCompositeId(metadata, entity, columnName, row, metamodel,
metadata.getIdAttribute(), metadata.getEntityClazz(), dataType);
} else {
entity = DSClientUtilities.assign(row, entity, metadata, dataType.getName(), entityType, columnName,
null, metamodel);
}
}
}
return entity;
} | java | {
"resource": ""
} |
q164117 | DSClient.getCompoundKey | train | private Object getCompoundKey(Attribute attribute, Object entity)
throws InstantiationException, IllegalAccessException {
Object compoundKeyObject = null;
if (entity != null) {
compoundKeyObject = PropertyAccessorHelper.getObject(entity, (Field) attribute.getJavaMember());
if (compoundKeyObject == null) {
compoundKeyObject = ((AbstractAttribute) attribute).getBindableJavaType().newInstance();
}
}
return compoundKeyObject;
} | java | {
"resource": ""
} |
q164118 | CouchDBQueryInterpreter.setKeyValues | train | public void setKeyValues(String keyName, Object obj)
{
if (this.keyValues == null)
{
this.keyValues = new HashMap<String, Object>();
}
this.keyValues.put(keyName, obj);
} | java | {
"resource": ""
} |
q164119 | ESQuery.buildAggregation | train | public AggregationBuilder buildAggregation(KunderaQuery query, EntityMetadata entityMetadata, QueryBuilder filter)
{
SelectStatement selectStatement = query.getSelectStatement();
// To apply filter for where clause
AggregationBuilder aggregationBuilder = buildWhereAggregations(entityMetadata, filter);
if (KunderaQueryUtils.hasGroupBy(query.getJpqlExpression()))
{
TermsBuilder termsBuilder = processGroupByClause(selectStatement.getGroupByClause(), entityMetadata, query);
aggregationBuilder.subAggregation(termsBuilder);
}
else
{
if (KunderaQueryUtils.hasHaving(query.getJpqlExpression()))
{
logger.error("Identified having clause without group by, Throwing not supported operation Exception");
throw new UnsupportedOperationException(
"Currently, Having clause without group by caluse is not supported.");
}
else
{
aggregationBuilder = (selectStatement != null) ? query.isAggregated() ? buildSelectAggregations(
aggregationBuilder, selectStatement, entityMetadata) : null : null;
}
}
return aggregationBuilder;
} | java | {
"resource": ""
} |
q164120 | ESQuery.addHavingClause | train | private AggregationBuilder addHavingClause(Expression havingExpression, AggregationBuilder aggregationBuilder,
EntityMetadata entityMetadata)
{
if (havingExpression instanceof ComparisonExpression)
{
Expression expression = ((ComparisonExpression) havingExpression).getLeftExpression();
if (!isAggregationExpression(expression))
{
logger.error("Having clause conditions over non metric aggregated are not supported.");
throw new UnsupportedOperationException(
"Currently, Having clause without Metric aggregations are not supported.");
}
return checkIfKeyExists(expression.toParsedText()) ? aggregationBuilder
.subAggregation(getMetricsAggregation(expression, entityMetadata)) : aggregationBuilder;
}
else if (havingExpression instanceof AndExpression)
{
AndExpression andExpression = (AndExpression) havingExpression;
addHavingClause(andExpression.getLeftExpression(), aggregationBuilder, entityMetadata);
addHavingClause(andExpression.getRightExpression(), aggregationBuilder, entityMetadata);
return aggregationBuilder;
}
else if (havingExpression instanceof OrExpression)
{
OrExpression orExpression = (OrExpression) havingExpression;
addHavingClause(orExpression.getLeftExpression(), aggregationBuilder, entityMetadata);
addHavingClause(orExpression.getRightExpression(), aggregationBuilder, entityMetadata);
return aggregationBuilder;
}
else
{
logger.error(havingExpression + "not supported in having clause.");
throw new UnsupportedOperationException(havingExpression + "not supported in having clause.");
}
} | java | {
"resource": ""
} |
q164121 | ESQuery.processGroupByClause | train | private TermsBuilder processGroupByClause(Expression expression, EntityMetadata entityMetadata, KunderaQuery query)
{
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
entityMetadata.getPersistenceUnit());
Expression groupByClause = ((GroupByClause) expression).getGroupByItems();
if (groupByClause instanceof CollectionExpression)
{
logger.error("More than one item found in group by clause.");
throw new UnsupportedOperationException("Currently, Group By on more than one field is not supported.");
}
SelectStatement selectStatement = query.getSelectStatement();
// To apply terms and tophits aggregation to serve group by
String jPAField = KunderaCoreUtils.getJPAColumnName(groupByClause.toParsedText(), entityMetadata, metaModel);
TermsBuilder termsBuilder = AggregationBuilders.terms(ESConstants.GROUP_BY).field(jPAField).size(0);
// Hard coded value for a max number of record that a group can contain.
TopHitsBuilder topHitsBuilder = getTopHitsAggregation(selectStatement, null, entityMetadata);
termsBuilder.subAggregation(topHitsBuilder);
// To apply the metric aggregations (Min, max... etc) in select clause
buildSelectAggregations(termsBuilder, query.getSelectStatement(), entityMetadata);
if (KunderaQueryUtils.hasHaving(query.getJpqlExpression()))
{
addHavingClause(((HavingClause) selectStatement.getHavingClause()).getConditionalExpression(),
termsBuilder, entityMetadata);
}
if (KunderaQueryUtils.hasOrderBy(query.getJpqlExpression()))
{
processOrderByClause(termsBuilder, KunderaQueryUtils.getOrderByClause(query.getJpqlExpression()),
groupByClause, entityMetadata);
}
return termsBuilder;
} | java | {
"resource": ""
} |
q164122 | ESQuery.processOrderByClause | train | private void processOrderByClause(TermsBuilder termsBuilder, Expression orderByExpression,
Expression groupByClause, EntityMetadata entityMetadata)
{
Expression orderByClause = (OrderByClause) orderByExpression;
OrderByItem orderByItems = (OrderByItem) ((OrderByClause) orderByClause).getOrderByItems();
if (orderByClause instanceof CollectionExpression
|| !(orderByItems.getExpression().toParsedText().equalsIgnoreCase(groupByClause.toParsedText())))
{
logger.error("Order by and group by on different field are not supported simultaneously");
throw new UnsupportedOperationException(
"Order by and group by on different field are not supported simultaneously");
}
String ordering = orderByItems.getOrdering().toString();
termsBuilder.order(Terms.Order.term(!ordering.equalsIgnoreCase(Expression.DESC)));
} | java | {
"resource": ""
} |
q164123 | ESQuery.getTopHitsAggregation | train | private TopHitsBuilder getTopHitsAggregation(SelectStatement selectStatement, Integer size,
EntityMetadata entityMetadata)
{
TopHitsBuilder topHitsBuilder = AggregationBuilders.topHits(ESConstants.TOP_HITS);
if (size != null)
{
topHitsBuilder.setSize(size);
}
return topHitsBuilder;
} | java | {
"resource": ""
} |
q164124 | ESQuery.buildWhereAggregations | train | private FilterAggregationBuilder buildWhereAggregations(EntityMetadata entityMetadata, QueryBuilder filter)
{
filter = filter != null ? filter : QueryBuilders.matchAllQuery();
FilterAggregationBuilder filteragg = AggregationBuilders.filter(ESConstants.AGGREGATION_NAME).filter(filter);
return filteragg;
} | java | {
"resource": ""
} |
q164125 | ESQuery.buildSelectAggregations | train | private AggregationBuilder buildSelectAggregations(AggregationBuilder aggregationBuilder,
SelectStatement selectStatement, EntityMetadata entityMetadata)
{
Expression expression = ((SelectClause) selectStatement.getSelectClause()).getSelectExpression();
if (expression instanceof CollectionExpression)
{
aggregationBuilder = appendAggregation((CollectionExpression) expression, entityMetadata,
aggregationBuilder);
}
else
{
if (isAggregationExpression(expression) && checkIfKeyExists(expression.toParsedText()))
aggregationBuilder.subAggregation(getMetricsAggregation(expression, entityMetadata));
}
return aggregationBuilder;
} | java | {
"resource": ""
} |
q164126 | ESQuery.appendAggregation | train | private AggregationBuilder appendAggregation(CollectionExpression collectionExpression,
EntityMetadata entityMetadata, AggregationBuilder aggregationBuilder)
{
ListIterable<Expression> functionlist = collectionExpression.children();
for (Expression function : functionlist)
{
if (isAggregationExpression(function) && checkIfKeyExists(function.toParsedText()))
{
aggregationBuilder.subAggregation(getMetricsAggregation(function, entityMetadata));
}
}
return aggregationBuilder;
} | java | {
"resource": ""
} |
q164127 | ESQuery.getMetricsAggregation | train | private MetricsAggregationBuilder getMetricsAggregation(Expression expression, EntityMetadata entityMetadata)
{
AggregateFunction function = (AggregateFunction) expression;
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
entityMetadata.getPersistenceUnit());
String jPAColumnName = KunderaCoreUtils.getJPAColumnName(function.toParsedText(), entityMetadata, metaModel);
MetricsAggregationBuilder aggregationBuilder = null;
switch (function.getIdentifier())
{
case Expression.MIN:
aggregationBuilder = AggregationBuilders.min(function.toParsedText()).field(jPAColumnName);
break;
case Expression.MAX:
aggregationBuilder = AggregationBuilders.max(function.toParsedText()).field(jPAColumnName);
break;
case Expression.SUM:
aggregationBuilder = AggregationBuilders.sum(function.toParsedText()).field(jPAColumnName);
break;
case Expression.AVG:
aggregationBuilder = AggregationBuilders.avg(function.toParsedText()).field(jPAColumnName);
break;
case Expression.COUNT:
aggregationBuilder = AggregationBuilders.count(function.toParsedText()).field(jPAColumnName);
break;
}
return aggregationBuilder;
} | java | {
"resource": ""
} |
q164128 | ESQuery.checkIfKeyExists | train | private boolean checkIfKeyExists(String key)
{
if (aggregationsKeySet == null)
{
aggregationsKeySet = new HashSet<String>();
}
return aggregationsKeySet.add(key);
} | java | {
"resource": ""
} |
q164129 | PelopsClientFactory.removePool | train | private void removePool(IThriftPool pool)
{
Pelops.removePool(PelopsUtils.getPoolName(pool));
Node[] nodes = ((CommonsBackedPool) pool).getCluster().getNodes();
logger.warn("{} :{} host appears to be down, trying for next ", nodes, ((CommonsBackedPool) pool).getCluster()
.getConnectionConfig().getThriftPort());
CassandraHost cassandraHost = ((CassandraHostConfiguration) configuration).getCassandraHost(
nodes[0].getAddress(), ((CommonsBackedPool) pool).getCluster().getConnectionConfig().getThriftPort());
hostPools.remove(cassandraHost);
} | java | {
"resource": ""
} |
q164130 | CouchDBSchemaManager.dropSchema | train | @Override
public void dropSchema()
{
try
{
for (TableInfo tableInfo : tableInfos)
{
HttpResponse deleteResponse = null;
Map<String, MapReduce> views = new HashMap<String, MapReduce>();
String id = CouchDBConstants.DESIGN + tableInfo.getTableName();
CouchDBDesignDocument designDocument = getDesignDocument(id);
designDocument.setLanguage(CouchDBConstants.LANGUAGE);
views = designDocument.getViews();
if (views != null)
{
StringBuilder builder = new StringBuilder("rev=");
builder.append(designDocument.get_rev());
URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase()
+ CouchDBConstants.URL_SEPARATOR + id, builder.toString(), null);
HttpDelete delete = new HttpDelete(uri);
try
{
deleteResponse = httpClient.execute(httpHost, delete, CouchDBUtils.getContext(httpHost));
}
finally
{
CouchDBUtils.closeContent(deleteResponse);
}
}
}
}
catch (Exception e)
{
logger.error("Error while creating database, caused by {}.", e);
throw new SchemaGenerationException("Error while creating database", e, "couchDB");
}
} | java | {
"resource": ""
} |
q164131 | CouchDBSchemaManager.initiateClient | train | @Override
protected boolean initiateClient()
{
try
{
SchemeSocketFactory ssf = null;
ssf = PlainSocketFactory.getSocketFactory();
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", Integer.parseInt(port), ssf));
PoolingClientConnectionManager ccm = new PoolingClientConnectionManager(schemeRegistry);
httpClient = new DefaultHttpClient(ccm);
httpHost = new HttpHost(hosts[0], Integer.parseInt(port), "http");
// Http params
httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");
// basic authentication
if (userName != null && password != null)
{
((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(
new AuthScope(hosts[0], Integer.parseInt(port)),
new UsernamePasswordCredentials(userName, password));
}
// request interceptor
((DefaultHttpClient) httpClient).addRequestInterceptor(new HttpRequestInterceptor()
{
public void process(final HttpRequest request, final HttpContext context) throws IOException
{
if (logger.isInfoEnabled())
{
RequestLine requestLine = request.getRequestLine();
logger.info(">> " + requestLine.getMethod() + " " + URI.create(requestLine.getUri()).getPath());
}
}
});
// response interceptor
((DefaultHttpClient) httpClient).addResponseInterceptor(new HttpResponseInterceptor()
{
public void process(final HttpResponse response, final HttpContext context) throws IOException
{
if (logger.isInfoEnabled())
logger.info("<< Status: " + response.getStatusLine().getStatusCode());
}
});
}
catch (Exception e)
{
logger.error("Error Creating HTTP client {}. ", e);
throw new IllegalStateException(e);
}
return true;
} | java | {
"resource": ""
} |
q164132 | CouchDBSchemaManager.validate | train | @Override
protected void validate(List<TableInfo> tableInfos)
{
try
{
if (!checkForDBExistence())
{
throw new SchemaGenerationException("Database " + databaseName + " not exist");
}
for (TableInfo tableInfo : tableInfos)
{
Map<String, MapReduce> views = new HashMap<String, MapReduce>();
String id = CouchDBConstants.DESIGN + tableInfo.getTableName();
CouchDBDesignDocument designDocument = getDesignDocument(id);
designDocument.setLanguage(CouchDBConstants.LANGUAGE);
views = designDocument.getViews();
if (views == null)
{
logger.warn("No view exist for table " + tableInfo.getTableName()
+ "so any query will not produce any result");
return;
}
for (IndexInfo indexInfo : tableInfo.getColumnsToBeIndexed())
{
if (views.get(indexInfo.getColumnName()) == null)
{
logger.warn("No view exist for column " + indexInfo.getColumnName() + " of table "
+ tableInfo.getTableName() + "so any query on column " + indexInfo.getColumnName()
+ "will not produce any result");
}
}
// for id column.
if (views.get(tableInfo.getIdColumnName()) == null)
{
logger.warn("No view exist for id column " + tableInfo.getIdColumnName() + " of table "
+ tableInfo.getTableName() + "so any query on id column " + tableInfo.getIdColumnName()
+ "will not produce any result");
}
// for select all.
if (views.get("all") == null)
{
logger.warn("No view exist for select all for table " + tableInfo.getTableName()
+ "so select all query will not produce any result");
}
}
}
catch (Exception e)
{
throw new SchemaGenerationException("Database " + databaseName + " not exist");
}
} | java | {
"resource": ""
} |
q164133 | CouchDBSchemaManager.update | train | @Override
protected void update(List<TableInfo> tableInfos)
{
try
{
HttpResponse response = null;
createDatabaseIfNotExist(false);
for (TableInfo tableInfo : tableInfos)
{
String id = CouchDBConstants.DESIGN + tableInfo.getTableName();
CouchDBDesignDocument designDocument = getDesignDocument(id);
designDocument.setLanguage(CouchDBConstants.LANGUAGE);
Map<String, MapReduce> views = designDocument.getViews();
if (views == null)
{
views = new HashMap<String, MapReduce>();
}
for (IndexInfo indexInfo : tableInfo.getColumnsToBeIndexed())
{
createViewIfNotExist(views, indexInfo.getColumnName());
}
// for id column.
createViewIfNotExist(views, tableInfo.getIdColumnName());
// for select all.
createViewForSelectAllIfNotExist(tableInfo, views);
// for selecting specific field
createViewForSelectSpecificFields(views);
designDocument.setViews(views);
URI uri = null;
if (designDocument.get_rev() == null)
{
uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase()
+ CouchDBConstants.URL_SEPARATOR + id, null, null);
}
else
{
StringBuilder builder = new StringBuilder("rev=");
builder.append(designDocument.get_rev());
uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase()
+ CouchDBConstants.URL_SEPARATOR + id, builder.toString(), null);
}
HttpPut put = new HttpPut(uri);
String jsonObject = gson.toJson(designDocument);
StringEntity entity = new StringEntity(jsonObject);
put.setEntity(entity);
try
{
response = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));
}
finally
{
CouchDBUtils.closeContent(response);
}
}
// creating views for various aggregations in the following
// order:
// -- COUNT SUM MAX MIN AVG
// IMPORTANT: The aggregations does not support WHERE clause
createDesignDocForAggregations();
}
catch (Exception e)
{
logger.error("Error while creating database, caused by {}.", e);
throw new SchemaGenerationException("Error while creating database", e, "couchDB");
}
} | java | {
"resource": ""
} |
q164134 | CouchDBSchemaManager.create | train | @Override
protected void create(List<TableInfo> tableInfos)
{
try
{
HttpResponse response = null;
createDatabaseIfNotExist(true);
for (TableInfo tableInfo : tableInfos)
{
CouchDBDesignDocument designDocument = new CouchDBDesignDocument();
Map<String, MapReduce> views = new HashMap<String, CouchDBDesignDocument.MapReduce>();
designDocument.setLanguage(CouchDBConstants.LANGUAGE);
String id = CouchDBConstants.DESIGN + tableInfo.getTableName();
for (IndexInfo indexInfo : tableInfo.getColumnsToBeIndexed())
{
createView(views, indexInfo.getColumnName());
}
// for id column.
createView(views, tableInfo.getIdColumnName());
// for select all.
createViewForSelectAll(tableInfo, views);
// for selecting specific field
createViewForSelectSpecificFields(views);
designDocument.setViews(views);
URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase() + CouchDBConstants.URL_SEPARATOR
+ id, null, null);
HttpPut put = new HttpPut(uri);
String jsonObject = gson.toJson(designDocument);
StringEntity entity = new StringEntity(jsonObject);
put.setEntity(entity);
try
{
response = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));
}
finally
{
CouchDBUtils.closeContent(response);
}
}
// creating views for various aggregations in the following
// order:
// -- COUNT SUM MAX MIN AVG
// IMPORTANT: The aggregations does not support WHERE clause
createDesignDocForAggregations();
}
catch (Exception e)
{
logger.error("Error while creating database {} , caused by {}.", databaseName, e);
throw new SchemaGenerationException("Error while creating database", e, "couchDB");
}
} | java | {
"resource": ""
} |
q164135 | CouchDBSchemaManager.createDesignDocForAggregations | train | private void createDesignDocForAggregations() throws URISyntaxException, UnsupportedEncodingException, IOException,
ClientProtocolException
{
HttpResponse response = null;
URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase() + CouchDBConstants.URL_SEPARATOR
+ "_design/" + CouchDBConstants.AGGREGATIONS, null, null);
HttpPut put = new HttpPut(uri);
CouchDBDesignDocument designDocument = new CouchDBDesignDocument();
Map<String, MapReduce> views = new HashMap<String, CouchDBDesignDocument.MapReduce>();
designDocument.setLanguage(CouchDBConstants.LANGUAGE);
createViewForCount(views);
createViewForSum(views);
createViewForMax(views);
createViewForMin(views);
createViewForAvg(views);
designDocument.setViews(views);
String jsonObject = gson.toJson(designDocument);
StringEntity entity = new StringEntity(jsonObject);
put.setEntity(entity);
try
{
response = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));
}
finally
{
CouchDBUtils.closeContent(response);
}
} | java | {
"resource": ""
} |
q164136 | CouchDBSchemaManager.createViewForSelectSpecificFields | train | private void createViewForSelectSpecificFields(Map<String, MapReduce> views)
{
if (views.get(CouchDBConstants.FIELDS) == null)
{
MapReduce mapr = new MapReduce();
mapr.setMap("function(doc){for(field in doc){emit(field, doc[field]);}}");
views.put(CouchDBConstants.FIELDS, mapr);
}
} | java | {
"resource": ""
} |
q164137 | CouchDBSchemaManager.createViewForCount | train | private void createViewForCount(Map<String, MapReduce> views)
{
if (views.get(CouchDBConstants.COUNT) == null)
{
MapReduce mapr = new MapReduce();
mapr.setMap("function(doc){" + "for(field in doc){if(field!=\"" + CouchDBConstants.ENTITYNAME
+ "\"){var o = doc[field];emit(field+\"_\"+doc." + CouchDBConstants.ENTITYNAME + ", o);" + "}}"
+ "emit(\"" + CouchDBConstants.ALL + "_\"+doc." + CouchDBConstants.ENTITYNAME + ", null);}");
mapr.setReduce("function(keys, values){return values.length;}");
views.put(CouchDBConstants.COUNT, mapr);
}
} | java | {
"resource": ""
} |
q164138 | CouchDBSchemaManager.createViewForSum | train | private void createViewForSum(Map<String, MapReduce> views)
{
if (views.get(CouchDBConstants.SUM) == null)
{
MapReduce mapr = new MapReduce();
mapr.setMap("function(doc){for(field in doc){var o = doc[field];if(typeof(o)==\"number\")emit(field+\"_\"+doc."
+ CouchDBConstants.ENTITYNAME + ", o);}}");
mapr.setReduce("function(keys, values){return sum(values);}");
views.put(CouchDBConstants.SUM, mapr);
}
} | java | {
"resource": ""
} |
q164139 | CouchDBSchemaManager.createViewForMax | train | private void createViewForMax(Map<String, MapReduce> views)
{
if (views.get(CouchDBConstants.MAX) == null)
{
MapReduce mapr = new MapReduce();
mapr.setMap("function(doc){for(field in doc){var o = doc[field];if(typeof(o)==\"number\")emit(field+\"_\"+doc."
+ CouchDBConstants.ENTITYNAME + ", o);}}");
mapr.setReduce("function(keys, values){return Math.max.apply(Math, values);}");
views.put(CouchDBConstants.MAX, mapr);
}
} | java | {
"resource": ""
} |
q164140 | CouchDBSchemaManager.createViewForMin | train | private void createViewForMin(Map<String, MapReduce> views)
{
if (views.get(CouchDBConstants.MIN) == null)
{
MapReduce mapr = new MapReduce();
mapr.setMap("function(doc){for(field in doc){var o = doc[field];if(typeof(o)==\"number\")emit(field+\"_\"+doc."
+ CouchDBConstants.ENTITYNAME + ", o);}}");
mapr.setReduce("function(keys, values){return Math.min.apply(Math, values);}");
views.put(CouchDBConstants.MIN, mapr);
}
} | java | {
"resource": ""
} |
q164141 | CouchDBSchemaManager.createViewForAvg | train | private void createViewForAvg(Map<String, MapReduce> views)
{
if (views.get(CouchDBConstants.AVG) == null)
{
MapReduce mapr = new MapReduce();
mapr.setMap("function(doc){for(field in doc){var o = doc[field];if(typeof(o)==\"number\")emit(field+\"_\"+doc."
+ CouchDBConstants.ENTITYNAME + ", o);}}");
mapr.setReduce("function(keys, values){return sum(values)/values.length;}");
views.put(CouchDBConstants.AVG, mapr);
}
} | java | {
"resource": ""
} |
q164142 | CouchDBSchemaManager.createViewIfNotExist | train | private void createViewIfNotExist(Map<String, MapReduce> views, String columnName)
{
if (views.get(columnName) == null)
{
createView(views, columnName);
}
} | java | {
"resource": ""
} |
q164143 | CouchDBSchemaManager.createViewForSelectAllIfNotExist | train | private void createViewForSelectAllIfNotExist(TableInfo tableInfo, Map<String, MapReduce> views)
{
if (views.get("all") == null)
{
createViewForSelectAll(tableInfo, views);
}
} | java | {
"resource": ""
} |
q164144 | CouchDBSchemaManager.createViewForSelectAll | train | private void createViewForSelectAll(TableInfo tableInfo, Map<String, MapReduce> views)
{
MapReduce mapr = new MapReduce();
mapr.setMap("function(doc){if(doc." + tableInfo.getIdColumnName() + "){emit(null, doc);}}");
views.put("all", mapr);
} | java | {
"resource": ""
} |
q164145 | CouchDBSchemaManager.createDatabaseIfNotExist | train | private void createDatabaseIfNotExist(boolean drop) throws URISyntaxException, IOException, ClientProtocolException
{
boolean exist = checkForDBExistence();
if (exist && drop)
{
dropDatabase();
exist = false;
}
if (!exist)
{
URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase(), null, null);
HttpPut put = new HttpPut(uri);
HttpResponse putRes = null;
try
{
// creating database.
putRes = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));
}
finally
{
CouchDBUtils.closeContent(putRes);
}
}
} | java | {
"resource": ""
} |
q164146 | CouchDBSchemaManager.checkForDBExistence | train | private boolean checkForDBExistence() throws ClientProtocolException, IOException, URISyntaxException
{
URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase(), null, null);
HttpGet get = new HttpGet(uri);
HttpResponse getRes = null;
try
{
// creating database.
getRes = httpClient.execute(httpHost, get, CouchDBUtils.getContext(httpHost));
if (getRes.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
{
return true;
}
return false;
}
finally
{
CouchDBUtils.closeContent(getRes);
}
} | java | {
"resource": ""
} |
q164147 | CouchDBSchemaManager.dropDatabase | train | private void dropDatabase() throws IOException, ClientProtocolException, URISyntaxException
{
HttpResponse delRes = null;
try
{
URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
CouchDBConstants.URL_SEPARATOR + databaseName.toLowerCase(), null, null);
HttpDelete delete = new HttpDelete(uri);
delRes = httpClient.execute(httpHost, delete, CouchDBUtils.getContext(httpHost));
}
finally
{
CouchDBUtils.closeContent(delRes);
}
} | java | {
"resource": ""
} |
q164148 | MetamodelConfiguration.mapClazztoPu | train | private Map<String, List<String>> mapClazztoPu(Class<?> clazz, String pu, Map<String, List<String>> clazzToPuMap)
{
List<String> puCol = new ArrayList<String>(1);
if (clazzToPuMap == null)
{
clazzToPuMap = new HashMap<String, List<String>>();
}
else
{
if (clazzToPuMap.containsKey(clazz.getName()))
{
puCol = clazzToPuMap.get(clazz.getName());
}
}
if (!puCol.contains(pu))
{
puCol.add(pu);
clazzToPuMap.put(clazz.getName(), puCol);
String annotateEntityName = clazz.getAnnotation(Entity.class).name();
if (!StringUtils.isBlank(annotateEntityName))
{
clazzToPuMap.put(annotateEntityName, puCol);
}
}
return clazzToPuMap;
} | java | {
"resource": ""
} |
q164149 | EventLogQueue.onUpdate | train | private void onUpdate(EventLog log)
{
if (updateEvents == null)
{
updateEvents = new ConcurrentHashMap<Object, EventLog>();
}
updateEvents.put(log.getEntityId(), log);
} | java | {
"resource": ""
} |
q164150 | EventLogQueue.onInsert | train | private void onInsert(EventLog log)
{
if (insertEvents == null)
{
insertEvents = new ConcurrentHashMap<Object, EventLog>();
}
insertEvents.put(log.getEntityId(), log);
} | java | {
"resource": ""
} |
q164151 | CouchbaseSchemaManager.createIdIndex | train | private void createIdIndex(String bucketName)
{
Bucket bucket = null;
try
{
bucket = CouchbaseBucketUtils.openBucket(cluster, bucketName, csmd.getBucketProperty("bucket.password"));
/*
* Ignoring if indexes pre-exist
*/
bucket.bucketManager().createN1qlPrimaryIndex(buildIndexName(bucketName), true, false);
LOGGER.debug("Niql primary Index are created for bucket [" + bucketName + "].");
}
catch (CouchbaseException cex)
{
LOGGER.error("Not able to create Niql primary index for bucket [" + bucketName + "].", cex);
throw new KunderaException("Not able to create Niql primary index for bucket [" + bucketName + "].", cex);
}
finally
{
CouchbaseBucketUtils.closeBucket(bucket);
}
} | java | {
"resource": ""
} |
q164152 | CouchbaseSchemaManager.removeBucket | train | private void removeBucket(String name)
{
try
{
if (clusterManager.removeBucket(name))
{
LOGGER.info("Bucket [" + name + "] is removed!");
}
else
{
LOGGER.error("Not able to remove bucket [" + name + "].");
throw new KunderaException("Not able to remove bucket [" + name + "].");
}
}
catch (CouchbaseException ex)
{
LOGGER.error("Not able to remove bucket [" + name + "].", ex);
throw new KunderaException("Not able to remove bucket [" + name + "].", ex);
}
} | java | {
"resource": ""
} |
q164153 | CouchbaseSchemaManager.addBucket | train | private void addBucket(String name)
{
String qouta = csmd.getBucketProperty("bucket.quota");
int bucketQuota = qouta != null ? Integer.parseInt(qouta) : DEFAULT_RAM_SIZE_IN_MB;
BucketSettings bucketSettings = new DefaultBucketSettings.Builder().type(BucketType.COUCHBASE).name(name)
.quota(bucketQuota).build();
try
{
clusterManager.insertBucket(bucketSettings);
LOGGER.info("Bucket [" + name + "] is added!");
}
catch (CouchbaseException ex)
{
LOGGER.error("Not able to add bucket [" + name + "].", ex);
throw new KunderaException("Not able to add bucket [" + name + "].", ex);
}
} | java | {
"resource": ""
} |
q164154 | CouchbaseSchemaManager.buildIndexName | train | private String buildIndexName(String bucketName)
{
if (bucketName == null)
{
throw new KunderaException("Bucket Name can't be null!");
}
return (bucketName + CouchbaseConstants.INDEX_SUFFIX).toLowerCase();
} | java | {
"resource": ""
} |
q164155 | TeradataSparkClient.getConnectionString | train | public String getConnectionString(EntityMetadata m)
{
Properties properties = new Properties();
String fileName = "teradata.properties";
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(fileName);
if (inputStream != null)
{
try
{
properties.load(inputStream);
}
catch (IOException e)
{
throw new RuntimeException("Property file: " + fileName + "not found in the classpath", e);
}
}
else
{
throw new RuntimeException("Property file: " + fileName + "not found in the classpath");
}
String connectionString = "jdbc:teradata://" + properties.getProperty("teradata.host") + "/database="
+ m.getSchema() + ",tmode=ANSI,charset=UTF8,user=" + properties.getProperty("teradata.user")
+ ",password=" + properties.getProperty("teradata.password") + "";
return connectionString;
} | java | {
"resource": ""
} |
q164156 | KunderaJTAUserTransaction.setImplementor | train | public void setImplementor(ResourceManager implementor)
{
KunderaTransaction tx = threadLocal.get();
if (tx == null)
{
throw new IllegalStateException("Cannot get Transaction to start");
}
tx.setImplementor(implementor);
} | java | {
"resource": ""
} |
q164157 | Relation.getJoinColumnName | train | public String getJoinColumnName(final KunderaMetadata kunderaMetadata)
{
if(joinColumnName == null && isJoinedByPrimaryKey)
{
EntityMetadata joinClassMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, targetEntity);
joinColumnName = ((AbstractAttribute)joinClassMetadata.getIdAttribute()).getJPAColumnName();
}
if(joinTableMetadata != null)
{
joinColumnName = joinTableMetadata.getJoinColumns() != null? joinTableMetadata.getJoinColumns().iterator().next():null;
}
if(isBiDirectional())
{
// Give precedence to join column name!
if(biDirectionalField.isAnnotationPresent(JoinColumn.class))
{
joinColumnName = biDirectionalField.getAnnotation(JoinColumn.class).name();
}
}
return joinColumnName !=null? joinColumnName:property.getName();
} | java | {
"resource": ""
} |
q164158 | Relation.isUnary | train | public boolean isUnary()
{
return type.equals(Relation.ForeignKey.ONE_TO_ONE) || type.equals(Relation.ForeignKey.MANY_TO_ONE);
} | java | {
"resource": ""
} |
q164159 | Relation.isCollection | train | public boolean isCollection()
{
return type.equals(Relation.ForeignKey.ONE_TO_MANY) || type.equals(Relation.ForeignKey.MANY_TO_MANY);
} | java | {
"resource": ""
} |
q164160 | RethinkDBClient.populateRmap | train | private MapObject populateRmap(EntityMetadata entityMetadata, Object entity)
{
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata()
.getMetamodel(entityMetadata.getPersistenceUnit());
Class entityClazz = entityMetadata.getEntityClazz();
EntityType entityType = metaModel.entity(entityClazz);
Set<Attribute> attributes = entityType.getAttributes();
Iterator<Attribute> iterator = attributes.iterator();
return iterateAndPopulateRmap(entity, metaModel, iterator);
} | java | {
"resource": ""
} |
q164161 | RethinkDBClient.iterateAndPopulateRmap | train | private MapObject iterateAndPopulateRmap(Object entity, MetamodelImpl metaModel, Iterator<Attribute> iterator)
{
MapObject map = r.hashMap();
while (iterator.hasNext())
{
Attribute attribute = iterator.next();
Field field = (Field) attribute.getJavaMember();
Object value = PropertyAccessorHelper.getObject(entity, field);
if (field.isAnnotationPresent(Id.class))
{
map.with(ID, value);
}
else
{
map.with(((AbstractAttribute) attribute).getJPAColumnName(), value);
}
}
return map;
} | java | {
"resource": ""
} |
q164162 | ResultIterator.fetchObject | train | private E fetchObject()
{
try
{
String previousSkip = "&skip=" + (skipCounter - 1);
String currentSkip = "&skip=" + skipCounter;
int indexOf = q.indexOf(previousSkip);
if (indexOf > 0)
{
q.replace(indexOf, indexOf + previousSkip.length(), currentSkip);
}
else if (skipCounter > 0)
{
q.append(currentSkip);
}
client.executeQueryAndGetResults(q, _id, m, results, interpreter);
skipCounter++;
}
catch (Exception e)
{
logger.error("Error while executing query, caused by {}.", e);
throw new KunderaException("Error while executing query, caused by : " + e);
}
if (results != null && !results.isEmpty())
{
Object object = results.get(0);
results = new ArrayList();
if (!m.isRelationViaJoinTable() && (m.getRelationNames() == null || (m.getRelationNames().isEmpty())))
{
return (E) object;
}
else
{
return setRelationEntities(object, client, m);
}
}
return null;
} | java | {
"resource": ""
} |
q164163 | CouchbaseClientFactory.splitHostNames | train | private String[] splitHostNames(String hostNames)
{
String[] hostArray = hostNames.split(Constants.COMMA);
String[] hosts = new String[hostArray.length];
for (int i = 0; i < hostArray.length; i++)
{
hosts[i] = hostArray[i].trim();
}
return hosts;
} | java | {
"resource": ""
} |
q164164 | HBaseSchemaManager.getTableMetaData | train | private HTableDescriptor getTableMetaData(List<TableInfo> tableInfos)
{
HTableDescriptor tableDescriptor = new HTableDescriptor(databaseName);
Properties tableProperties = null;
schemas = HBasePropertyReader.hsmd.getDataStore() != null ? HBasePropertyReader.hsmd.getDataStore()
.getSchemas() : null;
if (schemas != null && !schemas.isEmpty())
{
for (Schema s : schemas)
{
if (s.getName() != null && s.getName().equalsIgnoreCase(databaseName))
{
tableProperties = s.getSchemaProperties();
tables = s.getTables();
}
}
}
for (TableInfo tableInfo : tableInfos)
{
if (tableInfo != null)
{
HColumnDescriptor hColumnDescriptor = getColumnDescriptor(tableInfo);
tableDescriptor.addFamily(hColumnDescriptor);
}
}
if (tableProperties != null)
{
for (Object o : tableProperties.keySet())
{
tableDescriptor.setValue(Bytes.toBytes(o.toString()), Bytes.toBytes(tableProperties.get(o).toString()));
}
}
return tableDescriptor;
} | java | {
"resource": ""
} |
q164165 | PelopsClient.persistJoinTable | train | public void persistJoinTable(JoinTableData joinTableData)
{
Mutator mutator = clientFactory.getMutator(pool);
String joinTableName = joinTableData.getJoinTableName();
String invJoinColumnName = joinTableData.getInverseJoinColumnName();
Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();
EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
joinTableData.getEntityClass());
if (isCql3Enabled(entityMetadata))
{
Cassandra.Client conn = null;
Object pooledConnection = null;
pooledConnection = getConnection();
conn = (org.apache.cassandra.thrift.Cassandra.Client) getConnection(pooledConnection);
persistJoinTableByCql(joinTableData, conn);
}
else
{
for (Object key : joinTableRecords.keySet())
{
Set<Object> values = joinTableRecords.get(key);
List<Column> columns = new ArrayList<Column>();
Class columnType = null;
for (Object value : values)
{
Column column = new Column();
column.setName(PropertyAccessorFactory.STRING.toBytes(invJoinColumnName
+ Constants.JOIN_COLUMN_NAME_SEPARATOR + value.toString()));
column.setValue(PropertyAccessorHelper.getBytes(value));
column.setTimestamp(generator.getTimestamp());
columnType = value.getClass();
columns.add(column);
}
createIndexesOnColumns(entityMetadata, joinTableName, columns, columnType);
mutator.writeColumns(joinTableName, Bytes.fromByteArray(PropertyAccessorHelper.getBytes(key)),
Arrays.asList(columns.toArray(new Column[0])));
}
}
if (log.isInfoEnabled())
{
log.info(" Persisted data with join table column family {}", joinTableData.getJoinTableName());
}
mutator.execute(getConsistencyLevel());
} | java | {
"resource": ""
} |
q164166 | PelopsClient.loadSuperColumns | train | @Override
public final List<SuperColumn> loadSuperColumns(String keyspace, String columnFamily, String rowId,
String... superColumnNames)
{
if (!isOpen())
throw new PersistenceException("PelopsClient is closed.");
Selector selector = clientFactory.getSelector(pool);
List<ByteBuffer> rowKeys = new ArrayList<ByteBuffer>();
rowKeys.add(ByteBuffer.wrap(rowId.getBytes()));
if (log.isInfoEnabled())
{
log.info("Retrieving record of super column family {} for row key {}", columnFamily, rowId);
}
return selector.getSuperColumnsFromRow(columnFamily, rowId, Selector.newColumnsPredicate(superColumnNames),
getConsistencyLevel());
} | java | {
"resource": ""
} |
q164167 | PelopsClient.findByRange | train | @Override
public List findByRange(byte[] minVal, byte[] maxVal, EntityMetadata m, boolean isWrapReq, List<String> relations,
List<String> columns, List<IndexExpression> conditions, int maxResults) throws Exception
{
Selector selector = clientFactory.getSelector(pool);
SlicePredicate slicePredicate = Selector.newColumnsPredicateAll(false, Integer.MAX_VALUE);
if (columns != null && !columns.isEmpty())
{
slicePredicate = Selector.newColumnsPredicate(columns.toArray(new String[] {}));
}
KeyRange keyRange = selector.newKeyRange(minVal != null ? Bytes.fromByteArray(minVal) : Bytes.fromUTF8(""),
maxVal != null ? Bytes.fromByteArray(maxVal) : Bytes.fromUTF8(""), maxResults);
if (conditions != null)
{
keyRange.setRow_filter(conditions);
keyRange.setRow_filterIsSet(true);
}
List<KeySlice> keys = selector.getKeySlices(new ColumnParent(m.getTableName()), keyRange, slicePredicate,
getConsistencyLevel());
List results = null;
if (keys != null)
{
results = populateEntitiesFromKeySlices(m, isWrapReq, relations, keys, dataHandler);
}
if (log.isInfoEnabled())
{
log.info("Returning entities for find by range for", results != null ? results.size() : null);
}
return results;
} | java | {
"resource": ""
} |
q164168 | AbstractAttribute.getJPAColumnName | train | public String getJPAColumnName()
{
// In case of Attribute override.
Column column = ((AbstractManagedType) this.managedType).getAttributeBinding(member);
if (column != null)
{
columnName = column.name();
}
return columnName;
} | java | {
"resource": ""
} |
q164169 | AbstractPropertyReader.onParseXML | train | private ClientProperties onParseXML(String propertyFileName, PersistenceUnitMetadata puMetadata)
{
InputStream inStream = puMetadata.getClassLoader().getResourceAsStream(propertyFileName);
if (inStream == null)
{
propertyFileName = KunderaCoreUtils.resolvePath(propertyFileName);
try
{
inStream = new FileInputStream(new File(propertyFileName));
}
catch (FileNotFoundException e)
{
log.warn("File {} not found, Caused by ", propertyFileName);
return null;
}
}
if (inStream != null)
{
xStream = getXStreamObject();
Object o = xStream.fromXML(inStream);
return (ClientProperties) o;
}
return null;
} | java | {
"resource": ""
} |
q164170 | KunderaQuery.initiateJPQLObject | train | private void initiateJPQLObject(final String jpaQuery) {
JPQLGrammar jpqlGrammar = EclipseLinkJPQLGrammar2_4.instance();
this.jpqlExpression = new JPQLExpression(jpaQuery, jpqlGrammar, "ql_statement", true);
setKunderaQueryTypeObject();
} | java | {
"resource": ""
} |
q164171 | KunderaQuery.setKunderaQueryTypeObject | train | private void setKunderaQueryTypeObject() {
try {
if (isSelectStatement()) {
this.setSelectStatement((SelectStatement) (this.getJpqlExpression().getQueryStatement()));
} else if (isUpdateStatement()) {
this.setUpdateStatement((UpdateStatement) (this.getJpqlExpression().getQueryStatement()));
} else if (isDeleteStatement()) {
this.setDeleteStatement((DeleteStatement) (this.getJpqlExpression().getQueryStatement()));
}
} catch (ClassCastException cce) {
throw new JPQLParseException("Bad query format : " + cce.getMessage());
}
} | java | {
"resource": ""
} |
q164172 | KunderaQuery.getClauseValue | train | public List<Object> getClauseValue(String paramString) {
if (typedParameter != null && typedParameter.getParameters() != null) {
List<FilterClause> clauses = typedParameter.getParameters().get(paramString);
if (clauses != null) {
return clauses.get(0).getValue();
} else {
throw new IllegalArgumentException("parameter is not a parameter of the query");
}
}
logger.error("Parameter {} is not a parameter of the query.", paramString);
throw new IllegalArgumentException("Parameter is not a parameter of the query.");
} | java | {
"resource": ""
} |
q164173 | KunderaQuery.getClauseValue | train | public List<Object> getClauseValue(Parameter param) {
Parameter match = null;
if (typedParameter != null && typedParameter.jpaParameters != null) {
for (Parameter p : typedParameter.jpaParameters) {
if (p.equals(param)) {
match = p;
if (typedParameter.getType().equals(Type.NAMED)) {
List<FilterClause> clauses = typedParameter.getParameters().get(":" + p.getName());
if (clauses != null) {
return clauses.get(0).getValue();
}
} else {
List<FilterClause> clauses = typedParameter.getParameters().get("?" + p.getPosition());
if (clauses != null) {
return clauses.get(0).getValue();
} else {
UpdateClause updateClause = typedParameter.getUpdateParameters().get("?" + p.getPosition());
if (updateClause != null) {
List<Object> value = new ArrayList<Object>();
value.add(updateClause.getValue());
return value;
}
}
}
break;
}
}
if (match == null) {
throw new IllegalArgumentException("parameter is not a parameter of the query");
}
}
logger.error("parameter{} is not a parameter of the query", param);
throw new IllegalArgumentException("parameter is not a parameter of the query");
} | java | {
"resource": ""
} |
q164174 | KunderaQuery.initUpdateClause | train | private void initUpdateClause() {
for (UpdateClause updateClause : updateClauseQueue) {
onTypedParameter(updateClause.getValue(), updateClause, updateClause.getProperty().trim());
}
} | java | {
"resource": ""
} |
q164175 | KunderaQuery.initEntityClass | train | private void initEntityClass() {
if (from == null) {
throw new JPQLParseException("Bad query format FROM clause is mandatory for SELECT queries");
}
String fromArray[] = from.split(" ");
if (!this.isDeleteUpdate) {
if (fromArray.length == 3 && fromArray[1].equalsIgnoreCase("as")) {
fromArray = new String[] { fromArray[0], fromArray[2] };
}
if (fromArray.length != 2) {
throw new JPQLParseException("Bad query format: " + from
+ ". Identification variable is mandatory in FROM clause for SELECT queries");
}
// TODO
StringTokenizer tokenizer = new StringTokenizer(result[0], ",");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (!StringUtils.containsAny(fromArray[1] + ".", token)) {
throw new QueryHandlerException("bad query format with invalid alias:" + token);
}
}
}
this.entityName = fromArray[0];
if (fromArray.length == 2)
this.entityAlias = fromArray[1];
persistenceUnit = kunderaMetadata.getApplicationMetadata().getMappedPersistenceUnit(entityName);
// Get specific metamodel.
MetamodelImpl model = getMetamodel(persistenceUnit);
if (model != null) {
entityClass = model.getEntityClass(entityName);
}
if (null == entityClass) {
logger.error(
"No entity {} found, please verify it is properly annotated with @Entity and not a mapped Super class",
entityName);
throw new QueryHandlerException("No entity found by the name: " + entityName);
}
EntityMetadata metadata = model.getEntityMetadata(entityClass);
if (metadata != null && !metadata.isIndexable()) {
throw new QueryHandlerException(entityClass + " is not indexed. Not possible to run a query on it."
+ " Check whether it was properly annotated for indexing.");
}
} | java | {
"resource": ""
} |
q164176 | KunderaQuery.initFilter | train | private void initFilter() {
EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);
Metamodel metaModel = kunderaMetadata.getApplicationMetadata().getMetamodel(getPersistenceUnit());
EntityType entityType = metaModel.entity(entityClass);
if (null == filter) {
List<String> clauses = new ArrayList<String>();
addDiscriminatorClause(clauses, entityType);
return;
}
WhereClause whereClause = KunderaQueryUtils.getWhereClause(getJpqlExpression());
KunderaQueryUtils.traverse(whereClause.getConditionalExpression(), metadata, kunderaMetadata, this, false);
for (Object filterClause : filtersQueue) {
if (!(filterClause instanceof String)) {
onTypedParameter(((FilterClause) filterClause));
}
}
addDiscriminatorClause(null, entityType);
} | java | {
"resource": ""
} |
q164177 | KunderaQuery.addDiscriminatorClause | train | private void addDiscriminatorClause(List<String> clauses, EntityType entityType) {
if (((AbstractManagedType) entityType).isInherited()) {
String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();
String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue();
if (discrColumn != null && discrValue != null) {
if (clauses != null && !clauses.isEmpty()) {
filtersQueue.add("AND");
}
FilterClause filterClause = new FilterClause(discrColumn, "=", discrValue, discrColumn);
filtersQueue.add(filterClause);
}
}
} | java | {
"resource": ""
} |
q164178 | KunderaQuery.filterJPAParameterInfo | train | private void filterJPAParameterInfo(Type type, String name, String fieldName) {
String attributeName = getAttributeName(fieldName);
Attribute entityAttribute =
((MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(persistenceUnit))
.getEntityAttribute(entityClass, attributeName);
Class fieldType = entityAttribute.getJavaType();
if (type.equals(Type.INDEXED)) {
typedParameter.addJPAParameter(new JPAParameter(null, Integer.valueOf(name), fieldType));
} else {
typedParameter.addJPAParameter(new JPAParameter(name, null, fieldType));
}
} | java | {
"resource": ""
} |
q164179 | KunderaQuery.getAttributeName | train | private String getAttributeName(String fieldName) {
String attributeName = fieldName;
if (fieldName.indexOf(".") != -1) {
attributeName = fieldName.substring(0, fieldName.indexOf("."));
}
return attributeName;
} | java | {
"resource": ""
} |
q164180 | KunderaQuery.addUpdateClause | train | public void addUpdateClause(final String property, final String value) {
UpdateClause updateClause = new UpdateClause(property.trim(), value.trim());
updateClauseQueue.add(updateClause);
addTypedParameter(
value.trim().startsWith("?") ? Type.INDEXED : value.trim().startsWith(":") ? Type.NAMED : null, property,
updateClause);
} | java | {
"resource": ""
} |
q164181 | KunderaQuery.addFilterClause | train | public void addFilterClause(final String property, final String condition, final Object value,
final String fieldName, final boolean ignoreCase) {
if (property != null && condition != null) {
FilterClause filterClause = new FilterClause(property.trim(), condition.trim(), value, fieldName);
filterClause.setIgnoreCase(ignoreCase);
filtersQueue.add(filterClause);
} else {
filtersQueue.add(property);
}
} | java | {
"resource": ""
} |
q164182 | KunderaQuery.getValue | train | private static Object getValue(Object value) {
if (value != null && value.getClass().isAssignableFrom(String.class)) {
return ((String) value).replaceAll("^'", "").replaceAll("'$", "").replaceAll("''", "'");
}
return value;
} | java | {
"resource": ""
} |
q164183 | ExecutorService.onQueryByEmail | train | static List<User> onQueryByEmail(final EntityManager em, final User user)
{
// Query by parameter (fetch user by email id)
String query = "Select u from User u where u.emailId =?1";
logger.info("");
logger.info("");
logger.info(query);
System.out.println("#######################Querying##########################################");
// find by named parameter(e.g. email)
List<User> fetchedUsers = findByEmail(em, query, user.getEmailId());
return fetchedUsers;
} | java | {
"resource": ""
} |
q164184 | ExecutorService.onPersist | train | static void onPersist(final EntityManager em, final User user)
{
logger.info("");
logger.info("");
logger.info("#######################Persisting##########################################");
logger.info("");
logger.info(user.toString());
persist(user, em);
logger.info("");
System.out.println("#######################Persisting##########################################");
logger.info("");
logger.info("");
} | java | {
"resource": ""
} |
q164185 | ExecutorService.findByKey | train | static User findByKey(final EntityManager em, final String userId)
{
User user = em.find(User.class, userId);
logger.info("[On Find by key]");
System.out.println("#######################START##########################################");
logger.info("\n");
logger.info("\t\t User's first name:" + user.getFirstName());
logger.info("\t\t User's emailId:" + user.getEmailId());
logger.info("\t\t User's Personal Details:" + user.getPersonalDetail().getName());
logger.info("\t\t User's Personal Details:" + user.getPersonalDetail().getPassword());
logger.info("\t\t User's total tweets:" + user.getTweets().size());
logger.info("\n");
System.out.println("#######################END############################################");
logger.info("\n");
return user;
} | java | {
"resource": ""
} |
q164186 | ExecutorService.findByQuery | train | @SuppressWarnings("unchecked")
static void findByQuery(final EntityManager em, final String query)
{
Query q = em.createNamedQuery(query);
logger.info("[On Find All by Query]");
List<User> users = q.getResultList();
if (users == null || users.isEmpty())
{
logger.info("0 Users Returned");
return;
}
System.out.println("#######################START##########################################");
logger.info("\t\t Total number of users:" + users.size());
logger.info("\t\t User's total tweets:" + users.get(0).getTweets().size());
printTweets(users);
logger.info("\n");
// logger.info("First tweet:" users.get(0).getTweets().);
System.out.println("#######################END############################################");
logger.info("\n");
} | java | {
"resource": ""
} |
q164187 | ExecutorService.findByNativeQuery | train | @SuppressWarnings("unchecked")
static void findByNativeQuery(final EntityManager em, final String query)
{
Query q = em.createNativeQuery(query, Tweets.class);
Map<String, Client> clients = (Map<String, Client>) em.getDelegate();
ThriftClient client = (ThriftClient) clients.get("twissandra");
client.setCqlVersion(CassandraConstants.CQL_VERSION_3_0);
logger.info("[On Find Tweets by CQL3]");
List<Tweets> tweets = q.getResultList();
System.out.println("#######################START##########################################");
logger.info("\t\t User's total tweets:" + tweets.size());
onPrintTweets(tweets);
logger.info("\n");
// logger.info("First tweet:" users.get(0).getTweets().);
System.out.println("#######################END############################################");
logger.info("\n");
} | java | {
"resource": ""
} |
q164188 | ExecutorService.onPrintTweets | train | private static void onPrintTweets(final List<Tweets> tweets)
{
for (Iterator<Tweets> iterator = tweets.iterator(); iterator.hasNext();)
{
int counter = 1;
while (iterator.hasNext())
{
logger.info("\n");
logger.info("\t\t Tweet No:#" + counter++);
Tweets rec = (Tweets) iterator.next();
logger.info("\t\t tweet is ->" + rec.getBody());
logger.info("\t\t Tweeted at ->" + rec.getTweetDate());
if (rec.getVideos() != null)
{
logger.info("\t\t Tweeted Contains Video ->" + rec.getVideos().size());
for (Iterator<Video> iteratorVideo = rec.getVideos().iterator(); iteratorVideo.hasNext();)
{
Video video = (Video) iteratorVideo.next();
logger.info(video);
}
}
}
}
} | java | {
"resource": ""
} |
q164189 | TableInfo.addElementCollectionMetadata | train | public void addElementCollectionMetadata(CollectionColumnInfo elementCollectionMetadata)
{
if (this.elementCollectionMetadatas == null)
{
this.elementCollectionMetadatas = new ArrayList<CollectionColumnInfo>();
}
if (!elementCollectionMetadatas.contains(elementCollectionMetadata))
{
elementCollectionMetadatas.add(elementCollectionMetadata);
}
} | java | {
"resource": ""
} |
q164190 | TableInfo.addColumnInfo | train | public void addColumnInfo(ColumnInfo columnInfo)
{
if (this.columnMetadatas == null)
{
this.columnMetadatas = new ArrayList<ColumnInfo>();
}
if (!columnMetadatas.contains(columnInfo) && !this.getIdColumnName().equals(columnInfo.getColumnName()))
{
columnMetadatas.add(columnInfo);
}
} | java | {
"resource": ""
} |
q164191 | TableInfo.addEmbeddedColumnInfo | train | public void addEmbeddedColumnInfo(EmbeddedColumnInfo embdColumnInfo)
{
if (this.embeddedColumnMetadatas == null)
{
this.embeddedColumnMetadatas = new ArrayList<EmbeddedColumnInfo>();
}
if (!embeddedColumnMetadatas.contains(embdColumnInfo))
{
embeddedColumnMetadatas.add(embdColumnInfo);
}
} | java | {
"resource": ""
} |
q164192 | TableInfo.addCollectionColumnMetadata | train | public void addCollectionColumnMetadata(CollectionColumnInfo collectionColumnMetadata)
{
if (this.collectionColumnMetadatas == null)
{
this.collectionColumnMetadatas = new ArrayList<CollectionColumnInfo>();
}
if (!collectionColumnMetadatas.contains(collectionColumnMetadata))
{
collectionColumnMetadatas.add(collectionColumnMetadata);
}
} | java | {
"resource": ""
} |
q164193 | TableInfo.getColumnToBeIndexed | train | public IndexInfo getColumnToBeIndexed(String columnName)
{
IndexInfo idxInfo = new IndexInfo(columnName);
if (columnToBeIndexed.contains(idxInfo))
{
int index = columnToBeIndexed.indexOf(idxInfo);
return getColumnsToBeIndexed().get(index);
}
return idxInfo;
} | java | {
"resource": ""
} |
q164194 | TableInfo.addToIndexedColumnList | train | public void addToIndexedColumnList(IndexInfo indexInfo)
{
ColumnInfo columnInfo = new ColumnInfo();
columnInfo.setColumnName(indexInfo.getColumnName());
if (getEmbeddedColumnMetadatas().isEmpty()
|| !getEmbeddedColumnMetadatas().get(0).getColumns().contains(columnInfo))
{
if (!columnToBeIndexed.contains(indexInfo))
{
columnToBeIndexed.add(indexInfo);
}
}
} | java | {
"resource": ""
} |
q164195 | EntityManagerFactoryImpl.close | train | @Override
public final void close()
{
if (isOpen())
{
closed = true;
// Shut cache provider down
if (cacheProvider != null)
{
cacheProvider.shutdown();
}
for (String pu : persistenceUnits)
{
((ClientLifeCycleManager) clientFactories.get(pu)).destroy();
}
this.persistenceUnits = null;
this.properties = null;
clientFactories.clear();
clientFactories = new ConcurrentHashMap<String, ClientFactory>();
}
else
{
throw new IllegalStateException("Entity manager factory has been closed");
}
} | java | {
"resource": ""
} |
q164196 | EntityManagerFactoryImpl.createEntityManager | train | @Override
public final EntityManager createEntityManager(Map map)
{
// For Application managed persistence context, type is always EXTENDED
if (isOpen())
{
return new EntityManagerImpl(this, map, transactionType, PersistenceContextType.EXTENDED);
}
throw new IllegalStateException("Entity manager factory has been closed.");
} | java | {
"resource": ""
} |
q164197 | EntityManagerFactoryImpl.getMetamodel | train | @Override
public Metamodel getMetamodel()
{
if (isOpen())
{
MetamodelImpl metamodel = null;
for (String pu : persistenceUnits)
{
metamodel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(pu);
if (metamodel != null)
{
return metamodel;
}
}
// return
// KunderaMetadataManager.getMetamodel(getPersistenceUnits());
}
throw new IllegalStateException("Entity manager factory has been closed.");
} | java | {
"resource": ""
} |
q164198 | EntityManagerFactoryImpl.configureClientFactories | train | private void configureClientFactories()
{
ClientMetadataBuilder builder = new ClientMetadataBuilder(getProperties(), kunderaMetadata,
getPersistenceUnits());
builder.buildClientFactoryMetadata(clientFactories, kunderaMetadata);
} | java | {
"resource": ""
} |
q164199 | EntityManagerFactoryImpl.initSecondLevelCache | train | private CacheProvider initSecondLevelCache(final PersistenceUnitMetadata puMetadata)
{
String classResourceName = (String) getProperties().get(PersistenceProperties.KUNDERA_CACHE_CONFIG_RESOURCE);
classResourceName = classResourceName != null ? classResourceName : puMetadata
.getProperty(PersistenceProperties.KUNDERA_CACHE_CONFIG_RESOURCE);
String cacheProviderClassName = (String) getProperties()
.get(PersistenceProperties.KUNDERA_CACHE_PROVIDER_CLASS);
cacheProviderClassName = cacheProviderClassName != null ? cacheProviderClassName : puMetadata
.getProperty(PersistenceProperties.KUNDERA_CACHE_PROVIDER_CLASS);
CacheProvider cacheProvider = null;
if (cacheProviderClassName != null)
{
try
{
Class<CacheProvider> cacheProviderClass = (Class<CacheProvider>) Class.forName(cacheProviderClassName);
cacheProvider = cacheProviderClass.newInstance();
cacheProvider.init(classResourceName);
}
catch (ClassNotFoundException e)
{
throw new CacheException("Could not find class " + cacheProviderClassName
+ ". Check whether you spelled it correctly in persistence.xml", e);
}
catch (InstantiationException e)
{
throw new CacheException("Could not instantiate " + cacheProviderClassName, e);
}
catch (IllegalAccessException e)
{
throw new CacheException(e);
}
}
if (cacheProvider == null)
{
cacheProvider = new NonOperationalCacheProvider();
}
return cacheProvider;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.