idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
35,700
public static KunderaProxy getProxy ( final String entityName , final Class < ? > persistentClass , final Class < ? > [ ] interfaces , final Method getIdentifierMethod , final Method setIdentifierMethod , final Object id , final PersistenceDelegator pd ) throws PersistenceException { final CglibLazyInitializer instance = new CglibLazyInitializer ( entityName , persistentClass , interfaces , id , getIdentifierMethod , setIdentifierMethod , pd ) ; final KunderaProxy proxy ; Class factory = getProxyFactory ( persistentClass , interfaces ) ; proxy = getProxyInstance ( factory , instance ) ; instance . constructed = true ; return proxy ; }
Gets the proxy .
35,701
private static KunderaProxy getProxyInstance ( Class factory , CglibLazyInitializer instance ) { KunderaProxy proxy ; try { Enhancer . registerCallbacks ( factory , new Callback [ ] { instance , null } ) ; proxy = ( KunderaProxy ) factory . newInstance ( ) ; } catch ( IllegalAccessException e ) { throw new LazyInitializationException ( e ) ; } catch ( InstantiationException e ) { throw new LazyInitializationException ( e ) ; } finally { Enhancer . registerCallbacks ( factory , null ) ; } return proxy ; }
Gets the proxy instance .
35,702
public static Class getProxyFactory ( Class persistentClass , Class [ ] interfaces ) throws PersistenceException { Enhancer e = new Enhancer ( ) ; e . setSuperclass ( interfaces . length == 1 ? persistentClass : null ) ; e . setInterfaces ( interfaces ) ; e . setCallbackTypes ( new Class [ ] { InvocationHandler . class , NoOp . class , } ) ; e . setCallbackFilter ( FINALIZE_FILTER ) ; e . setUseFactory ( false ) ; e . setInterceptDuringConstruction ( false ) ; return e . createClass ( ) ; }
Gets the proxy factory .
35,703
public static boolean isFindKeyOnly ( EntityMetadata metadata , List < Map < String , Object > > colToOutput ) { if ( colToOutput != null && colToOutput . size ( ) == 1 ) { String idCol = ( ( AbstractAttribute ) metadata . getIdAttribute ( ) ) . getJPAColumnName ( ) ; return idCol . equals ( colToOutput . get ( 0 ) . get ( Constants . DB_COL_NAME ) ) && ! ( boolean ) colToOutput . get ( 0 ) . get ( Constants . IS_EMBEDDABLE ) ; } else { return false ; } }
Checks if is find key only .
35,704
private Object findGFSEntity ( EntityMetadata entityMetadata , Class entityClass , Object key ) { GridFSDBFile outputFile = findGridFSDBFile ( entityMetadata , key ) ; return outputFile != null ? handler . getEntityFromGFSDBFile ( entityMetadata . getEntityClazz ( ) , instantiateEntity ( entityClass , null ) , entityMetadata , outputFile , kunderaMetadata ) : null ; }
Find GFS entity .
35,705
private GridFSDBFile findGridFSDBFile ( EntityMetadata entityMetadata , Object key ) { String id = ( ( AbstractAttribute ) entityMetadata . getIdAttribute ( ) ) . getJPAColumnName ( ) ; DBObject query = new BasicDBObject ( "metadata." + id , key ) ; KunderaGridFS gfs = new KunderaGridFS ( mongoDb , entityMetadata . getTableName ( ) ) ; return gfs . findOne ( query ) ; }
Find GRIDFSDBFile .
35,706
private < E > List < E > loadQueryDataGFS ( EntityMetadata entityMetadata , BasicDBObject mongoQuery , BasicDBObject orderBy , int maxResult , int firstResult , boolean isCountQuery ) { List < GridFSDBFile > gfsDBfiles = getGFSDBFiles ( mongoQuery , orderBy , entityMetadata . getTableName ( ) , maxResult , firstResult ) ; if ( isCountQuery ) { return ( List < E > ) Collections . singletonList ( gfsDBfiles . size ( ) ) ; } List entities = new ArrayList < E > ( ) ; for ( GridFSDBFile file : gfsDBfiles ) { populateGFSEntity ( entityMetadata , entities , file ) ; } return entities ; }
Load query data gfs .
35,707
private < E > List < E > loadQueryData ( EntityMetadata entityMetadata , BasicDBObject mongoQuery , BasicDBObject orderBy , int maxResult , int firstResult , boolean isCountQuery , BasicDBObject keys , String ... results ) throws InstantiationException , IllegalAccessException { String documentName = entityMetadata . getTableName ( ) ; List entities = new ArrayList < E > ( ) ; Object object = getDBCursorInstance ( mongoQuery , orderBy , maxResult , firstResult , keys , documentName , isCountQuery ) ; DBCursor cursor = null ; if ( object instanceof Long ) { List < Long > lst = new ArrayList < Long > ( ) ; lst . add ( ( Long ) object ) ; return ( List < E > ) lst ; } else { cursor = ( DBCursor ) object ; } if ( results != null && results . length > 0 ) { DBCollection dbCollection = mongoDb . getCollection ( documentName ) ; KunderaCoreUtils . printQuery ( "Find document: " + mongoQuery , showQuery ) ; for ( int i = 1 ; i < results . length ; i ++ ) { String result = results [ i ] ; if ( result != null && result . indexOf ( "." ) >= 0 ) { entities . addAll ( handler . getEmbeddedObjectList ( dbCollection , entityMetadata , documentName , mongoQuery , result , orderBy , maxResult , firstResult , keys , kunderaMetadata ) ) ; return entities ; } } } log . debug ( "Fetching data from " + documentName + " for Filter " + mongoQuery . toString ( ) ) ; while ( cursor . hasNext ( ) ) { DBObject fetchedDocument = cursor . next ( ) ; populateEntity ( entityMetadata , entities , fetchedDocument ) ; } return entities ; }
Load query data .
35,708
private void populateGFSEntity ( EntityMetadata entityMetadata , List entities , GridFSDBFile gfsDBFile ) { Object entity = instantiateEntity ( entityMetadata . getEntityClazz ( ) , null ) ; handler . getEntityFromGFSDBFile ( entityMetadata . getEntityClazz ( ) , entity , entityMetadata , gfsDBFile , kunderaMetadata ) ; entities . add ( entity ) ; }
Populate gfs entity .
35,709
public Object getDBCursorInstance ( BasicDBObject mongoQuery , BasicDBObject orderBy , int maxResult , int firstResult , BasicDBObject keys , String documentName , boolean isCountQuery ) { DBCollection dbCollection = mongoDb . getCollection ( documentName ) ; DBCursor cursor = null ; if ( isCountQuery ) return dbCollection . count ( mongoQuery ) ; else cursor = orderBy != null ? dbCollection . find ( mongoQuery , keys ) . sort ( orderBy ) . limit ( maxResult ) . skip ( firstResult ) : dbCollection . find ( mongoQuery , keys ) . limit ( maxResult ) . skip ( firstResult ) ; return cursor ; }
Gets the DB cursor instance .
35,710
private List < GridFSDBFile > getGFSDBFiles ( BasicDBObject mongoQuery , BasicDBObject sort , String collectionName , int maxResult , int firstResult ) { KunderaGridFS gfs = new KunderaGridFS ( mongoDb , collectionName ) ; return gfs . find ( mongoQuery , sort , firstResult , maxResult ) ; }
Gets the GFSDB files .
35,711
public List < Object > findByRelation ( String colName , Object colValue , Class entityClazz ) { EntityMetadata m = KunderaMetadataManager . getEntityMetadata ( kunderaMetadata , entityClazz ) ; DBCollection dbCollection = mongoDb . getCollection ( m . getTableName ( ) ) ; BasicDBObject query = new BasicDBObject ( ) ; query . put ( colName , MongoDBUtils . populateValue ( colValue , colValue . getClass ( ) ) ) ; KunderaCoreUtils . printQuery ( "Find by relation:" + query , showQuery ) ; DBCursor cursor = dbCollection . find ( query ) ; DBObject fetchedDocument = null ; List < Object > results = new ArrayList < Object > ( ) ; while ( cursor . hasNext ( ) ) { fetchedDocument = cursor . next ( ) ; populateEntity ( m , results , fetchedDocument ) ; } return results . isEmpty ( ) ? null : results ; }
Method to find entity for given association name and association value .
35,712
private void saveGridFSFile ( GridFSInputFile gfsInputFile , EntityMetadata m ) { try { DBCollection coll = mongoDb . getCollection ( m . getTableName ( ) + MongoDBUtils . FILES ) ; createUniqueIndexGFS ( coll , ( ( AbstractAttribute ) m . getIdAttribute ( ) ) . getJPAColumnName ( ) ) ; gfsInputFile . save ( ) ; log . info ( "Input GridFS file: " + gfsInputFile . getFilename ( ) + " is saved successfully in " + m . getTableName ( ) + MongoDBUtils . CHUNKS + " and metadata in " + m . getTableName ( ) + MongoDBUtils . FILES ) ; } catch ( MongoException e ) { log . error ( "Error in saving GridFS file in " + m . getTableName ( ) + MongoDBUtils . FILES + " or " + m . getTableName ( ) + MongoDBUtils . CHUNKS + " collections." ) ; throw new KunderaException ( "Error in saving GridFS file in " + m . getTableName ( ) + MongoDBUtils . FILES + " or " + m . getTableName ( ) + MongoDBUtils . CHUNKS + " collections. Caused By: " , e ) ; } try { gfsInputFile . validate ( ) ; log . info ( "Input GridFS file: " + gfsInputFile . getFilename ( ) + " is validated." ) ; } catch ( MongoException e ) { log . error ( "Error in validating GridFS file in " + m . getTableName ( ) + MongoDBUtils . FILES + " collection." ) ; throw new KunderaException ( "Error in validating GridFS file in " + m . getTableName ( ) + MongoDBUtils . FILES + " collection. Caused By: " , e ) ; } }
Save GRID FS file .
35,713
private void onPersistGFS ( Object entity , Object entityId , EntityMetadata entityMetadata , boolean isUpdate ) { KunderaGridFS gfs = new KunderaGridFS ( mongoDb , entityMetadata . getTableName ( ) ) ; if ( ! isUpdate ) { GridFSInputFile gfsInputFile = handler . getGFSInputFileFromEntity ( gfs , entityMetadata , entity , kunderaMetadata , isUpdate ) ; saveGridFSFile ( gfsInputFile , entityMetadata ) ; } else { Object val = handler . getLobFromGFSEntity ( gfs , entityMetadata , entity , kunderaMetadata ) ; String md5 = MongoDBUtils . calculateMD5 ( val ) ; GridFSDBFile outputFile = findGridFSDBFile ( entityMetadata , entityId ) ; if ( md5 . equals ( outputFile . getMD5 ( ) ) ) { DBObject metadata = handler . getMetadataFromGFSEntity ( gfs , entityMetadata , entity , kunderaMetadata ) ; outputFile . setMetaData ( metadata ) ; outputFile . save ( ) ; } else { GridFSInputFile gfsInputFile = handler . getGFSInputFileFromEntity ( gfs , entityMetadata , entity , kunderaMetadata , isUpdate ) ; ObjectId updatedId = ( ObjectId ) gfsInputFile . getId ( ) ; DBObject metadata = gfsInputFile . getMetaData ( ) ; saveGridFSFile ( gfsInputFile , entityMetadata ) ; DBObject query = new BasicDBObject ( "_id" , outputFile . getId ( ) ) ; gfs . remove ( query ) ; outputFile = gfs . findOne ( updatedId ) ; metadata . put ( ( ( AbstractAttribute ) entityMetadata . getIdAttribute ( ) ) . getJPAColumnName ( ) , entityId ) ; outputFile . setMetaData ( metadata ) ; outputFile . save ( ) ; } } }
On persist GFS .
35,714
private void onFlushBatch ( Map < String , BulkWriteOperation > bulkWriteOperationMap ) { if ( ! bulkWriteOperationMap . isEmpty ( ) ) { for ( BulkWriteOperation builder : bulkWriteOperationMap . values ( ) ) { try { builder . execute ( getWriteConcern ( ) ) ; } catch ( BulkWriteException bwex ) { log . error ( "Batch insertion is not performed due to error in write command. Caused By: " , bwex ) ; throw new KunderaException ( "Batch insertion is not performed due to error in write command. Caused By: " , bwex ) ; } catch ( MongoException mex ) { log . error ( "Batch insertion is not performed. Caused By: " , mex ) ; throw new KunderaException ( "Batch insertion is not performed. Caused By: " , mex ) ; } } } }
On flush batch .
35,715
private void onFlushCollection ( Map < String , List < DBObject > > collections ) { for ( String tableName : collections . keySet ( ) ) { DBCollection dbCollection = mongoDb . getCollection ( tableName ) ; KunderaCoreUtils . printQuery ( "Persist collection:" + tableName , showQuery ) ; try { dbCollection . insert ( collections . get ( tableName ) . toArray ( new DBObject [ 0 ] ) , getWriteConcern ( ) , encoder ) ; } catch ( MongoException ex ) { throw new KunderaException ( "document is not inserted in " + dbCollection . getFullName ( ) + " collection. Caused By:" , ex ) ; } } }
On collections flush .
35,716
private Map < String , List < DBObject > > onPersist ( Map < String , List < DBObject > > collections , Object entity , Object id , EntityMetadata metadata , List < RelationHolder > relationHolders , boolean isUpdate ) { persistenceUnit = metadata . getPersistenceUnit ( ) ; Map < String , DBObject > documents = handler . getDocumentFromEntity ( metadata , entity , relationHolders , kunderaMetadata ) ; if ( isUpdate ) { for ( String documentName : documents . keySet ( ) ) { BasicDBObject query = new BasicDBObject ( ) ; MetamodelImpl metaModel = ( MetamodelImpl ) kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( metadata . getPersistenceUnit ( ) ) ; if ( metaModel . isEmbeddable ( metadata . getIdAttribute ( ) . getBindableJavaType ( ) ) ) { MongoDBUtils . populateCompoundKey ( query , metadata , metaModel , id ) ; } else { query . put ( "_id" , MongoDBUtils . populateValue ( id , id . getClass ( ) ) ) ; } DBCollection dbCollection = mongoDb . getCollection ( documentName ) ; KunderaCoreUtils . printQuery ( "Persist collection:" + documentName , showQuery ) ; dbCollection . save ( documents . get ( documentName ) , getWriteConcern ( ) ) ; } } else { for ( String documentName : documents . keySet ( ) ) { List < DBObject > dbStatements = null ; if ( collections . containsKey ( documentName ) ) { dbStatements = collections . get ( documentName ) ; dbStatements . add ( documents . get ( documentName ) ) ; } else { dbStatements = new ArrayList < DBObject > ( ) ; dbStatements . add ( documents . get ( documentName ) ) ; collections . put ( documentName , dbStatements ) ; } } } return collections ; }
Executes on list of entities to be persisted .
35,717
public Object executeScript ( String script ) { Object result = mongoDb . eval ( script ) ; KunderaCoreUtils . printQuery ( "Execute mongo jscripts:" + script , showQuery ) ; return result ; }
Method to execute mongo jscripts .
35,718
private MapReduceCommand parseMapReduceCommand ( String jsonClause ) { String collectionName = jsonClause . replaceFirst ( "(?ms).*?\\.\\s*(.+?)\\s*\\.\\s*mapReduce\\s*\\(.*" , "$1" ) ; if ( collectionName . contains ( "getCollection" ) ) { collectionName = collectionName . replaceFirst ( ".*getCollection\\s*\\(\\s*(['\"])([^'\"]+)\\1\\s*\\).*" , "$2" ) ; } DBCollection collection = mongoDb . getCollection ( collectionName ) ; String body = jsonClause . replaceFirst ( "^(?ms).*?mapReduce\\s*\\(\\s*(.*)\\s*\\)\\s*;?\\s*$" , "$1" ) ; String mapFunction = findCommaSeparatedArgument ( body , 0 ) . trim ( ) ; String reduceFunction = findCommaSeparatedArgument ( body , 1 ) . trim ( ) ; String query = findCommaSeparatedArgument ( body , 2 ) . trim ( ) ; DBObject parameters = ( DBObject ) JSON . parse ( query ) ; DBObject mongoQuery ; if ( parameters . containsField ( "query" ) ) { mongoQuery = ( DBObject ) parameters . get ( "query" ) ; } else { mongoQuery = new BasicDBObject ( ) ; } return new MapReduceCommand ( collection , mapFunction , reduceFunction , null , MapReduceCommand . OutputType . INLINE , mongoQuery ) ; }
Parses the map reduce command .
35,719
private String findCommaSeparatedArgument ( String functionBody , int index ) { int start = 0 ; int found = - 1 ; int brackets = 0 ; int pos = 0 ; int length = functionBody . length ( ) ; while ( found < index && pos < length ) { char ch = functionBody . charAt ( pos ) ; switch ( ch ) { case ',' : if ( brackets == 0 ) { found ++ ; if ( found < index ) { start = pos + 1 ; } } break ; case '(' : case '[' : case '{' : brackets ++ ; break ; case ')' : case ']' : case '}' : brackets -- ; break ; } pos ++ ; } if ( found == index ) { return functionBody . substring ( start , pos - 1 ) ; } else if ( pos == length ) { return functionBody . substring ( start ) ; } else { return "" ; } }
Find comma separated argument .
35,720
private DBCursor parseAndScroll ( String jsonClause , String collectionName ) throws JSONParseException { BasicDBObject clause = ( BasicDBObject ) JSON . parse ( jsonClause ) ; DBCursor cursor = mongoDb . getCollection ( collectionName ) . find ( clause ) ; return cursor ; }
Parses the and scroll .
35,721
public int handleUpdateFunctions ( BasicDBObject query , BasicDBObject update , String collName ) { DBCollection collection = mongoDb . getCollection ( collName ) ; KunderaCoreUtils . printQuery ( "Update collection:" + query , showQuery ) ; WriteResult result = null ; try { result = collection . update ( query , update ) ; } catch ( MongoException ex ) { return - 1 ; } if ( result . getN ( ) <= 0 ) return - 1 ; return result . getN ( ) ; }
Handle update functions .
35,722
private void createUniqueIndexGFS ( DBCollection coll , String id ) { try { coll . createIndex ( new BasicDBObject ( "metadata." + id , 1 ) , new BasicDBObject ( "unique" , true ) ) ; } catch ( MongoException ex ) { throw new KunderaException ( "Error in creating unique indexes in " + coll . getFullName ( ) + " collection on " + id + " field" ) ; } }
Creates the unique index gfs .
35,723
public static Bucket openBucket ( CouchbaseCluster cluster , String name , String password ) { if ( cluster == null ) { throw new KunderaException ( "CouchbaseCluster object can't be null" ) ; } try { Bucket bucket ; if ( password != null && ! password . trim ( ) . isEmpty ( ) ) { bucket = cluster . openBucket ( name , password ) ; } else { bucket = cluster . openBucket ( name ) ; } LOGGER . debug ( "Bucket [" + name + "] is opened!" ) ; return bucket ; } catch ( CouchbaseException ex ) { LOGGER . error ( "Not able to open bucket [" + name + "]." , ex ) ; throw new KunderaException ( "Not able to open bucket [" + name + "]." , ex ) ; } }
Open bucket .
35,724
public static void closeBucket ( Bucket bucket ) { if ( bucket != null ) { if ( ! bucket . close ( ) ) { LOGGER . error ( "Not able to close bucket [" + bucket . name ( ) + "]." ) ; throw new KunderaException ( "Not able to close bucket [" + bucket . name ( ) + "]." ) ; } else { LOGGER . debug ( "Bucket [" + bucket . name ( ) + "] is closed!" ) ; } } }
Close bucket .
35,725
public Object find ( Class entityClass , Object rowId ) { EntityMetadata metadata = KunderaMetadataManager . getEntityMetadata ( kunderaMetadata , entityClass ) ; StringBuilder builder = createSelectQuery ( rowId , metadata , metadata . getTableName ( ) ) ; ResultSet rSet = this . execute ( builder . toString ( ) , null ) ; List results = iterateAndReturn ( rSet , metadata ) ; return results . isEmpty ( ) ? null : results . get ( 0 ) ; }
Finds an entity from database .
35,726
private StringBuilder createSelectQuery ( Object rowId , EntityMetadata metadata , String tableName ) { MetamodelImpl metaModel = ( MetamodelImpl ) kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( metadata . getPersistenceUnit ( ) ) ; CQLTranslator translator = new CQLTranslator ( ) ; String select_Query = translator . SELECTALL_QUERY ; select_Query = StringUtils . replace ( select_Query , CQLTranslator . COLUMN_FAMILY , translator . ensureCase ( new StringBuilder ( ) , tableName , false ) . toString ( ) ) ; StringBuilder builder = new StringBuilder ( select_Query ) ; builder . append ( CQLTranslator . ADD_WHERE_CLAUSE ) ; onWhereClause ( metadata , rowId , translator , builder , metaModel , metadata . getIdAttribute ( ) ) ; builder . delete ( builder . lastIndexOf ( CQLTranslator . AND_CLAUSE ) , builder . length ( ) ) ; return builder ; }
Creates the select query .
35,727
private void populateSecondaryTableData ( Object rowId , Object entity , MetamodelImpl metaModel , EntityMetadata metadata ) { AbstractManagedType managedType = ( AbstractManagedType ) metaModel . entity ( metadata . getEntityClazz ( ) ) ; List < String > secondaryTables = ( ( DefaultEntityAnnotationProcessor ) managedType . getEntityAnnotation ( ) ) . getSecondaryTablesName ( ) ; for ( String tableName : secondaryTables ) { StringBuilder builder = createSelectQuery ( rowId , metadata , tableName ) ; ResultSet rSet = this . execute ( builder . toString ( ) , null ) ; Iterator < Row > rowIter = rSet . iterator ( ) ; Row row = rowIter . next ( ) ; ColumnDefinitions columnDefs = row . getColumnDefinitions ( ) ; Iterator < Definition > columnDefIter = columnDefs . iterator ( ) ; entity = iteratorColumns ( metadata , metaModel , metaModel . entity ( metadata . getEntityClazz ( ) ) , new HashMap < String , Object > ( ) , entity , row , columnDefIter ) ; } }
Populates data form secondary tables of entity for given row key .
35,728
private Object iteratorColumns ( EntityMetadata metadata , MetamodelImpl metamodel , EntityType entityType , Map < String , Object > relationalValues , Object entity , Row row , Iterator < Definition > columnDefIter ) { while ( columnDefIter . hasNext ( ) ) { Definition columnDef = columnDefIter . next ( ) ; final String columnName = columnDef . getName ( ) ; DataType dataType = columnDef . getType ( ) ; if ( metadata . getRelationNames ( ) != null && metadata . getRelationNames ( ) . contains ( columnName ) && ! columnName . equals ( ( ( AbstractAttribute ) metadata . getIdAttribute ( ) ) . getJPAColumnName ( ) ) ) { Object relationalValue = DSClientUtilities . assign ( row , null , metadata , dataType . getName ( ) , entityType , columnName , null , metamodel ) ; relationalValues . put ( columnName , relationalValue ) ; } else { String fieldName = columnName . equals ( ( ( AbstractAttribute ) metadata . getIdAttribute ( ) ) . getJPAColumnName ( ) ) ? metadata . getIdAttribute ( ) . getName ( ) : metadata . getFieldName ( columnName ) ; Attribute attribute = fieldName != null ? entityType . getAttribute ( fieldName ) : null ; if ( attribute != null ) { if ( ! attribute . isAssociation ( ) ) { entity = DSClientUtilities . assign ( row , entity , metadata , dataType . getName ( ) , entityType , columnName , null , metamodel ) ; } } else if ( metamodel . isEmbeddable ( metadata . getIdAttribute ( ) . getBindableJavaType ( ) ) ) { entity = populateCompositeId ( metadata , entity , columnName , row , metamodel , metadata . getIdAttribute ( ) , metadata . getEntityClazz ( ) , dataType ) ; } else { entity = DSClientUtilities . assign ( row , entity , metadata , dataType . getName ( ) , entityType , columnName , null , metamodel ) ; } } } return entity ; }
Iterator columns .
35,729
private Object getCompoundKey ( Attribute attribute , Object entity ) throws InstantiationException , IllegalAccessException { Object compoundKeyObject = null ; if ( entity != null ) { compoundKeyObject = PropertyAccessorHelper . getObject ( entity , ( Field ) attribute . getJavaMember ( ) ) ; if ( compoundKeyObject == null ) { compoundKeyObject = ( ( AbstractAttribute ) attribute ) . getBindableJavaType ( ) . newInstance ( ) ; } } return compoundKeyObject ; }
Gets the compound key .
35,730
public void setKeyValues ( String keyName , Object obj ) { if ( this . keyValues == null ) { this . keyValues = new HashMap < String , Object > ( ) ; } this . keyValues . put ( keyName , obj ) ; }
Sets the key values .
35,731
public AggregationBuilder buildAggregation ( KunderaQuery query , EntityMetadata entityMetadata , QueryBuilder filter ) { SelectStatement selectStatement = query . getSelectStatement ( ) ; AggregationBuilder aggregationBuilder = buildWhereAggregations ( entityMetadata , filter ) ; if ( KunderaQueryUtils . hasGroupBy ( query . getJpqlExpression ( ) ) ) { TermsBuilder termsBuilder = processGroupByClause ( selectStatement . getGroupByClause ( ) , entityMetadata , query ) ; aggregationBuilder . subAggregation ( termsBuilder ) ; } else { if ( KunderaQueryUtils . hasHaving ( query . getJpqlExpression ( ) ) ) { logger . error ( "Identified having clause without group by, Throwing not supported operation Exception" ) ; throw new UnsupportedOperationException ( "Currently, Having clause without group by caluse is not supported." ) ; } else { aggregationBuilder = ( selectStatement != null ) ? query . isAggregated ( ) ? buildSelectAggregations ( aggregationBuilder , selectStatement , entityMetadata ) : null : null ; } } return aggregationBuilder ; }
Use aggregation .
35,732
private AggregationBuilder addHavingClause ( Expression havingExpression , AggregationBuilder aggregationBuilder , EntityMetadata entityMetadata ) { if ( havingExpression instanceof ComparisonExpression ) { Expression expression = ( ( ComparisonExpression ) havingExpression ) . getLeftExpression ( ) ; if ( ! isAggregationExpression ( expression ) ) { logger . error ( "Having clause conditions over non metric aggregated are not supported." ) ; throw new UnsupportedOperationException ( "Currently, Having clause without Metric aggregations are not supported." ) ; } return checkIfKeyExists ( expression . toParsedText ( ) ) ? aggregationBuilder . subAggregation ( getMetricsAggregation ( expression , entityMetadata ) ) : aggregationBuilder ; } else if ( havingExpression instanceof AndExpression ) { AndExpression andExpression = ( AndExpression ) havingExpression ; addHavingClause ( andExpression . getLeftExpression ( ) , aggregationBuilder , entityMetadata ) ; addHavingClause ( andExpression . getRightExpression ( ) , aggregationBuilder , entityMetadata ) ; return aggregationBuilder ; } else if ( havingExpression instanceof OrExpression ) { OrExpression orExpression = ( OrExpression ) havingExpression ; addHavingClause ( orExpression . getLeftExpression ( ) , aggregationBuilder , entityMetadata ) ; addHavingClause ( orExpression . getRightExpression ( ) , aggregationBuilder , entityMetadata ) ; return aggregationBuilder ; } else { logger . error ( havingExpression + "not supported in having clause." ) ; throw new UnsupportedOperationException ( havingExpression + "not supported in having clause." ) ; } }
Adds the having clauses .
35,733
private TermsBuilder processGroupByClause ( Expression expression , EntityMetadata entityMetadata , KunderaQuery query ) { MetamodelImpl metaModel = ( MetamodelImpl ) kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( entityMetadata . getPersistenceUnit ( ) ) ; Expression groupByClause = ( ( GroupByClause ) expression ) . getGroupByItems ( ) ; if ( groupByClause instanceof CollectionExpression ) { logger . error ( "More than one item found in group by clause." ) ; throw new UnsupportedOperationException ( "Currently, Group By on more than one field is not supported." ) ; } SelectStatement selectStatement = query . getSelectStatement ( ) ; String jPAField = KunderaCoreUtils . getJPAColumnName ( groupByClause . toParsedText ( ) , entityMetadata , metaModel ) ; TermsBuilder termsBuilder = AggregationBuilders . terms ( ESConstants . GROUP_BY ) . field ( jPAField ) . size ( 0 ) ; TopHitsBuilder topHitsBuilder = getTopHitsAggregation ( selectStatement , null , entityMetadata ) ; termsBuilder . subAggregation ( topHitsBuilder ) ; buildSelectAggregations ( termsBuilder , query . getSelectStatement ( ) , entityMetadata ) ; if ( KunderaQueryUtils . hasHaving ( query . getJpqlExpression ( ) ) ) { addHavingClause ( ( ( HavingClause ) selectStatement . getHavingClause ( ) ) . getConditionalExpression ( ) , termsBuilder , entityMetadata ) ; } if ( KunderaQueryUtils . hasOrderBy ( query . getJpqlExpression ( ) ) ) { processOrderByClause ( termsBuilder , KunderaQueryUtils . getOrderByClause ( query . getJpqlExpression ( ) ) , groupByClause , entityMetadata ) ; } return termsBuilder ; }
Process group by clause .
35,734
private void processOrderByClause ( TermsBuilder termsBuilder , Expression orderByExpression , Expression groupByClause , EntityMetadata entityMetadata ) { Expression orderByClause = ( OrderByClause ) orderByExpression ; OrderByItem orderByItems = ( OrderByItem ) ( ( OrderByClause ) orderByClause ) . getOrderByItems ( ) ; if ( orderByClause instanceof CollectionExpression || ! ( orderByItems . getExpression ( ) . toParsedText ( ) . equalsIgnoreCase ( groupByClause . toParsedText ( ) ) ) ) { logger . error ( "Order by and group by on different field are not supported simultaneously" ) ; throw new UnsupportedOperationException ( "Order by and group by on different field are not supported simultaneously" ) ; } String ordering = orderByItems . getOrdering ( ) . toString ( ) ; termsBuilder . order ( Terms . Order . term ( ! ordering . equalsIgnoreCase ( Expression . DESC ) ) ) ; }
Process order by clause .
35,735
private TopHitsBuilder getTopHitsAggregation ( SelectStatement selectStatement , Integer size , EntityMetadata entityMetadata ) { TopHitsBuilder topHitsBuilder = AggregationBuilders . topHits ( ESConstants . TOP_HITS ) ; if ( size != null ) { topHitsBuilder . setSize ( size ) ; } return topHitsBuilder ; }
Gets the top hits aggregation .
35,736
private FilterAggregationBuilder buildWhereAggregations ( EntityMetadata entityMetadata , QueryBuilder filter ) { filter = filter != null ? filter : QueryBuilders . matchAllQuery ( ) ; FilterAggregationBuilder filteragg = AggregationBuilders . filter ( ESConstants . AGGREGATION_NAME ) . filter ( filter ) ; return filteragg ; }
Builds the where aggregations .
35,737
private AggregationBuilder buildSelectAggregations ( AggregationBuilder aggregationBuilder , SelectStatement selectStatement , EntityMetadata entityMetadata ) { Expression expression = ( ( SelectClause ) selectStatement . getSelectClause ( ) ) . getSelectExpression ( ) ; if ( expression instanceof CollectionExpression ) { aggregationBuilder = appendAggregation ( ( CollectionExpression ) expression , entityMetadata , aggregationBuilder ) ; } else { if ( isAggregationExpression ( expression ) && checkIfKeyExists ( expression . toParsedText ( ) ) ) aggregationBuilder . subAggregation ( getMetricsAggregation ( expression , entityMetadata ) ) ; } return aggregationBuilder ; }
Builds the select aggregations .
35,738
private AggregationBuilder appendAggregation ( CollectionExpression collectionExpression , EntityMetadata entityMetadata , AggregationBuilder aggregationBuilder ) { ListIterable < Expression > functionlist = collectionExpression . children ( ) ; for ( Expression function : functionlist ) { if ( isAggregationExpression ( function ) && checkIfKeyExists ( function . toParsedText ( ) ) ) { aggregationBuilder . subAggregation ( getMetricsAggregation ( function , entityMetadata ) ) ; } } return aggregationBuilder ; }
Append aggregation .
35,739
private MetricsAggregationBuilder getMetricsAggregation ( Expression expression , EntityMetadata entityMetadata ) { AggregateFunction function = ( AggregateFunction ) expression ; MetamodelImpl metaModel = ( MetamodelImpl ) kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( entityMetadata . getPersistenceUnit ( ) ) ; String jPAColumnName = KunderaCoreUtils . getJPAColumnName ( function . toParsedText ( ) , entityMetadata , metaModel ) ; MetricsAggregationBuilder aggregationBuilder = null ; switch ( function . getIdentifier ( ) ) { case Expression . MIN : aggregationBuilder = AggregationBuilders . min ( function . toParsedText ( ) ) . field ( jPAColumnName ) ; break ; case Expression . MAX : aggregationBuilder = AggregationBuilders . max ( function . toParsedText ( ) ) . field ( jPAColumnName ) ; break ; case Expression . SUM : aggregationBuilder = AggregationBuilders . sum ( function . toParsedText ( ) ) . field ( jPAColumnName ) ; break ; case Expression . AVG : aggregationBuilder = AggregationBuilders . avg ( function . toParsedText ( ) ) . field ( jPAColumnName ) ; break ; case Expression . COUNT : aggregationBuilder = AggregationBuilders . count ( function . toParsedText ( ) ) . field ( jPAColumnName ) ; break ; } return aggregationBuilder ; }
Gets the aggregation .
35,740
private boolean checkIfKeyExists ( String key ) { if ( aggregationsKeySet == null ) { aggregationsKeySet = new HashSet < String > ( ) ; } return aggregationsKeySet . add ( key ) ; }
Checks whether key exist in ES Query .
35,741
private void removePool ( IThriftPool pool ) { Pelops . removePool ( PelopsUtils . getPoolName ( pool ) ) ; Node [ ] nodes = ( ( CommonsBackedPool ) pool ) . getCluster ( ) . getNodes ( ) ; logger . warn ( "{} :{} host appears to be down, trying for next " , nodes , ( ( CommonsBackedPool ) pool ) . getCluster ( ) . getConnectionConfig ( ) . getThriftPort ( ) ) ; CassandraHost cassandraHost = ( ( CassandraHostConfiguration ) configuration ) . getCassandraHost ( nodes [ 0 ] . getAddress ( ) , ( ( CommonsBackedPool ) pool ) . getCluster ( ) . getConnectionConfig ( ) . getThriftPort ( ) ) ; hostPools . remove ( cassandraHost ) ; }
Removes downed host pool from pool map .
35,742
public void dropSchema ( ) { try { for ( TableInfo tableInfo : tableInfos ) { HttpResponse deleteResponse = null ; Map < String , MapReduce > views = new HashMap < String , MapReduce > ( ) ; String id = CouchDBConstants . DESIGN + tableInfo . getTableName ( ) ; CouchDBDesignDocument designDocument = getDesignDocument ( id ) ; designDocument . setLanguage ( CouchDBConstants . LANGUAGE ) ; views = designDocument . getViews ( ) ; if ( views != null ) { StringBuilder builder = new StringBuilder ( "rev=" ) ; builder . append ( designDocument . get_rev ( ) ) ; URI uri = new URI ( CouchDBConstants . PROTOCOL , null , httpHost . getHostName ( ) , httpHost . getPort ( ) , CouchDBConstants . URL_SEPARATOR + databaseName . toLowerCase ( ) + CouchDBConstants . URL_SEPARATOR + id , builder . toString ( ) , null ) ; HttpDelete delete = new HttpDelete ( uri ) ; try { deleteResponse = httpClient . execute ( httpHost , delete , CouchDBUtils . getContext ( httpHost ) ) ; } finally { CouchDBUtils . closeContent ( deleteResponse ) ; } } } } catch ( Exception e ) { logger . error ( "Error while creating database, caused by {}." , e ) ; throw new SchemaGenerationException ( "Error while creating database" , e , "couchDB" ) ; } }
drop design document from db .
35,743
protected boolean initiateClient ( ) { try { SchemeSocketFactory ssf = null ; ssf = PlainSocketFactory . getSocketFactory ( ) ; SchemeRegistry schemeRegistry = new SchemeRegistry ( ) ; schemeRegistry . register ( new Scheme ( "http" , Integer . parseInt ( port ) , ssf ) ) ; PoolingClientConnectionManager ccm = new PoolingClientConnectionManager ( schemeRegistry ) ; httpClient = new DefaultHttpClient ( ccm ) ; httpHost = new HttpHost ( hosts [ 0 ] , Integer . parseInt ( port ) , "http" ) ; httpClient . getParams ( ) . setParameter ( CoreProtocolPNames . HTTP_CONTENT_CHARSET , "UTF-8" ) ; if ( userName != null && password != null ) { ( ( AbstractHttpClient ) httpClient ) . getCredentialsProvider ( ) . setCredentials ( new AuthScope ( hosts [ 0 ] , Integer . parseInt ( port ) ) , new UsernamePasswordCredentials ( userName , password ) ) ; } ( ( DefaultHttpClient ) httpClient ) . addRequestInterceptor ( new HttpRequestInterceptor ( ) { public void process ( final HttpRequest request , final HttpContext context ) throws IOException { if ( logger . isInfoEnabled ( ) ) { RequestLine requestLine = request . getRequestLine ( ) ; logger . info ( ">> " + requestLine . getMethod ( ) + " " + URI . create ( requestLine . getUri ( ) ) . getPath ( ) ) ; } } } ) ; ( ( DefaultHttpClient ) httpClient ) . addResponseInterceptor ( new HttpResponseInterceptor ( ) { public void process ( final HttpResponse response , final HttpContext context ) throws IOException { if ( logger . isInfoEnabled ( ) ) logger . info ( "<< Status: " + response . getStatusLine ( ) . getStatusCode ( ) ) ; } } ) ; } catch ( Exception e ) { logger . error ( "Error Creating HTTP client {}. " , e ) ; throw new IllegalStateException ( e ) ; } return true ; }
Instantiate http client .
35,744
protected void validate ( List < TableInfo > tableInfos ) { try { if ( ! checkForDBExistence ( ) ) { throw new SchemaGenerationException ( "Database " + databaseName + " not exist" ) ; } for ( TableInfo tableInfo : tableInfos ) { Map < String , MapReduce > views = new HashMap < String , MapReduce > ( ) ; String id = CouchDBConstants . DESIGN + tableInfo . getTableName ( ) ; CouchDBDesignDocument designDocument = getDesignDocument ( id ) ; designDocument . setLanguage ( CouchDBConstants . LANGUAGE ) ; views = designDocument . getViews ( ) ; if ( views == null ) { logger . warn ( "No view exist for table " + tableInfo . getTableName ( ) + "so any query will not produce any result" ) ; return ; } for ( IndexInfo indexInfo : tableInfo . getColumnsToBeIndexed ( ) ) { if ( views . get ( indexInfo . getColumnName ( ) ) == null ) { logger . warn ( "No view exist for column " + indexInfo . getColumnName ( ) + " of table " + tableInfo . getTableName ( ) + "so any query on column " + indexInfo . getColumnName ( ) + "will not produce any result" ) ; } } if ( views . get ( tableInfo . getIdColumnName ( ) ) == null ) { logger . warn ( "No view exist for id column " + tableInfo . getIdColumnName ( ) + " of table " + tableInfo . getTableName ( ) + "so any query on id column " + tableInfo . getIdColumnName ( ) + "will not produce any result" ) ; } if ( views . get ( "all" ) == null ) { logger . warn ( "No view exist for select all for table " + tableInfo . getTableName ( ) + "so select all query will not produce any result" ) ; } } } catch ( Exception e ) { throw new SchemaGenerationException ( "Database " + databaseName + " not exist" ) ; } }
Validate design document .
35,745
protected void update ( List < TableInfo > tableInfos ) { try { HttpResponse response = null ; createDatabaseIfNotExist ( false ) ; for ( TableInfo tableInfo : tableInfos ) { String id = CouchDBConstants . DESIGN + tableInfo . getTableName ( ) ; CouchDBDesignDocument designDocument = getDesignDocument ( id ) ; designDocument . setLanguage ( CouchDBConstants . LANGUAGE ) ; Map < String , MapReduce > views = designDocument . getViews ( ) ; if ( views == null ) { views = new HashMap < String , MapReduce > ( ) ; } for ( IndexInfo indexInfo : tableInfo . getColumnsToBeIndexed ( ) ) { createViewIfNotExist ( views , indexInfo . getColumnName ( ) ) ; } createViewIfNotExist ( views , tableInfo . getIdColumnName ( ) ) ; createViewForSelectAllIfNotExist ( tableInfo , views ) ; createViewForSelectSpecificFields ( views ) ; designDocument . setViews ( views ) ; URI uri = null ; if ( designDocument . get_rev ( ) == null ) { uri = new URI ( CouchDBConstants . PROTOCOL , null , httpHost . getHostName ( ) , httpHost . getPort ( ) , CouchDBConstants . URL_SEPARATOR + databaseName . toLowerCase ( ) + CouchDBConstants . URL_SEPARATOR + id , null , null ) ; } else { StringBuilder builder = new StringBuilder ( "rev=" ) ; builder . append ( designDocument . get_rev ( ) ) ; uri = new URI ( CouchDBConstants . PROTOCOL , null , httpHost . getHostName ( ) , httpHost . getPort ( ) , CouchDBConstants . URL_SEPARATOR + databaseName . toLowerCase ( ) + CouchDBConstants . URL_SEPARATOR + id , builder . toString ( ) , null ) ; } HttpPut put = new HttpPut ( uri ) ; String jsonObject = gson . toJson ( designDocument ) ; StringEntity entity = new StringEntity ( jsonObject ) ; put . setEntity ( entity ) ; try { response = httpClient . execute ( httpHost , put , CouchDBUtils . getContext ( httpHost ) ) ; } finally { CouchDBUtils . closeContent ( response ) ; } } createDesignDocForAggregations ( ) ; } catch ( Exception e ) { logger . error ( "Error while creating database, caused by {}." , e ) ; throw new SchemaGenerationException ( "Error while creating database" , e , "couchDB" ) ; } }
Update design document .
35,746
protected void create ( List < TableInfo > tableInfos ) { try { HttpResponse response = null ; createDatabaseIfNotExist ( true ) ; for ( TableInfo tableInfo : tableInfos ) { CouchDBDesignDocument designDocument = new CouchDBDesignDocument ( ) ; Map < String , MapReduce > views = new HashMap < String , CouchDBDesignDocument . MapReduce > ( ) ; designDocument . setLanguage ( CouchDBConstants . LANGUAGE ) ; String id = CouchDBConstants . DESIGN + tableInfo . getTableName ( ) ; for ( IndexInfo indexInfo : tableInfo . getColumnsToBeIndexed ( ) ) { createView ( views , indexInfo . getColumnName ( ) ) ; } createView ( views , tableInfo . getIdColumnName ( ) ) ; createViewForSelectAll ( tableInfo , views ) ; createViewForSelectSpecificFields ( views ) ; designDocument . setViews ( views ) ; URI uri = new URI ( CouchDBConstants . PROTOCOL , null , httpHost . getHostName ( ) , httpHost . getPort ( ) , CouchDBConstants . URL_SEPARATOR + databaseName . toLowerCase ( ) + CouchDBConstants . URL_SEPARATOR + id , null , null ) ; HttpPut put = new HttpPut ( uri ) ; String jsonObject = gson . toJson ( designDocument ) ; StringEntity entity = new StringEntity ( jsonObject ) ; put . setEntity ( entity ) ; try { response = httpClient . execute ( httpHost , put , CouchDBUtils . getContext ( httpHost ) ) ; } finally { CouchDBUtils . closeContent ( response ) ; } } createDesignDocForAggregations ( ) ; } catch ( Exception e ) { logger . error ( "Error while creating database {} , caused by {}." , databaseName , e ) ; throw new SchemaGenerationException ( "Error while creating database" , e , "couchDB" ) ; } }
Create database and design document .
35,747
private void createDesignDocForAggregations ( ) throws URISyntaxException , UnsupportedEncodingException , IOException , ClientProtocolException { HttpResponse response = null ; URI uri = new URI ( CouchDBConstants . PROTOCOL , null , httpHost . getHostName ( ) , httpHost . getPort ( ) , CouchDBConstants . URL_SEPARATOR + databaseName . toLowerCase ( ) + CouchDBConstants . URL_SEPARATOR + "_design/" + CouchDBConstants . AGGREGATIONS , null , null ) ; HttpPut put = new HttpPut ( uri ) ; CouchDBDesignDocument designDocument = new CouchDBDesignDocument ( ) ; Map < String , MapReduce > views = new HashMap < String , CouchDBDesignDocument . MapReduce > ( ) ; designDocument . setLanguage ( CouchDBConstants . LANGUAGE ) ; createViewForCount ( views ) ; createViewForSum ( views ) ; createViewForMax ( views ) ; createViewForMin ( views ) ; createViewForAvg ( views ) ; designDocument . setViews ( views ) ; String jsonObject = gson . toJson ( designDocument ) ; StringEntity entity = new StringEntity ( jsonObject ) ; put . setEntity ( entity ) ; try { response = httpClient . execute ( httpHost , put , CouchDBUtils . getContext ( httpHost ) ) ; } finally { CouchDBUtils . closeContent ( response ) ; } }
Creates the design doc for aggregations .
35,748
private void createViewForSelectSpecificFields ( Map < String , MapReduce > views ) { if ( views . get ( CouchDBConstants . FIELDS ) == null ) { MapReduce mapr = new MapReduce ( ) ; mapr . setMap ( "function(doc){for(field in doc){emit(field, doc[field]);}}" ) ; views . put ( CouchDBConstants . FIELDS , mapr ) ; } }
Creates the view for select specific fields .
35,749
private void createViewForCount ( Map < String , MapReduce > views ) { if ( views . get ( CouchDBConstants . COUNT ) == null ) { MapReduce mapr = new MapReduce ( ) ; mapr . setMap ( "function(doc){" + "for(field in doc){if(field!=\"" + CouchDBConstants . ENTITYNAME + "\"){var o = doc[field];emit(field+\"_\"+doc." + CouchDBConstants . ENTITYNAME + ", o);" + "}}" + "emit(\"" + CouchDBConstants . ALL + "_\"+doc." + CouchDBConstants . ENTITYNAME + ", null);}" ) ; mapr . setReduce ( "function(keys, values){return values.length;}" ) ; views . put ( CouchDBConstants . COUNT , mapr ) ; } }
Creates the view for count .
35,750
private void createViewForSum ( Map < String , MapReduce > views ) { if ( views . get ( CouchDBConstants . SUM ) == null ) { MapReduce mapr = new MapReduce ( ) ; mapr . setMap ( "function(doc){for(field in doc){var o = doc[field];if(typeof(o)==\"number\")emit(field+\"_\"+doc." + CouchDBConstants . ENTITYNAME + ", o);}}" ) ; mapr . setReduce ( "function(keys, values){return sum(values);}" ) ; views . put ( CouchDBConstants . SUM , mapr ) ; } }
Creates the view for sum .
35,751
private void createViewForMax ( Map < String , MapReduce > views ) { if ( views . get ( CouchDBConstants . MAX ) == null ) { MapReduce mapr = new MapReduce ( ) ; mapr . setMap ( "function(doc){for(field in doc){var o = doc[field];if(typeof(o)==\"number\")emit(field+\"_\"+doc." + CouchDBConstants . ENTITYNAME + ", o);}}" ) ; mapr . setReduce ( "function(keys, values){return Math.max.apply(Math, values);}" ) ; views . put ( CouchDBConstants . MAX , mapr ) ; } }
Creates the view for max .
35,752
private void createViewForMin ( Map < String , MapReduce > views ) { if ( views . get ( CouchDBConstants . MIN ) == null ) { MapReduce mapr = new MapReduce ( ) ; mapr . setMap ( "function(doc){for(field in doc){var o = doc[field];if(typeof(o)==\"number\")emit(field+\"_\"+doc." + CouchDBConstants . ENTITYNAME + ", o);}}" ) ; mapr . setReduce ( "function(keys, values){return Math.min.apply(Math, values);}" ) ; views . put ( CouchDBConstants . MIN , mapr ) ; } }
Creates the view for min .
35,753
private void createViewForAvg ( Map < String , MapReduce > views ) { if ( views . get ( CouchDBConstants . AVG ) == null ) { MapReduce mapr = new MapReduce ( ) ; mapr . setMap ( "function(doc){for(field in doc){var o = doc[field];if(typeof(o)==\"number\")emit(field+\"_\"+doc." + CouchDBConstants . ENTITYNAME + ", o);}}" ) ; mapr . setReduce ( "function(keys, values){return sum(values)/values.length;}" ) ; views . put ( CouchDBConstants . AVG , mapr ) ; } }
Creates the view for avg .
35,754
private void createViewIfNotExist ( Map < String , MapReduce > views , String columnName ) { if ( views . get ( columnName ) == null ) { createView ( views , columnName ) ; } }
Creates the view if not exist .
35,755
private void createViewForSelectAllIfNotExist ( TableInfo tableInfo , Map < String , MapReduce > views ) { if ( views . get ( "all" ) == null ) { createViewForSelectAll ( tableInfo , views ) ; } }
Creates the view for select all if not exist .
35,756
private void createViewForSelectAll ( TableInfo tableInfo , Map < String , MapReduce > views ) { MapReduce mapr = new MapReduce ( ) ; mapr . setMap ( "function(doc){if(doc." + tableInfo . getIdColumnName ( ) + "){emit(null, doc);}}" ) ; views . put ( "all" , mapr ) ; }
Creates the view for select all .
35,757
private void createDatabaseIfNotExist ( boolean drop ) throws URISyntaxException , IOException , ClientProtocolException { boolean exist = checkForDBExistence ( ) ; if ( exist && drop ) { dropDatabase ( ) ; exist = false ; } if ( ! exist ) { URI uri = new URI ( CouchDBConstants . PROTOCOL , null , httpHost . getHostName ( ) , httpHost . getPort ( ) , CouchDBConstants . URL_SEPARATOR + databaseName . toLowerCase ( ) , null , null ) ; HttpPut put = new HttpPut ( uri ) ; HttpResponse putRes = null ; try { putRes = httpClient . execute ( httpHost , put , CouchDBUtils . getContext ( httpHost ) ) ; } finally { CouchDBUtils . closeContent ( putRes ) ; } } }
Creates the database if not exist .
35,758
private boolean checkForDBExistence ( ) throws ClientProtocolException , IOException , URISyntaxException { URI uri = new URI ( CouchDBConstants . PROTOCOL , null , httpHost . getHostName ( ) , httpHost . getPort ( ) , CouchDBConstants . URL_SEPARATOR + databaseName . toLowerCase ( ) , null , null ) ; HttpGet get = new HttpGet ( uri ) ; HttpResponse getRes = null ; try { getRes = httpClient . execute ( httpHost , get , CouchDBUtils . getContext ( httpHost ) ) ; if ( getRes . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_OK ) { return true ; } return false ; } finally { CouchDBUtils . closeContent ( getRes ) ; } }
Check for db existence .
35,759
private void dropDatabase ( ) throws IOException , ClientProtocolException , URISyntaxException { HttpResponse delRes = null ; try { URI uri = new URI ( CouchDBConstants . PROTOCOL , null , httpHost . getHostName ( ) , httpHost . getPort ( ) , CouchDBConstants . URL_SEPARATOR + databaseName . toLowerCase ( ) , null , null ) ; HttpDelete delete = new HttpDelete ( uri ) ; delRes = httpClient . execute ( httpHost , delete , CouchDBUtils . getContext ( httpHost ) ) ; } finally { CouchDBUtils . closeContent ( delRes ) ; } }
Drop database .
35,760
private Map < String , List < String > > mapClazztoPu ( Class < ? > clazz , String pu , Map < String , List < String > > clazzToPuMap ) { List < String > puCol = new ArrayList < String > ( 1 ) ; if ( clazzToPuMap == null ) { clazzToPuMap = new HashMap < String , List < String > > ( ) ; } else { if ( clazzToPuMap . containsKey ( clazz . getName ( ) ) ) { puCol = clazzToPuMap . get ( clazz . getName ( ) ) ; } } if ( ! puCol . contains ( pu ) ) { puCol . add ( pu ) ; clazzToPuMap . put ( clazz . getName ( ) , puCol ) ; String annotateEntityName = clazz . getAnnotation ( Entity . class ) . name ( ) ; if ( ! StringUtils . isBlank ( annotateEntityName ) ) { clazzToPuMap . put ( annotateEntityName , puCol ) ; } } return clazzToPuMap ; }
Method to prepare class simple name to list of pu s mapping . 1 class can be mapped to multiple persistence units in case of RDBMS in other cases it will only be 1!
35,761
private void onUpdate ( EventLog log ) { if ( updateEvents == null ) { updateEvents = new ConcurrentHashMap < Object , EventLog > ( ) ; } updateEvents . put ( log . getEntityId ( ) , log ) ; }
On update .
35,762
private void onInsert ( EventLog log ) { if ( insertEvents == null ) { insertEvents = new ConcurrentHashMap < Object , EventLog > ( ) ; } insertEvents . put ( log . getEntityId ( ) , log ) ; }
On insert .
35,763
private void createIdIndex ( String bucketName ) { Bucket bucket = null ; try { bucket = CouchbaseBucketUtils . openBucket ( cluster , bucketName , csmd . getBucketProperty ( "bucket.password" ) ) ; bucket . bucketManager ( ) . createN1qlPrimaryIndex ( buildIndexName ( bucketName ) , true , false ) ; LOGGER . debug ( "Niql primary Index are created for bucket [" + bucketName + "]." ) ; } catch ( CouchbaseException cex ) { LOGGER . error ( "Not able to create Niql primary index for bucket [" + bucketName + "]." , cex ) ; throw new KunderaException ( "Not able to create Niql primary index for bucket [" + bucketName + "]." , cex ) ; } finally { CouchbaseBucketUtils . closeBucket ( bucket ) ; } }
Creates the id index .
35,764
private void removeBucket ( String name ) { try { if ( clusterManager . removeBucket ( name ) ) { LOGGER . info ( "Bucket [" + name + "] is removed!" ) ; } else { LOGGER . error ( "Not able to remove bucket [" + name + "]." ) ; throw new KunderaException ( "Not able to remove bucket [" + name + "]." ) ; } } catch ( CouchbaseException ex ) { LOGGER . error ( "Not able to remove bucket [" + name + "]." , ex ) ; throw new KunderaException ( "Not able to remove bucket [" + name + "]." , ex ) ; } }
Removes the bucket .
35,765
private void addBucket ( String name ) { String qouta = csmd . getBucketProperty ( "bucket.quota" ) ; int bucketQuota = qouta != null ? Integer . parseInt ( qouta ) : DEFAULT_RAM_SIZE_IN_MB ; BucketSettings bucketSettings = new DefaultBucketSettings . Builder ( ) . type ( BucketType . COUCHBASE ) . name ( name ) . quota ( bucketQuota ) . build ( ) ; try { clusterManager . insertBucket ( bucketSettings ) ; LOGGER . info ( "Bucket [" + name + "] is added!" ) ; } catch ( CouchbaseException ex ) { LOGGER . error ( "Not able to add bucket [" + name + "]." , ex ) ; throw new KunderaException ( "Not able to add bucket [" + name + "]." , ex ) ; } }
Adds the bucket .
35,766
private String buildIndexName ( String bucketName ) { if ( bucketName == null ) { throw new KunderaException ( "Bucket Name can't be null!" ) ; } return ( bucketName + CouchbaseConstants . INDEX_SUFFIX ) . toLowerCase ( ) ; }
Builds the index name .
35,767
public String getConnectionString ( EntityMetadata m ) { Properties properties = new Properties ( ) ; String fileName = "teradata.properties" ; InputStream inputStream = getClass ( ) . getClassLoader ( ) . getResourceAsStream ( fileName ) ; if ( inputStream != null ) { try { properties . load ( inputStream ) ; } catch ( IOException e ) { throw new RuntimeException ( "Property file: " + fileName + "not found in the classpath" , e ) ; } } else { throw new RuntimeException ( "Property file: " + fileName + "not found in the classpath" ) ; } String connectionString = "jdbc:teradata://" + properties . getProperty ( "teradata.host" ) + "/database=" + m . getSchema ( ) + ",tmode=ANSI,charset=UTF8,user=" + properties . getProperty ( "teradata.user" ) + ",password=" + properties . getProperty ( "teradata.password" ) + "" ; return connectionString ; }
Gets the connection string .
35,768
public void setImplementor ( ResourceManager implementor ) { KunderaTransaction tx = threadLocal . get ( ) ; if ( tx == null ) { throw new IllegalStateException ( "Cannot get Transaction to start" ) ; } tx . setImplementor ( implementor ) ; }
Links referenced resource to current transaction thread .
35,769
public String getJoinColumnName ( final KunderaMetadata kunderaMetadata ) { if ( joinColumnName == null && isJoinedByPrimaryKey ) { EntityMetadata joinClassMetadata = KunderaMetadataManager . getEntityMetadata ( kunderaMetadata , targetEntity ) ; joinColumnName = ( ( AbstractAttribute ) joinClassMetadata . getIdAttribute ( ) ) . getJPAColumnName ( ) ; } if ( joinTableMetadata != null ) { joinColumnName = joinTableMetadata . getJoinColumns ( ) != null ? joinTableMetadata . getJoinColumns ( ) . iterator ( ) . next ( ) : null ; } if ( isBiDirectional ( ) ) { if ( biDirectionalField . isAnnotationPresent ( JoinColumn . class ) ) { joinColumnName = biDirectionalField . getAnnotation ( JoinColumn . class ) . name ( ) ; } } return joinColumnName != null ? joinColumnName : property . getName ( ) ; }
Gets the join column name .
35,770
public boolean isUnary ( ) { return type . equals ( Relation . ForeignKey . ONE_TO_ONE ) || type . equals ( Relation . ForeignKey . MANY_TO_ONE ) ; }
Checks if is unary .
35,771
public boolean isCollection ( ) { return type . equals ( Relation . ForeignKey . ONE_TO_MANY ) || type . equals ( Relation . ForeignKey . MANY_TO_MANY ) ; }
Checks if is collection .
35,772
private MapObject populateRmap ( EntityMetadata entityMetadata , Object entity ) { MetamodelImpl metaModel = ( MetamodelImpl ) kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( entityMetadata . getPersistenceUnit ( ) ) ; Class entityClazz = entityMetadata . getEntityClazz ( ) ; EntityType entityType = metaModel . entity ( entityClazz ) ; Set < Attribute > attributes = entityType . getAttributes ( ) ; Iterator < Attribute > iterator = attributes . iterator ( ) ; return iterateAndPopulateRmap ( entity , metaModel , iterator ) ; }
Populate rmap .
35,773
private MapObject iterateAndPopulateRmap ( Object entity , MetamodelImpl metaModel , Iterator < Attribute > iterator ) { MapObject map = r . hashMap ( ) ; while ( iterator . hasNext ( ) ) { Attribute attribute = iterator . next ( ) ; Field field = ( Field ) attribute . getJavaMember ( ) ; Object value = PropertyAccessorHelper . getObject ( entity , field ) ; if ( field . isAnnotationPresent ( Id . class ) ) { map . with ( ID , value ) ; } else { map . with ( ( ( AbstractAttribute ) attribute ) . getJPAColumnName ( ) , value ) ; } } return map ; }
Iterate and populate rmap .
35,774
private E fetchObject ( ) { try { String previousSkip = "&skip=" + ( skipCounter - 1 ) ; String currentSkip = "&skip=" + skipCounter ; int indexOf = q . indexOf ( previousSkip ) ; if ( indexOf > 0 ) { q . replace ( indexOf , indexOf + previousSkip . length ( ) , currentSkip ) ; } else if ( skipCounter > 0 ) { q . append ( currentSkip ) ; } client . executeQueryAndGetResults ( q , _id , m , results , interpreter ) ; skipCounter ++ ; } catch ( Exception e ) { logger . error ( "Error while executing query, caused by {}." , e ) ; throw new KunderaException ( "Error while executing query, caused by : " + e ) ; } if ( results != null && ! results . isEmpty ( ) ) { Object object = results . get ( 0 ) ; results = new ArrayList ( ) ; if ( ! m . isRelationViaJoinTable ( ) && ( m . getRelationNames ( ) == null || ( m . getRelationNames ( ) . isEmpty ( ) ) ) ) { return ( E ) object ; } else { return setRelationEntities ( object , client , m ) ; } } return null ; }
Fetch object .
35,775
private String [ ] splitHostNames ( String hostNames ) { String [ ] hostArray = hostNames . split ( Constants . COMMA ) ; String [ ] hosts = new String [ hostArray . length ] ; for ( int i = 0 ; i < hostArray . length ; i ++ ) { hosts [ i ] = hostArray [ i ] . trim ( ) ; } return hosts ; }
Split host names .
35,776
private HTableDescriptor getTableMetaData ( List < TableInfo > tableInfos ) { HTableDescriptor tableDescriptor = new HTableDescriptor ( databaseName ) ; Properties tableProperties = null ; schemas = HBasePropertyReader . hsmd . getDataStore ( ) != null ? HBasePropertyReader . hsmd . getDataStore ( ) . getSchemas ( ) : null ; if ( schemas != null && ! schemas . isEmpty ( ) ) { for ( Schema s : schemas ) { if ( s . getName ( ) != null && s . getName ( ) . equalsIgnoreCase ( databaseName ) ) { tableProperties = s . getSchemaProperties ( ) ; tables = s . getTables ( ) ; } } } for ( TableInfo tableInfo : tableInfos ) { if ( tableInfo != null ) { HColumnDescriptor hColumnDescriptor = getColumnDescriptor ( tableInfo ) ; tableDescriptor . addFamily ( hColumnDescriptor ) ; } } if ( tableProperties != null ) { for ( Object o : tableProperties . keySet ( ) ) { tableDescriptor . setValue ( Bytes . toBytes ( o . toString ( ) ) , Bytes . toBytes ( tableProperties . get ( o ) . toString ( ) ) ) ; } } return tableDescriptor ; }
get Table metadata method returns the HTableDescriptor of table for given tableInfo
35,777
public void persistJoinTable ( JoinTableData joinTableData ) { Mutator mutator = clientFactory . getMutator ( pool ) ; String joinTableName = joinTableData . getJoinTableName ( ) ; String invJoinColumnName = joinTableData . getInverseJoinColumnName ( ) ; Map < Object , Set < Object > > joinTableRecords = joinTableData . getJoinTableRecords ( ) ; EntityMetadata entityMetadata = KunderaMetadataManager . getEntityMetadata ( kunderaMetadata , joinTableData . getEntityClass ( ) ) ; if ( isCql3Enabled ( entityMetadata ) ) { Cassandra . Client conn = null ; Object pooledConnection = null ; pooledConnection = getConnection ( ) ; conn = ( org . apache . cassandra . thrift . Cassandra . Client ) getConnection ( pooledConnection ) ; persistJoinTableByCql ( joinTableData , conn ) ; } else { for ( Object key : joinTableRecords . keySet ( ) ) { Set < Object > values = joinTableRecords . get ( key ) ; List < Column > columns = new ArrayList < Column > ( ) ; Class columnType = null ; for ( Object value : values ) { Column column = new Column ( ) ; column . setName ( PropertyAccessorFactory . STRING . toBytes ( invJoinColumnName + Constants . JOIN_COLUMN_NAME_SEPARATOR + value . toString ( ) ) ) ; column . setValue ( PropertyAccessorHelper . getBytes ( value ) ) ; column . setTimestamp ( generator . getTimestamp ( ) ) ; columnType = value . getClass ( ) ; columns . add ( column ) ; } createIndexesOnColumns ( entityMetadata , joinTableName , columns , columnType ) ; mutator . writeColumns ( joinTableName , Bytes . fromByteArray ( PropertyAccessorHelper . getBytes ( key ) ) , Arrays . asList ( columns . toArray ( new Column [ 0 ] ) ) ) ; } } if ( log . isInfoEnabled ( ) ) { log . info ( " Persisted data with join table column family {}" , joinTableData . getJoinTableName ( ) ) ; } mutator . execute ( getConsistencyLevel ( ) ) ; }
Persists records into Join Table .
35,778
public final List < SuperColumn > loadSuperColumns ( String keyspace , String columnFamily , String rowId , String ... superColumnNames ) { if ( ! isOpen ( ) ) throw new PersistenceException ( "PelopsClient is closed." ) ; Selector selector = clientFactory . getSelector ( pool ) ; List < ByteBuffer > rowKeys = new ArrayList < ByteBuffer > ( ) ; rowKeys . add ( ByteBuffer . wrap ( rowId . getBytes ( ) ) ) ; if ( log . isInfoEnabled ( ) ) { log . info ( "Retrieving record of super column family {} for row key {}" , columnFamily , rowId ) ; } return selector . getSuperColumnsFromRow ( columnFamily , rowId , Selector . newColumnsPredicate ( superColumnNames ) , getConsistencyLevel ( ) ) ; }
Load super columns .
35,779
public List findByRange ( byte [ ] minVal , byte [ ] maxVal , EntityMetadata m , boolean isWrapReq , List < String > relations , List < String > columns , List < IndexExpression > conditions , int maxResults ) throws Exception { Selector selector = clientFactory . getSelector ( pool ) ; SlicePredicate slicePredicate = Selector . newColumnsPredicateAll ( false , Integer . MAX_VALUE ) ; if ( columns != null && ! columns . isEmpty ( ) ) { slicePredicate = Selector . newColumnsPredicate ( columns . toArray ( new String [ ] { } ) ) ; } KeyRange keyRange = selector . newKeyRange ( minVal != null ? Bytes . fromByteArray ( minVal ) : Bytes . fromUTF8 ( "" ) , maxVal != null ? Bytes . fromByteArray ( maxVal ) : Bytes . fromUTF8 ( "" ) , maxResults ) ; if ( conditions != null ) { keyRange . setRow_filter ( conditions ) ; keyRange . setRow_filterIsSet ( true ) ; } List < KeySlice > keys = selector . getKeySlices ( new ColumnParent ( m . getTableName ( ) ) , keyRange , slicePredicate , getConsistencyLevel ( ) ) ; List results = null ; if ( keys != null ) { results = populateEntitiesFromKeySlices ( m , isWrapReq , relations , keys , dataHandler ) ; } if ( log . isInfoEnabled ( ) ) { log . info ( "Returning entities for find by range for" , results != null ? results . size ( ) : null ) ; } return results ; }
Find by range .
35,780
public String getJPAColumnName ( ) { Column column = ( ( AbstractManagedType ) this . managedType ) . getAttributeBinding ( member ) ; if ( column != null ) { columnName = column . name ( ) ; } return columnName ; }
Returns assigned jpa column name .
35,781
private ClientProperties onParseXML ( String propertyFileName , PersistenceUnitMetadata puMetadata ) { InputStream inStream = puMetadata . getClassLoader ( ) . getResourceAsStream ( propertyFileName ) ; if ( inStream == null ) { propertyFileName = KunderaCoreUtils . resolvePath ( propertyFileName ) ; try { inStream = new FileInputStream ( new File ( propertyFileName ) ) ; } catch ( FileNotFoundException e ) { log . warn ( "File {} not found, Caused by " , propertyFileName ) ; return null ; } } if ( inStream != null ) { xStream = getXStreamObject ( ) ; Object o = xStream . fromXML ( inStream ) ; return ( ClientProperties ) o ; } return null ; }
If property file is xml .
35,782
private void initiateJPQLObject ( final String jpaQuery ) { JPQLGrammar jpqlGrammar = EclipseLinkJPQLGrammar2_4 . instance ( ) ; this . jpqlExpression = new JPQLExpression ( jpaQuery , jpqlGrammar , "ql_statement" , true ) ; setKunderaQueryTypeObject ( ) ; }
Initiate jpql object .
35,783
private void setKunderaQueryTypeObject ( ) { try { if ( isSelectStatement ( ) ) { this . setSelectStatement ( ( SelectStatement ) ( this . getJpqlExpression ( ) . getQueryStatement ( ) ) ) ; } else if ( isUpdateStatement ( ) ) { this . setUpdateStatement ( ( UpdateStatement ) ( this . getJpqlExpression ( ) . getQueryStatement ( ) ) ) ; } else if ( isDeleteStatement ( ) ) { this . setDeleteStatement ( ( DeleteStatement ) ( this . getJpqlExpression ( ) . getQueryStatement ( ) ) ) ; } } catch ( ClassCastException cce ) { throw new JPQLParseException ( "Bad query format : " + cce . getMessage ( ) ) ; } }
Sets the kundera query type object .
35,784
public List < Object > getClauseValue ( String paramString ) { if ( typedParameter != null && typedParameter . getParameters ( ) != null ) { List < FilterClause > clauses = typedParameter . getParameters ( ) . get ( paramString ) ; if ( clauses != null ) { return clauses . get ( 0 ) . getValue ( ) ; } else { throw new IllegalArgumentException ( "parameter is not a parameter of the query" ) ; } } logger . error ( "Parameter {} is not a parameter of the query." , paramString ) ; throw new IllegalArgumentException ( "Parameter is not a parameter of the query." ) ; }
Returns clause value for supplied parameter .
35,785
public List < Object > getClauseValue ( Parameter param ) { Parameter match = null ; if ( typedParameter != null && typedParameter . jpaParameters != null ) { for ( Parameter p : typedParameter . jpaParameters ) { if ( p . equals ( param ) ) { match = p ; if ( typedParameter . getType ( ) . equals ( Type . NAMED ) ) { List < FilterClause > clauses = typedParameter . getParameters ( ) . get ( ":" + p . getName ( ) ) ; if ( clauses != null ) { return clauses . get ( 0 ) . getValue ( ) ; } } else { List < FilterClause > clauses = typedParameter . getParameters ( ) . get ( "?" + p . getPosition ( ) ) ; if ( clauses != null ) { return clauses . get ( 0 ) . getValue ( ) ; } else { UpdateClause updateClause = typedParameter . getUpdateParameters ( ) . get ( "?" + p . getPosition ( ) ) ; if ( updateClause != null ) { List < Object > value = new ArrayList < Object > ( ) ; value . add ( updateClause . getValue ( ) ) ; return value ; } } } break ; } } if ( match == null ) { throw new IllegalArgumentException ( "parameter is not a parameter of the query" ) ; } } logger . error ( "parameter{} is not a parameter of the query" , param ) ; throw new IllegalArgumentException ( "parameter is not a parameter of the query" ) ; }
Returns specific clause value .
35,786
private void initUpdateClause ( ) { for ( UpdateClause updateClause : updateClauseQueue ) { onTypedParameter ( updateClause . getValue ( ) , updateClause , updateClause . getProperty ( ) . trim ( ) ) ; } }
Inits the update clause .
35,787
private void initEntityClass ( ) { if ( from == null ) { throw new JPQLParseException ( "Bad query format FROM clause is mandatory for SELECT queries" ) ; } String fromArray [ ] = from . split ( " " ) ; if ( ! this . isDeleteUpdate ) { if ( fromArray . length == 3 && fromArray [ 1 ] . equalsIgnoreCase ( "as" ) ) { fromArray = new String [ ] { fromArray [ 0 ] , fromArray [ 2 ] } ; } if ( fromArray . length != 2 ) { throw new JPQLParseException ( "Bad query format: " + from + ". Identification variable is mandatory in FROM clause for SELECT queries" ) ; } StringTokenizer tokenizer = new StringTokenizer ( result [ 0 ] , "," ) ; while ( tokenizer . hasMoreTokens ( ) ) { String token = tokenizer . nextToken ( ) ; if ( ! StringUtils . containsAny ( fromArray [ 1 ] + "." , token ) ) { throw new QueryHandlerException ( "bad query format with invalid alias:" + token ) ; } } } this . entityName = fromArray [ 0 ] ; if ( fromArray . length == 2 ) this . entityAlias = fromArray [ 1 ] ; persistenceUnit = kunderaMetadata . getApplicationMetadata ( ) . getMappedPersistenceUnit ( entityName ) ; MetamodelImpl model = getMetamodel ( persistenceUnit ) ; if ( model != null ) { entityClass = model . getEntityClass ( entityName ) ; } if ( null == entityClass ) { logger . error ( "No entity {} found, please verify it is properly annotated with @Entity and not a mapped Super class" , entityName ) ; throw new QueryHandlerException ( "No entity found by the name: " + entityName ) ; } EntityMetadata metadata = model . getEntityMetadata ( entityClass ) ; if ( metadata != null && ! metadata . isIndexable ( ) ) { throw new QueryHandlerException ( entityClass + " is not indexed. Not possible to run a query on it." + " Check whether it was properly annotated for indexing." ) ; } }
Inits the entity class .
35,788
private void initFilter ( ) { EntityMetadata metadata = KunderaMetadataManager . getEntityMetadata ( kunderaMetadata , entityClass ) ; Metamodel metaModel = kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( getPersistenceUnit ( ) ) ; EntityType entityType = metaModel . entity ( entityClass ) ; if ( null == filter ) { List < String > clauses = new ArrayList < String > ( ) ; addDiscriminatorClause ( clauses , entityType ) ; return ; } WhereClause whereClause = KunderaQueryUtils . getWhereClause ( getJpqlExpression ( ) ) ; KunderaQueryUtils . traverse ( whereClause . getConditionalExpression ( ) , metadata , kunderaMetadata , this , false ) ; for ( Object filterClause : filtersQueue ) { if ( ! ( filterClause instanceof String ) ) { onTypedParameter ( ( ( FilterClause ) filterClause ) ) ; } } addDiscriminatorClause ( null , entityType ) ; }
Inits the filter .
35,789
private void addDiscriminatorClause ( List < String > clauses , EntityType entityType ) { if ( ( ( AbstractManagedType ) entityType ) . isInherited ( ) ) { String discrColumn = ( ( AbstractManagedType ) entityType ) . getDiscriminatorColumn ( ) ; String discrValue = ( ( AbstractManagedType ) entityType ) . getDiscriminatorValue ( ) ; if ( discrColumn != null && discrValue != null ) { if ( clauses != null && ! clauses . isEmpty ( ) ) { filtersQueue . add ( "AND" ) ; } FilterClause filterClause = new FilterClause ( discrColumn , "=" , discrValue , discrColumn ) ; filtersQueue . add ( filterClause ) ; } } }
Adds the discriminator clause .
35,790
private void filterJPAParameterInfo ( Type type , String name , String fieldName ) { String attributeName = getAttributeName ( fieldName ) ; Attribute entityAttribute = ( ( MetamodelImpl ) kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( persistenceUnit ) ) . getEntityAttribute ( entityClass , attributeName ) ; Class fieldType = entityAttribute . getJavaType ( ) ; if ( type . equals ( Type . INDEXED ) ) { typedParameter . addJPAParameter ( new JPAParameter ( null , Integer . valueOf ( name ) , fieldType ) ) ; } else { typedParameter . addJPAParameter ( new JPAParameter ( name , null , fieldType ) ) ; } }
Filter jpa parameter info .
35,791
private String getAttributeName ( String fieldName ) { String attributeName = fieldName ; if ( fieldName . indexOf ( "." ) != - 1 ) { attributeName = fieldName . substring ( 0 , fieldName . indexOf ( "." ) ) ; } return attributeName ; }
Gets the attribute name .
35,792
public void addUpdateClause ( final String property , final String value ) { UpdateClause updateClause = new UpdateClause ( property . trim ( ) , value . trim ( ) ) ; updateClauseQueue . add ( updateClause ) ; addTypedParameter ( value . trim ( ) . startsWith ( "?" ) ? Type . INDEXED : value . trim ( ) . startsWith ( ":" ) ? Type . NAMED : null , property , updateClause ) ; }
Adds the update clause .
35,793
public void addFilterClause ( final String property , final String condition , final Object value , final String fieldName , final boolean ignoreCase ) { if ( property != null && condition != null ) { FilterClause filterClause = new FilterClause ( property . trim ( ) , condition . trim ( ) , value , fieldName ) ; filterClause . setIgnoreCase ( ignoreCase ) ; filtersQueue . add ( filterClause ) ; } else { filtersQueue . add ( property ) ; } }
Adds the filter clause .
35,794
private static Object getValue ( Object value ) { if ( value != null && value . getClass ( ) . isAssignableFrom ( String . class ) ) { return ( ( String ) value ) . replaceAll ( "^'" , "" ) . replaceAll ( "'$" , "" ) . replaceAll ( "''" , "'" ) ; } return value ; }
Method to skip string literal as per JPA specification . if literal starts is enclose within then skip and include in case of replace it with .
35,795
static List < User > onQueryByEmail ( final EntityManager em , final User user ) { String query = "Select u from User u where u.emailId =?1" ; logger . info ( "" ) ; logger . info ( "" ) ; logger . info ( query ) ; System . out . println ( "#######################Querying##########################################" ) ; List < User > fetchedUsers = findByEmail ( em , query , user . getEmailId ( ) ) ; return fetchedUsers ; }
on query with user email id
35,796
static void onPersist ( final EntityManager em , final User user ) { logger . info ( "" ) ; logger . info ( "" ) ; logger . info ( "#######################Persisting##########################################" ) ; logger . info ( "" ) ; logger . info ( user . toString ( ) ) ; persist ( user , em ) ; logger . info ( "" ) ; System . out . println ( "#######################Persisting##########################################" ) ; logger . info ( "" ) ; logger . info ( "" ) ; }
On persist user .
35,797
static User findByKey ( final EntityManager em , final String userId ) { User user = em . find ( User . class , userId ) ; logger . info ( "[On Find by key]" ) ; System . out . println ( "#######################START##########################################" ) ; logger . info ( "\n" ) ; logger . info ( "\t\t User's first name:" + user . getFirstName ( ) ) ; logger . info ( "\t\t User's emailId:" + user . getEmailId ( ) ) ; logger . info ( "\t\t User's Personal Details:" + user . getPersonalDetail ( ) . getName ( ) ) ; logger . info ( "\t\t User's Personal Details:" + user . getPersonalDetail ( ) . getPassword ( ) ) ; logger . info ( "\t\t User's total tweets:" + user . getTweets ( ) . size ( ) ) ; logger . info ( "\n" ) ; System . out . println ( "#######################END############################################" ) ; logger . info ( "\n" ) ; return user ; }
On find by user id .
35,798
@ SuppressWarnings ( "unchecked" ) static void findByQuery ( final EntityManager em , final String query ) { Query q = em . createNamedQuery ( query ) ; logger . info ( "[On Find All by Query]" ) ; List < User > users = q . getResultList ( ) ; if ( users == null || users . isEmpty ( ) ) { logger . info ( "0 Users Returned" ) ; return ; } System . out . println ( "#######################START##########################################" ) ; logger . info ( "\t\t Total number of users:" + users . size ( ) ) ; logger . info ( "\t\t User's total tweets:" + users . get ( 0 ) . getTweets ( ) . size ( ) ) ; printTweets ( users ) ; logger . info ( "\n" ) ; System . out . println ( "#######################END############################################" ) ; logger . info ( "\n" ) ; }
on find by wild search query .
35,799
@ SuppressWarnings ( "unchecked" ) static void findByNativeQuery ( final EntityManager em , final String query ) { Query q = em . createNativeQuery ( query , Tweets . class ) ; Map < String , Client > clients = ( Map < String , Client > ) em . getDelegate ( ) ; ThriftClient client = ( ThriftClient ) clients . get ( "twissandra" ) ; client . setCqlVersion ( CassandraConstants . CQL_VERSION_3_0 ) ; logger . info ( "[On Find Tweets by CQL3]" ) ; List < Tweets > tweets = q . getResultList ( ) ; System . out . println ( "#######################START##########################################" ) ; logger . info ( "\t\t User's total tweets:" + tweets . size ( ) ) ; onPrintTweets ( tweets ) ; logger . info ( "\n" ) ; System . out . println ( "#######################END############################################" ) ; logger . info ( "\n" ) ; }
On find by native CQL3 query .