_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q163900 | Reader.scanClass | train | public void scanClass(InputStream bits) throws IOException
{
DataInputStream dstream = new DataInputStream(new BufferedInputStream(bits));
ClassFile cf = null;
try
{
cf = new ClassFile(dstream);
String className = cf.getName();
List<String> annotations = new ArrayList<String>();
accumulateAnnotations(annotations, (AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.visibleTag));
accumulateAnnotations(annotations,
(AnnotationsAttribute) cf.getAttribute(AnnotationsAttribute.invisibleTag));
// iterate through all valid annotations
for (String validAnn : getValidAnnotations())
{
// check if the current class has one?
if (annotations.contains(validAnn))
{
// fire all listeners
for (AnnotationDiscoveryListener listener : getAnnotationDiscoveryListeners())
{
listener.discovered(className);
}
}
}
}
finally
{
dstream.close();
bits.close();
}
} | java | {
"resource": ""
} |
q163901 | Reader.accumulateAnnotations | train | public void accumulateAnnotations(List<String> annotations, AnnotationsAttribute annatt)
{
if (null == annatt)
{
return;
}
for (Annotation ann : annatt.getAnnotations())
{
annotations.add(ann.getTypeName());
}
} | java | {
"resource": ""
} |
q163902 | Reader.getResourceIterator | train | public ResourceIterator getResourceIterator(URL url, Filter filter)
{
String urlString = url.toString();
try
{
if (urlString.endsWith("!/"))
{
urlString = urlString.substring(4);
urlString = urlString.substring(0, urlString.length() - 2);
url = new URL(urlString);
}
if (urlString.endsWith(".class"))
{
File f = new File(url.getPath());
return new ClassFileIterator(f);
}
else if (!urlString.endsWith("/"))
{
return new JarFileIterator(url.openStream(), filter);
}
else
{
if (!url.getProtocol().equals("file"))
{
throw new ResourceReadingException("Unable to understand protocol: " + url.getProtocol());
}
File f = new File(url.getPath());
if (f.isDirectory() || url.getProtocol().toUpperCase().equals(AllowedProtocol.VFS.name()))
{
return new ClassFileIterator(f, filter);
}
else
{
return new JarFileIterator(url.openStream(), filter);
}
}
}
catch (MalformedURLException e)
{
throw new ResourceReadingException(e);
}
catch (IOException e)
{
throw new ResourceReadingException(e);
}
} | java | {
"resource": ""
} |
q163903 | RedisClientFactory.getConnection | train | Jedis getConnection()
{
if (logger.isDebugEnabled())
logger.info("borrowing connection from pool");
Object poolOrConnection = getConnectionPoolOrConnection();
if (poolOrConnection != null && poolOrConnection instanceof JedisPool)
{
Jedis connection = ((JedisPool) getConnectionPoolOrConnection()).getResource();
connection.getClient().setTimeoutInfinite();
Map props = RedisPropertyReader.rsmd.getProperties();
// set external xml properties.
if (props != null)
{
// props.
for (Object key : props.keySet())
{
connection.configSet(key.toString(), props.get(key).toString());
}
}
return connection;
}
else
{
PersistenceUnitMetadata puMetadata = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(
getPersistenceUnit());
Properties props = puMetadata.getProperties();
String contactNode = null;
String defaultPort = null;
String password = null;
if (externalProperties != null)
{
contactNode = (String) externalProperties.get(PersistenceProperties.KUNDERA_NODES);
defaultPort = (String) externalProperties.get(PersistenceProperties.KUNDERA_PORT);
password = (String) externalProperties.get(PersistenceProperties.KUNDERA_PASSWORD);
}
if (contactNode == null)
{
contactNode = RedisPropertyReader.rsmd.getHost() != null ? RedisPropertyReader.rsmd.getHost()
: (String) props.get(PersistenceProperties.KUNDERA_NODES);
}
if (defaultPort == null)
{
defaultPort = RedisPropertyReader.rsmd.getPort() != null ? RedisPropertyReader.rsmd.getPort()
: (String) props.get(PersistenceProperties.KUNDERA_PORT);
}
if (password == null)
{
password = RedisPropertyReader.rsmd.getPassword() != null ? RedisPropertyReader.rsmd.getPassword()
: (String) props.get(PersistenceProperties.KUNDERA_PASSWORD);
}
if (defaultPort == null || !StringUtils.isNumeric(defaultPort))
{
throw new RuntimeException("Invalid port provided: " + defaultPort);
}
Jedis connection = new Jedis(contactNode, Integer.parseInt(defaultPort));
if (password != null)
{
connection.auth(password);
}
connection.connect();
return connection;
}
} | java | {
"resource": ""
} |
q163904 | DoubleAccessor.toLong | train | private long toLong(byte[] data)
{
if (data == null || data.length != 8)
return 0x0;
// ----------
return (long) (
// (Below) convert to longs before shift because digits
// are lost with ints beyond the 32-bit limit
(long) (0xff & data[0]) << 56 | (long) (0xff & data[1]) << 48 | (long) (0xff & data[2]) << 40
| (long) (0xff & data[3]) << 32 | (long) (0xff & data[4]) << 24 | (long) (0xff & data[5]) << 16
| (long) (0xff & data[6]) << 8 | (long) (0xff & data[7]) << 0);
} | java | {
"resource": ""
} |
q163905 | DoubleAccessor.fromLong | train | private byte[] fromLong(long data)
{
return new byte[] { (byte) ((data >> 56) & 0xff), (byte) ((data >> 48) & 0xff), (byte) ((data >> 40) & 0xff),
(byte) ((data >> 32) & 0xff), (byte) ((data >> 24) & 0xff), (byte) ((data >> 16) & 0xff),
(byte) ((data >> 8) & 0xff), (byte) ((data >> 0) & 0xff), };
} | java | {
"resource": ""
} |
q163906 | PersistenceUnitMetadata.addJarFile | train | public void addJarFile(String jarFile)
{
if (jarFiles == null)
{
jarFiles = new HashSet<String>();
}
this.jarFiles.add(jarFile);
addJarFileUrl(jarFile);
} | java | {
"resource": ""
} |
q163907 | PersistenceUnitMetadata.getManagedURLs | train | public List<URL> getManagedURLs()
{
// should we cache it?
List<URL> managedURL = getJarFileUrls();
if (managedURL == null)
{
managedURL = new ArrayList<URL>(1);
}
if (!getExcludeUnlistedClasses())
{
managedURL.add(getPersistenceUnitRootUrl());
}
return managedURL;
} | java | {
"resource": ""
} |
q163908 | PersistenceUnitMetadata.addJarFileUrl | train | private void addJarFileUrl(String jarFile)
{
if (jarUrls == null)
{
jarUrls = new HashSet<URL>();
}
try
{
jarUrls.add(new File(jarFile).toURI().toURL());
}
catch (MalformedURLException e)
{
log.error("Error while mapping jar-file url" + jarFile + "caused by:" + e.getMessage());
throw new IllegalArgumentException("Invalid jar-file URL:" + jarFile + "Caused by: " + e);
}
} | java | {
"resource": ""
} |
q163909 | PersistenceUnitMetadata.getClient | train | public String getClient()
{
String client = null;
if (this.properties != null)
{
client = (String) this.properties.get(PersistenceProperties.KUNDERA_CLIENT_FACTORY);
}
if (client == null)
{
log.error("kundera.client property is missing for persistence unit:" + persistenceUnitName);
throw new IllegalArgumentException("kundera.client property is missing for persistence unit:"
+ persistenceUnitName);
}
return client;
} | java | {
"resource": ""
} |
q163910 | PersistenceUnitMetadata.getBatchSize | train | public int getBatchSize()
{
if (isBatch())
{
String batchSize = getProperty(PersistenceProperties.KUNDERA_BATCH_SIZE);
int batch_Size = Integer.valueOf(batchSize);
if (batch_Size == 0)
{
throw new IllegalArgumentException("kundera.batch.size property must be numeric and > 0");
}
return batch_Size;
}
return 0;
} | java | {
"resource": ""
} |
q163911 | DocumentIndexer.prepareDocumentForSuperColumn | train | protected Document prepareDocumentForSuperColumn(EntityMetadata metadata, Object object, String embeddedColumnName,
String parentId, Class<?> clazz) {
Document currentDoc;
currentDoc = new Document();
// Add entity class and row key info to document
addEntityClassToDocument(metadata, object, currentDoc, null);
// Add super column name to document
addSuperColumnNameToDocument(embeddedColumnName, currentDoc);
addParentKeyToDocument(parentId, currentDoc, clazz);
return currentDoc;
} | java | {
"resource": ""
} |
q163912 | DocumentIndexer.addParentKeyToDocument | train | protected void addParentKeyToDocument(String parentId, Document currentDoc, Class<?> clazz) {
// if (parentId != null)
if (clazz != null && parentId != null) {
Field luceneField =
new Field(IndexingConstants.PARENT_ID_FIELD, parentId, Field.Store.YES, Field.Index.ANALYZED_NO_NORMS);
currentDoc.add(luceneField);
Field fieldClass =
new Field(IndexingConstants.PARENT_ID_CLASS, clazz.getCanonicalName().toLowerCase(), Field.Store.YES,
Field.Index.ANALYZED);
currentDoc.add(fieldClass);
}
} | java | {
"resource": ""
} |
q163913 | DocumentIndexer.createSuperColumnDocument | train | protected void createSuperColumnDocument(EntityMetadata metadata, Object object, Document currentDoc,
Object embeddedObject, EmbeddableType superColumn, MetamodelImpl metamodel) {
// Add all super column fields into document
Set<Attribute> attributes = superColumn.getAttributes();
Iterator<Attribute> iter = attributes.iterator();
while (iter.hasNext()) {
Attribute attr = iter.next();
java.lang.reflect.Field field = (java.lang.reflect.Field) attr.getJavaMember();
String colName = field.getName();
String indexName = metadata.getIndexName();
addFieldToDocument(embeddedObject, currentDoc, field, colName, indexName);
}
// Add all entity fields to document
addEntityFieldsToDocument(metadata, object, currentDoc, metamodel);
} | java | {
"resource": ""
} |
q163914 | DocumentIndexer.addSuperColumnNameToDocument | train | private void addSuperColumnNameToDocument(String superColumnName, Document currentDoc) {
Field luceneField = new Field(SUPERCOLUMN_INDEX, superColumnName, Store.YES, Field.Index.NO);
currentDoc.add(luceneField);
} | java | {
"resource": ""
} |
q163915 | DocumentIndexer.addEntityFieldsToDocument | train | protected void addEntityFieldsToDocument(EntityMetadata metadata, Object entity, Document document,
MetamodelImpl metaModel) {
String indexName = metadata.getIndexName();
Map<String, PropertyIndex> indexProperties = metadata.getIndexProperties();
for (String columnName : indexProperties.keySet()) {
PropertyIndex index = indexProperties.get(columnName);
java.lang.reflect.Field property = index.getProperty();
String propertyName = index.getName();
addFieldToDocument(entity, document, property, propertyName, indexName);
}
if (metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType())) {
Object id = PropertyAccessorHelper.getId(entity, metadata);
EmbeddableType embeddableId = metaModel.embeddable(metadata.getIdAttribute().getBindableJavaType());
Set<Attribute> embeddedAttributes = embeddableId.getAttributes();
indexCompositeKey(embeddedAttributes, metadata, id, document, metaModel);
}
} | java | {
"resource": ""
} |
q163916 | DocumentIndexer.addEntityClassToDocument | train | protected void addEntityClassToDocument(EntityMetadata metadata, Object entity, Document document,
final MetamodelImpl metaModel) {
try {
Field luceneField;
Object id;
id = PropertyAccessorHelper.getId(entity, metadata);
// Indexing composite keys
if (metaModel != null && metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType())) {
id = KunderaCoreUtils.prepareCompositeKey(metadata.getIdAttribute(), metaModel, id);
}
luceneField =
new Field(IndexingConstants.ENTITY_ID_FIELD, id.toString(), Field.Store.YES, Field.Index.ANALYZED);
// luceneField.set
// adding class
// namespace
// /*Field.Store.YES, Field.Index.ANALYZED_NO_NORMS*/);
document.add(luceneField);
// index namespace for unique deletion
luceneField =
new Field(IndexingConstants.KUNDERA_ID_FIELD, getKunderaId(metadata, id), Field.Store.YES,
Field.Index.ANALYZED); // adding
// class
// namespace
// Field.Store.YES/*, Field.Index.ANALYZED_NO_NORMS*/);
document.add(luceneField);
// index entity class
luceneField =
new Field(IndexingConstants.ENTITY_CLASS_FIELD, metadata.getEntityClazz().getCanonicalName()
.toLowerCase(), Field.Store.YES, Field.Index.ANALYZED);
document.add(luceneField);
//
luceneField = new Field("timestamp", System.currentTimeMillis() + "", Field.Store.YES, Field.Index.NO);
document.add(luceneField);
// index index name
luceneField =
new Field(IndexingConstants.ENTITY_INDEXNAME_FIELD, metadata.getIndexName(), Field.Store.NO,
Field.Index.ANALYZED_NO_NORMS);
document.add(luceneField);
luceneField =
new Field(getCannonicalPropertyName(metadata.getEntityClazz().getSimpleName(),
((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName()), id.toString(),
Field.Store.YES, Field.Index.ANALYZED_NO_NORMS);
document.add(luceneField);
} catch (PropertyAccessException e) {
throw new IllegalArgumentException("Id could not be read from object " + entity);
}
} | java | {
"resource": ""
} |
q163917 | DocumentIndexer.addFieldToDocument | train | private void addFieldToDocument(Object object, Document document, java.lang.reflect.Field field, String colName,
String indexName) {
try {
Object obj = PropertyAccessorHelper.getObject(object, field);
// String str =
// String value = (obj == null) ? null : obj.toString();
if (obj != null) {
Field luceneField =
new Field(getCannonicalPropertyName(indexName, colName), obj.toString(), Field.Store.YES,
Field.Index.ANALYZED_NO_NORMS);
document.add(luceneField);
} else {
LOG.warn("value is null for field" + field.getName());
}
} catch (PropertyAccessException e) {
LOG.error("Error in accessing field, Caused by:" + e.getMessage());
throw new LuceneIndexingException("Error in accessing field:" + field.getName(), e);
}
} | java | {
"resource": ""
} |
q163918 | DocumentIndexer.getKunderaId | train | protected String getKunderaId(EntityMetadata metadata, Object id) {
return metadata.getEntityClazz().getCanonicalName() + IndexingConstants.DELIMETER + id;
} | java | {
"resource": ""
} |
q163919 | OracleNoSQLClientProperties.setTimeOut | train | private void setTimeOut(Object value)
{
if (value instanceof Integer)
{
this.oracleNoSQLClient.setTimeout((Integer) value);
}
else if (value instanceof String)
{
this.oracleNoSQLClient.setTimeout(Integer.valueOf((String) value));
}
} | java | {
"resource": ""
} |
q163920 | OracleNoSQLClientProperties.setTimeUnit | train | private void setTimeUnit(Object value)
{
if (value instanceof TimeUnit)
{
this.oracleNoSQLClient.setTimeUnit((TimeUnit) value);
}
else if (value instanceof String)
{
this.oracleNoSQLClient.setTimeUnit(TimeUnit.valueOf((String) value));
}
} | java | {
"resource": ""
} |
q163921 | OracleNoSQLClientProperties.setBatchSize | train | private void setBatchSize(Object value)
{
if (value instanceof Integer)
{
this.oracleNoSQLClient.setBatchSize((Integer) value);
}
else if (value instanceof String)
{
this.oracleNoSQLClient.setBatchSize(Integer.valueOf((String) value));
}
} | java | {
"resource": ""
} |
q163922 | CassandraClientBase.populateFkey | train | protected Column populateFkey(String rlName, Object rlValue, long timestamp) throws PropertyAccessException {
Column col = new Column();
col.setName(PropertyAccessorFactory.STRING.toBytes(rlName));
col.setValue(PropertyAccessorHelper.getBytes(rlValue));
col.setTimestamp(timestamp);
return col;
} | java | {
"resource": ""
} |
q163923 | CassandraClientBase.computeEntityViaColumns | train | protected void computeEntityViaColumns(EntityMetadata m, boolean isRelation, List<String> relations,
List<Object> entities, Map<ByteBuffer, List<Column>> qResults) {
MetamodelImpl metaModel =
(MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());
EntityType entityType = metaModel.entity(m.getEntityClazz());
List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();
for (ByteBuffer key : qResults.keySet()) {
onColumn(m, isRelation, relations, entities, qResults.get(key), subManagedType, key);
}
} | java | {
"resource": ""
} |
q163924 | CassandraClientBase.computeEntityViaSuperColumns | train | protected void computeEntityViaSuperColumns(EntityMetadata m, boolean isRelation, List<String> relations,
List<Object> entities, Map<ByteBuffer, List<SuperColumn>> qResults) {
for (ByteBuffer key : qResults.keySet()) {
onSuperColumn(m, isRelation, relations, entities, qResults.get(key), key);
}
} | java | {
"resource": ""
} |
q163925 | CassandraClientBase.onSuperColumn | train | protected void onSuperColumn(EntityMetadata m, boolean isRelation, List<String> relations, List<Object> entities,
List<SuperColumn> superColumns, ByteBuffer key) {
Object e = null;
Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), key.array());
ThriftRow tr = new ThriftRow(id, m.getTableName(), new ArrayList<Column>(0), superColumns,
new ArrayList<CounterColumn>(0), new ArrayList<CounterSuperColumn>(0));
e = getDataHandler().populateEntity(tr, m, KunderaCoreUtils.getEntity(e), relations, isRelation);
if (log.isInfoEnabled()) {
log.info("Populating data for super column family of clazz {} and row key {}.", m.getEntityClazz(),
tr.getId());
}
if (e != null) {
entities.add(e);
}
} | java | {
"resource": ""
} |
q163926 | CassandraClientBase.populateCounterFkey | train | private CounterColumn populateCounterFkey(String rlName, Object rlValue) {
CounterColumn counterCol = new CounterColumn();
counterCol.setName(PropertyAccessorFactory.STRING.toBytes(rlName));
counterCol.setValue((Long) rlValue);
return counterCol;
} | java | {
"resource": ""
} |
q163927 | CassandraClientBase.deleteRecordFromCounterColumnFamily | train | protected void deleteRecordFromCounterColumnFamily(Object pKey, String tableName, EntityMetadata metadata,
ConsistencyLevel consistencyLevel) {
ColumnPath path = new ColumnPath(tableName);
Cassandra.Client conn = null;
Object pooledConnection = null;
try {
pooledConnection = getConnection();
conn = (org.apache.cassandra.thrift.Cassandra.Client) getConnection(pooledConnection);
if (log.isInfoEnabled()) {
log.info("Removing data for counter column family {}.", tableName);
}
conn.remove_counter((CassandraUtilities.toBytes(pKey, metadata.getIdAttribute().getJavaType())), path,
consistencyLevel);
} catch (Exception e) {
log.error("Error during executing delete, Caused by: .", e);
throw new PersistenceException(e);
} finally {
releaseConnection(pooledConnection);
}
} | java | {
"resource": ""
} |
q163928 | CassandraClientBase.createIndexesOnColumns | train | protected void createIndexesOnColumns(EntityMetadata m, String tableName, List<Column> columns, Class columnType) {
Object pooledConnection = null;
try {
Cassandra.Client api = null;
pooledConnection = getConnection();
api = (org.apache.cassandra.thrift.Cassandra.Client) getConnection(pooledConnection);
KsDef ksDef = api.describe_keyspace(m.getSchema());
List<CfDef> cfDefs = ksDef.getCf_defs();
// Column family definition on which secondary index creation is
// required
CfDef columnFamilyDefToUpdate = null;
boolean isUpdatable = false;
for (CfDef cfDef : cfDefs) {
if (cfDef.getName().equals(tableName)) {
columnFamilyDefToUpdate = cfDef;
break;
}
}
if (columnFamilyDefToUpdate == null) {
log.error("Join table {} not available.", tableName);
throw new PersistenceException("table" + tableName + " not found!");
}
// create a column family, in case it is not already available.
// Get list of indexes already created
List<ColumnDef> columnMetadataList = columnFamilyDefToUpdate.getColumn_metadata();
List<String> indexList = new ArrayList<String>();
if (columnMetadataList != null) {
for (ColumnDef columnDef : columnMetadataList) {
indexList.add(new StringAccessor().fromBytes(String.class, columnDef.getName()));
}
// need to set them to null else it is giving problem on update
// column family and trying to add again existing indexes.
// columnFamilyDefToUpdate.column_metadata = null;
}
// Iterate over all columns for creating secondary index on them
for (Column column : columns) {
ColumnDef columnDef = new ColumnDef();
columnDef.setName(column.getName());
columnDef.setValidation_class(CassandraValidationClassMapper.getValidationClass(columnType, false));
columnDef.setIndex_type(IndexType.KEYS);
// Add secondary index only if it's not already created
// (if already created, it would be there in column family
// definition)
if (!indexList.contains(new StringAccessor().fromBytes(String.class, column.getName()))) {
isUpdatable = true;
columnFamilyDefToUpdate.addToColumn_metadata(columnDef);
}
}
// Finally, update column family with modified column family
// definition
if (isUpdatable) {
columnFamilyDefToUpdate.setKey_validation_class(CassandraValidationClassMapper
.getValidationClass(m.getIdAttribute().getJavaType(), isCql3Enabled(m)));
api.system_update_column_family(columnFamilyDefToUpdate);
}
} catch (Exception e) {
log.warn("Could not create secondary index on column family {}, Caused by: . ", tableName, e);
} finally {
releaseConnection(pooledConnection);
}
} | java | {
"resource": ""
} |
q163929 | CassandraClientBase.find | train | public Object find(Class entityClass, Object rowId) {
EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClass);
List<String> relationNames = entityMetadata.getRelationNames();
return find(entityClass, entityMetadata, rowId, relationNames);
} | java | {
"resource": ""
} |
q163930 | CassandraClientBase.isCql3Enabled | train | public boolean isCql3Enabled(EntityMetadata metadata) {
if (metadata != null) {
MetamodelImpl metaModel =
(MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(metadata.getPersistenceUnit());
if (metaModel.isEmbeddable(metadata.getIdAttribute().getBindableJavaType())) {
return true;
}
// added for embeddables support on cql3
AbstractManagedType managedType = (AbstractManagedType) metaModel.entity(metadata.getEntityClazz());
if (managedType.hasEmbeddableAttribute()) {
return getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0);
}
if (getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0)
&& metadata.getType().equals(Type.SUPER_COLUMN_FAMILY)) {
log.warn(
"Super Columns not supported by cql, Any operation on supercolumn family will be executed using thrift, returning false.");
return false;
}
return getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0);
}
return getCqlVersion().equalsIgnoreCase(CassandraConstants.CQL_VERSION_3_0);
} | java | {
"resource": ""
} |
q163931 | CassandraClientBase.executeSelectQuery | train | public List executeSelectQuery(Class clazz, List<String> relationalField, CassandraDataHandler dataHandler,
boolean isNative, String cqlQuery) {
if (log.isDebugEnabled()) {
log.debug("Executing cql query {}.", cqlQuery);
}
List entities = new ArrayList<Object>();
EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);
MetamodelImpl metaModel =
(MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(entityMetadata.getPersistenceUnit());
EntityType entityType = metaModel.entity(entityMetadata.getEntityClazz());
List<AbstractManagedType> subManagedType = ((AbstractManagedType) entityType).getSubManagedType();
if (subManagedType.isEmpty()) {
entities.addAll(cqlClient.executeQuery(clazz, relationalField, dataHandler, true, isNative, cqlQuery));
} else {
for (AbstractManagedType subEntity : subManagedType) {
EntityMetadata subEntityMetadata =
KunderaMetadataManager.getEntityMetadata(kunderaMetadata, subEntity.getJavaType());
entities.addAll(cqlClient.executeQuery(subEntityMetadata.getEntityClazz(), relationalField, dataHandler,
true, isNative, cqlQuery));
}
}
return entities;
} | java | {
"resource": ""
} |
q163932 | CassandraClientBase.executeScalarQuery | train | public List executeScalarQuery(String cqlQuery) {
CqlResult cqlResult = null;
List results = new ArrayList();
try {
if (log.isDebugEnabled()) {
log.debug("Executing query {}.", cqlQuery);
}
cqlResult = (CqlResult) executeCQLQuery(cqlQuery, true);
if (cqlResult != null && (cqlResult.getRows() != null || cqlResult.getRowsSize() > 0)) {
results = new ArrayList<Object>(cqlResult.getRowsSize());
Iterator<CqlRow> iter = cqlResult.getRowsIterator();
while (iter.hasNext()) {
Map<String, Object> entity = new HashMap<String, Object>();
CqlRow row = iter.next();
for (Column column : row.getColumns()) {
if (column != null) {
String thriftColumnName =
PropertyAccessorFactory.STRING.fromBytes(String.class, column.getName());
if (column.getValue() == null) {
entity.put(thriftColumnName, null);
} else {
entity.put(thriftColumnName,
composeColumnValue(cqlResult.getSchema(), column.getValue(), column.getName()));
}
}
}
results.add(entity);
}
}
} catch (Exception e) {
log.error("Error while executing native CQL query Caused by {}.", e);
throw new PersistenceException(e);
}
return results;
} | java | {
"resource": ""
} |
q163933 | CassandraClientBase.composeColumnValue | train | private Object composeColumnValue(CqlMetadata cqlMetadata, byte[] thriftColumnValue, byte[] thriftColumnName) {
Map<ByteBuffer, String> schemaTypes = cqlMetadata.getValue_types();
AbstractType<?> type = null;
try {
type = TypeParser.parse(schemaTypes.get(ByteBuffer.wrap(thriftColumnName)));
} catch (SyntaxException | ConfigurationException ex) {
log.error(ex.getMessage());
throw new KunderaException("Error while deserializing column value " + ex);
}
if (type.isCollection()) {
return ((CollectionSerializer) type.getSerializer())
.deserializeForNativeProtocol(ByteBuffer.wrap(thriftColumnValue), ProtocolVersion.V2);
}
return type.compose(ByteBuffer.wrap(thriftColumnValue));
} | java | {
"resource": ""
} |
q163934 | CassandraClientBase.populateEntitiesFromKeySlices | train | protected List populateEntitiesFromKeySlices(EntityMetadata m, boolean isWrapReq, List<String> relations,
List<KeySlice> keys, CassandraDataHandler dataHandler) throws Exception {
List results;
MetamodelImpl metaModel =
(MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(m.getPersistenceUnit());
Set<String> superColumnAttribs = metaModel.getEmbeddables(m.getEntityClazz()).keySet();
results = new ArrayList(keys.size());
ThriftDataResultHelper dataGenerator = new ThriftDataResultHelper();
for (KeySlice key : keys) {
List<ColumnOrSuperColumn> columns = key.getColumns();
byte[] rowKey = key.getKey();
Object id = PropertyAccessorHelper.getObject(m.getIdAttribute().getJavaType(), rowKey);
Object e = null;
Map<ByteBuffer, List<ColumnOrSuperColumn>> data = new HashMap<ByteBuffer, List<ColumnOrSuperColumn>>(1);
data.put(ByteBuffer.wrap(rowKey), columns);
ThriftRow tr = new ThriftRow();
tr.setId(id);
tr.setColumnFamilyName(m.getTableName());
tr = dataGenerator.translateToThriftRow(data, m.isCounterColumnType(), m.getType(), tr);
e = dataHandler.populateEntity(tr, m, KunderaCoreUtils.getEntity(e), relations, isWrapReq);
if (e != null) {
results.add(e);
}
}
return results;
} | java | {
"resource": ""
} |
q163935 | CassandraClientBase.createInsertQuery | train | protected List<String> createInsertQuery(EntityMetadata entityMetadata, Object entity,
Cassandra.Client cassandra_client, List<RelationHolder> rlHolders, Object ttlColumns) {
List<String> insert_Queries = new ArrayList<String>();
CQLTranslator translator = new CQLTranslator();
HashMap<TranslationType, Map<String, StringBuilder>> translation = translator.prepareColumnOrColumnValues(
entity, entityMetadata, TranslationType.ALL, externalProperties, kunderaMetadata);
Map<String, StringBuilder> columnNamesMap = translation.get(TranslationType.COLUMN);
Map<String, StringBuilder> columnValuesMap = translation.get(TranslationType.VALUE);
for (String tableName : columnNamesMap.keySet()) {
String insert_Query = translator.INSERT_QUERY;
insert_Query = StringUtils.replace(insert_Query, CQLTranslator.COLUMN_FAMILY,
translator.ensureCase(new StringBuilder(), tableName, false).toString());
String columnNames = columnNamesMap.get(tableName).toString();
String columnValues = columnValuesMap.get(tableName).toString();
StringBuilder columnNameBuilder = new StringBuilder(columnNames);
StringBuilder columnValueBuilder = new StringBuilder(columnValues);
for (RelationHolder rl : rlHolders) {
columnValueBuilder =
onRelationColumns(columnNames, columnValues, columnNameBuilder, columnValueBuilder, rl);
columnNameBuilder.append(",");
columnValueBuilder.append(",");
translator.appendColumnName(columnNameBuilder, rl.getRelationName());
translator.appendValue(columnValueBuilder, rl.getRelationValue().getClass(), rl.getRelationValue(),
true, false);
}
insert_Query =
StringUtils.replace(insert_Query, CQLTranslator.COLUMN_VALUES, columnValueBuilder.toString());
insert_Query = StringUtils.replace(insert_Query, CQLTranslator.COLUMNS, columnNameBuilder.toString());
if (log.isDebugEnabled()) {
log.debug("Returning cql query {}.", insert_Query);
}
if (ttlColumns != null && ttlColumns instanceof Integer) {
int ttl = ((Integer) ttlColumns).intValue();
if (ttl != 0) {
insert_Query = insert_Query + " USING TTL " + ttl;
}
}
insert_Queries.add(insert_Query);
}
return insert_Queries;
} | java | {
"resource": ""
} |
q163936 | CassandraClientBase.onRelationColumns | train | private StringBuilder onRelationColumns(String columnNames, String columnValues, StringBuilder columnNameBuilder,
StringBuilder columnValueBuilder, RelationHolder rl) {
int relnameIndx = columnNameBuilder.indexOf("\"" + rl.getRelationName() + "\"");
if (relnameIndx != -1 && rl.getRelationValue() != null) {
List<String> cNameArray = Arrays.asList(columnNames.split(","));
List<String> cValueArray = new ArrayList<String>(Arrays.asList(columnValues.split(",")));
int cValueIndex = cNameArray.indexOf("\"" + rl.getRelationName() + "\"");
if (cValueArray.get(cValueIndex).equals("null")) {
columnNameBuilder.delete(relnameIndx - 1, relnameIndx + rl.getRelationName().length() + 2);
cValueArray.remove(cValueIndex);
columnValueBuilder =
new StringBuilder(cValueArray.toString().substring(1, cValueArray.toString().length() - 1));
}
}
return columnValueBuilder;
} | java | {
"resource": ""
} |
q163937 | CassandraClientBase.getPersistQueries | train | protected List<String> getPersistQueries(EntityMetadata entityMetadata, Object entity,
org.apache.cassandra.thrift.Cassandra.Client conn, List<RelationHolder> rlHolders, Object ttlColumns) {
List<String> queries;
if (entityMetadata.isCounterColumnType()) {
queries = createUpdateQueryForCounter(entityMetadata, entity, conn, rlHolders);
} else {
queries = createInsertQuery(entityMetadata, entity, conn, rlHolders, ttlColumns);
}
return queries;
} | java | {
"resource": ""
} |
q163938 | CassandraClientBase.onDeleteQuery | train | protected String onDeleteQuery(EntityMetadata metadata, String tableName, MetamodelImpl metaModel,
Object keyObject) {
CQLTranslator translator = new CQLTranslator();
String deleteQuery = CQLTranslator.DELETE_QUERY;
deleteQuery = StringUtils.replace(deleteQuery, CQLTranslator.COLUMN_FAMILY,
translator.ensureCase(new StringBuilder(), tableName, false).toString());
StringBuilder deleteQueryBuilder = new StringBuilder(deleteQuery);
deleteQueryBuilder.append(CQLTranslator.ADD_WHERE_CLAUSE);
onWhereClause(metadata, keyObject, translator, deleteQueryBuilder, metaModel, metadata.getIdAttribute());
// strip last "AND" clause.
deleteQueryBuilder.delete(deleteQueryBuilder.lastIndexOf(CQLTranslator.AND_CLAUSE),
deleteQueryBuilder.length());
if (log.isDebugEnabled()) {
log.debug("Returning delete query {}.", deleteQueryBuilder.toString());
}
return deleteQueryBuilder.toString();
} | java | {
"resource": ""
} |
q163939 | CassandraClientBase.onWhereClause | train | protected void onWhereClause(EntityMetadata metadata, Object key, CQLTranslator translator,
StringBuilder queryBuilder, MetamodelImpl metaModel, SingularAttribute attribute) {
// SingularAttribute idAttribute = metadata.getIdAttribute();
if (metaModel.isEmbeddable(attribute.getBindableJavaType())) {
Field[] fields = attribute.getBindableJavaType().getDeclaredFields();
EmbeddableType compoundKey = metaModel.embeddable(attribute.getBindableJavaType());
for (Field field : fields) {
if (field != null && !Modifier.isStatic(field.getModifiers())
&& !Modifier.isTransient(field.getModifiers()) && !field.isAnnotationPresent(Transient.class)) {
attribute = (SingularAttribute) compoundKey.getAttribute(field.getName());
Object valueObject = PropertyAccessorHelper.getObject(key, field);
if (metaModel.isEmbeddable(((AbstractAttribute) attribute).getBindableJavaType())) {
onWhereClause(metadata, valueObject, translator, queryBuilder, metaModel, attribute);
} else {
String columnName = ((AbstractAttribute) attribute).getJPAColumnName();
translator.buildWhereClause(queryBuilder, field.getType(), columnName, valueObject,
CQLTranslator.EQ_CLAUSE, false);
}
}
}
} else {
translator.buildWhereClause(
queryBuilder, ((AbstractAttribute) attribute).getBindableJavaType(), CassandraUtilities
.getIdColumnName(kunderaMetadata, metadata, getExternalProperties(), isCql3Enabled(metadata)),
key, translator.EQ_CLAUSE, false);
}
} | java | {
"resource": ""
} |
q163940 | CassandraClientBase.getRawClient | train | public Cassandra.Client getRawClient(final String schema) {
Cassandra.Client client = null;
Object pooledConnection;
pooledConnection = getConnection();
client = (org.apache.cassandra.thrift.Cassandra.Client) getConnection(pooledConnection);
try {
client.set_cql_version(getCqlVersion());
} catch (Exception e) {
log.error("Error during borrowing a connection , Caused by: {}.", e);
throw new KunderaException(e);
} finally {
releaseConnection(pooledConnection);
}
return client;
} | java | {
"resource": ""
} |
q163941 | CassandraClientBase.executeCQLQuery | train | protected Object executeCQLQuery(String cqlQuery, boolean isCql3Enabled) {
Cassandra.Client conn = null;
Object pooledConnection = null;
pooledConnection = getConnection();
conn = (org.apache.cassandra.thrift.Cassandra.Client) getConnection(pooledConnection);
try {
if (isCql3Enabled || isCql3Enabled()) {
return execute(cqlQuery, conn);
}
KunderaCoreUtils.printQuery(cqlQuery, showQuery);
if (log.isDebugEnabled()) {
log.debug("Executing cql query {}.", cqlQuery);
}
return conn.execute_cql_query(ByteBufferUtil.bytes(cqlQuery), org.apache.cassandra.thrift.Compression.NONE);
} catch (Exception ex) {
if (log.isErrorEnabled()) {
log.error("Error during executing query {}, Caused by: {} .", cqlQuery, ex);
}
throw new PersistenceException(ex);
} finally {
releaseConnection(pooledConnection);
}
} | java | {
"resource": ""
} |
q163942 | CassandraClientBase.populateCqlVersion | train | private void populateCqlVersion(Map<String, Object> externalProperties) {
String cqlVersion =
externalProperties != null ? (String) externalProperties.get(CassandraConstants.CQL_VERSION) : null;
if (cqlVersion == null || !(cqlVersion != null && (cqlVersion.equals(CassandraConstants.CQL_VERSION_2_0)
|| cqlVersion.equals(CassandraConstants.CQL_VERSION_3_0)))) {
cqlVersion = (CassandraPropertyReader.csmd != null ? CassandraPropertyReader.csmd.getCqlVersion()
: CassandraConstants.CQL_VERSION_2_0);
}
if (cqlVersion.equals(CassandraConstants.CQL_VERSION_3_0)) {
setCqlVersion(CassandraConstants.CQL_VERSION_3_0);
} else {
setCqlVersion(CassandraConstants.CQL_VERSION_2_0);
}
} | java | {
"resource": ""
} |
q163943 | CassandraClientBase.execute | train | public <T> T execute(final String query, final Object connection,
final List<KunderaQuery.BindParameter> parameters) {
throw new KunderaException("not implemented");
} | java | {
"resource": ""
} |
q163944 | CassandraClientBase.persistJoinTableByCql | train | protected void persistJoinTableByCql(JoinTableData joinTableData, Cassandra.Client conn) {
String joinTableName = joinTableData.getJoinTableName();
String invJoinColumnName = joinTableData.getInverseJoinColumnName();
Map<Object, Set<Object>> joinTableRecords = joinTableData.getJoinTableRecords();
EntityMetadata entityMetadata =
KunderaMetadataManager.getEntityMetadata(kunderaMetadata, joinTableData.getEntityClass());
// need to bring in an insert query for this
// add columns & execute query
CQLTranslator translator = new CQLTranslator();
String batch_Query = CQLTranslator.BATCH_QUERY;
String insert_Query = translator.INSERT_QUERY;
StringBuilder builder = new StringBuilder();
builder.append(CQLTranslator.DEFAULT_KEY_NAME);
builder.append(CQLTranslator.COMMA_STR);
builder.append(translator.ensureCase(new StringBuilder(), joinTableData.getJoinColumnName(), false));
builder.append(CQLTranslator.COMMA_STR);
builder.append(translator.ensureCase(new StringBuilder(), joinTableData.getInverseJoinColumnName(), false));
insert_Query = StringUtils.replace(insert_Query, CQLTranslator.COLUMN_FAMILY,
translator.ensureCase(new StringBuilder(), joinTableName, false).toString());
insert_Query = StringUtils.replace(insert_Query, CQLTranslator.COLUMNS, builder.toString());
StringBuilder columnValueBuilder = new StringBuilder();
StringBuilder statements = new StringBuilder();
// insert query for each row key
for (Object key : joinTableRecords.keySet()) {
PropertyAccessor accessor =
PropertyAccessorFactory.getPropertyAccessor((Field) entityMetadata.getIdAttribute().getJavaMember());
Set<Object> values = joinTableRecords.get(key); // join column value
for (Object value : values) {
if (value != null) {
String insertQuery = insert_Query;
columnValueBuilder.append(CQLTranslator.QUOTE_STR);
columnValueBuilder.append(
PropertyAccessorHelper.getString(key) + "\001" + PropertyAccessorHelper.getString(value));
columnValueBuilder.append(CQLTranslator.QUOTE_STR);
columnValueBuilder.append(CQLTranslator.COMMA_STR);
translator.appendValue(columnValueBuilder, key.getClass(), key, true, false);
columnValueBuilder.append(CQLTranslator.COMMA_STR);
translator.appendValue(columnValueBuilder, value.getClass(), value, true, false);
insertQuery =
StringUtils.replace(insertQuery, CQLTranslator.COLUMN_VALUES, columnValueBuilder.toString());
statements.append(insertQuery);
statements.append(" ");
}
}
}
if (!StringUtils.isBlank(statements.toString())) {
batch_Query = StringUtils.replace(batch_Query, CQLTranslator.STATEMENT, statements.toString());
StringBuilder batchBuilder = new StringBuilder();
batchBuilder.append(batch_Query);
batchBuilder.append(CQLTranslator.APPLY_BATCH);
execute(batchBuilder.toString(), conn);
}
} | java | {
"resource": ""
} |
q163945 | CassandraClientBase.getColumnsByIdUsingCql | train | protected <E> List<E> getColumnsByIdUsingCql(String schemaName, String tableName, String pKeyColumnName,
String columnName, Object pKeyColumnValue, Class columnJavaType) {
// select columnName from tableName where pKeyColumnName =
// pKeyColumnValue
List results = new ArrayList();
CQLTranslator translator = new CQLTranslator();
String selectQuery = translator.SELECT_QUERY;
selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMN_FAMILY,
translator.ensureCase(new StringBuilder(), tableName, false).toString());
selectQuery = StringUtils.replace(selectQuery, CQLTranslator.COLUMNS,
translator.ensureCase(new StringBuilder(), columnName, false).toString());
StringBuilder selectQueryBuilder = new StringBuilder(selectQuery);
selectQueryBuilder.append(CQLTranslator.ADD_WHERE_CLAUSE);
translator.buildWhereClause(selectQueryBuilder, columnJavaType, pKeyColumnName, pKeyColumnValue,
CQLTranslator.EQ_CLAUSE, false);
selectQueryBuilder.delete(selectQueryBuilder.lastIndexOf(CQLTranslator.AND_CLAUSE),
selectQueryBuilder.length());
CqlResult cqlResult = execute(selectQueryBuilder.toString(), getRawClient(schemaName));
Iterator<CqlRow> rowIter = cqlResult.getRows().iterator();
while (rowIter.hasNext()) {
CqlRow row = rowIter.next();
if (!row.getColumns().isEmpty()) {
Column column = row.getColumns().get(0);
Object columnValue = CassandraDataTranslator.decompose(columnJavaType, column.getValue(), true);
results.add(columnValue);
}
}
return results;
} | java | {
"resource": ""
} |
q163946 | CassandraClientBase.findIdsByColumnUsingCql | train | protected <E> List<E> findIdsByColumnUsingCql(String schemaName, String tableName, String pKeyName,
String columnName, Object columnValue, Class entityClazz) {
EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityClazz);
return getColumnsByIdUsingCql(schemaName, tableName, columnName,
((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName(), columnValue,
metadata.getIdAttribute().getBindableJavaType());
} | java | {
"resource": ""
} |
q163947 | EntityAnnotationRule.checkValidClass | train | private boolean checkValidClass(Class<?> clazz) {
return clazz.isAnnotationPresent(Entity.class) || clazz.isAnnotationPresent(MappedSuperclass.class)
|| clazz.isAnnotationPresent(Embeddable.class);
} | java | {
"resource": ""
} |
q163948 | ESResponseWrapper.parseResponse | train | public List parseResponse(SearchResponse response, AbstractAggregationBuilder aggregation, String[] fieldsToSelect,
MetamodelImpl metaModel, Class clazz, final EntityMetadata entityMetadata, KunderaQuery query)
{
logger.debug("Response of query: " + response);
List results = new ArrayList();
EntityType entityType = metaModel.entity(clazz);
if (aggregation == null)
{
SearchHits hits = response.getHits();
if (fieldsToSelect != null && fieldsToSelect.length > 1 && !(fieldsToSelect[1] == null))
{
for (SearchHit hit : hits.getHits())
{
if (fieldsToSelect.length == 2)
{
results.add(hit
.getFields()
.get(((AbstractAttribute) metaModel.entity(clazz).getAttribute(fieldsToSelect[1]))
.getJPAColumnName()).getValue());
}
else
{
List temp = new ArrayList();
for (int i = 1; i < fieldsToSelect.length; i++)
{
temp.add(hit
.getFields()
.get(((AbstractAttribute) metaModel.entity(clazz).getAttribute(fieldsToSelect[i]))
.getJPAColumnName()).getValue());
}
results.add(temp);
}
}
}
else
{
results = getEntityObjects(clazz, entityMetadata, entityType, hits);
}
}
else
{
results = parseAggregatedResponse(response, query, metaModel, clazz, entityMetadata);
}
return results;
} | java | {
"resource": ""
} |
q163949 | ESResponseWrapper.parseAggregatedResponse | train | private List parseAggregatedResponse(SearchResponse response, KunderaQuery query, MetamodelImpl metaModel,
Class clazz, EntityMetadata entityMetadata)
{
List results, temp = new ArrayList<>();
InternalAggregations internalAggs = ((InternalFilter) response.getAggregations().getAsMap()
.get(ESConstants.AGGREGATION_NAME)).getAggregations();
if (query.isSelectStatement() && KunderaQueryUtils.hasGroupBy(query.getJpqlExpression()))
{
Terms buckets = (Terms) (internalAggs).getAsMap().get(ESConstants.GROUP_BY);
filterBuckets(buckets, query);
results = onIterateBuckets(buckets, query, metaModel, clazz, entityMetadata);
}
else
{
results = new ArrayList<>();
temp = buildRecords(internalAggs, response.getHits(), query, metaModel, clazz, entityMetadata);
for (Object value : temp)
{
if (!value.toString().equalsIgnoreCase(ESConstants.INFINITY))
{
results.add(value);
}
}
}
return results;
} | java | {
"resource": ""
} |
q163950 | ESResponseWrapper.onIterateBuckets | train | private List onIterateBuckets(Terms buckets, KunderaQuery query, MetamodelImpl metaModel, Class clazz,
EntityMetadata entityMetadata)
{
List temp, results = new ArrayList<>();
for (Terms.Bucket entry : buckets.getBuckets())
{
logger.debug("key [{}], doc_count [{}]", entry.getKey(), entry.getDocCount());
Aggregations aggregations = entry.getAggregations();
TopHits topHits = aggregations.get(ESConstants.TOP_HITS);
temp = buildRecords((InternalAggregations) aggregations, topHits.getHits(), query, metaModel, clazz,
entityMetadata);
results.add(temp.size() == 1 ? temp.get(0) : temp);
}
return results;
} | java | {
"resource": ""
} |
q163951 | ESResponseWrapper.parseAggregations | train | public Map<String, Object> parseAggregations(SearchResponse response, KunderaQuery query, MetamodelImpl metaModel,
Class clazz, EntityMetadata m)
{
Map<String, Object> aggregationsMap = new LinkedHashMap<>();
if (query.isAggregated() == true && response.getAggregations() != null)
{
InternalAggregations internalAggs = ((InternalFilter) response.getAggregations().getAsMap()
.get(ESConstants.AGGREGATION_NAME)).getAggregations();
ListIterable<Expression> iterable = getSelectExpressionOrder(query);
if (query.isSelectStatement() && KunderaQueryUtils.hasGroupBy(query.getJpqlExpression()))
{
Terms buckets = (Terms) (internalAggs).getAsMap().get(ESConstants.GROUP_BY);
filterBuckets(buckets, query);
for (Terms.Bucket bucket : buckets.getBuckets())
{
logger.debug("key [{}], doc_count [{}]", bucket.getKey(), bucket.getDocCount());
TopHits topHits = bucket.getAggregations().get(ESConstants.TOP_HITS);
aggregationsMap.put(topHits.getHits().getAt(0).getId(),
buildRecords(iterable, (InternalAggregations) bucket.getAggregations()));
}
}
else
{
aggregationsMap = buildRecords(iterable, internalAggs);
}
}
return aggregationsMap;
} | java | {
"resource": ""
} |
q163952 | ESResponseWrapper.buildRecords | train | private Map<String, Object> buildRecords(ListIterable<Expression> iterable, InternalAggregations internalAgg)
{
Map<String, Object> temp = new HashMap<>();
Iterator<Expression> itr = iterable.iterator();
while (itr.hasNext())
{
Expression exp = itr.next();
if (AggregateFunction.class.isAssignableFrom(exp.getClass()))
{
Object value = getAggregatedResult(internalAgg, ((AggregateFunction) exp).getIdentifier(), exp);
if (!value.toString().equalsIgnoreCase(ESConstants.INFINITY))
{
temp.put(exp.toParsedText(), Double.valueOf(value.toString()));
}
}
}
return temp;
} | java | {
"resource": ""
} |
q163953 | ESResponseWrapper.buildRecords | train | private List buildRecords(InternalAggregations internalAgg, SearchHits topHits, KunderaQuery query,
MetamodelImpl metaModel, Class clazz, EntityMetadata entityMetadata)
{
List temp = new ArrayList<>();
Iterator<Expression> orderIterator = getSelectExpressionOrder(query).iterator();
while (orderIterator.hasNext())
{
Expression exp = orderIterator.next();
String text = exp.toActualText();
String field = KunderaQueryUtils.isAggregatedExpression(exp) ? text.substring(
text.indexOf(ESConstants.DOT) + 1, text.indexOf(ESConstants.RIGHT_BRACKET)) : text.substring(
text.indexOf(ESConstants.DOT) + 1, text.length());
temp.add(KunderaQueryUtils.isAggregatedExpression(exp) ? getAggregatedResult(internalAgg,
((AggregateFunction) exp).getIdentifier(), exp) : getFirstResult(query, field, topHits, clazz,
metaModel, entityMetadata));
}
return temp;
} | java | {
"resource": ""
} |
q163954 | ESResponseWrapper.filterBuckets | train | private Terms filterBuckets(Terms buckets, KunderaQuery query)
{
Expression havingClause = query.getSelectStatement().getHavingClause();
if (!(havingClause instanceof NullExpression) && havingClause != null)
{
Expression conditionalExpression = ((HavingClause) havingClause).getConditionalExpression();
for (Iterator<Bucket> bucketIterator = buckets.getBuckets().iterator(); bucketIterator.hasNext();)
{
InternalAggregations internalAgg = (InternalAggregations) bucketIterator.next().getAggregations();
if (!isValidBucket(internalAgg, query, conditionalExpression))
{
bucketIterator.remove();
}
}
}
return buckets;
} | java | {
"resource": ""
} |
q163955 | ESResponseWrapper.isValidBucket | train | private boolean isValidBucket(InternalAggregations internalAgg, KunderaQuery query, Expression conditionalExpression)
{
if (conditionalExpression instanceof ComparisonExpression)
{
Expression expression = ((ComparisonExpression) conditionalExpression).getLeftExpression();
Object leftValue = getAggregatedResult(internalAgg, ((AggregateFunction) expression).getIdentifier(),
expression);
String rightValue = ((ComparisonExpression) conditionalExpression).getRightExpression().toParsedText();
return validateBucket(leftValue.toString(), rightValue,
((ComparisonExpression) conditionalExpression).getIdentifier());
}
else if (LogicalExpression.class.isAssignableFrom(conditionalExpression.getClass()))
{
Expression leftExpression = null, rightExpression = null;
if (conditionalExpression instanceof AndExpression)
{
AndExpression andExpression = (AndExpression) conditionalExpression;
leftExpression = andExpression.getLeftExpression();
rightExpression = andExpression.getRightExpression();
}
else
{
OrExpression orExpression = (OrExpression) conditionalExpression;
leftExpression = orExpression.getLeftExpression();
rightExpression = orExpression.getRightExpression();
}
return validateBucket(isValidBucket(internalAgg, query, leftExpression),
isValidBucket(internalAgg, query, rightExpression),
((LogicalExpression) conditionalExpression).getIdentifier());
}
else
{
logger.error("Expression " + conditionalExpression + " in having clause is not supported in Kundera");
throw new UnsupportedOperationException(conditionalExpression
+ " in having clause is not supported in Kundera");
}
} | java | {
"resource": ""
} |
q163956 | ESResponseWrapper.getFirstResult | train | private Object getFirstResult(KunderaQuery query, String field, SearchHits hits, Class clazz, Metamodel metaModel,
EntityMetadata entityMetadata)
{
Object entity;
if (query.getEntityAlias().equals(field))
{
entity = getEntityObjects(clazz, entityMetadata, metaModel.entity(clazz), hits).get(0);
}
else
{
String jpaField = ((AbstractAttribute) metaModel.entity(clazz).getAttribute(field)).getJPAColumnName();
entity = query.getSelectStatement().hasGroupByClause() ? hits.getAt(0).sourceAsMap().get(jpaField) : hits
.getAt(0).getFields().get(jpaField).getValue();
}
return entity;
} | java | {
"resource": ""
} |
q163957 | ESResponseWrapper.getAggregatedResult | train | private Object getAggregatedResult(InternalAggregations internalAggs, String identifier, Expression exp)
{
switch (identifier)
{
case Expression.MIN:
return (((InternalMin) internalAggs.get(exp.toParsedText())).getValue());
case Expression.MAX:
return (((InternalMax) internalAggs.get(exp.toParsedText())).getValue());
case Expression.AVG:
return (((InternalAvg) internalAggs.get(exp.toParsedText())).getValue());
case Expression.SUM:
return (((InternalSum) internalAggs.get(exp.toParsedText())).getValue());
case Expression.COUNT:
return (((InternalValueCount) internalAggs.get(exp.toParsedText())).getValue());
}
throw new KunderaException("No support for " + identifier + " aggregation.");
} | java | {
"resource": ""
} |
q163958 | ESResponseWrapper.wrapFindResult | train | public Object wrapFindResult(Map<String, Object> searchResults, EntityType entityType, Object result,
EntityMetadata metadata, boolean b)
{
return wrap(searchResults, entityType, result, metadata, b);
} | java | {
"resource": ""
} |
q163959 | ESResponseWrapper.onEnum | train | private Object onEnum(Attribute attribute, Object fieldValue)
{
if (((Field) attribute.getJavaMember()).getType().isEnum())
{
EnumAccessor accessor = new EnumAccessor();
fieldValue = accessor.fromString(((AbstractAttribute) attribute).getBindableJavaType(),
fieldValue.toString());
}
return fieldValue;
} | java | {
"resource": ""
} |
q163960 | ESResponseWrapper.onId | train | private Object onId(Object key, Attribute attribute, Object fieldValue)
{
if (SingularAttribute.class.isAssignableFrom(attribute.getClass()) && ((SingularAttribute) attribute).isId())
{
key = fieldValue;
}
return key;
} | java | {
"resource": ""
} |
q163961 | ESResponseWrapper.getSelectExpressionOrder | train | public ListIterable<Expression> getSelectExpressionOrder(KunderaQuery query)
{
if (!KunderaQueryUtils.isSelectStatement(query.getJpqlExpression()))
{
return null;
}
Expression selectExpression = ((SelectClause) (query.getSelectStatement()).getSelectClause())
.getSelectExpression();
List<Expression> list;
if (!(selectExpression instanceof CollectionExpression))
{
list = new LinkedList<Expression>();
list.add(selectExpression);
return new SnapshotCloneListIterable<Expression>(list);
}
else
{
return selectExpression.children();
}
} | java | {
"resource": ""
} |
q163962 | ESResponseWrapper.getEntityObjects | train | private List getEntityObjects(Class clazz, final EntityMetadata entityMetadata, EntityType entityType,
SearchHits hits)
{
List results = new ArrayList();
Object entity = null;
for (SearchHit hit : hits.getHits())
{
entity = KunderaCoreUtils.createNewInstance(clazz);
Map<String, Object> hitResult = hit.sourceAsMap();
results.add(wrap(hitResult, entityType, entity, entityMetadata, false));
}
return results;
} | java | {
"resource": ""
} |
q163963 | MetaModelBuilder.isPluralAttribute | train | private boolean isPluralAttribute(Field attribute)
{
return attribute.getType().equals(Collection.class) || attribute.getType().equals(Set.class)
|| attribute.getType().equals(List.class) || attribute.getType().equals(Map.class);
} | java | {
"resource": ""
} |
q163964 | MetaModelBuilder.getPersistentAttributeType | train | static PersistentAttributeType getPersistentAttributeType(Field member)
{
PersistentAttributeType attributeType = PersistentAttributeType.BASIC;
if (member.isAnnotationPresent(ElementCollection.class))
{
attributeType = PersistentAttributeType.ELEMENT_COLLECTION;
}
else if (member.isAnnotationPresent(OneToMany.class))
{
attributeType = PersistentAttributeType.ONE_TO_MANY;
}
else if (member.isAnnotationPresent(ManyToMany.class))
{
attributeType = PersistentAttributeType.MANY_TO_MANY;
}
else if (member.isAnnotationPresent(ManyToOne.class))
{
attributeType = PersistentAttributeType.MANY_TO_ONE;
}
else if (member.isAnnotationPresent(OneToOne.class))
{
attributeType = PersistentAttributeType.ONE_TO_ONE;
}
else if (member.isAnnotationPresent(Embedded.class))
{
attributeType = PersistentAttributeType.EMBEDDED;
}
return attributeType;
} | java | {
"resource": ""
} |
q163965 | MetaModelBuilder.buildManagedType | train | private <X> AbstractManagedType<X> buildManagedType(Class<X> clazz, boolean isIdClass)
{
AbstractManagedType<X> managedType = null;
if (clazz.isAnnotationPresent(Embeddable.class))
{
validate(clazz, true);
if (!embeddables.containsKey(clazz))
{
managedType = new DefaultEmbeddableType<X>(clazz, PersistenceType.EMBEDDABLE, getType(
clazz.getSuperclass(), isIdClass));
onDeclaredFields(clazz, managedType);
embeddables.put(clazz, managedType);
}
else
{
managedType = (AbstractManagedType<X>) embeddables.get(clazz);
}
}
else if (clazz.isAnnotationPresent(MappedSuperclass.class))
{
validate(clazz, false);
// if (!mappedSuperClassTypes.containsKey(clazz))
// {
managedType = new DefaultMappedSuperClass<X>(clazz, PersistenceType.MAPPED_SUPERCLASS,
(AbstractIdentifiableType) getType(clazz.getSuperclass(), isIdClass));
onDeclaredFields(clazz, managedType);
mappedSuperClassTypes.put(clazz, (MappedSuperclassType<?>) managedType);
// }
// else
// {
// managedType = (AbstractManagedType<X>)
// mappedSuperClassTypes.get(clazz);
// }
}
else if (clazz.isAnnotationPresent(Entity.class) || isIdClass)
{
if (!managedTypes.containsKey(clazz))
{
managedType = new DefaultEntityType<X>(clazz, PersistenceType.ENTITY,
(AbstractIdentifiableType) getType(clazz.getSuperclass(), isIdClass));
// in case of @IdClass, it is a temporary managed type.
if (!isIdClass)
{
managedTypes.put(clazz, (EntityType<?>) managedType);
}
}
else
{
managedType = (AbstractManagedType<X>) managedTypes.get(clazz);
}
}
return managedType;
} | java | {
"resource": ""
} |
q163966 | MetaModelBuilder.getType | train | private AbstractManagedType getType(Class clazz, boolean isIdClass)
{
if (clazz != null && !clazz.equals(Object.class))
{
return processInternal(clazz, isIdClass);
}
return null;
} | java | {
"resource": ""
} |
q163967 | MetaModelBuilder.onDeclaredFields | train | private <X> void onDeclaredFields(Class<X> clazz, AbstractManagedType<X> managedType)
{
Field[] embeddedFields = clazz.getDeclaredFields();
for (Field f : embeddedFields)
{
if (isNonTransient(f))
{
new TypeBuilder<T>(f).build(managedType, f.getType());
}
}
} | java | {
"resource": ""
} |
q163968 | KuduDBClient.addPredicatesToScannerBuilder | train | private void addPredicatesToScannerBuilder(KuduScannerBuilder scannerBuilder, EmbeddableType embeddable,
Field[] fields, MetamodelImpl metaModel, Object key)
{
for (Field f : fields)
{
if (!ReflectUtils.isTransientOrStatic(f))
{
Object value = PropertyAccessorHelper.getObject(key, f);
if (f.getType().isAnnotationPresent(Embeddable.class))
{
// nested
addPredicatesToScannerBuilder(scannerBuilder, (EmbeddableType) metaModel.embeddable(f.getType()),
f.getType().getDeclaredFields(), metaModel, value);
}
else
{
Attribute attribute = embeddable.getAttribute(f.getName());
Type type = KuduDBValidationClassMapper.getValidTypeForClass(f.getType());
ColumnSchema column = new ColumnSchema.ColumnSchemaBuilder(
((AbstractAttribute) attribute).getJPAColumnName(), type).build();
KuduPredicate predicate = KuduDBDataHandler.getEqualComparisonPredicate(column, type, value);
scannerBuilder.addPredicate(predicate);
}
}
}
} | java | {
"resource": ""
} |
q163969 | KuduDBClient.populateEmbeddedColumn | train | private void populateEmbeddedColumn(Object entity, RowResult result, EmbeddableType embeddable,
MetamodelImpl metaModel)
{
Set<Attribute> attributes = embeddable.getAttributes();
Iterator<Attribute> iterator = attributes.iterator();
iterateAndPopulateEntity(entity, result, metaModel, iterator);
} | java | {
"resource": ""
} |
q163970 | KuduDBClient.deleteByColumn | train | @Override
public void deleteByColumn(String schemaName, String tableName, String columnName, Object columnValue)
{ // TODO Auto-generated method stub
} | java | {
"resource": ""
} |
q163971 | KuduDBClient.populatePartialRow | train | private void populatePartialRow(PartialRow row, 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();
iterateAndPopulateRow(row, entity, metaModel, iterator);
} | java | {
"resource": ""
} |
q163972 | KuduDBClient.populatePartialRowForEmbeddedColumn | train | private void populatePartialRowForEmbeddedColumn(PartialRow row, EmbeddableType embeddable, Object EmbEntity,
MetamodelImpl metaModel)
{
Set<Attribute> attributes = embeddable.getAttributes();
Iterator<Attribute> iterator = attributes.iterator();
iterateAndPopulateRow(row, EmbEntity, metaModel, iterator);
} | java | {
"resource": ""
} |
q163973 | KuduDBClient.iterateAndPopulateRow | train | private void iterateAndPopulateRow(PartialRow row, Object entity, MetamodelImpl metaModel,
Iterator<Attribute> iterator)
{
while (iterator.hasNext())
{
Attribute attribute = iterator.next();
Field field = (Field) attribute.getJavaMember();
Object value = PropertyAccessorHelper.getObject(entity, field);
if (attribute.getJavaType().isAnnotationPresent(Embeddable.class))
{
EmbeddableType emb = metaModel.embeddable(attribute.getJavaType());
populatePartialRowForEmbeddedColumn(row, emb, value, metaModel);
}
else
{
Type type = KuduDBValidationClassMapper.getValidTypeForClass(field.getType());
if (type != null)
{
KuduDBDataHandler.addToRow(row, ((AbstractAttribute) attribute).getJPAColumnName(), value, type);
}
}
}
} | java | {
"resource": ""
} |
q163974 | KuduDBClient.addPrimaryKeyToRow | train | private void addPrimaryKeyToRow(PartialRow row, EmbeddableType embeddable, Field[] fields, MetamodelImpl metaModel,
Object key)
{
for (Field f : fields)
{
if (!ReflectUtils.isTransientOrStatic(f))
{
Object value = PropertyAccessorHelper.getObject(key, f);
if (f.getType().isAnnotationPresent(Embeddable.class))
{
// nested
addPrimaryKeyToRow(row, (EmbeddableType) metaModel.embeddable(f.getType()),
f.getType().getDeclaredFields(), metaModel, value);
}
else
{
Attribute attribute = embeddable.getAttribute(f.getName());
Type type = KuduDBValidationClassMapper.getValidTypeForClass(f.getType());
KuduDBDataHandler.addToRow(row, ((AbstractAttribute) attribute).getJPAColumnName(), value, type);
}
}
}
} | java | {
"resource": ""
} |
q163975 | PersistenceDelegator.findById | train | public <E> E findById(final Class<E> entityClass, final Object primaryKey)
{
E e = find(entityClass, primaryKey);
if (e == null)
{
return null;
}
// Return a copy of this entity
return (E) (e);
} | java | {
"resource": ""
} |
q163976 | PersistenceDelegator.remove | train | public void remove(Object e)
{
// Invoke Pre Remove Events
// TODO Check for validity also as per JPA
if (e == null)
{
throw new IllegalArgumentException("Entity to be removed must not be null.");
}
EntityMetadata metadata = getMetadata(e.getClass());
// Create an object graph of the entity object
ObjectGraph graph = new GraphGenerator().generateGraph(e, this, new ManagedState());
Node node = graph.getHeadNode();
try
{
lock.writeLock().lock();
// TODO : push into action queue, get original end-point from
// persistenceContext first!
// Action/ExecutionQueue/ActivityQueue :-> id, name, EndPoint,
// changed
// state
// Change state of node, after successful flush processing.
node.setPersistenceDelegator(this);
node.remove();
// build flush stack.
flushManager.buildFlushStack(node, EventType.DELETE);
// Flush node.
flush();
}
finally
{
lock.writeLock().unlock();
}
// clear out graph
graph.clear();
graph = null;
if (log.isDebugEnabled())
{
log.debug("Data removed successfully for entity : " + e.getClass());
}
} | java | {
"resource": ""
} |
q163977 | PersistenceDelegator.detach | train | public void detach(Object entity)
{
Node node = getPersistenceCache().getMainCache().getNodeFromCache(entity, getMetadata(entity.getClass()), this);
if (node != null)
{
node.detach();
}
} | java | {
"resource": ""
} |
q163978 | PersistenceDelegator.contains | train | boolean contains(Object entity)
{
Node node = getPersistenceCache().getMainCache().getNodeFromCache(entity, getMetadata(entity.getClass()), this);
return node != null && node.isInState(ManagedState.class);
} | java | {
"resource": ""
} |
q163979 | PersistenceDelegator.refresh | train | public void refresh(Object entity)
{
if (contains(entity))
{
MainCache mainCache = (MainCache) getPersistenceCache().getMainCache();
Node node = mainCache.getNodeFromCache(entity, getMetadata(entity.getClass()), this);
// Locking as it might read from persistence context.
try
{
lock.readLock().lock();
node.setPersistenceDelegator(this);
node.refresh();
}
finally
{
lock.readLock().unlock();
}
}
else
{
throw new IllegalArgumentException("This is not a valid or managed entity, can't be refreshed");
}
} | java | {
"resource": ""
} |
q163980 | PersistenceDelegator.populateClientProperties | train | void populateClientProperties(Map properties)
{
if (properties != null && !properties.isEmpty())
{
Map<String, Client> clientMap = getDelegate();
if (!clientMap.isEmpty())
{
// TODO If we have two pu for same client then? Need to discuss
// with Amresh.
for (Client client : clientMap.values())
{
if (client instanceof ClientPropertiesSetter)
{
ClientPropertiesSetter cps = (ClientPropertiesSetter) client;
cps.populateClientProperties(client, properties);
}
}
}
}
else
{
if (log.isDebugEnabled())
{
log.debug("Can't set Client properties as None/ Null was supplied");
}
}
} | java | {
"resource": ""
} |
q163981 | PersistenceDelegator.loadClient | train | void loadClient(String persistenceUnit, Client client)
{
if (!clientMap.containsKey(persistenceUnit) && client != null)
{
clientMap.put(persistenceUnit, client);
}
} | java | {
"resource": ""
} |
q163982 | PersistenceDelegator.execute | train | private void execute()
{
for (Client client : clientMap.values())
{
if (client != null && client instanceof Batcher)
{
// if no batch operation performed{may be running in
// transaction?}
if (((Batcher) client).getBatchSize() == 0 || ((Batcher) client).executeBatch() > 0)
{
flushJoinTableData();
}
}
}
} | java | {
"resource": ""
} |
q163983 | PersistenceDelegator.flushJoinTableData | train | private void flushJoinTableData()
{
if (applyFlush())
{
for (JoinTableData jtData : flushManager.getJoinTableData())
{
if (!jtData.isProcessed())
{
EntityMetadata m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata,
jtData.getEntityClass());
Client client = getClient(m);
if (OPERATION.INSERT.equals(jtData.getOperation()))
{
client.persistJoinTable(jtData);
jtData.setProcessed(true);
}
else if (OPERATION.DELETE.equals(jtData.getOperation()))
{
for (Object pk : jtData.getJoinTableRecords().keySet())
{
client.deleteByColumn(m.getSchema(), jtData.getJoinTableName(),
jtData.getJoinColumnName(), pk);
}
jtData.setProcessed(true);
}
}
}
}
} | java | {
"resource": ""
} |
q163984 | PersistenceDelegator.getCoordinator | train | Coordinator getCoordinator()
{
coordinator = new Coordinator();
try
{
for (String pu : clientMap.keySet())
{
PersistenceUnitMetadata puMetadata = KunderaMetadataManager.getPersistenceUnitMetadata(kunderaMetadata,
pu);
String txResource = puMetadata.getProperty(PersistenceProperties.KUNDERA_TRANSACTION_RESOURCE);
if (txResource != null)
{
TransactionResource resource = (TransactionResource) Class.forName(txResource).newInstance();
coordinator.addResource(resource, pu);
Client client = clientMap.get(pu);
if (!(client instanceof TransactionBinder))
{
throw new KunderaTransactionException(
"Client : "
+ client.getClass()
+ " must implement TransactionBinder interface, if {kundera.transaction.resource.class} property provided!");
}
else
{
((TransactionBinder) client).bind(resource);
}
}
else
{
coordinator.addResource(new DefaultTransactionResource(clientMap.get(pu)), pu);
}
}
}
catch (Exception e)
{
log.error("Error while initializing Transaction Resource:", e);
throw new KunderaTransactionException(e);
}
return coordinator;
} | java | {
"resource": ""
} |
q163985 | GenericClientFactory.loadClientMetadata | train | protected void loadClientMetadata(Map<String, Object> puProperties)
{
clientMetadata = new ClientMetadata();
String luceneDirectoryPath = puProperties != null ? (String) puProperties
.get(PersistenceProperties.KUNDERA_INDEX_HOME_DIR) : null;
String indexerClass = puProperties != null ? (String) puProperties
.get(PersistenceProperties.KUNDERA_INDEXER_CLASS) : null;
String autoGenClass = puProperties != null ? (String) puProperties
.get(PersistenceProperties.KUNDERA_AUTO_GENERATOR_CLASS) : null;
if (indexerClass == null)
{
indexerClass = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(persistenceUnit)
.getProperties().getProperty(PersistenceProperties.KUNDERA_INDEXER_CLASS);
}
if (autoGenClass == null)
{
autoGenClass = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(persistenceUnit)
.getProperties().getProperty(PersistenceProperties.KUNDERA_AUTO_GENERATOR_CLASS);
}
if (luceneDirectoryPath == null)
{
luceneDirectoryPath = kunderaMetadata.getApplicationMetadata().getPersistenceUnitMetadata(persistenceUnit)
.getProperty(PersistenceProperties.KUNDERA_INDEX_HOME_DIR);
}
if (autoGenClass != null)
{
clientMetadata.setAutoGenImplementor(autoGenClass);
}
// in case set empty via external property, means want to avoid lucene
// directory set up.
if (luceneDirectoryPath != null && !StringUtils.isEmpty(luceneDirectoryPath))
{
// Add client metadata
clientMetadata.setLuceneIndexDir(luceneDirectoryPath);
// Set Index Manager
try
{
Method method = Class.forName(IndexingConstants.LUCENE_INDEXER).getDeclaredMethod("getInstance",
String.class);
Indexer indexer = (Indexer) method.invoke(null, luceneDirectoryPath);
indexManager = new IndexManager(indexer, kunderaMetadata);
}
catch (Exception e)
{
logger.error(
"Missing lucene from classpath. Please make sure those are available to load lucene directory {}!",
luceneDirectoryPath);
throw new InvalidConfigurationException(e);
}
// indexManager = new IndexManager(LuceneIndexer.getInstance(new
// StandardAnalyzer(Version.LUCENE_CURRENT),
// luceneDirectoryPath));
}
else if (indexerClass != null)
{
try
{
Class<?> indexerClazz = Class.forName(indexerClass);
Indexer indexer = (Indexer) indexerClazz.newInstance();
indexManager = new IndexManager(indexer, kunderaMetadata);
clientMetadata.setIndexImplementor(indexerClass);
}
catch (Exception cnfex)
{
logger.error("Error while initialzing indexer:" + indexerClass, cnfex);
throw new KunderaException(cnfex);
}
}
else
{
indexManager = new IndexManager(null, kunderaMetadata);
}
// if
// (kunderaMetadata.getClientMetadata(persistenceUnit)
// ==
// null)
// {
// kunderaMetadata.addClientMetadata(persistenceUnit,
// clientMetadata);
// }
} | java | {
"resource": ""
} |
q163986 | GenericClientFactory.getClientInstance | train | @Override
public Client getClientInstance()
{
// if threadsafe recycle the same single instance; if not create a new
// instance
if (isThreadSafe())
{
logger.info("Returning threadsafe used client instance for persistence unit : " + persistenceUnit);
if (client == null)
{
client = instantiateClient(persistenceUnit);
}
}
else
{
logger.debug("Returning fresh client instance for persistence unit : " + persistenceUnit);
// no need to hold a client reference.
return instantiateClient(persistenceUnit);
}
return client;
} | java | {
"resource": ""
} |
q163987 | HBaseDataHandler.onFindKeyOnly | train | private FilterList onFindKeyOnly(FilterList filterList, boolean isFindKeyOnly)
{
if (isFindKeyOnly)
{
if (filterList == null)
{
filterList = new FilterList();
}
filterList.addFilter(new KeyOnlyFilter());
}
return filterList;
} | java | {
"resource": ""
} |
q163988 | HBaseDataHandler.getExtPropertyFilters | train | private FilterList getExtPropertyFilters(EntityMetadata m, FilterList filterList)
{
Filter filter = getFilter(m.getTableName());
if (filter != null)
{
if (filterList == null)
{
filterList = new FilterList();
}
filterList.addFilter(filter);
}
return filterList;
} | java | {
"resource": ""
} |
q163989 | HBaseDataHandler.createHbaseRow | train | public HBaseRow createHbaseRow(EntityMetadata m, Object entity, Object rowId, List<RelationHolder> relations)
throws IOException
{
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
m.getPersistenceUnit());
EntityType entityType = metaModel.entity(m.getEntityClazz());
Set<Attribute> attributes = entityType.getAttributes();
if (metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))
{
rowId = KunderaCoreUtils.prepareCompositeKey(m, rowId);
}
HBaseRow hbaseRow = new HBaseRow(rowId, new ArrayList<HBaseCell>());
// handle attributes and embeddables
createCellsAndAddToRow(entity, metaModel, attributes, hbaseRow, m, -1, "");
// handle relations
if (relations != null && !relations.isEmpty())
{
hbaseRow.addCells(getRelationCell(m, rowId, relations));
}
// handle inheritence
String discrColumn = ((AbstractManagedType) entityType).getDiscriminatorColumn();
String discrValue = ((AbstractManagedType) entityType).getDiscriminatorValue();
if (discrColumn != null && discrValue != null)
{
hbaseRow.addCell(new HBaseCell(m.getTableName(), discrColumn, discrValue));
}
return hbaseRow;
} | java | {
"resource": ""
} |
q163990 | HBaseDataHandler.getRelationCell | train | private List<HBaseCell> getRelationCell(EntityMetadata m, Object rowId, List<RelationHolder> relations)
throws IOException
{
List<HBaseCell> relationCells = new ArrayList<HBaseCell>();
for (RelationHolder relation : relations)
{
HBaseCell hBaseCell = new HBaseCell(m.getTableName(), relation.getRelationName(),
relation.getRelationValue());
relationCells.add(hBaseCell);
}
return relationCells;
} | java | {
"resource": ""
} |
q163991 | HBaseDataHandler.writeHbaseRowInATable | train | private void writeHbaseRowInATable(String tableName, HBaseRow hbaseRow) throws IOException
{
Table hTable = gethTable(tableName);
((HBaseWriter) hbaseWriter).writeRow(hTable, hbaseRow);
hTable.close();
} | java | {
"resource": ""
} |
q163992 | HBaseDataHandler.createCellsAndAddToRow | train | private void createCellsAndAddToRow(Object entity, MetamodelImpl metaModel, Set<Attribute> attributes,
HBaseRow hbaseRow, EntityMetadata m, int count, String prefix)
{
AbstractAttribute idCol = (AbstractAttribute) m.getIdAttribute();
for (Attribute attribute : attributes)
{
AbstractAttribute absAttrib = (AbstractAttribute) attribute;
Class clazz = absAttrib.getBindableJavaType();
if (metaModel.isEmbeddable(clazz))
{
Set<Attribute> attribEmbeddables = metaModel.embeddable(absAttrib.getBindableJavaType())
.getAttributes();
Object embeddedField = PropertyAccessorHelper.getObject(entity, (Field) attribute.getJavaMember());
if (attribute.isCollection() && embeddedField != null)
{
int newCount = count + 1;
String newPrefix = prefix != "" ? prefix + absAttrib.getJPAColumnName() + HBaseUtils.DELIM
: absAttrib.getJPAColumnName() + HBaseUtils.DELIM;
List listOfEmbeddables = (List) embeddedField;
addColumnForCollectionSize(hbaseRow, listOfEmbeddables.size(), newPrefix, m.getTableName());
for (Object obj : listOfEmbeddables)
{
createCellsAndAddToRow(obj, metaModel, attribEmbeddables, hbaseRow, m, newCount++, newPrefix);
}
}
else if (embeddedField != null)
{
String newPrefix = prefix != "" ? prefix + absAttrib.getJPAColumnName() + HBaseUtils.DOT
: absAttrib.getJPAColumnName() + HBaseUtils.DOT;
createCellsAndAddToRow(embeddedField, metaModel, attribEmbeddables, hbaseRow, m, count, newPrefix);
}
}
else if (!attribute.isCollection() && !attribute.isAssociation())
{
String columnFamily = absAttrib.getTableName() != null ? absAttrib.getTableName() : m.getTableName();
String columnName = absAttrib.getJPAColumnName();
columnName = count != -1 ? prefix + columnName + HBaseUtils.DELIM + count : prefix + columnName;
Object value = PropertyAccessorHelper.getObject(entity, (Field) attribute.getJavaMember());
HBaseCell hbaseCell = new HBaseCell(columnFamily, columnName, value);
if (!idCol.getName().equals(attribute.getName()) && value != null)
{
hbaseRow.addCell(hbaseCell);
}
}
}
} | java | {
"resource": ""
} |
q163993 | HBaseDataHandler.gethTable | train | public Table gethTable(final String tableName) throws IOException
{
return connection.getTable(TableName.valueOf(tableName));
} | java | {
"resource": ""
} |
q163994 | HBaseDataHandler.populateEntityFromHBaseData | train | private Object populateEntityFromHBaseData(Object entity, HBaseDataWrapper hbaseData, EntityMetadata m,
Object rowKey)
{
try
{
Map<String, Object> relations = new HashMap<String, Object>();
if (entity.getClass().isAssignableFrom(EnhanceEntity.class))
{
relations = ((EnhanceEntity) entity).getRelations();
entity = ((EnhanceEntity) entity).getEntity();
}
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
m.getPersistenceUnit());
EntityType entityType = metaModel.entity(m.getEntityClazz());
Set<Attribute> attributes = ((AbstractManagedType) entityType).getAttributes();
writeValuesToEntity(entity, hbaseData, m, metaModel, attributes, m.getRelationNames(), relations, -1, "");
if (!relations.isEmpty())
{
return new EnhanceEntity(entity, rowKey, relations);
}
return entity;
}
catch (PropertyAccessException e1)
{
throw new RuntimeException(e1);
}
} | java | {
"resource": ""
} |
q163995 | HBaseDataHandler.writeValuesToEntity | train | private void writeValuesToEntity(Object entity, HBaseDataWrapper hbaseData, EntityMetadata m,
MetamodelImpl metaModel, Set<Attribute> attributes, List<String> relationNames,
Map<String, Object> relations, int count, String prefix)
{
for (Attribute attribute : attributes)
{
Class javaType = ((AbstractAttribute) attribute).getBindableJavaType();
if (metaModel.isEmbeddable(javaType))
{
processEmbeddable(entity, hbaseData, m, metaModel, count, prefix, attribute, javaType);
}
else if (!attribute.isCollection())
{
String columnName = ((AbstractAttribute) attribute).getJPAColumnName();
columnName = count != -1 ? prefix + columnName + HBaseUtils.DELIM + count : prefix + columnName;
String idColName = ((AbstractAttribute) m.getIdAttribute()).getJPAColumnName();
String colFamily = ((AbstractAttribute) attribute).getTableName() != null ? ((AbstractAttribute) attribute)
.getTableName() : m.getTableName();
byte[] columnValue = hbaseData.getColumnValue(HBaseUtils.getColumnDataKey(colFamily, columnName));
if (relationNames != null && relationNames.contains(columnName) && columnValue != null
&& columnValue.length > 0)
{
EntityType entityType = metaModel.entity(m.getEntityClazz());
relations.put(columnName, getObjectFromByteArray(entityType, columnValue, columnName, m));
}
else if (!idColName.equals(columnName) && columnValue != null)
{
PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), columnValue);
}
}
}
} | java | {
"resource": ""
} |
q163996 | HBaseDataHandler.processEmbeddable | train | private void processEmbeddable(Object entity, HBaseDataWrapper hbaseData, EntityMetadata m,
MetamodelImpl metaModel, int count, String prefix, Attribute attribute, Class javaType)
{
Set<Attribute> attribEmbeddables = metaModel.embeddable(javaType).getAttributes();
Object embeddedField = KunderaCoreUtils.createNewInstance(javaType);
if (!attribute.isCollection())
{
String newPrefix = prefix != "" ? prefix + ((AbstractAttribute) attribute).getJPAColumnName()
+ HBaseUtils.DOT : ((AbstractAttribute) attribute).getJPAColumnName() + HBaseUtils.DOT;
writeValuesToEntity(embeddedField, hbaseData, m, metaModel, attribEmbeddables, null, null, count, newPrefix);
PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), embeddedField);
}
else
{
int newCount = count + 1;
String newPrefix = prefix != "" ? prefix + ((AbstractAttribute) attribute).getJPAColumnName()
+ HBaseUtils.DELIM : ((AbstractAttribute) attribute).getJPAColumnName() + HBaseUtils.DELIM;
List embeddedCollection = new ArrayList();
byte[] columnValue = hbaseData.getColumnValue(HBaseUtils.getColumnDataKey(m.getTableName(), newPrefix
+ HBaseUtils.SIZE));
int size = 0;
if (columnValue != null)
{
size = Bytes.toInt(columnValue);
}
while (size != newCount)
{
embeddedField = KunderaCoreUtils.createNewInstance(javaType);
writeValuesToEntity(embeddedField, hbaseData, m, metaModel, attribEmbeddables, null, null, newCount++,
newPrefix);
embeddedCollection.add(embeddedField);
}
PropertyAccessorHelper.set(entity, (Field) attribute.getJavaMember(), embeddedCollection);
}
} | java | {
"resource": ""
} |
q163997 | HBaseDataHandler.setFilter | train | public void setFilter(Filter filter)
{
if (this.filter == null)
{
this.filter = new FilterList();
}
if (filter != null)
{
this.filter.addFilter(filter);
}
} | java | {
"resource": ""
} |
q163998 | HBaseDataHandler.onRead | train | private List onRead(EntityMetadata m, List<Map<String, Object>> columnsToOutput, Table hTable,
List<HBaseDataWrapper> results) throws IOException
{
Class clazz = m.getEntityClazz();
List outputResults = new ArrayList();
try
{
if (results != null)
{
return columnsToOutput != null && !columnsToOutput.isEmpty() ? returnSpecificFieldList(m,
columnsToOutput, results, outputResults) : returnEntityObjectList(m, results, outputResults);
}
}
catch (Exception e)
{
logger.error("Error while creating an instance of {}, Caused by: .", clazz, e);
throw new PersistenceException(e);
}
finally
{
if (hTable != null)
{
closeHTable(hTable);
}
}
return outputResults;
} | java | {
"resource": ""
} |
q163999 | HBaseDataHandler.returnEntityObjectList | train | private List returnEntityObjectList(EntityMetadata m, List<HBaseDataWrapper> results, List outputResults)
{
Map<Object, Object> entityListMap = new HashMap<Object, Object>();
MetamodelImpl metaModel = (MetamodelImpl) kunderaMetadata.getApplicationMetadata().getMetamodel(
m.getPersistenceUnit());
EntityType entityType = metaModel.entity(m.getEntityClazz());
List<AbstractManagedType> subManagedTypes = ((AbstractManagedType) entityType).getSubManagedType();
Map<String, Class> discrValueToEntityClazz = new HashMap<String, Class>();
String discrColumn = null;
if (subManagedTypes != null && !subManagedTypes.isEmpty())
{
for (AbstractManagedType subEntity : subManagedTypes)
{
discrColumn = ((AbstractManagedType) subEntity).getDiscriminatorColumn();
discrValueToEntityClazz.put(subEntity.getDiscriminatorValue(), subEntity.getJavaType());
}
}
for (HBaseDataWrapper data : results)
{
Class clazz = null;
if (discrValueToEntityClazz != null && !discrValueToEntityClazz.isEmpty())
{
String discrColumnKey = HBaseUtils.getColumnDataKey(m.getTableName(), discrColumn);
String discrValue = Bytes.toString(data.getColumnValue(discrColumnKey));
clazz = discrValueToEntityClazz.get(discrValue);
m = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, clazz);
}
else
{
clazz = m.getEntityClazz();
}
Object entity = KunderaCoreUtils.createNewInstance(clazz); // Entity
Object rowKeyValue = HBaseUtils.fromBytes(m, metaModel, data.getRowKey());
if (!metaModel.isEmbeddable(m.getIdAttribute().getBindableJavaType()))
{
PropertyAccessorHelper.setId(entity, m, rowKeyValue);
}
if (entityListMap.get(rowKeyValue) != null)
{
entity = entityListMap.get(rowKeyValue);
}
entity = populateEntityFromHBaseData(entity, data, m, null);
if (entity != null)
{
entityListMap.put(rowKeyValue, entity);
}
}
for (Object obj : entityListMap.values())
{
outputResults.add(obj);
}
return outputResults;
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.