idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
35,400
public static void createDesignDocumentIfNotExist ( HttpClient httpClient , HttpHost httpHost , Gson gson , String tableName , String schemaName , String viewName , List < String > columns ) throws URISyntaxException , UnsupportedEncodingException , IOException , ClientProtocolException { URI uri ; HttpResponse response = null ; CouchDBDesignDocument designDocument = CouchDBUtils . getDesignDocument ( httpClient , httpHost , gson , tableName , schemaName ) ; Map < String , MapReduce > views = designDocument . getViews ( ) ; if ( views == null ) { views = new HashMap < String , MapReduce > ( ) ; } if ( views . get ( viewName . toString ( ) ) == null ) { CouchDBUtils . createView ( views , viewName , columns ) ; } String id = CouchDBConstants . DESIGN + tableName ; if ( designDocument . get_rev ( ) == null ) { uri = new URI ( CouchDBConstants . PROTOCOL , null , httpHost . getHostName ( ) , httpHost . getPort ( ) , CouchDBConstants . URL_SEPARATOR + schemaName . 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 + schemaName . toLowerCase ( ) + CouchDBConstants . URL_SEPARATOR + id , builder . toString ( ) , null ) ; } HttpPut put = new HttpPut ( uri ) ; 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 document if not exist .
35,401
private static CouchDBDesignDocument getDesignDocument ( HttpClient httpClient , HttpHost httpHost , Gson gson , String tableName , String schemaName ) { HttpResponse response = null ; try { String id = CouchDBConstants . DESIGN + tableName ; URI uri = new URI ( CouchDBConstants . PROTOCOL , null , httpHost . getHostName ( ) , httpHost . getPort ( ) , CouchDBConstants . URL_SEPARATOR + schemaName . toLowerCase ( ) + CouchDBConstants . URL_SEPARATOR + id , null , null ) ; HttpGet get = new HttpGet ( uri ) ; get . addHeader ( "Accept" , "application/json" ) ; response = httpClient . execute ( httpHost , get , CouchDBUtils . getContext ( httpHost ) ) ; InputStream content = response . getEntity ( ) . getContent ( ) ; Reader reader = new InputStreamReader ( content ) ; JsonObject jsonObject = gson . fromJson ( reader , JsonObject . class ) ; return gson . fromJson ( jsonObject , CouchDBDesignDocument . class ) ; } catch ( Exception e ) { log . error ( "Error while fetching design document object, Caused by: ." , e ) ; throw new KunderaException ( e ) ; } finally { CouchDBUtils . closeContent ( response ) ; } }
Gets the design document .
35,402
private void createIndexOnTable ( TableInfo tableInfo ) { List < IndexInfo > indexColumns = tableInfo . getColumnsToBeIndexed ( ) ; for ( IndexInfo indexInfo : indexColumns ) { if ( indexInfo . getIndexType ( ) != null && indexInfo . getIndexType ( ) . toLowerCase ( ) . equals ( Constants . COMPOSITE ) ) { String [ ] columnNames = indexInfo . getColumnName ( ) . split ( Constants . COMMA ) ; createIndex ( tableInfo . getTableName ( ) , indexInfo . getIndexName ( ) , columnNames ) ; } else { createIndex ( tableInfo . getTableName ( ) , indexInfo . getIndexName ( ) , indexInfo . getColumnName ( ) ) ; } } }
Creates the index on table .
35,403
private String buildCreateDDLQuery ( TableInfo tableInfo ) { String statement ; boolean flag = false ; StringBuilder compoundKeys = null ; StringBuilder builder = new StringBuilder ( ) ; builder . append ( "CREATE TABLE " ) ; builder . append ( tableInfo . getTableName ( ) ) ; builder . append ( Constants . OPEN_ROUND_BRACKET ) ; if ( ! tableInfo . getTableIdType ( ) . isAnnotationPresent ( Embeddable . class ) ) { builder . append ( tableInfo . getIdColumnName ( ) ) ; builder . append ( Constants . SPACE ) ; String idType = tableInfo . getTableIdType ( ) . getSimpleName ( ) . toLowerCase ( ) ; builder . append ( OracleNoSQLValidationClassMapper . getValidIdType ( idType ) ) ; builder . append ( Constants . COMMA ) ; } for ( ColumnInfo columnInfo : tableInfo . getColumnMetadatas ( ) ) { builder . append ( columnInfo . getColumnName ( ) ) ; builder . append ( Constants . SPACE ) ; String coulmnType = columnInfo . getType ( ) . getSimpleName ( ) . toLowerCase ( ) ; builder . append ( OracleNoSQLValidationClassMapper . getValidType ( coulmnType ) ) ; builder . append ( Constants . COMMA ) ; } for ( EmbeddedColumnInfo embeddedColumnInfo : tableInfo . getEmbeddedColumnMetadatas ( ) ) { if ( tableInfo . getIdColumnName ( ) . equals ( embeddedColumnInfo . getEmbeddedColumnName ( ) ) ) { compoundKeys = new StringBuilder ( ) ; flag = true ; } for ( ColumnInfo columnInfo : embeddedColumnInfo . getColumns ( ) ) { builder . append ( columnInfo . getColumnName ( ) ) ; builder . append ( Constants . SPACE ) ; String coulmnType = columnInfo . getType ( ) . getSimpleName ( ) . toLowerCase ( ) ; builder . append ( OracleNoSQLValidationClassMapper . getValidType ( coulmnType ) ) ; builder . append ( Constants . COMMA ) ; if ( flag ) { compoundKeys . append ( columnInfo . getColumnName ( ) ) ; compoundKeys . append ( Constants . COMMA ) ; } } flag = false ; } builder . append ( "PRIMARY KEY" ) ; builder . append ( Constants . OPEN_ROUND_BRACKET ) ; if ( ! tableInfo . getTableIdType ( ) . isAnnotationPresent ( Embeddable . class ) ) { builder . append ( tableInfo . getIdColumnName ( ) ) ; } else { compoundKeys . deleteCharAt ( compoundKeys . length ( ) - 1 ) ; builder . append ( compoundKeys . toString ( ) ) ; } builder . append ( Constants . CLOSE_ROUND_BRACKET ) ; builder . append ( Constants . CLOSE_ROUND_BRACKET ) ; statement = builder . toString ( ) ; return statement ; }
Builds the create ddl query .
35,404
private String buildAlterDDLQuery ( TableInfo tableInfo , Map < String , String > newColumns ) { String statement ; StringBuilder builder = new StringBuilder ( ) ; builder . append ( "ALTER TABLE " ) ; builder . append ( tableInfo . getTableName ( ) ) ; builder . append ( Constants . OPEN_ROUND_BRACKET ) ; for ( Map . Entry < String , String > entry : newColumns . entrySet ( ) ) { builder . append ( "ADD " ) ; builder . append ( entry . getKey ( ) ) ; builder . append ( Constants . SPACE ) ; String coulmnType = entry . getValue ( ) . toLowerCase ( ) ; builder . append ( OracleNoSQLValidationClassMapper . getValidType ( coulmnType ) ) ; builder . append ( Constants . COMMA ) ; } builder . deleteCharAt ( builder . length ( ) - 1 ) ; builder . append ( Constants . CLOSE_ROUND_BRACKET ) ; statement = builder . toString ( ) ; return statement ; }
Builds the alter ddl query .
35,405
public Node createProxyNode ( Object sourceNodeId , Object targetNodeId , GraphDatabaseService graphDb , EntityMetadata sourceEntityMetadata , EntityMetadata targetEntityMetadata ) { String sourceNodeIdColumnName = ( ( AbstractAttribute ) sourceEntityMetadata . getIdAttribute ( ) ) . getJPAColumnName ( ) ; String targetNodeIdColumnName = ( ( AbstractAttribute ) targetEntityMetadata . getIdAttribute ( ) ) . getJPAColumnName ( ) ; Node node = graphDb . createNode ( ) ; node . setProperty ( PROXY_NODE_TYPE_KEY , PROXY_NODE_VALUE ) ; node . setProperty ( sourceNodeIdColumnName , sourceNodeId ) ; node . setProperty ( targetNodeIdColumnName , targetNodeId ) ; return node ; }
Create Proxy nodes into Neo4J . Proxy nodes are defined as nodes in Neo4J that refer to a record in some other database . They cater to polyglot persistence cases .
35,406
private void populateNodeProperties ( Object entity , EntityMetadata m , Node node ) { MetamodelImpl metaModel = ( MetamodelImpl ) kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( m . getPersistenceUnit ( ) ) ; EntityType entityType = metaModel . entity ( m . getEntityClazz ( ) ) ; Set < Attribute > attributes = entityType . getSingularAttributes ( ) ; for ( Attribute attribute : attributes ) { Field field = ( Field ) attribute . getJavaMember ( ) ; if ( ! attribute . isCollection ( ) && ! attribute . isAssociation ( ) && ! ( ( SingularAttribute ) attribute ) . isId ( ) ) { String columnName = ( ( AbstractAttribute ) attribute ) . getJPAColumnName ( ) ; Object value = PropertyAccessorHelper . getObject ( entity , field ) ; if ( value != null ) { node . setProperty ( columnName , toNeo4JProperty ( value ) ) ; } } } }
Populates Node properties from Entity object
35,407
private String serializeIdAttributeValue ( final EntityMetadata m , MetamodelImpl metaModel , Object id ) { if ( ! metaModel . isEmbeddable ( m . getIdAttribute ( ) . getBindableJavaType ( ) ) ) { return null ; } Class < ? > embeddableClass = m . getIdAttribute ( ) . getBindableJavaType ( ) ; String idUniqueValue = "" ; for ( Field embeddedField : embeddableClass . getDeclaredFields ( ) ) { if ( ! ReflectUtils . isTransientOrStatic ( embeddedField ) ) { Object value = PropertyAccessorHelper . getObject ( id , embeddedField ) ; if ( value != null && ! StringUtils . isEmpty ( value . toString ( ) ) ) idUniqueValue = idUniqueValue + value + COMPOSITE_KEY_SEPARATOR ; } } if ( idUniqueValue . endsWith ( COMPOSITE_KEY_SEPARATOR ) ) idUniqueValue = idUniqueValue . substring ( 0 , idUniqueValue . length ( ) - COMPOSITE_KEY_SEPARATOR . length ( ) ) ; return idUniqueValue ; }
Prepares ID column value for embedded IDs by combining its attributes
35,408
private Object deserializeIdAttributeValue ( final EntityMetadata m , String idValue ) { if ( idValue == null ) { return null ; } Class < ? > embeddableClass = m . getIdAttribute ( ) . getBindableJavaType ( ) ; Object embeddedObject = embeddedObject = KunderaCoreUtils . createNewInstance ( embeddableClass ) ; List < String > tokens = new ArrayList < String > ( ) ; StringTokenizer st = new StringTokenizer ( ( String ) idValue , COMPOSITE_KEY_SEPARATOR ) ; while ( st . hasMoreTokens ( ) ) { tokens . add ( ( String ) st . nextElement ( ) ) ; } int count = 0 ; for ( Field embeddedField : embeddableClass . getDeclaredFields ( ) ) { if ( ! ReflectUtils . isTransientOrStatic ( embeddedField ) ) { if ( count < tokens . size ( ) ) { String value = tokens . get ( count ++ ) ; PropertyAccessorHelper . set ( embeddedObject , embeddedField , value ) ; } } } return embeddedObject ; }
Prepares Embedded ID field from value prepared via serializeIdAttributeValue method .
35,409
public Object toNeo4JProperty ( Object source ) { if ( source instanceof BigDecimal || source instanceof BigInteger ) { return source . toString ( ) ; } else if ( ( source instanceof Calendar ) || ( source instanceof GregorianCalendar ) ) { return PropertyAccessorHelper . fromSourceToTargetClass ( String . class , Date . class , ( ( Calendar ) source ) . getTime ( ) ) ; } if ( source instanceof Date ) { Class < ? > sourceClass = source . getClass ( ) ; return PropertyAccessorHelper . fromSourceToTargetClass ( String . class , sourceClass , source ) ; } return source ; }
Converts a given field value to an object that is Neo4J compatible
35,410
public Node searchNode ( Object key , EntityMetadata m , GraphDatabaseService graphDb , boolean skipProxy ) { Node node = null ; String idColumnName = ( ( AbstractAttribute ) m . getIdAttribute ( ) ) . getJPAColumnName ( ) ; final MetamodelImpl metaModel = ( MetamodelImpl ) kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( m . getPersistenceUnit ( ) ) ; if ( metaModel . isEmbeddable ( m . getIdAttribute ( ) . getBindableJavaType ( ) ) ) { key = serializeIdAttributeValue ( m , metaModel , key ) ; } if ( indexer . isNodeAutoIndexingEnabled ( graphDb ) ) { ReadableIndex < Node > autoNodeIndex = graphDb . index ( ) . getNodeAutoIndexer ( ) . getAutoIndex ( ) ; IndexHits < Node > nodesFound = autoNodeIndex . get ( idColumnName , key ) ; node = getMatchingNodeFromIndexHits ( nodesFound , skipProxy ) ; } else { Index < Node > nodeIndex = graphDb . index ( ) . forNodes ( m . getIndexName ( ) ) ; IndexHits < Node > nodesFound = nodeIndex . get ( idColumnName , key ) ; node = getMatchingNodeFromIndexHits ( nodesFound , skipProxy ) ; } return node ; }
Searches a node from the database for a given key
35,411
protected Node getMatchingNodeFromIndexHits ( IndexHits < Node > nodesFound , boolean skipProxy ) { Node node = null ; try { if ( nodesFound == null || nodesFound . size ( ) == 0 || ! nodesFound . hasNext ( ) ) { return null ; } else { if ( skipProxy ) node = getNonProxyNode ( nodesFound ) ; else node = nodesFound . next ( ) ; } } finally { nodesFound . close ( ) ; } return node ; }
Fetches first Non - proxy node from Index Hits
35,412
private Node getNonProxyNode ( IndexHits < Node > nodesFound ) { Node node = null ; if ( nodesFound . hasNext ( ) ) { node = nodesFound . next ( ) ; } else { return null ; } try { Object proxyNodeProperty = node . getProperty ( PROXY_NODE_TYPE_KEY ) ; } catch ( NotFoundException e ) { return node ; } catch ( IllegalStateException e ) { return node ; } return getNonProxyNode ( nodesFound ) ; }
Fetches Non - proxy nodes from index hits
35,413
protected void exportSchema ( final String persistenceUnit , List < TableInfo > tables ) { this . puMetadata = kunderaMetadata . getApplicationMetadata ( ) . getPersistenceUnitMetadata ( persistenceUnit ) ; String paramString = externalProperties != null ? ( String ) externalProperties . get ( PersistenceProperties . KUNDERA_CLIENT_FACTORY ) : null ; if ( clientFactory != null && ( ( clientFactory . equalsIgnoreCase ( puMetadata . getProperties ( ) . getProperty ( PersistenceProperties . KUNDERA_CLIENT_FACTORY ) ) ) || ( paramString != null && clientFactory . equalsIgnoreCase ( paramString ) ) ) ) { readConfigProperties ( puMetadata ) ; if ( operation != null && initiateClient ( ) ) { tableInfos = tables ; handleOperations ( tables ) ; } } }
Export schema handles the handleOperation method .
35,414
private void handleOperations ( List < TableInfo > tableInfos ) { SchemaOperationType operationType = SchemaOperationType . getInstance ( operation ) ; switch ( operationType ) { case createdrop : create_drop ( tableInfos ) ; break ; case create : create ( tableInfos ) ; break ; case update : update ( tableInfos ) ; break ; case validate : validate ( tableInfos ) ; break ; } }
Handle operations .
35,415
public static PersistenceUnitMetadata getPersistenceUnitMetadata ( final KunderaMetadata kunderaMetadata , String persistenceUnit ) { if ( persistenceUnit != null && kunderaMetadata != null ) { return kunderaMetadata . getApplicationMetadata ( ) . getPersistenceUnitMetadata ( persistenceUnit ) ; } return null ; }
Gets the persistence unit metadata .
35,416
public static EntityMetadata getEntityMetadata ( final KunderaMetadata kunderaMetadata , Class entityClass ) { if ( entityClass == null ) { throw new KunderaException ( "Invalid class provided " + entityClass ) ; } List < String > persistenceUnits = kunderaMetadata . getApplicationMetadata ( ) . getMappedPersistenceUnit ( entityClass ) ; if ( persistenceUnits != null ) { for ( String pu : persistenceUnits ) { MetamodelImpl metamodel = getMetamodel ( kunderaMetadata , pu ) ; EntityMetadata metadata = metamodel . getEntityMetadata ( entityClass ) ; if ( metadata != null && metadata . getPersistenceUnit ( ) . equals ( pu ) ) { return metadata ; } } } if ( log . isDebugEnabled ( ) ) log . warn ( "No Entity metadata found for the class " + entityClass + ". Any CRUD operation on this entity will fail." + "If your entity is for RDBMS, make sure you put fully qualified entity class" + " name under <class></class> tag in persistence.xml for RDBMS " + "persistence unit. Returning null value." ) ; return null ; }
Finds ands returns Entity metadata for a given array of PUs .
35,417
public void updateNodeIndex ( EntityMetadata entityMetadata , GraphDatabaseService graphDb , Node node , MetamodelImpl metaModel ) { if ( ! isNodeAutoIndexingEnabled ( graphDb ) && entityMetadata . isIndexable ( ) ) { Index < Node > nodeIndex = graphDb . index ( ) . forNodes ( entityMetadata . getIndexName ( ) ) ; nodeIndex . remove ( node ) ; addNodeIndex ( entityMetadata , node , nodeIndex , metaModel ) ; } }
If node auto - indexing is disabled Update index for this node manually
35,418
public void updateRelationshipIndex ( EntityMetadata entityMetadata , GraphDatabaseService graphDb , Relationship relationship , MetamodelImpl metaModel ) { if ( ! isRelationshipAutoIndexingEnabled ( graphDb ) && entityMetadata . isIndexable ( ) ) { Index < Relationship > relationshipIndex = graphDb . index ( ) . forRelationships ( entityMetadata . getIndexName ( ) ) ; relationshipIndex . remove ( relationship ) ; addRelationshipIndex ( entityMetadata , relationship , relationshipIndex , metaModel ) ; } }
If relationship auto - indexing is disabled Update index for this relationship manually
35,419
public static Class < ? > getValidationClassInstance ( Class < ? > dataType , boolean isCql3Enabled ) { resetMapperForCQL3 ( isCql3Enabled ) ; Class < ? > validation_class ; validation_class = validationClassMapper . get ( dataType ) ; if ( validation_class == null ) { if ( dataType . isEnum ( ) ) { validation_class = UTF8Type . class ; } else { validation_class = BytesType . class ; } } resetMapperForThrift ( isCql3Enabled ) ; return validation_class ; }
Gets the validation class instance .
35,420
public static TypeSerializer < ? > getValidationSerializerClassInstance ( Class < ? > dataType , boolean isCql3Enabled ) { resetMapperForCQL3 ( isCql3Enabled ) ; TypeSerializer < ? > validation_class ; validation_class = validationSerializerClassMapper . get ( dataType ) ; if ( validation_class == null ) { if ( dataType . isEnum ( ) ) { validation_class = UTF8Serializer . instance ; } else { validation_class = BytesSerializer . instance ; } } resetMapperForThrift ( isCql3Enabled ) ; return validation_class ; }
Gets the validation serializer class instance .
35,421
public static String getValueTypeName ( Class < ? > dataType , List < Class < ? > > genericClasses , boolean isCql3Enabled ) throws SyntaxException , ConfigurationException , IllegalArgumentException , IllegalAccessException , NoSuchFieldException , SecurityException { String valueType ; Class < ? > validation_class = getValidationClassInstance ( dataType , isCql3Enabled ) ; valueType = validation_class . toString ( ) ; if ( validation_class . equals ( ListType . class ) ) { TypeParser parser = new TypeParser ( getValidationClass ( genericClasses . get ( 0 ) , isCql3Enabled ) ) ; valueType = ListType . getInstance ( parser . parse ( ) , true ) . toString ( ) ; } else if ( validation_class . equals ( SetType . class ) ) { TypeParser parser = new TypeParser ( getValidationClass ( genericClasses . get ( 0 ) , isCql3Enabled ) ) ; valueType = SetType . getInstance ( parser . parse ( ) , true ) . toString ( ) ; } else if ( validation_class . equals ( MapType . class ) ) { Class keyClass = CassandraValidationClassMapper . getValidationClassInstance ( genericClasses . get ( 0 ) , true ) ; Class valueClass = CassandraValidationClassMapper . getValidationClassInstance ( genericClasses . get ( 1 ) , true ) ; Object keyClassInstance = keyClass . getDeclaredField ( "instance" ) . get ( null ) ; Object valueClassInstance = valueClass . getDeclaredField ( "instance" ) . get ( null ) ; valueType = MapType . getInstance ( ( AbstractType ) keyClassInstance , ( AbstractType ) valueClassInstance , true ) . toString ( ) ; } return valueType ; }
Gets the value type name .
35,422
private static void resetMapperForCQL3 ( boolean isCql3Enabled ) { if ( isCql3Enabled ) { validationClassMapper . put ( Byte . class , Int32Type . class ) ; validationClassMapper . put ( byte . class , Int32Type . class ) ; validationClassMapper . put ( Short . class , Int32Type . class ) ; validationClassMapper . put ( short . class , Int32Type . class ) ; validationClassMapper . put ( java . sql . Time . class , TimestampType . class ) ; validationClassMapper . put ( java . sql . Date . class , TimestampType . class ) ; validationClassMapper . put ( java . util . Date . class , TimestampType . class ) ; validationClassMapper . put ( java . sql . Timestamp . class , TimestampType . class ) ; } }
Reset mapper for cq l3 .
35,423
private static void resetMapperForThrift ( boolean isCql3Enabled ) { if ( isCql3Enabled ) { validationClassMapper . put ( Byte . class , BytesType . class ) ; validationClassMapper . put ( byte . class , BytesType . class ) ; validationClassMapper . put ( Short . class , IntegerType . class ) ; validationClassMapper . put ( short . class , IntegerType . class ) ; validationClassMapper . put ( java . sql . Time . class , DateType . class ) ; validationClassMapper . put ( java . sql . Date . class , DateType . class ) ; validationClassMapper . put ( java . util . Date . class , DateType . class ) ; validationClassMapper . put ( java . sql . Timestamp . class , DateType . class ) ; } }
Reset mapper for thrift .
35,424
public static CassandraType getCassandraDataTypeClass ( Class clazz ) { if ( clazz . isEnum ( ) ) { return CassandraType . STRING ; } return typeToClazz . get ( clazz ) ; }
Gets the cassandra data type class .
35,425
public static Collection marshalCollection ( Class cassandraTypeClazz , Collection result , Class clazz , Class resultTypeClass ) { Collection mappedCollection = result ; if ( cassandraTypeClazz . isAssignableFrom ( BytesType . class ) ) { mappedCollection = ( Collection ) PropertyAccessorHelper . getObject ( resultTypeClass ) ; for ( Object value : result ) { byte [ ] valueAsBytes = new byte [ ( ( ByteBuffer ) value ) . remaining ( ) ] ; ( ( ByteBuffer ) value ) . get ( valueAsBytes ) ; mappedCollection . add ( PropertyAccessorHelper . getObject ( clazz , valueAsBytes ) ) ; } } return mappedCollection ; }
Marshal collection .
35,426
private void validateQueryResults ( String query , N1qlQueryResult result ) { LOGGER . debug ( "Query output status: " + result . finalSuccess ( ) ) ; if ( ! result . finalSuccess ( ) ) { StringBuilder errorBuilder = new StringBuilder ( ) ; for ( JsonObject obj : result . errors ( ) ) { errorBuilder . append ( obj . toString ( ) ) ; errorBuilder . append ( "\n" ) ; } errorBuilder . deleteCharAt ( errorBuilder . length ( ) - 1 ) ; String errors = errorBuilder . toString ( ) ; LOGGER . error ( errors ) ; throw new KunderaException ( "Not able to execute query/statement:" + query + ". More details : " + errors ) ; } }
Validate query results .
35,427
public static void populateCompoundKey ( DBObject dbObj , EntityMetadata m , MetamodelImpl metaModel , Object id ) { EmbeddableType compoundKey = metaModel . embeddable ( m . getIdAttribute ( ) . getBindableJavaType ( ) ) ; BasicDBObject compoundKeyObj = new BasicDBObject ( ) ; compoundKeyObj = getCompoundKeyColumns ( m , id , compoundKey , metaModel ) ; dbObj . put ( "_id" , compoundKeyObj ) ; }
Populate compound key .
35,428
public static BasicDBObject getCompoundKeyColumns ( EntityMetadata m , Object id , EmbeddableType compoundKey , MetamodelImpl metaModel ) { BasicDBObject compoundKeyObj = new BasicDBObject ( ) ; Set < Attribute > attribs = compoundKey . getDeclaredAttributes ( ) ; Field [ ] fields = m . getIdAttribute ( ) . getBindableJavaType ( ) . getDeclaredFields ( ) ; for ( Attribute attr : attribs ) { Field f = ( Field ) attr . getJavaMember ( ) ; if ( ! ReflectUtils . isTransientOrStatic ( f ) ) { if ( f . getAnnotation ( Embedded . class ) != null ) { EmbeddableType emb = metaModel . embeddable ( f . getType ( ) ) ; Object val = PropertyAccessorHelper . getObject ( id , f ) ; BasicDBObject dbVal = getCompoundKeyColumns ( m , val , emb , metaModel ) ; compoundKeyObj . put ( ( ( AbstractAttribute ) attr ) . getJPAColumnName ( ) , dbVal ) ; } else { compoundKeyObj . put ( ( ( AbstractAttribute ) attr ) . getJPAColumnName ( ) , populateValue ( PropertyAccessorHelper . getObject ( id , ( Field ) attr . getJavaMember ( ) ) , ( ( AbstractAttribute ) attr ) . getBindableJavaType ( ) ) ) ; } } } return compoundKeyObj ; }
Gets the compound key columns .
35,429
public static Object populateValue ( Object valObj , Class clazz ) { if ( isUTF8Value ( clazz ) || clazz . isEnum ( ) ) { return valObj . toString ( ) ; } else if ( ( valObj instanceof Calendar ) || ( valObj instanceof GregorianCalendar ) ) { return ( ( Calendar ) valObj ) . getTime ( ) ; } else if ( CollectionExpression . class . isAssignableFrom ( clazz ) ) { CollectionExpression collExpr = ( CollectionExpression ) valObj ; List < String > texts = new ArrayList < String > ( collExpr . childrenSize ( ) ) ; for ( Expression childExpr : collExpr . orderedChildren ( ) ) { if ( childExpr instanceof StringLiteral ) { StringLiteral stringLiteral = ( StringLiteral ) childExpr ; texts . add ( stringLiteral . getUnquotedText ( ) ) ; } } return texts ; } return valObj ; }
Populate value .
35,430
private static boolean isUTF8Value ( Class < ? > clazz ) { return ( clazz . isAssignableFrom ( BigDecimal . class ) ) || ( clazz . isAssignableFrom ( BigInteger . class ) || ( clazz . isAssignableFrom ( String . class ) ) || ( clazz . isAssignableFrom ( char . class ) ) || ( clazz . isAssignableFrom ( Character . class ) ) ) ; }
Checks if is UT f8 value .
35,431
public static Object getTranslatedObject ( Object value , Class < ? > sourceClass , Class < ? > targetClass ) { if ( sourceClass . isAssignableFrom ( Date . class ) ) { value = PropertyAccessorHelper . fromDate ( targetClass , sourceClass , value ) ; } else { value = PropertyAccessorHelper . fromSourceToTargetClass ( targetClass , sourceClass , value ) ; } return value ; }
Gets the translated object .
35,432
public static DBObject getDBObject ( EntityMetadata m , String tableName , Map < String , DBObject > dbObjects , MetamodelImpl metaModel , Object id ) { tableName = tableName != null ? tableName : m . getTableName ( ) ; DBObject dbObj = dbObjects . get ( tableName ) ; if ( dbObj == null ) { dbObj = new BasicDBObject ( ) ; dbObjects . put ( tableName , dbObj ) ; } if ( metaModel . isEmbeddable ( m . getIdAttribute ( ) . getBindableJavaType ( ) ) ) { MongoDBUtils . populateCompoundKey ( dbObj , m , metaModel , id ) ; } else { dbObj . put ( "_id" , MongoDBUtils . populateValue ( id , id . getClass ( ) ) ) ; } return dbObj ; }
Gets the DB object .
35,433
public static String calculateMD5 ( Object val ) { MessageDigest md = null ; try { md = MessageDigest . getInstance ( "MD5" ) ; } catch ( NoSuchAlgorithmException e ) { logger . error ( "Unable to calculate MD5 for file, Caused By: " , e ) ; } md . update ( ( byte [ ] ) val ) ; byte [ ] digest = md . digest ( ) ; return DatatypeConverter . printHexBinary ( digest ) . toLowerCase ( ) ; }
Calculate m d5 .
35,434
private void setNext ( ) { initial = true ; try { if ( next != null ) { jar . closeEntry ( ) ; } next = null ; do { next = jar . getNextJarEntry ( ) ; } while ( next != null && ( next . isDirectory ( ) || ( filter == null || ! filter . accepts ( next . getName ( ) ) ) ) ) ; if ( next == null ) { close ( ) ; } } catch ( IOException e ) { throw new ResourceReadingException ( "Failed to browse jar:" , e ) ; } }
Sets the next .
35,435
protected int onExecuteUpdate ( ) { EntityMetadata m = getEntityMetadata ( ) ; Client client = m != null ? persistenceDelegeator . getClient ( m ) : persistenceDelegeator . getClient ( kunderaQuery . getPersistenceUnit ( ) ) ; externalProperties = ( ( CassandraClientBase ) client ) . getExternalProperties ( ) ; ApplicationMetadata appMetadata = kunderaMetadata . getApplicationMetadata ( ) ; String query = appMetadata . getQuery ( getJPAQuery ( ) ) ; boolean isNative = kunderaQuery . isNative ( ) ; if ( isNative ) { ( ( CassandraClientBase ) client ) . executeQuery ( m == null ? null : m . getEntityClazz ( ) , null , isNative , query != null ? query : getJPAQuery ( ) ) ; } else if ( kunderaQuery . isDeleteUpdate ( ) ) { if ( ! isQueryConvertibleToCQL ( kunderaQuery ) ) { return onUpdateDeleteEvent ( ) ; } else { query = null ; if ( kunderaQuery . isUpdateClause ( ) ) { query = createUpdateQuery ( kunderaQuery ) ; } else { query = createDeleteQuery ( kunderaQuery ) ; } return ( ( CassandraClientBase ) client ) . executeUpdateDeleteQuery ( query ) ; } } return 0 ; }
On executeUpdate .
35,436
private boolean isQueryConvertibleToCQL ( KunderaQuery kunderaQuery ) { EntityMetadata m = kunderaQuery . getEntityMetadata ( ) ; if ( kunderaQuery . isUpdateClause ( ) && m . isCounterColumnType ( ) ) return false ; List < String > opsNotAllowed = Arrays . asList ( new String [ ] { ">" , "<" , ">=" , "<=" } ) ; boolean result = false ; if ( ! kunderaQuery . getFilterClauseQueue ( ) . isEmpty ( ) ) { String idColumn = ( ( AbstractAttribute ) m . getIdAttribute ( ) ) . getJPAColumnName ( ) ; for ( Object o : kunderaQuery . getFilterClauseQueue ( ) ) { if ( o instanceof FilterClause ) { FilterClause filterClause = ( FilterClause ) o ; if ( ! idColumn . equals ( filterClause . getProperty ( ) ) || opsNotAllowed . contains ( filterClause . getCondition ( ) ) ) { result = false ; break ; } result = true ; } } } return result ; }
Checks whether a given JPA DML query is convertible to CQL .
35,437
private void addCompositeIdToColumns ( MetamodelImpl metamodel , EmbeddableType compoundKey , List < String > columns , Field field ) { if ( ! ReflectUtils . isTransientOrStatic ( field ) ) { Attribute compositeColumn = compoundKey . getAttribute ( field . getName ( ) ) ; if ( compositeColumn . getJavaType ( ) . isAnnotationPresent ( Embeddable . class ) ) { EmbeddableType partitionCol = metamodel . embeddable ( compositeColumn . getJavaType ( ) ) ; Set < Attribute > cols = partitionCol . getAttributes ( ) ; for ( Attribute col : cols ) { Field f = ( Field ) col . getJavaMember ( ) ; if ( ! ReflectUtils . isTransientOrStatic ( f ) ) { columns . add ( ( ( AbstractAttribute ) col ) . getJPAColumnName ( ) ) ; } } } else { columns . add ( ( ( AbstractAttribute ) compositeColumn ) . getJPAColumnName ( ) ) ; } } }
Adds the composite id to columns .
35,438
Map < Boolean , List < IndexClause > > prepareIndexClause ( EntityMetadata m , boolean isQueryForInvertedIndex ) { IndexClause indexClause = new IndexClause ( new ArrayList < IndexExpression > ( ) , ByteBufferUtil . EMPTY_BYTE_BUFFER , maxResult ) ; List < IndexClause > clauses = new ArrayList < IndexClause > ( ) ; List < IndexExpression > expr = new ArrayList < IndexExpression > ( ) ; Map < Boolean , List < IndexClause > > idxClauses = new HashMap < Boolean , List < IndexClause > > ( 1 ) ; String idColumn = ( ( AbstractAttribute ) m . getIdAttribute ( ) ) . getJPAColumnName ( ) ; boolean idPresent = false ; if ( log . isInfoEnabled ( ) ) { log . info ( "Preparing index clause for query {}" , getJPAQuery ( ) ) ; } for ( Object o : getKunderaQuery ( ) . getFilterClauseQueue ( ) ) { if ( o instanceof FilterClause ) { FilterClause clause = ( ( FilterClause ) o ) ; String fieldName = clause . getProperty ( ) ; if ( ! idPresent && idColumn . equalsIgnoreCase ( fieldName ) ) { idPresent = true ; } String condition = clause . getCondition ( ) ; List < Object > value = clause . getValue ( ) ; if ( value != null && value . size ( ) > 1 ) { log . error ( "IN clause is not enabled for thrift, use cql3." ) ; throw new QueryHandlerException ( "IN clause is not enabled for thrift, use cql3." ) ; } IndexOperator operator = getOperator ( condition , idPresent ) ; IndexExpression expression = new IndexExpression ( ByteBufferUtil . bytes ( fieldName ) , operator , getBytesValue ( fieldName , m , value . get ( 0 ) ) ) ; expr . add ( expression ) ; } else { String opr = o . toString ( ) ; if ( opr . equalsIgnoreCase ( "or" ) ) { log . error ( "Support for OR clause is not enabled within cassandra." ) ; throw new QueryHandlerException ( "Unsupported clause " + opr + " for cassandra." ) ; } } } if ( ! StringUtils . isBlank ( getKunderaQuery ( ) . getFilter ( ) ) ) { indexClause . setExpressions ( expr ) ; clauses . add ( indexClause ) ; } idxClauses . put ( idPresent , clauses ) ; return idxClauses ; }
Prepare index clause .
35,439
ByteBuffer getBytesValue ( String jpaFieldName , EntityMetadata m , Object value ) { Attribute idCol = m . getIdAttribute ( ) ; MetamodelImpl metaModel = ( MetamodelImpl ) kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( m . getPersistenceUnit ( ) ) ; EntityType entity = metaModel . entity ( m . getEntityClazz ( ) ) ; Field f = null ; boolean isId = false ; if ( ( ( AbstractAttribute ) idCol ) . getJPAColumnName ( ) . equals ( jpaFieldName ) ) { f = ( Field ) idCol . getJavaMember ( ) ; isId = true ; } else { if ( jpaFieldName != null && jpaFieldName . indexOf ( Constants . INDEX_TABLE_ROW_KEY_DELIMITER ) > 0 ) { String embeddedFieldName = jpaFieldName . substring ( 0 , jpaFieldName . indexOf ( Constants . INDEX_TABLE_ROW_KEY_DELIMITER ) ) ; String columnFieldName = jpaFieldName . substring ( jpaFieldName . indexOf ( Constants . INDEX_TABLE_ROW_KEY_DELIMITER ) + 1 , jpaFieldName . length ( ) ) ; Attribute embeddedAttr = entity . getAttribute ( embeddedFieldName ) ; try { Class < ? > embeddedClass = embeddedAttr . getJavaType ( ) ; if ( Collection . class . isAssignableFrom ( embeddedClass ) ) { Class < ? > genericClass = PropertyAccessorHelper . getGenericClass ( ( Field ) embeddedAttr . getJavaMember ( ) ) ; f = genericClass . getDeclaredField ( columnFieldName ) ; } else { f = embeddedClass . getDeclaredField ( columnFieldName ) ; } } catch ( SecurityException e ) { log . error ( "Error while extrating " + jpaFieldName + ", Caused by: " , e ) ; throw new QueryHandlerException ( "Error while extrating " + jpaFieldName + "." ) ; } catch ( NoSuchFieldException e ) { log . error ( "Error while extrating " + jpaFieldName + ", Caused by: " , e ) ; throw new QueryHandlerException ( "Error while extrating " + jpaFieldName + "." ) ; } } else { String discriminatorColumn = ( ( AbstractManagedType ) entity ) . getDiscriminatorColumn ( ) ; if ( ! jpaFieldName . equals ( discriminatorColumn ) ) { String fieldName = m . getFieldName ( jpaFieldName ) ; Attribute col = entity . getAttribute ( fieldName ) ; if ( col == null ) { throw new QueryHandlerException ( "column type is null for: " + jpaFieldName ) ; } f = ( Field ) col . getJavaMember ( ) ; } } } if ( f != null && f . getType ( ) != null ) { return CassandraUtilities . toBytes ( value , f ) ; } else { return CassandraUtilities . toBytes ( value , String . class ) ; } }
Returns bytes value for given value .
35,440
public String onQueryOverCQL3 ( EntityMetadata m , Client client , MetamodelImpl metaModel , List < String > relations ) { Class compoundKeyClass = m . getIdAttribute ( ) . getBindableJavaType ( ) ; EmbeddableType compoundKey = null ; String idColumn ; if ( metaModel . isEmbeddable ( compoundKeyClass ) ) { compoundKey = metaModel . embeddable ( compoundKeyClass ) ; idColumn = ( ( AbstractAttribute ) m . getIdAttribute ( ) ) . getJPAColumnName ( ) ; } else { idColumn = ( ( AbstractAttribute ) m . getIdAttribute ( ) ) . getJPAColumnName ( ) ; } StringBuilder builder = new StringBuilder ( ) ; boolean isPresent = false ; List < String > columns = getColumnList ( m , metaModel , getKunderaQuery ( ) . getResult ( ) , compoundKey ) ; String selectQuery = setSelectQuery ( columns ) ; CQLTranslator translator = new CQLTranslator ( ) ; selectQuery = StringUtils . replace ( selectQuery , CQLTranslator . COLUMN_FAMILY , translator . ensureCase ( new StringBuilder ( ) , m . getTableName ( ) , false ) . toString ( ) ) ; builder = CassandraUtilities . appendColumns ( builder , columns , selectQuery , translator ) ; addWhereClause ( builder ) ; onCondition ( m , metaModel , compoundKey , idColumn , builder , isPresent , translator , true ) ; return builder . toString ( ) ; }
On query over composite columns .
35,441
private String setSelectQuery ( List < String > columns ) { if ( columns != null && ! columns . isEmpty ( ) ) { return CQLTranslator . SELECT_QUERY ; } if ( kunderaQuery . isAggregated ( ) ) { Expression selectExpression = ( ( SelectClause ) kunderaQuery . getSelectStatement ( ) . getSelectClause ( ) ) . getSelectExpression ( ) ; if ( selectExpression instanceof CountFunction ) { return CQLTranslator . SELECT_COUNT_QUERY ; } } return CQLTranslator . SELECTALL_QUERY ; }
Sets the select query .
35,442
private void onLimit ( StringBuilder builder ) { if ( Integer . MAX_VALUE != maxResult ) { builder . append ( CQLTranslator . LIMIT ) ; builder . append ( isSingleResult ? 1 : this . maxResult ) ; } }
Add provided max result limit .
35,443
private boolean getCompoundKeyColumn ( MetamodelImpl metamodel , EmbeddableType keyObj , StringBuilder builder , boolean isPresent , CQLTranslator translator , String fieldName , String condition , List < Object > value , boolean useInClause ) { fieldName = fieldName . substring ( fieldName . indexOf ( "." ) + 1 ) ; if ( fieldName . indexOf ( "." ) > 0 ) { String compositePartitionkeyName = fieldName . substring ( 0 , fieldName . indexOf ( "." ) ) ; AbstractAttribute attribute = ( AbstractAttribute ) keyObj . getAttribute ( compositePartitionkeyName ) ; fieldName = fieldName . substring ( fieldName . indexOf ( "." ) + 1 ) ; EmbeddableType compositePartitionkey = metamodel . embeddable ( attribute . getBindableJavaType ( ) ) ; attribute = ( AbstractAttribute ) compositePartitionkey . getAttribute ( fieldName ) ; String columnName = attribute . getJPAColumnName ( ) ; isPresent = buildWhereClause ( builder , isPresent , translator , condition , value , useInClause , attribute , columnName , false ) ; } else if ( metamodel . isEmbeddable ( ( ( AbstractAttribute ) keyObj . getAttribute ( fieldName ) ) . getBindableJavaType ( ) ) ) { AbstractAttribute attribute = ( AbstractAttribute ) keyObj . getAttribute ( fieldName ) ; Set < Attribute > attributes = metamodel . embeddable ( attribute . getBindableJavaType ( ) ) . getAttributes ( ) ; if ( ! useInClause ) { for ( Attribute nestedAttribute : attributes ) { String columnName = ( ( AbstractAttribute ) nestedAttribute ) . getJPAColumnName ( ) ; Object valueObject = PropertyAccessorHelper . getObject ( value . isEmpty ( ) ? null : value . get ( 0 ) , ( Field ) nestedAttribute . getJavaMember ( ) ) ; translator . buildWhereClause ( builder , nestedAttribute . getJavaType ( ) , columnName , valueObject , condition , false ) ; } } else { throw new IllegalArgumentException ( "In clause is not supported on first part of partition key." ) ; } isPresent = true ; } else { AbstractAttribute attribute = ( AbstractAttribute ) keyObj . getAttribute ( fieldName ) ; String columnName = attribute . getJPAColumnName ( ) ; isPresent = buildWhereClause ( builder , isPresent , translator , condition , value , useInClause , attribute , columnName , false ) ; } return isPresent ; }
Gets the compound key column .
35,444
private StringBuilder appendOrderByClause ( MetamodelImpl metaModel , EntityMetadata m , EmbeddableType keyObj , StringBuilder builder , CQLTranslator translator ) { List < SortOrdering > orders = getKunderaQuery ( ) . getOrdering ( ) ; if ( orders != null ) { builder . append ( CQLTranslator . SPACE_STRING ) ; builder . append ( CQLTranslator . SORT_CLAUSE ) ; for ( SortOrdering order : orders ) { String orderColumnName = order . getColumnName ( ) ; orderColumnName = orderColumnName . substring ( orderColumnName . indexOf ( "." ) + 1 , orderColumnName . length ( ) ) ; String orderByColumnName ; if ( StringUtils . contains ( orderColumnName , '.' ) ) { String propertyName = orderColumnName . substring ( 0 , orderColumnName . indexOf ( "." ) ) ; Attribute embeddableAttribute = metaModel . getEntityAttribute ( m . getEntityClazz ( ) , propertyName ) ; EmbeddableType embeddableType = metaModel . embeddable ( ( ( AbstractAttribute ) embeddableAttribute ) . getBindableJavaType ( ) ) ; orderColumnName = orderColumnName . substring ( orderColumnName . indexOf ( "." ) + 1 ) ; AbstractAttribute attribute = ( AbstractAttribute ) embeddableType . getAttribute ( orderColumnName ) ; orderByColumnName = attribute . getJPAColumnName ( ) ; } else { Attribute attribute = metaModel . getEntityAttribute ( m . getEntityClazz ( ) , orderColumnName ) ; orderByColumnName = ( ( AbstractAttribute ) attribute ) . getJPAColumnName ( ) ; } builder = translator . ensureCase ( builder , orderByColumnName , false ) ; builder . append ( CQLTranslator . SPACE_STRING ) ; builder . append ( order . getOrder ( ) ) ; builder . append ( CQLTranslator . COMMA_STR ) ; } if ( ! orders . isEmpty ( ) ) { builder . deleteCharAt ( builder . lastIndexOf ( CQLTranslator . COMMA_STR ) ) ; } } return builder ; }
Append order by clause .
35,445
private boolean extractCompositeKey ( MetamodelImpl metaModel , EmbeddableType keyObj , StringBuilder builder , CQLTranslator translator , List < Object > value , boolean useInClause , Map < Attribute , List < Object > > columnValues , Field field ) { Attribute compositeColumn = keyObj . getAttribute ( field . getName ( ) ) ; String jpaColumnName = ( ( AbstractAttribute ) compositeColumn ) . getJPAColumnName ( ) ; if ( useInClause ) { for ( Object embeddedObject : value ) { Object valueObject = PropertyAccessorHelper . getObject ( embeddedObject , field ) ; if ( metaModel . isEmbeddable ( ( ( AbstractAttribute ) compositeColumn ) . getBindableJavaType ( ) ) ) { Set < Attribute > attributes = metaModel . embeddable ( ( ( AbstractAttribute ) compositeColumn ) . getBindableJavaType ( ) ) . getAttributes ( ) ; for ( Attribute nestedAttribute : attributes ) { List < Object > valueList = columnValues . get ( compositeColumn ) ; if ( valueList == null ) { valueList = new ArrayList < Object > ( ) ; } Object obj = PropertyAccessorHelper . getObject ( valueObject , ( Field ) nestedAttribute . getJavaMember ( ) ) ; valueList . add ( obj ) ; columnValues . put ( nestedAttribute , valueList ) ; } } else { List < Object > valueList = columnValues . get ( compositeColumn ) ; if ( valueList == null ) { valueList = new ArrayList < Object > ( ) ; } valueList . add ( valueObject ) ; columnValues . put ( compositeColumn , valueList ) ; } } } else { Object valueObject = PropertyAccessorHelper . getObject ( value . isEmpty ( ) ? null : value . get ( 0 ) , field ) ; if ( metaModel . isEmbeddable ( ( ( AbstractAttribute ) compositeColumn ) . getBindableJavaType ( ) ) ) { Set < Attribute > attributes = metaModel . embeddable ( ( ( AbstractAttribute ) compositeColumn ) . getBindableJavaType ( ) ) . getAttributes ( ) ; for ( Attribute nestedAttribute : attributes ) { String columnName = ( ( AbstractAttribute ) nestedAttribute ) . getJPAColumnName ( ) ; Object obj = PropertyAccessorHelper . getObject ( valueObject , ( Field ) nestedAttribute . getJavaMember ( ) ) ; translator . buildWhereClause ( builder , nestedAttribute . getJavaType ( ) , columnName , obj , CQLTranslator . EQ_CLAUSE , false ) ; } return true ; } else { translator . buildWhereClause ( builder , field . getType ( ) , jpaColumnName , valueObject , CQLTranslator . EQ_CLAUSE , false ) ; return true ; } } return false ; }
Extract composite key .
35,446
private boolean buildWhereClause ( StringBuilder builder , boolean isPresent , CQLTranslator translator , String condition , List < Object > value , boolean useInClause , AbstractAttribute idAttributeColumn , String columnName , boolean useToken ) { if ( value . isEmpty ( ) ) { isPresent = appendIn ( builder , translator , columnName ) ; builder . append ( "( )" ) ; builder . append ( " AND " ) ; } else if ( useInClause && value . size ( ) > 1 ) { isPresent = appendInClause ( builder , translator , value , idAttributeColumn . getBindableJavaType ( ) , columnName , isPresent ) ; } else { translator . buildWhereClause ( builder , ( ( Attribute ) idAttributeColumn ) . getJavaType ( ) , columnName , value . isEmpty ( ) ? null : value . get ( 0 ) , condition , useToken ) ; } return isPresent ; }
Builds the where clause .
35,447
private boolean appendIn ( StringBuilder builder , CQLTranslator translator , String columnName ) { boolean isPresent ; isPresent = true ; translator . ensureCase ( builder , columnName , false ) ; builder . append ( " IN " ) ; return isPresent ; }
Append in .
35,448
private boolean appendInClause ( StringBuilder queryBuilder , CQLTranslator translator , List < Object > value , Class fieldClazz , String columnName , boolean isPresent ) { isPresent = appendIn ( queryBuilder , translator , columnName ) ; queryBuilder . append ( "(" ) ; for ( Object objectvalue : value ) { translator . appendValue ( queryBuilder , fieldClazz , objectvalue , isPresent , false ) ; queryBuilder . append ( ", " ) ; } queryBuilder . deleteCharAt ( queryBuilder . lastIndexOf ( ", " ) ) ; queryBuilder . append ( ") " ) ; queryBuilder . append ( " AND " ) ; return isPresent ; }
Append in clause .
35,449
void addWhereClause ( StringBuilder builder ) { if ( ! getKunderaQuery ( ) . getFilterClauseQueue ( ) . isEmpty ( ) ) { builder . append ( CQLTranslator . ADD_WHERE_CLAUSE ) ; } }
Adds the where clause .
35,450
public void setRelationalEntities ( List enhanceEntities , Client client , EntityMetadata m ) { super . setRelationEntities ( enhanceEntities , client , m ) ; }
Sets the relational entities .
35,451
public String createUpdateQuery ( KunderaQuery kunderaQuery ) { EntityMetadata metadata = kunderaQuery . getEntityMetadata ( ) ; MetamodelImpl metaModel = ( MetamodelImpl ) kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( metadata . getPersistenceUnit ( ) ) ; CQLTranslator translator = new CQLTranslator ( ) ; String update_Query = translator . UPDATE_QUERY ; String tableName = metadata . getTableName ( ) ; update_Query = StringUtils . replace ( update_Query , CQLTranslator . COLUMN_FAMILY , translator . ensureCase ( new StringBuilder ( ) , tableName , false ) . toString ( ) ) ; StringBuilder builder = new StringBuilder ( update_Query ) ; Object ttlColumns = ( ( CassandraClientBase ) persistenceDelegeator . getClient ( metadata ) ) . getTtlValues ( ) . get ( metadata . getTableName ( ) ) ; if ( ( ttlColumns != null && ttlColumns instanceof Integer ) || this . ttl != null ) { int ttl = this . ttl != null ? this . ttl : ( ( Integer ) ttlColumns ) . intValue ( ) ; if ( ttl != 0 ) { builder . append ( " USING TTL " ) ; builder . append ( ttl ) ; builder . append ( " " ) ; } } builder . append ( CQLTranslator . ADD_SET_CLAUSE ) ; for ( UpdateClause updateClause : kunderaQuery . getUpdateClauseQueue ( ) ) { String property = updateClause . getProperty ( ) ; String jpaColumnName = getColumnName ( metadata , property ) ; Object value = updateClause . getValue ( ) ; translator . buildSetClause ( metadata , builder , jpaColumnName , value ) ; } builder . delete ( builder . lastIndexOf ( CQLTranslator . COMMA_STR ) , builder . length ( ) ) ; builder . append ( CQLTranslator . ADD_WHERE_CLAUSE ) ; Class compoundKeyClass = metadata . getIdAttribute ( ) . getBindableJavaType ( ) ; EmbeddableType compoundKey = null ; String idColumn ; if ( metaModel . isEmbeddable ( compoundKeyClass ) ) { compoundKey = metaModel . embeddable ( compoundKeyClass ) ; idColumn = ( ( AbstractAttribute ) metadata . getIdAttribute ( ) ) . getJPAColumnName ( ) ; } else { idColumn = ( ( AbstractAttribute ) metadata . getIdAttribute ( ) ) . getJPAColumnName ( ) ; } onCondition ( metadata , metaModel , compoundKey , idColumn , builder , false , translator , false ) ; return builder . toString ( ) ; }
Create Update CQL query from a given JPA query .
35,452
public String createDeleteQuery ( KunderaQuery kunderaQuery ) { EntityMetadata metadata = kunderaQuery . getEntityMetadata ( ) ; MetamodelImpl metaModel = ( MetamodelImpl ) kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( metadata . getPersistenceUnit ( ) ) ; CQLTranslator translator = new CQLTranslator ( ) ; String delete_query = translator . DELETE_QUERY ; String tableName = kunderaQuery . getEntityMetadata ( ) . getTableName ( ) ; delete_query = StringUtils . replace ( delete_query , CQLTranslator . COLUMN_FAMILY , translator . ensureCase ( new StringBuilder ( ) , tableName , false ) . toString ( ) ) ; StringBuilder builder = new StringBuilder ( delete_query ) ; builder . append ( CQLTranslator . ADD_WHERE_CLAUSE ) ; Class compoundKeyClass = metadata . getIdAttribute ( ) . getBindableJavaType ( ) ; EmbeddableType compoundKey = null ; String idColumn ; if ( metaModel . isEmbeddable ( compoundKeyClass ) ) { compoundKey = metaModel . embeddable ( compoundKeyClass ) ; idColumn = ( ( AbstractAttribute ) metadata . getIdAttribute ( ) ) . getJPAColumnName ( ) ; } else { idColumn = ( ( AbstractAttribute ) metadata . getIdAttribute ( ) ) . getJPAColumnName ( ) ; } onCondition ( metadata , metaModel , compoundKey , idColumn , builder , false , translator , false ) ; return builder . toString ( ) ; }
Create Delete query from a given JPA query .
35,453
private void buildWhereClause ( KunderaQuery kunderaQuery , EntityMetadata metadata , MetamodelImpl metaModel , CQLTranslator translator , StringBuilder builder ) { for ( Object clause : kunderaQuery . getFilterClauseQueue ( ) ) { FilterClause filterClause = ( FilterClause ) clause ; Field f = ( Field ) metaModel . entity ( metadata . getEntityClazz ( ) ) . getAttribute ( metadata . getFieldName ( filterClause . getProperty ( ) ) ) . getJavaMember ( ) ; String jpaColumnName = getColumnName ( metadata , filterClause . getProperty ( ) ) ; if ( metaModel . isEmbeddable ( metadata . getIdAttribute ( ) . getBindableJavaType ( ) ) ) { Field [ ] fields = metadata . getIdAttribute ( ) . getBindableJavaType ( ) . getDeclaredFields ( ) ; EmbeddableType compoundKey = metaModel . embeddable ( metadata . getIdAttribute ( ) . getBindableJavaType ( ) ) ; for ( Field field : fields ) { if ( field != null && ! Modifier . isStatic ( field . getModifiers ( ) ) && ! Modifier . isTransient ( field . getModifiers ( ) ) && ! field . isAnnotationPresent ( Transient . class ) ) { Attribute attribute = compoundKey . getAttribute ( field . getName ( ) ) ; String columnName = ( ( AbstractAttribute ) attribute ) . getJPAColumnName ( ) ; Object value = PropertyAccessorHelper . getObject ( filterClause . getValue ( ) . get ( 0 ) , field ) ; translator . buildWhereClause ( builder , field . getType ( ) , columnName , value , filterClause . getCondition ( ) , false ) ; } } } else { translator . buildWhereClause ( builder , f . getType ( ) , jpaColumnName , filterClause . getValue ( ) . get ( 0 ) , filterClause . getCondition ( ) , false ) ; } } builder . delete ( builder . lastIndexOf ( CQLTranslator . AND_CLAUSE ) , builder . length ( ) ) ; }
Builds where Clause .
35,454
private String getColumnName ( EntityMetadata metadata , String property ) { MetamodelImpl metaModel = ( MetamodelImpl ) kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( metadata . getPersistenceUnit ( ) ) ; String jpaColumnName = null ; if ( property . equals ( ( ( AbstractAttribute ) metadata . getIdAttribute ( ) ) . getJPAColumnName ( ) ) ) { jpaColumnName = CassandraUtilities . getIdColumnName ( kunderaMetadata , metadata , ( ( CassandraClientBase ) persistenceDelegeator . getClient ( metadata ) ) . getExternalProperties ( ) , ( ( CassandraClientBase ) persistenceDelegeator . getClient ( metadata ) ) . isCql3Enabled ( metadata ) ) ; } else { jpaColumnName = ( ( AbstractAttribute ) metaModel . getEntityAttribute ( metadata . getEntityClazz ( ) , property ) ) . getJPAColumnName ( ) ; } return jpaColumnName ; }
Gets column name for a given field name .
35,455
public static void populateColumnAndSuperColumnMaps ( EntityMetadata m , Map < String , Field > columnNameToFieldMap , Map < String , Field > superColumnNameToFieldMap , final KunderaMetadata kunderaMetadata ) { getEmbeddableType ( m , columnNameToFieldMap , superColumnNameToFieldMap , kunderaMetadata ) ; }
Populate column and super column maps .
35,456
public static Map < String , Field > createColumnsFieldMap ( EntityMetadata m , EmbeddableType superColumn ) { Map < String , Field > columnNameToFieldMap = new HashMap < String , Field > ( ) ; Set < Attribute > attributes = superColumn . getAttributes ( ) ; for ( Attribute column : attributes ) { columnNameToFieldMap . put ( ( ( AbstractAttribute ) column ) . getJPAColumnName ( ) , ( Field ) column . getJavaMember ( ) ) ; } return columnNameToFieldMap ; }
Creates the columns field map .
35,457
public static Map < String , Field > createSuperColumnsFieldMap ( final EntityMetadata m , final KunderaMetadata kunderaMetadata ) { Map < String , Field > superColumnNameToFieldMap = new HashMap < String , Field > ( ) ; getEmbeddableType ( m , null , superColumnNameToFieldMap , kunderaMetadata ) ; return superColumnNameToFieldMap ; }
Creates the super columns field map .
35,458
public static Collection getEmbeddedCollectionInstance ( Field embeddedCollectionField ) { Collection embeddedCollection = null ; Class embeddedCollectionFieldClass = embeddedCollectionField . getType ( ) ; if ( embeddedCollection == null || embeddedCollection . isEmpty ( ) ) { if ( embeddedCollectionFieldClass . equals ( List . class ) ) { embeddedCollection = new ArrayList < Object > ( ) ; } else if ( embeddedCollectionFieldClass . equals ( Set . class ) ) { embeddedCollection = new HashSet < Object > ( ) ; } else { throw new InvalidEntityDefinitionException ( "Field " + embeddedCollectionField . getName ( ) + " must be either instance of List or Set" ) ; } } return embeddedCollection ; }
Gets the embedded collection instance .
35,459
public static Object getEmbeddedGenericObjectInstance ( Field embeddedCollectionField ) { Class < ? > embeddedClass = PropertyAccessorHelper . getGenericClass ( embeddedCollectionField ) ; Object embeddedObject = null ; try { embeddedClass . getConstructor ( ) ; embeddedObject = embeddedClass . newInstance ( ) ; } catch ( NoSuchMethodException nsme ) { throw new PersistenceException ( embeddedClass . getName ( ) + " is @Embeddable and must have a default no-argument constructor." ) ; } catch ( InstantiationException e ) { throw new PersistenceException ( embeddedClass . getName ( ) + " could not be instantiated" ) ; } catch ( IllegalAccessException e ) { throw new PersistenceException ( embeddedClass . getName ( ) + " could not be accessed" ) ; } return embeddedObject ; }
Gets the embedded generic object instance .
35,460
public static String getEmbeddedCollectionPrefix ( String embeddedCollectionName ) { return embeddedCollectionName . substring ( 0 , embeddedCollectionName . indexOf ( Constants . EMBEDDED_COLUMN_NAME_DELIMITER ) ) ; }
Gets the embedded collection prefix .
35,461
public static String getEmbeddedCollectionPostfix ( String embeddedCollectionName ) { return embeddedCollectionName . substring ( embeddedCollectionName . lastIndexOf ( Constants . EMBEDDED_COLUMN_NAME_DELIMITER ) + 1 , embeddedCollectionName . length ( ) ) ; }
Gets the embedded collection postfix .
35,462
public static String serializeKeys ( Set < String > foreignKeys ) { if ( null == foreignKeys || foreignKeys . isEmpty ( ) ) { return null ; } StringBuilder sb = new StringBuilder ( ) ; for ( String key : foreignKeys ) { if ( sb . length ( ) > 0 ) { sb . append ( Constants . FOREIGN_KEY_SEPARATOR ) ; } sb . append ( key ) ; } return sb . toString ( ) ; }
Creates a string representation of a set of foreign keys by combining them together separated by ~ character .
35,463
public static Set < String > deserializeKeys ( String foreignKeys ) { Set < String > keys = new HashSet < String > ( ) ; if ( null == foreignKeys || foreignKeys . isEmpty ( ) ) { return keys ; } String array [ ] = foreignKeys . split ( Constants . FOREIGN_KEY_SEPARATOR ) ; for ( String element : array ) { keys . add ( element ) ; } return keys ; }
Splits foreign keys into Set .
35,464
public static void setSchemaAndPersistenceUnit ( EntityMetadata m , String schemaStr , Map puProperties ) { if ( schemaStr . indexOf ( Constants . SCHEMA_PERSISTENCE_UNIT_SEPARATOR ) > 0 ) { String schemaName = null ; if ( puProperties != null ) { schemaName = ( String ) puProperties . get ( PersistenceProperties . KUNDERA_KEYSPACE ) ; } if ( schemaName == null ) { schemaName = schemaStr . substring ( 0 , schemaStr . indexOf ( Constants . SCHEMA_PERSISTENCE_UNIT_SEPARATOR ) ) ; } m . setSchema ( schemaName ) ; m . setPersistenceUnit ( schemaStr . substring ( schemaStr . indexOf ( Constants . SCHEMA_PERSISTENCE_UNIT_SEPARATOR ) + 1 , schemaStr . length ( ) ) ) ; } else { m . setSchema ( StringUtils . isBlank ( schemaStr ) ? null : schemaStr ) ; } }
Sets the schema and persistence unit .
35,465
public static String getMappedName ( EntityMetadata parentMetadata , Relation relation , final KunderaMetadata kunderaMetadata ) { if ( relation != null ) { String joinColumn = relation . getJoinColumnName ( kunderaMetadata ) ; if ( joinColumn == null ) { Class clazz = relation . getTargetEntity ( ) ; EntityMetadata metadata = KunderaMetadataManager . getEntityMetadata ( kunderaMetadata , clazz ) ; joinColumn = relation . getType ( ) . equals ( ForeignKey . ONE_TO_MANY ) ? ( ( AbstractAttribute ) parentMetadata . getIdAttribute ( ) ) . getJPAColumnName ( ) : ( ( AbstractAttribute ) metadata . getIdAttribute ( ) ) . getJPAColumnName ( ) ; } return joinColumn ; } return null ; }
Returns mapped relational name in case of bi directional mapping it will return back pKey name of associated entity .
35,466
public static String getEnclosingEmbeddedFieldName ( EntityMetadata m , String criteria , boolean viaColumnName , final KunderaMetadata kunderaMetadata ) { String enclosingEmbeddedFieldName = null ; StringTokenizer strToken = new StringTokenizer ( criteria , "." ) ; String embeddableAttributeName = null ; String embeddedFieldName = null ; String nestedEmbeddedFieldName = null ; if ( strToken . countTokens ( ) > 0 ) { embeddableAttributeName = strToken . nextToken ( ) ; } if ( strToken . countTokens ( ) > 0 ) { embeddedFieldName = strToken . nextToken ( ) ; } if ( strToken . countTokens ( ) > 0 ) { nestedEmbeddedFieldName = strToken . nextToken ( ) ; } Metamodel metaModel = kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( m . getPersistenceUnit ( ) ) ; EntityType entity = metaModel . entity ( m . getEntityClazz ( ) ) ; try { Attribute attribute = entity . getAttribute ( embeddableAttributeName ) ; if ( ( ( MetamodelImpl ) metaModel ) . isEmbeddable ( ( ( AbstractAttribute ) attribute ) . getBindableJavaType ( ) ) ) { EmbeddableType embeddable = metaModel . embeddable ( ( ( AbstractAttribute ) attribute ) . getBindableJavaType ( ) ) ; Iterator < Attribute > attributeIter = embeddable . getAttributes ( ) . iterator ( ) ; while ( attributeIter . hasNext ( ) ) { AbstractAttribute attrib = ( AbstractAttribute ) attributeIter . next ( ) ; if ( viaColumnName && attrib . getName ( ) . equals ( embeddedFieldName ) ) { if ( nestedEmbeddedFieldName != null && ( ( MetamodelImpl ) metaModel ) . isEmbeddable ( ( ( AbstractAttribute ) attrib ) . getBindableJavaType ( ) ) ) { EmbeddableType nestedEmbeddable = metaModel . embeddable ( ( ( AbstractAttribute ) attrib ) . getBindableJavaType ( ) ) ; Iterator < Attribute > iter = embeddable . getAttributes ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { AbstractAttribute nestedAttribute = ( AbstractAttribute ) iter . next ( ) ; if ( viaColumnName && nestedAttribute . getName ( ) . equals ( embeddedFieldName ) ) { return nestedAttribute . getName ( ) ; } if ( ! viaColumnName && nestedAttribute . getJPAColumnName ( ) . equals ( embeddedFieldName ) ) { return nestedAttribute . getName ( ) ; } } } else if ( nestedEmbeddedFieldName != null && ! ( ( MetamodelImpl ) metaModel ) . isEmbeddable ( ( ( AbstractAttribute ) attrib ) . getBindableJavaType ( ) ) ) { return null ; } else { return attribute . getName ( ) ; } } if ( ! viaColumnName && attrib . getJPAColumnName ( ) . equals ( embeddedFieldName ) ) { return attribute . getName ( ) ; } } } } catch ( IllegalArgumentException iax ) { return null ; } return enclosingEmbeddedFieldName ; }
Gets the enclosing document name .
35,467
public static boolean defaultTransactionSupported ( final String persistenceUnit , final KunderaMetadata kunderaMetadata ) { PersistenceUnitMetadata puMetadata = KunderaMetadataManager . getPersistenceUnitMetadata ( kunderaMetadata , persistenceUnit ) ; String txResource = puMetadata . getProperty ( PersistenceProperties . KUNDERA_TRANSACTION_RESOURCE ) ; if ( txResource == null ) { return true ; } else if ( txResource . isEmpty ( ) ) { throw new IllegalArgumentException ( "Property " + PersistenceProperties . KUNDERA_TRANSACTION_RESOURCE + " is blank" ) ; } else { return false ; } }
If client specific to parameterized persistence unit does not support transaction return true else will return false .
35,468
public static boolean isBasicElementCollectionField ( Field collectionField ) { if ( ! Collection . class . isAssignableFrom ( collectionField . getType ( ) ) && ! Map . class . isAssignableFrom ( collectionField . getType ( ) ) ) { return false ; } List < Class < ? > > genericClasses = PropertyAccessorHelper . getGenericClasses ( collectionField ) ; for ( Class genericClass : genericClasses ) { if ( genericClass . getAnnotation ( Embeddable . class ) != null ) { return false ; } } return true ; }
Checks whether a given field is Element collection field of BASIC type
35,469
public static boolean containsBasicElementCollectionField ( final EntityMetadata m , final KunderaMetadata kunderaMetadata ) { Metamodel metaModel = kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( m . getPersistenceUnit ( ) ) ; EntityType entityType = metaModel . entity ( m . getEntityClazz ( ) ) ; Iterator < Attribute > iter = entityType . getAttributes ( ) . iterator ( ) ; while ( iter . hasNext ( ) ) { Attribute attr = iter . next ( ) ; if ( attr . isCollection ( ) && ! attr . isAssociation ( ) && isBasicElementCollectionField ( ( Field ) attr . getJavaMember ( ) ) ) { return true ; } } return false ; }
Checks whether an entity with given metadata contains a collection field
35,470
public static boolean onCheckValidationConstraints ( Field attribute ) { return attribute . isAnnotationPresent ( AssertFalse . class ) || attribute . isAnnotationPresent ( AssertTrue . class ) || attribute . isAnnotationPresent ( DecimalMax . class ) || attribute . isAnnotationPresent ( DecimalMin . class ) || attribute . isAnnotationPresent ( Digits . class ) || attribute . isAnnotationPresent ( Future . class ) || attribute . isAnnotationPresent ( Max . class ) || attribute . isAnnotationPresent ( Min . class ) || attribute . isAnnotationPresent ( NotNull . class ) || attribute . isAnnotationPresent ( Null . class ) || attribute . isAnnotationPresent ( Past . class ) || attribute . isAnnotationPresent ( Pattern . class ) || attribute . isAnnotationPresent ( Size . class ) ; }
Returns true if an entity contains attributes with validation constraints enabled
35,471
public static RelationMetadataProcessor getRelationMetadataProcessor ( Field relationField , KunderaMetadata kunderaMetadata ) { RelationMetadataProcessor relProcessor = null ; if ( relationField . isAnnotationPresent ( OneToOne . class ) ) { relProcessor = new OneToOneRelationMetadataProcessor ( kunderaMetadata ) ; } else if ( relationField . isAnnotationPresent ( OneToMany . class ) ) { relProcessor = new OneToManyRelationMetadataProcessor ( kunderaMetadata ) ; } else if ( relationField . isAnnotationPresent ( ManyToOne . class ) ) { relProcessor = new ManyToOneRelationMetadataProcessor ( kunderaMetadata ) ; } else if ( relationField . isAnnotationPresent ( ManyToMany . class ) ) { relProcessor = new ManyToManyRelationMetadataProcessor ( kunderaMetadata ) ; } return relProcessor ; }
Gets the relation metadata processor .
35,472
public static boolean onAutoGenerateId ( Field idField , Object idValue ) { if ( idField . isAnnotationPresent ( GeneratedValue . class ) ) { return ! isIdSet ( idValue , idField ) ; } return false ; }
Validates and set id in case not set and intended for auto generation .
35,473
private Map < String , Object > parseInsertIntoQuery ( String query ) { Map < String , Object > persistDetails = new HashMap < String , Object > ( ) ; String insertReg = "(?i)^insert\\s+into\\s+(\\S+)\\s+(?:as\\s+(\\S+)\\s+)?FROM\\s+\\((.*)\\)$" ; Pattern r = Pattern . compile ( insertReg ) ; Matcher m = r . matcher ( query ) ; if ( m . find ( ) ) { try { parsePersistClause ( m . group ( 1 ) , persistDetails ) ; persistDetails . put ( "format" , m . group ( 2 ) ) ; persistDetails . put ( "fetchQuery" , m . group ( 3 ) ) ; } catch ( Exception e ) { throw new KunderaException ( "Invalid Query" ) ; } } else { throw new KunderaException ( "Invalid Query" ) ; } return persistDetails ; }
Parses the insert into query .
35,474
private Map < String , Object > parsePersistClause ( String persistClause , Map < String , Object > persistDetails ) throws KunderaException { Pattern pattern = Pattern . compile ( "^([^.]+)\\.(?:([^.]+)\\.([^.]+)|\\[([^\\]]+)\\])$" ) ; Matcher matcher = pattern . matcher ( persistClause ) ; if ( matcher . find ( ) ) { persistDetails . put ( "client" , matcher . group ( 1 ) ) ; switch ( matcher . group ( 1 ) . toLowerCase ( ) ) { case SparkPropertiesConstants . CLIENT_CASSANDRA : persistDetails . put ( "keyspace" , matcher . group ( 2 ) ) ; persistDetails . put ( "table" , matcher . group ( 3 ) ) ; break ; case SparkPropertiesConstants . CLIENT_FS : persistDetails . put ( SparkPropertiesConstants . FS_OUTPUT_FILE_PATH , matcher . group ( 4 ) ) ; break ; case SparkPropertiesConstants . CLIENT_HDFS : persistDetails . put ( SparkPropertiesConstants . HDFS_OUTPUT_FILE_PATH , matcher . group ( 4 ) ) ; break ; case SparkPropertiesConstants . CLIENT_HIVE : persistDetails . put ( "keyspace" , matcher . group ( 2 ) ) ; persistDetails . put ( "table" , matcher . group ( 3 ) ) ; break ; default : throw new UnsupportedOperationException ( "Not Supported for this client" ) ; } } else { throw new KunderaException ( "Invalid Query" ) ; } return persistDetails ; }
Parses the persist clause .
35,475
public int getDataFrameSize ( DataFrame dataFrame ) { long l = dataFrame != null ? dataFrame . count ( ) : 0 ; if ( l < Integer . MIN_VALUE || l > Integer . MAX_VALUE ) { logger . error ( l + " cannot be cast to int without changing its value." ) ; return 0 ; } return ( int ) l ; }
Gets the data frame size .
35,476
private DataFrame getDataFrameToPersist ( String query , String subQuery ) { EntityMetadata entityMetadata = getEntityMetadata ( ) ; Client client = entityMetadata != null ? persistenceDelegeator . getClient ( entityMetadata ) : persistenceDelegeator . getClient ( kunderaQuery . getPersistenceUnit ( ) ) ; return ( ( SparkClient ) client ) . getDataFrame ( subQuery , entityMetadata , getKunderaQuery ( ) ) ; }
Gets the data frame to persist .
35,477
boolean isAggregatedQuery ( ) { if ( kunderaQuery . getSelectStatement ( ) != null ) { Expression exp = ( ( SelectClause ) kunderaQuery . getSelectStatement ( ) . getSelectClause ( ) ) . getSelectExpression ( ) ; return AggregateFunction . class . isAssignableFrom ( exp . getClass ( ) ) ; } else { return false ; } }
Checks if is aggregated query .
35,478
private boolean isCountQuery ( ) { if ( getKunderaQuery ( ) . getSelectStatement ( ) != null ) { final Expression selectClause = getKunderaQuery ( ) . getSelectStatement ( ) . getSelectClause ( ) ; if ( selectClause instanceof SelectClause ) { final Expression expression = ( ( SelectClause ) selectClause ) . getSelectExpression ( ) ; return expression instanceof CountFunction ; } } return false ; }
Checks if is count query .
35,479
private void populateQueryComponents ( EntityMetadata m , QueryComponent sq ) { boolean hasChildren = false ; if ( sq . children != null && sq . children . size ( ) > 0 ) { hasChildren = true ; for ( QueryComponent subQ : sq . children ) { populateQueryComponents ( m , subQ ) ; } } if ( sq . clauses . size ( ) > 0 || hasChildren ) { if ( sq . clauses . size ( ) > 0 ) { sq . actualQuery = createSubMongoQuery ( m , sq . clauses ) ; } if ( hasChildren ) { List < BasicDBObject > childQs = new ArrayList < BasicDBObject > ( ) ; if ( sq . clauses . size ( ) > 0 ) childQs . add ( sq . actualQuery ) ; for ( QueryComponent subQ : sq . children ) { childQs . add ( subQ . actualQuery ) ; } if ( childQs . size ( ) == 1 ) { sq . actualQuery = childQs . get ( 0 ) ; } else if ( sq . isAnd ) { BasicDBObject dbo = new BasicDBObject ( "$and" , childQs ) ; sq . actualQuery = dbo ; } else { BasicDBObject dbo = new BasicDBObject ( "$or" , childQs ) ; sq . actualQuery = dbo ; } } } }
Populate query components .
35,480
private static QueryComponent getQueryComponent ( Queue filterClauseQueue ) { QueryComponent subQuery = new QueryComponent ( ) ; QueryComponent currentSubQuery = subQuery ; for ( Object object : filterClauseQueue ) { if ( object instanceof FilterClause ) { currentSubQuery . clauses . add ( object ) ; } else if ( object instanceof String ) { String interClauseConstruct = ( String ) object ; if ( interClauseConstruct . equals ( "(" ) ) { QueryComponent temp = new QueryComponent ( ) ; currentSubQuery . children . add ( temp ) ; temp . parent = currentSubQuery ; currentSubQuery = temp ; } else if ( interClauseConstruct . equals ( ")" ) ) { currentSubQuery = currentSubQuery . parent ; } else if ( interClauseConstruct . equalsIgnoreCase ( "AND" ) ) { currentSubQuery . isAnd = true ; } else if ( interClauseConstruct . equalsIgnoreCase ( "OR" ) ) { currentSubQuery . isAnd = false ; } } } return subQuery ; }
Gets the query component .
35,481
public BasicDBObject createMongoQuery ( EntityMetadata m , Queue filterClauseQueue ) { QueryComponent sq = getQueryComponent ( filterClauseQueue ) ; populateQueryComponents ( m , sq ) ; return sq . actualQuery == null ? new BasicDBObject ( ) : sq . actualQuery ; }
Creates the mongo query .
35,482
private BasicDBObject getKeys ( EntityMetadata m , String [ ] columns ) { BasicDBObject keys = new BasicDBObject ( ) ; if ( columns != null && columns . length > 0 ) { MetamodelImpl metaModel = ( MetamodelImpl ) kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( m . getPersistenceUnit ( ) ) ; EntityType entity = metaModel . entity ( m . getEntityClazz ( ) ) ; for ( int i = 1 ; i < columns . length ; i ++ ) { if ( columns [ i ] != null ) { Attribute col = entity . getAttribute ( columns [ i ] ) ; if ( col == null ) { throw new QueryHandlerException ( "column type is null for: " + columns ) ; } keys . put ( ( ( AbstractAttribute ) col ) . getJPAColumnName ( ) , 1 ) ; } } } return keys ; }
Gets the keys .
35,483
private BasicDBObject createAggregation ( EntityMetadata metadata ) { if ( kunderaQuery . getSelectStatement ( ) != null ) { Metamodel metaModel = kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( metadata . getPersistenceUnit ( ) ) ; EntityType entityType = metaModel . entity ( metadata . getEntityClazz ( ) ) ; AbstractManagedType managedType = ( AbstractManagedType ) metaModel . entity ( metadata . getEntityClazz ( ) ) ; boolean hasLob = managedType . hasLobAttribute ( ) ; BasicDBObject aggregation = new BasicDBObject ( ) ; SelectClause selectClause = ( SelectClause ) kunderaQuery . getSelectStatement ( ) . getSelectClause ( ) ; Expression expression = selectClause . getSelectExpression ( ) ; buildAggregation ( aggregation , expression , metadata , entityType , hasLob ) ; if ( aggregation . size ( ) == 0 ) { return null ; } if ( ! aggregation . containsField ( "_id" ) ) { aggregation . put ( "_id" , null ) ; } return aggregation ; } return null ; }
Get the aggregation object .
35,484
private void buildAggregation ( DBObject group , Expression expression , EntityMetadata metadata , EntityType entityType , boolean hasLob ) { if ( expression instanceof AggregateFunction ) { AggregateFunction aggregateFunction = ( AggregateFunction ) expression ; String identifier = aggregateFunction . getIdentifier ( ) . toLowerCase ( ) ; Expression child = aggregateFunction . getExpression ( ) ; if ( child instanceof StateFieldPathExpression ) { StateFieldPathExpression sfpExp = ( StateFieldPathExpression ) child ; String columnName = getColumnName ( metadata , entityType , sfpExp . toActualText ( ) ) ; String actualColumnName = columnName ; if ( hasLob ) { actualColumnName = "metadata." + columnName ; } else if ( metadata . getIdAttribute ( ) . equals ( entityType . getAttribute ( metadata . getFieldName ( columnName ) ) ) ) { actualColumnName = "_id" ; } BasicDBObject item = new BasicDBObject ( "$" + identifier , "$" + actualColumnName ) ; group . put ( identifier + "_" + columnName , item ) ; } else if ( expression instanceof CountFunction ) { group . put ( "count" , new BasicDBObject ( "$sum" , 1 ) ) ; } } else if ( expression instanceof CollectionExpression ) { for ( Expression child : expression . children ( ) ) { buildAggregation ( group , child , metadata , entityType , hasLob ) ; } } else if ( expression instanceof StateFieldPathExpression ) { StateFieldPathExpression sfpExp = ( StateFieldPathExpression ) expression ; BasicDBObject idObject ; Object existing = group . get ( "_id" ) ; if ( existing != null ) { idObject = ( BasicDBObject ) existing ; } else { idObject = new BasicDBObject ( ) ; group . put ( "_id" , idObject ) ; } String columnName = getColumnName ( metadata , entityType , sfpExp . toActualText ( ) ) ; String actualColumnName = columnName ; if ( hasLob ) { actualColumnName = "metadata." + columnName ; } idObject . put ( columnName , "$" + actualColumnName ) ; } }
Build the aggregation parameters .
35,485
private BasicDBObject getOrderByClause ( final EntityMetadata metadata ) { BasicDBObject orderByClause = null ; Metamodel metaModel = kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( metadata . getPersistenceUnit ( ) ) ; EntityType entityType = metaModel . entity ( metadata . getEntityClazz ( ) ) ; AbstractManagedType managedType = ( AbstractManagedType ) metaModel . entity ( metadata . getEntityClazz ( ) ) ; List < SortOrdering > orders = kunderaQuery . getOrdering ( ) ; if ( orders != null ) { orderByClause = new BasicDBObject ( ) ; if ( ! managedType . hasLobAttribute ( ) ) { for ( SortOrdering order : orders ) { orderByClause . append ( getColumnName ( metadata , entityType , order . getColumnName ( ) ) , order . getOrder ( ) . equals ( SortOrder . ASC ) ? 1 : - 1 ) ; } } else { for ( SortOrdering order : orders ) { orderByClause . append ( "metadata." + getColumnName ( metadata , entityType , order . getColumnName ( ) ) , order . getOrder ( ) . equals ( SortOrder . ASC ) ? 1 : - 1 ) ; } } } return orderByClause ; }
Prepare order by clause .
35,486
private int handleSpecialFunctions ( ) { boolean needsSpecialAttention = false ; outer : for ( UpdateClause c : kunderaQuery . getUpdateClauseQueue ( ) ) { for ( int i = 0 ; i < FUNCTION_KEYWORDS . length ; i ++ ) { if ( c . getValue ( ) instanceof String ) { String func = c . getValue ( ) . toString ( ) ; func = func . replaceAll ( " " , "" ) ; if ( func . toUpperCase ( ) . matches ( FUNCTION_KEYWORDS [ i ] ) ) { needsSpecialAttention = true ; c . setValue ( func ) ; break outer ; } } } } if ( ! needsSpecialAttention ) return - 1 ; EntityMetadata m = getEntityMetadata ( ) ; Metamodel metaModel = kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( m . getPersistenceUnit ( ) ) ; Queue filterClauseQueue = kunderaQuery . getFilterClauseQueue ( ) ; BasicDBObject query = createMongoQuery ( m , filterClauseQueue ) ; BasicDBObject update = new BasicDBObject ( ) ; for ( UpdateClause c : kunderaQuery . getUpdateClauseQueue ( ) ) { String columName = getColumnName ( m , metaModel . entity ( m . getEntityClazz ( ) ) , c . getProperty ( ) ) ; boolean isSpecialFunction = false ; for ( int i = 0 ; i < FUNCTION_KEYWORDS . length ; i ++ ) { if ( c . getValue ( ) instanceof String && c . getValue ( ) . toString ( ) . toUpperCase ( ) . matches ( FUNCTION_KEYWORDS [ i ] ) ) { isSpecialFunction = true ; if ( c . getValue ( ) . toString ( ) . toUpperCase ( ) . startsWith ( "INCREMENT(" ) ) { String val = c . getValue ( ) . toString ( ) . toUpperCase ( ) ; val = val . substring ( 10 , val . indexOf ( ")" ) ) ; update . put ( "$inc" , new BasicDBObject ( columName , Integer . valueOf ( val ) ) ) ; } else if ( c . getValue ( ) . toString ( ) . toUpperCase ( ) . startsWith ( "DECREMENT(" ) ) { String val = c . getValue ( ) . toString ( ) . toUpperCase ( ) ; val = val . substring ( 10 , val . indexOf ( ")" ) ) ; update . put ( "$inc" , new BasicDBObject ( columName , - Integer . valueOf ( val ) ) ) ; } } } if ( ! isSpecialFunction ) { update . put ( columName , c . getValue ( ) ) ; } } Client client = persistenceDelegeator . getClient ( m ) ; return ( ( MongoDBClient ) client ) . handleUpdateFunctions ( query , update , m . getTableName ( ) ) ; }
Handle special functions .
35,487
private String getColumnName ( EntityMetadata metadata , EntityType entityType , String property ) { String columnName = null ; if ( property . indexOf ( "." ) > 0 ) { property = property . substring ( ( kunderaQuery . getEntityAlias ( ) + "." ) . length ( ) ) ; } try { columnName = ( ( AbstractAttribute ) entityType . getAttribute ( property ) ) . getJPAColumnName ( ) ; } catch ( IllegalArgumentException iaex ) { log . warn ( "No column found by this name : " + property + " checking for embeddedfield" ) ; } if ( columnName == null && property . indexOf ( "." ) > 0 ) { String enclosingEmbeddedField = MetadataUtils . getEnclosingEmbeddedFieldName ( metadata , property , true , kunderaMetadata ) ; if ( enclosingEmbeddedField != null ) { columnName = property ; } } if ( columnName == null ) { log . error ( "No column found by this name : " + property ) ; throw new JPQLParseException ( "No column found by this name : " + property + ". Check your query." ) ; } return columnName ; }
Gets the column name .
35,488
public static String createLikeRegex ( String expr , boolean ignoreCase ) { String regex = createRegex ( expr , ignoreCase ) ; regex = regex . replace ( "_" , "." ) . replace ( "%" , ".*?" ) ; return regex ; }
Create regular expression equivalent to any like operator string match function .
35,489
public static String createRegex ( String value , boolean ignoreCase ) { if ( value == null ) { throw new IllegalArgumentException ( "String cannot be null" ) ; } int len = value . length ( ) ; if ( len == 0 ) { return "" ; } StringBuilder sb = new StringBuilder ( len * 2 ) ; if ( ignoreCase ) { sb . append ( "(?i)" ) ; } sb . append ( "^" ) ; for ( int i = 0 ; i < len ; i ++ ) { char c = value . charAt ( i ) ; if ( "[](){}.*+?$^|#\\" . indexOf ( c ) != - 1 ) { sb . append ( "\\" ) ; } sb . append ( c ) ; } sb . append ( "$" ) ; return sb . toString ( ) ; }
Generates the regular expression for matching string for like operator .
35,490
private URL loadResource ( String configurationResourceName ) { ClassLoader standardClassloader = ClassLoaderUtil . getStandardClassLoader ( ) ; URL url = null ; if ( standardClassloader != null ) { url = standardClassloader . getResource ( configurationResourceName ) ; } if ( url == null ) { url = this . getClass ( ) . getResource ( configurationResourceName ) ; } log . info ( "Creating EhCacheFactory from a specified resource: " + configurationResourceName + " Resolved to URL: " + url ) ; if ( url == null ) { log . warn ( "A configurationResourceName was set to {} but the resource could not be loaded from the classpath.Ehcache will configure itself using defaults." , configurationResourceName ) ; } return url ; }
Load resource .
35,491
private void setScanCriteria ( Scan scan , String columnFamily , List < Map < String , Object > > columnsToOutput , Filter filter ) { if ( filter != null ) { scan . setFilter ( filter ) ; } }
Sets the scan criteria .
35,492
private List < HBaseDataWrapper > scanResults ( final String tableName , List < HBaseDataWrapper > results ) throws IOException { if ( fetchSize == null ) { for ( Result result : scanner ) { HBaseDataWrapper data = new HBaseDataWrapper ( tableName , result . getRow ( ) ) ; data . setColumns ( result . listCells ( ) ) ; results . add ( data ) ; } scanner = null ; resultsIter = null ; } return results ; }
Scan results .
35,493
public List < HBaseDataWrapper > loadAll ( final Table hTable , final List < Object > rows , final String columnFamily , final String [ ] columns ) throws IOException { setTableName ( hTable ) ; List < HBaseDataWrapper > results = new ArrayList < HBaseDataWrapper > ( ) ; List < Get > getRequest = new ArrayList < Get > ( ) ; for ( Object rowKey : rows ) { if ( rowKey != null ) { byte [ ] rowKeyBytes = HBaseUtils . getBytes ( rowKey ) ; Get request = new Get ( rowKeyBytes ) ; getRequest . add ( request ) ; } } Result [ ] rawResult = hTable . get ( getRequest ) ; for ( Result result : rawResult ) { List < Cell > cells = result . listCells ( ) ; if ( cells != null ) { HBaseDataWrapper data = new HBaseDataWrapper ( tableName , result . getRow ( ) ) ; data . setColumns ( cells ) ; results . add ( data ) ; } } return results ; }
Load all .
35,494
public boolean hasNext ( ) { if ( scanner == null ) { return false ; } else { if ( fetchSize != null ) { if ( counter < fetchSize ) { return resultsIter . hasNext ( ) ; } } else { return resultsIter . hasNext ( ) ; } } return false ; }
Checks for next .
35,495
public static boolean isInvertedIndexingApplicable ( EntityMetadata m , boolean useSecondryIndex ) { boolean invertedIndexingApplicable = useSecondryIndex && CassandraPropertyReader . csmd . isInvertedIndexingEnabled ( m . getSchema ( ) ) && m . getType ( ) . isSuperColumnFamilyMetadata ( ) && ! m . isCounterColumnType ( ) ; return invertedIndexingApplicable ; }
Checks whether Inverted indexing is applicable for a given entity whose metadata is passed as parameter
35,496
private void alterColumn ( AlterTableOptions alterTableOptions , Schema schema , ColumnInfo columnInfo , AtomicBoolean updated ) { if ( ! KuduDBDataHandler . hasColumn ( schema , columnInfo . getColumnName ( ) ) ) { alterTableOptions . addNullableColumn ( columnInfo . getColumnName ( ) , KuduDBValidationClassMapper . getValidTypeForClass ( columnInfo . getType ( ) ) ) ; updated . set ( true ) ; } else { if ( ! schema . getColumn ( columnInfo . getColumnName ( ) ) . getType ( ) . equals ( KuduDBValidationClassMapper . getValidTypeForClass ( columnInfo . getType ( ) ) ) ) { alterTableOptions . dropColumn ( columnInfo . getColumnName ( ) ) ; alterTableOptions . addNullableColumn ( columnInfo . getColumnName ( ) , KuduDBValidationClassMapper . getValidTypeForClass ( columnInfo . getType ( ) ) ) ; updated . set ( true ) ; } } }
Alter column .
35,497
private void createKuduTable ( TableInfo tableInfo ) { List < ColumnSchema > columns = new ArrayList < ColumnSchema > ( ) ; if ( tableInfo . getTableIdType ( ) . isAnnotationPresent ( Embeddable . class ) ) { MetamodelImpl metaModel = ( MetamodelImpl ) kunderaMetadata . getApplicationMetadata ( ) . getMetamodel ( puMetadata . getPersistenceUnitName ( ) ) ; EmbeddableType embeddableIdType = metaModel . embeddable ( tableInfo . getTableIdType ( ) ) ; Field [ ] fields = tableInfo . getTableIdType ( ) . getDeclaredFields ( ) ; addPrimaryKeyColumnsFromEmbeddable ( columns , embeddableIdType , fields , metaModel ) ; } else { columns . add ( new ColumnSchema . ColumnSchemaBuilder ( tableInfo . getIdColumnName ( ) , KuduDBValidationClassMapper . getValidTypeForClass ( tableInfo . getTableIdType ( ) ) ) . key ( true ) . build ( ) ) ; } for ( ColumnInfo columnInfo : tableInfo . getColumnMetadatas ( ) ) { ColumnSchemaBuilder columnSchemaBuilder = new ColumnSchema . ColumnSchemaBuilder ( columnInfo . getColumnName ( ) , KuduDBValidationClassMapper . getValidTypeForClass ( columnInfo . getType ( ) ) ) ; columns . add ( columnSchemaBuilder . build ( ) ) ; } for ( EmbeddedColumnInfo embColumnInfo : tableInfo . getEmbeddedColumnMetadatas ( ) ) { if ( embColumnInfo . getEmbeddedColumnName ( ) . equals ( tableInfo . getIdColumnName ( ) ) ) { continue ; } buildColumnsFromEmbeddableColumn ( embColumnInfo , columns ) ; } Schema schema = new Schema ( columns ) ; try { CreateTableOptions builder = new CreateTableOptions ( ) ; List < String > rangeKeys = new ArrayList < > ( ) ; if ( tableInfo . getTableIdType ( ) . isAnnotationPresent ( Embeddable . class ) ) { Iterator < ColumnSchema > colIter = columns . iterator ( ) ; while ( colIter . hasNext ( ) ) { ColumnSchema col = colIter . next ( ) ; if ( col . isKey ( ) ) { rangeKeys . add ( col . getName ( ) ) ; } } } else { rangeKeys . add ( tableInfo . getIdColumnName ( ) ) ; } builder . setRangePartitionColumns ( rangeKeys ) ; client . createTable ( tableInfo . getTableName ( ) , schema , builder ) ; logger . debug ( "Table: " + tableInfo . getTableName ( ) + " created successfully" ) ; } catch ( Exception e ) { logger . error ( "Table: " + tableInfo . getTableName ( ) + " cannot be created, Caused by: " + e . getMessage ( ) , e ) ; throw new SchemaGenerationException ( "Table: " + tableInfo . getTableName ( ) + " cannot be created, Caused by: " + e . getMessage ( ) , e , "Kudu" ) ; } }
Creates the kudu table .
35,498
private Object onAutoGenerator ( EntityMetadata m , Client < ? > client , Object e ) { Object autogenerator = getAutoGenClazz ( client ) ; if ( autogenerator instanceof AutoGenerator ) { Object generatedId = ( ( AutoGenerator ) autogenerator ) . generate ( 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 data type for ids : " + m . getIdAttribute ( ) . getJavaType ( ) ) ; throw new KunderaException ( "Unknown data type for ids : " + m . getIdAttribute ( ) . getJavaType ( ) , iae ) ; } } throw new IllegalArgumentException ( GenerationType . class . getSimpleName ( ) + "." + GenerationType . AUTO + " Strategy not supported by this client :" + client . getClass ( ) . getName ( ) ) ; }
Generate Id when given auto generation strategy .
35,499
private Object onSequenceGenerator ( EntityMetadata m , Client < ? > client , IdDiscriptor keyValue , Object e ) { Object seqgenerator = getAutoGenClazz ( client ) ; if ( seqgenerator instanceof SequenceGenerator ) { Object generatedId = ( ( SequenceGenerator ) seqgenerator ) . generate ( keyValue . getSequenceDiscriptor ( ) , 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 . SEQUENCE + " Strategy not supported by this client :" + client . getClass ( ) . getName ( ) ) ; }
Generate Id when given sequence generation strategy .