idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
35,500
private Object onTableGenerator ( EntityMetadata m , Client < ? > client , IdDiscriptor keyValue , Object e ) { Object tablegenerator = getAutoGenClazz ( client ) ; if ( tablegenerator instanceof TableGenerator ) { Object generatedId = ( ( TableGenerator ) tablegenerator ) . generate ( keyValue . getTableDiscriptor ( ) , ( ClientBase ) client , m . getIdAttribute ( ) . getJavaType ( ) . getSimpleName ( ) ) ; try { generatedId = PropertyAccessorHelper . fromSourceToTargetClass ( m . getIdAttribute ( ) . getJavaType ( ) , generatedId . getClass ( ) , generatedId ) ; PropertyAccessorHelper . setId ( e , m , generatedId ) ; return generatedId ; } catch ( IllegalArgumentException iae ) { log . error ( "Unknown integral data type for ids : " + m . getIdAttribute ( ) . getJavaType ( ) ) ; throw new KunderaException ( "Unknown integral data type for ids : " + m . getIdAttribute ( ) . getJavaType ( ) , iae ) ; } } throw new IllegalArgumentException ( GenerationType . class . getSimpleName ( ) + "." + GenerationType . TABLE + " Strategy not supported by this client :" + client . getClass ( ) . getName ( ) ) ; }
Generate Id when given table generation strategy .
35,501
protected List populateEntities ( EntityMetadata m , Client client ) { ClientMetadata clientMetadata = ( ( ClientBase ) client ) . getClientMetadata ( ) ; this . useLuceneOrES = ! MetadataUtils . useSecondryIndex ( clientMetadata ) ; if ( useLuceneOrES ) { return populateUsingLucene ( m , client , null , kunderaQuery . getResult ( ) ) ; } else { CouchDBQueryInterpreter interpreter = onTranslation ( getKunderaQuery ( ) . getFilterClauseQueue ( ) , m ) ; return ( ( CouchDBClient ) client ) . createAndExecuteQuery ( interpreter ) ; } }
Populate results .
35,502
protected List recursivelyPopulateEntities ( EntityMetadata m , Client client ) { List < EnhanceEntity > ls = populateEntities ( m , client ) ; return setRelationEntities ( ls , client , m ) ; }
Recursively populate entity .
35,503
private CouchDBQueryInterpreter onAggregatedQuery ( EntityMetadata m , CouchDBQueryInterpreter interpreter , KunderaQuery kunderaQuery ) { interpreter . setAggregation ( true ) ; SelectStatement selectStatement = kunderaQuery . getSelectStatement ( ) ; Expression whereClause = selectStatement . getWhereClause ( ) ; if ( ! NullExpression . class . isAssignableFrom ( whereClause . getClass ( ) ) ) { throw new KunderaException ( "Aggregations with where clause are yet not supported in CouchDB" ) ; } SelectClause selectClause = ( SelectClause ) selectStatement . getSelectClause ( ) ; Expression expression = selectClause . getSelectExpression ( ) ; if ( CountFunction . class . isAssignableFrom ( expression . getClass ( ) ) ) { interpreter . setAggregationType ( CouchDBConstants . COUNT ) ; Expression exp = ( ( CountFunction ) expression ) . getExpression ( ) ; setAggregationColInInterpreter ( m , interpreter , exp ) ; } else if ( MinFunction . class . isAssignableFrom ( expression . getClass ( ) ) ) { interpreter . setAggregationType ( CouchDBConstants . MIN ) ; Expression exp = ( ( MinFunction ) expression ) . getExpression ( ) ; setAggregationColInInterpreter ( m , interpreter , exp ) ; } else if ( MaxFunction . class . isAssignableFrom ( expression . getClass ( ) ) ) { interpreter . setAggregationType ( CouchDBConstants . MAX ) ; Expression exp = ( ( MaxFunction ) expression ) . getExpression ( ) ; setAggregationColInInterpreter ( m , interpreter , exp ) ; } else if ( AvgFunction . class . isAssignableFrom ( expression . getClass ( ) ) ) { interpreter . setAggregationType ( CouchDBConstants . AVG ) ; Expression exp = ( ( AvgFunction ) expression ) . getExpression ( ) ; setAggregationColInInterpreter ( m , interpreter , exp ) ; } else if ( SumFunction . class . isAssignableFrom ( expression . getClass ( ) ) ) { interpreter . setAggregationType ( CouchDBConstants . SUM ) ; Expression exp = ( ( SumFunction ) expression ) . getExpression ( ) ; setAggregationColInInterpreter ( m , interpreter , exp ) ; } else { throw new KunderaException ( "This query is currently not supported in CouchDB" ) ; } return interpreter ; }
On aggregated query .
35,504
private void setAggregationColInInterpreter ( EntityMetadata m , CouchDBQueryInterpreter interpreter , Expression exp ) { if ( StateFieldPathExpression . class . isAssignableFrom ( exp . getClass ( ) ) ) { Map < String , Object > map = KunderaQueryUtils . setFieldClazzAndColumnFamily ( exp , m , kunderaMetadata ) ; interpreter . setAggregationColumn ( ( String ) map . get ( Constants . COL_NAME ) ) ; } }
Sets the aggregation col in interpreter .
35,505
private List < Map < String , Object > > getColumnsToOutput ( EntityMetadata m , KunderaQuery kunderaQuery ) { if ( kunderaQuery . isSelectStatement ( ) ) { SelectStatement selectStatement = kunderaQuery . getSelectStatement ( ) ; SelectClause selectClause = ( SelectClause ) selectStatement . getSelectClause ( ) ; return KunderaQueryUtils . readSelectClause ( selectClause . getSelectExpression ( ) , m , false , kunderaMetadata ) ; } return new ArrayList ( ) ; }
Gets the columns to output .
35,506
public boolean isUseSecondryIndex ( ) { return StringUtils . isEmpty ( LuceneIndexDir ) && StringUtils . isBlank ( LuceneIndexDir ) && StringUtils . isEmpty ( indexImplementor ) && StringUtils . isBlank ( indexImplementor ) ; }
Checks if is use secondry index .
35,507
public Object getObjectInstance ( Object obj , Name name , Context nameCtx , Hashtable environment ) throws Exception { Reference ref = ( Reference ) obj ; Object ret = null ; if ( ref . getClassName ( ) . equals ( "javax.transaction.UserTransaction" ) || ref . getClassName ( ) . equals ( "com.impetus.kundera.persistence.jta.KunderaJTAUserTransaction" ) ) { ret = KunderaJTAUserTransaction . getCurrentTx ( ) ; } if ( ret == null ) { ret = new KunderaJTAUserTransaction ( ) ; } return ret ; }
Returns reference to userTransaction object .
35,508
private Map < String , Object > populateRelations ( List < String > relations , Object [ ] o ) { Map < String , Object > relationVal = new HashMap < String , Object > ( relations . size ( ) ) ; int counter = 1 ; for ( String r : relations ) { relationVal . put ( r , o [ counter ++ ] ) ; } return relationVal ; }
Populate relations .
35,509
private boolean isStringProperty ( EntityType entityType , Attribute attribute ) { String discriminatorColumn = ( ( AbstractManagedType ) entityType ) . getDiscriminatorColumn ( ) ; if ( attribute . getName ( ) . equals ( discriminatorColumn ) ) { return true ; } return attribute != null ? ( ( AbstractAttribute ) attribute ) . getBindableJavaType ( ) . isAssignableFrom ( String . class ) || ( ( AbstractAttribute ) attribute ) . getBindableJavaType ( ) . isAssignableFrom ( Character . class ) || ( ( AbstractAttribute ) attribute ) . getBindableJavaType ( ) . isAssignableFrom ( char . class ) || ( ( AbstractAttribute ) attribute ) . getBindableJavaType ( ) . isAssignableFrom ( Date . class ) || ( ( AbstractAttribute ) attribute ) . getBindableJavaType ( ) . isAssignableFrom ( java . util . Date . class ) : false ; }
Checks if is string property .
35,510
public static void main ( String [ ] args ) { EntityManagerFactory emf = Persistence . createEntityManagerFactory ( "twissandra,twingo,twirdbms" ) ; EntityManager em = emf . createEntityManager ( ) ; try { Set < User > users = UserBroker . brokeUserList ( args [ 0 ] ) ; for ( Iterator < User > iterator = users . iterator ( ) ; iterator . hasNext ( ) ; ) { User user = ( User ) iterator . next ( ) ; ExecutorService . onPersist ( em , user ) ; ExecutorService . findByKey ( em , "BigDataUser" ) ; List < User > fetchedUsers = ExecutorService . onQueryByEmail ( em , user ) ; if ( fetchedUsers != null && fetchedUsers . size ( ) > 0 ) { logger . info ( user . toString ( ) ) ; } logger . info ( "" ) ; System . out . println ( "#######################Querying##########################################" ) ; logger . info ( "" ) ; logger . info ( "" ) ; } String query = "Select u from User u" ; logger . info ( query ) ; ExecutorService . findByQuery ( em , query ) ; logger . info ( "" ) ; System . out . println ( "#######################Querying##########################################" ) ; logger . info ( "" ) ; logger . info ( "" ) ; query = "Select * from tweets where user_id='RDBMSUser'" ; logger . info ( query ) ; ExecutorService . findByNativeQuery ( em , query ) ; } finally { onDestroyDBResources ( emf , em ) ; } }
main runner method
35,511
private static void onDestroyDBResources ( EntityManagerFactory emf , EntityManager em ) { if ( emf != null ) { emf . close ( ) ; } if ( em != null ) { em . close ( ) ; } }
After successful processing close entity manager and it s factory instance .
35,512
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 ) ) ; for ( String validAnn : getValidAnnotations ( ) ) { if ( annotations . contains ( validAnn ) ) { for ( AnnotationDiscoveryListener listener : getAnnotationDiscoveryListeners ( ) ) { listener . discovered ( className ) ; } } } } finally { dstream . close ( ) ; bits . close ( ) ; } }
Scan class .
35,513
public void accumulateAnnotations ( List < String > annotations , AnnotationsAttribute annatt ) { if ( null == annatt ) { return ; } for ( Annotation ann : annatt . getAnnotations ( ) ) { annotations . add ( ann . getTypeName ( ) ) ; } }
Accumulate annotations .
35,514
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 ) ; } }
Gets the resource iterator .
35,515
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 ( ) ; if ( props != null ) { 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 ; } }
Retrieving connection from connection pool .
35,516
private long toLong ( byte [ ] data ) { if ( data == null || data . length != 8 ) return 0x0 ; return ( long ) ( ( 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 ) ; }
To long .
35,517
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 ) , } ; }
From long .
35,518
public void addJarFile ( String jarFile ) { if ( jarFiles == null ) { jarFiles = new HashSet < String > ( ) ; } this . jarFiles . add ( jarFile ) ; addJarFileUrl ( jarFile ) ; }
Sets the jar files .
35,519
public List < URL > getManagedURLs ( ) { List < URL > managedURL = getJarFileUrls ( ) ; if ( managedURL == null ) { managedURL = new ArrayList < URL > ( 1 ) ; } if ( ! getExcludeUnlistedClasses ( ) ) { managedURL . add ( getPersistenceUnitRootUrl ( ) ) ; } return managedURL ; }
Returns list of managed urls .
35,520
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 ) ; } }
Adds jar file URL .
35,521
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 ; }
Gets the client . In case client is not configure it throws IllegalArgumentException .
35,522
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 ; }
Return batch . size value .
35,523
protected Document prepareDocumentForSuperColumn ( EntityMetadata metadata , Object object , String embeddedColumnName , String parentId , Class < ? > clazz ) { Document currentDoc ; currentDoc = new Document ( ) ; addEntityClassToDocument ( metadata , object , currentDoc , null ) ; addSuperColumnNameToDocument ( embeddedColumnName , currentDoc ) ; addParentKeyToDocument ( parentId , currentDoc , clazz ) ; return currentDoc ; }
Prepare document .
35,524
protected void addParentKeyToDocument ( String parentId , Document currentDoc , Class < ? > clazz ) { 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 ) ; } }
Index parent key .
35,525
protected void createSuperColumnDocument ( EntityMetadata metadata , Object object , Document currentDoc , Object embeddedObject , EmbeddableType superColumn , MetamodelImpl metamodel ) { 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 ) ; } addEntityFieldsToDocument ( metadata , object , currentDoc , metamodel ) ; }
Index super column .
35,526
private void addSuperColumnNameToDocument ( String superColumnName , Document currentDoc ) { Field luceneField = new Field ( SUPERCOLUMN_INDEX , superColumnName , Store . YES , Field . Index . NO ) ; currentDoc . add ( luceneField ) ; }
Index super column name .
35,527
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 ) ; } }
Adds the index properties .
35,528
protected void addEntityClassToDocument ( EntityMetadata metadata , Object entity , Document document , final MetamodelImpl metaModel ) { try { Field luceneField ; Object id ; id = PropertyAccessorHelper . getId ( entity , metadata ) ; 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 ) ; document . add ( luceneField ) ; luceneField = new Field ( IndexingConstants . KUNDERA_ID_FIELD , getKunderaId ( metadata , id ) , Field . Store . YES , Field . Index . ANALYZED ) ; document . add ( luceneField ) ; 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 ) ; 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 ) ; } }
Prepare index document .
35,529
private void addFieldToDocument ( Object object , Document document , java . lang . reflect . Field field , String colName , String indexName ) { try { Object obj = PropertyAccessorHelper . getObject ( object , field ) ; 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 ) ; } }
Index field .
35,530
protected String getKunderaId ( EntityMetadata metadata , Object id ) { return metadata . getEntityClazz ( ) . getCanonicalName ( ) + IndexingConstants . DELIMETER + id ; }
Gets the kundera id .
35,531
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 ) ) ; } }
set time out
35,532
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 ) ) ; } }
set time unit
35,533
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 ) ) ; } }
set batch size
35,534
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 ; }
Populates foreign key as column .
35,535
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 ) ; } }
Compute entity via columns .
35,536
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 ) ; } }
Compute entity via super columns .
35,537
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 ) ; } }
On super column .
35,538
private CounterColumn populateCounterFkey ( String rlName , Object rlValue ) { CounterColumn counterCol = new CounterColumn ( ) ; counterCol . setName ( PropertyAccessorFactory . STRING . toBytes ( rlName ) ) ; counterCol . setValue ( ( Long ) rlValue ) ; return counterCol ; }
Populate counter fkey .
35,539
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 ) ; } }
Deletes record for given primary key from counter column family .
35,540
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 ( ) ; 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!" ) ; } 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 ( ) ) ) ; } } for ( Column column : columns ) { ColumnDef columnDef = new ColumnDef ( ) ; columnDef . setName ( column . getName ( ) ) ; columnDef . setValidation_class ( CassandraValidationClassMapper . getValidationClass ( columnType , false ) ) ; columnDef . setIndex_type ( IndexType . KEYS ) ; if ( ! indexList . contains ( new StringAccessor ( ) . fromBytes ( String . class , column . getName ( ) ) ) ) { isUpdatable = true ; columnFamilyDefToUpdate . addToColumn_metadata ( columnDef ) ; } } 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 ) ; } }
Creates secondary indexes on columns if not already created .
35,541
public Object find ( Class entityClass , Object rowId ) { EntityMetadata entityMetadata = KunderaMetadataManager . getEntityMetadata ( kunderaMetadata , entityClass ) ; List < String > relationNames = entityMetadata . getRelationNames ( ) ; return find ( entityClass , entityMetadata , rowId , relationNames ) ; }
Finds an entiry from database .
35,542
public boolean isCql3Enabled ( EntityMetadata metadata ) { if ( metadata != null ) { MetamodelImpl metaModel = ( MetamodelImpl ) kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( metadata . getPersistenceUnit ( ) ) ; if ( metaModel . isEmbeddable ( metadata . getIdAttribute ( ) . getBindableJavaType ( ) ) ) { return true ; } 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 ) ; }
Returns true in case of composite Id and if cql3 opted and not a embedded entity .
35,543
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 ; }
Executes Select CQL Query .
35,544
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 ; }
Execute scalar query .
35,545
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 ) ) ; }
Compose column value .
35,546
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 ; }
Populate entities from key slices .
35,547
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 ; }
Return insert query string for given entity .
35,548
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 ; }
On relation columns .
35,549
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 ; }
Gets the persist queries .
35,550
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 ( ) ) ; deleteQueryBuilder . delete ( deleteQueryBuilder . lastIndexOf ( CQLTranslator . AND_CLAUSE ) , deleteQueryBuilder . length ( ) ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Returning delete query {}." , deleteQueryBuilder . toString ( ) ) ; } return deleteQueryBuilder . toString ( ) ; }
On delete query .
35,551
protected void onWhereClause ( EntityMetadata metadata , Object key , CQLTranslator translator , StringBuilder queryBuilder , MetamodelImpl metaModel , SingularAttribute attribute ) { 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 ) ; } }
On where clause .
35,552
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 ; }
Returns raw cassandra client from thrift connection pool .
35,553
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 ) ; } }
Executes query string using cql3 .
35,554
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 ) ; } }
Populate cql version .
35,555
public < T > T execute ( final String query , final Object connection , final List < KunderaQuery . BindParameter > parameters ) { throw new KunderaException ( "not implemented" ) ; }
Execute with bind parameters
35,556
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 ( ) ) ; 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 ( ) ; for ( Object key : joinTableRecords . keySet ( ) ) { PropertyAccessor accessor = PropertyAccessorFactory . getPropertyAccessor ( ( Field ) entityMetadata . getIdAttribute ( ) . getJavaMember ( ) ) ; Set < Object > values = joinTableRecords . get ( key ) ; 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 ) ; } }
Persist join table by cql .
35,557
protected < E > List < E > getColumnsByIdUsingCql ( String schemaName , String tableName , String pKeyColumnName , String columnName , Object pKeyColumnValue , Class columnJavaType ) { 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 ; }
Find inverse join column values for join column .
35,558
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 ( ) ) ; }
Find join column values for inverse join column .
35,559
private boolean checkValidClass ( Class < ? > clazz ) { return clazz . isAnnotationPresent ( Entity . class ) || clazz . isAnnotationPresent ( MappedSuperclass . class ) || clazz . isAnnotationPresent ( Embeddable . class ) ; }
checks for a valid entity definition
35,560
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 ; }
Parses the response .
35,561
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 ; }
Parses the aggregated response .
35,562
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 ; }
On iterate buckets .
35,563
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 ; }
Parses the aggregations .
35,564
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 ; }
Builds the records .
35,565
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 ; }
Parses the records .
35,566
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 ; }
Filter buckets .
35,567
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" ) ; } }
Checks if is valid bucket .
35,568
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 ; }
Gets the first result .
35,569
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." ) ; }
Gets the aggregated result .
35,570
public Object wrapFindResult ( Map < String , Object > searchResults , EntityType entityType , Object result , EntityMetadata metadata , boolean b ) { return wrap ( searchResults , entityType , result , metadata , b ) ; }
Wrap find result .
35,571
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 ; }
On enum .
35,572
private Object onId ( Object key , Attribute attribute , Object fieldValue ) { if ( SingularAttribute . class . isAssignableFrom ( attribute . getClass ( ) ) && ( ( SingularAttribute ) attribute ) . isId ( ) ) { key = fieldValue ; } return key ; }
On id .
35,573
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 ( ) ; } }
Gets the select expression order .
35,574
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 ; }
Gets the entity objects .
35,575
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 ) ; }
Returns true if attribute belongs plural hierarchy .
35,576
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 ; }
Gets the persistent attribute type .
35,577
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 ) ; managedType = new DefaultMappedSuperClass < X > ( clazz , PersistenceType . MAPPED_SUPERCLASS , ( AbstractIdentifiableType ) getType ( clazz . getSuperclass ( ) , isIdClass ) ) ; onDeclaredFields ( clazz , managedType ) ; mappedSuperClassTypes . put ( clazz , ( MappedSuperclassType < ? > ) managedType ) ; } else if ( clazz . isAnnotationPresent ( Entity . class ) || isIdClass ) { if ( ! managedTypes . containsKey ( clazz ) ) { managedType = new DefaultEntityType < X > ( clazz , PersistenceType . ENTITY , ( AbstractIdentifiableType ) getType ( clazz . getSuperclass ( ) , isIdClass ) ) ; if ( ! isIdClass ) { managedTypes . put ( clazz , ( EntityType < ? > ) managedType ) ; } } else { managedType = ( AbstractManagedType < X > ) managedTypes . get ( clazz ) ; } } return managedType ; }
Builds the managed type .
35,578
private AbstractManagedType getType ( Class clazz , boolean isIdClass ) { if ( clazz != null && ! clazz . equals ( Object . class ) ) { return processInternal ( clazz , isIdClass ) ; } return null ; }
Gets the super type .
35,579
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 ( ) ) ; } } }
On declared fields .
35,580
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 ) ) { 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 ) ; } } } }
Adds the predicates to scanner builder .
35,581
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 ) ; }
Populate embedded column .
35,582
public void deleteByColumn ( String schemaName , String tableName , String columnName , Object columnValue ) { }
Delete by column .
35,583
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 ) ; }
Populate partial row .
35,584
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 ) ; }
Populate partial row for embedded column .
35,585
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 ) ; } } } }
Iterate and populate row .
35,586
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 ) ) { 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 ) ; } } } }
Adds the primary key to row .
35,587
public < E > E findById ( final Class < E > entityClass , final Object primaryKey ) { E e = find ( entityClass , primaryKey ) ; if ( e == null ) { return null ; } return ( E ) ( e ) ; }
Find object based on primary key either form persistence cache or from database
35,588
public void remove ( Object e ) { if ( e == null ) { throw new IllegalArgumentException ( "Entity to be removed must not be null." ) ; } EntityMetadata metadata = getMetadata ( e . getClass ( ) ) ; ObjectGraph graph = new GraphGenerator ( ) . generateGraph ( e , this , new ManagedState ( ) ) ; Node node = graph . getHeadNode ( ) ; try { lock . writeLock ( ) . lock ( ) ; node . setPersistenceDelegator ( this ) ; node . remove ( ) ; flushManager . buildFlushStack ( node , EventType . DELETE ) ; flush ( ) ; } finally { lock . writeLock ( ) . unlock ( ) ; } graph . clear ( ) ; graph = null ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Data removed successfully for entity : " + e . getClass ( ) ) ; } }
Removes an entity object from persistence cache .
35,589
public void detach ( Object entity ) { Node node = getPersistenceCache ( ) . getMainCache ( ) . getNodeFromCache ( entity , getMetadata ( entity . getClass ( ) ) , this ) ; if ( node != null ) { node . detach ( ) ; } }
Remove the given entity from the persistence context causing a managed entity to become detached .
35,590
boolean contains ( Object entity ) { Node node = getPersistenceCache ( ) . getMainCache ( ) . getNodeFromCache ( entity , getMetadata ( entity . getClass ( ) ) , this ) ; return node != null && node . isInState ( ManagedState . class ) ; }
Check if the instance is a managed entity instance belonging to the current persistence context .
35,591
public void refresh ( Object entity ) { if ( contains ( entity ) ) { MainCache mainCache = ( MainCache ) getPersistenceCache ( ) . getMainCache ( ) ; Node node = mainCache . getNodeFromCache ( entity , getMetadata ( entity . getClass ( ) ) , this ) ; 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" ) ; } }
Refresh the state of the instance from the database overwriting changes made to the entity if any .
35,592
void populateClientProperties ( Map properties ) { if ( properties != null && ! properties . isEmpty ( ) ) { Map < String , Client > clientMap = getDelegate ( ) ; if ( ! clientMap . isEmpty ( ) ) { 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" ) ; } } }
Populates client specific properties .
35,593
void loadClient ( String persistenceUnit , Client client ) { if ( ! clientMap . containsKey ( persistenceUnit ) && client != null ) { clientMap . put ( persistenceUnit , client ) ; } }
Pre load client specific to persistence unit .
35,594
private void execute ( ) { for ( Client client : clientMap . values ( ) ) { if ( client != null && client instanceof Batcher ) { if ( ( ( Batcher ) client ) . getBatchSize ( ) == 0 || ( ( Batcher ) client ) . executeBatch ( ) > 0 ) { flushJoinTableData ( ) ; } } } }
Executes batch .
35,595
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 ) ; } } } } }
On flushing join table data
35,596
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 ; }
Returns transaction coordinator .
35,597
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 ) ; } if ( luceneDirectoryPath != null && ! StringUtils . isEmpty ( luceneDirectoryPath ) ) { clientMetadata . setLuceneIndexDir ( luceneDirectoryPath ) ; 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 ) ; } } 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 ) ; } }
Load client metadata .
35,598
public Client getClientInstance ( ) { 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 ) ; return instantiateClient ( persistenceUnit ) ; } return client ; }
Gets the client instance .
35,599
private FilterList onFindKeyOnly ( FilterList filterList , boolean isFindKeyOnly ) { if ( isFindKeyOnly ) { if ( filterList == null ) { filterList = new FilterList ( ) ; } filterList . addFilter ( new KeyOnlyFilter ( ) ) ; } return filterList ; }
On find key only .